Documentation
¶
Index ¶
- func AuthMarker() gin.HandlerFunc
- func Authz() gin.HandlerFunc
- func BaseAuth() gin.HandlerFunc
- func Builtin() []gin.HandlerFunc
- func CircuitBreaker() gin.HandlerFunc
- func Delay(duration time.Duration) gin.HandlerFunc
- func DelayRandom(minDuration, maxDuration time.Duration) gin.HandlerFunc
- func DelayWithConfig(delayFunc func(*gin.Context) time.Duration) gin.HandlerFunc
- func GetSpanFromContext(c *gin.Context) trace.Span
- func IAMSession() gin.HandlerFunc
- func IPBlacklist(blacklist []string) gin.HandlerFunc
- func IPFilter(config *IPFilterConfig) gin.HandlerFunc
- func IPWhitelist(whitelist []string) gin.HandlerFunc
- func Init() (err error)
- func IsStreamingRoute(method, path string) bool
- func JwtAuth() gin.HandlerFunc
- func MFAVerificationRateLimit() gin.HandlerFunc
- func MarkStreamingRoute(method, path string)
- func RecordError(c *gin.Context, err error)
- func Register(middlewares ...gin.HandlerFunc)
- func RegisterAuth(middlewares ...gin.HandlerFunc)
- func RequestSizeLimit(maxSize int64) gin.HandlerFunc
- func SecurityHeaders(config *SecurityHeadersConfig) gin.HandlerFunc
- func SetApplyHandlers(commonHandler, authHandler func(gin.HandlerFunc))
- func Timeout(timeout time.Duration) gin.HandlerFunc
- type IPFilterConfig
- type RouteParamsManager
- type SecurityHeadersConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthMarker ¶
func AuthMarker() gin.HandlerFunc
AuthMarker is a middleware that marks the current route as requiring authentication. This middleware sets a flag in gin.Context to indicate that the current route requires authentication.
func Authz ¶
func Authz() gin.HandlerFunc
Authz authorizes requests using RBAC. It derives subject from trusted request context and blocks anonymous requests. Authz must be called before config.Init so config.Init can read AUTH_RBAC_ENABLED from the environment and enable RBAC initialization.
Authz must run after an authentication middleware that populates consts.CTX_USER_ID. When using built-in IAM sessions, register IAMSession before Authz; otherwise a valid session cookie is rejected as "permission denied" because Authz cannot find the authenticated subject yet.
The request tenant has exactly one source: consts.CTX_TENANT_ID, read as it stands when this middleware runs, defaulted to tenant.Default when empty. Whatever trusted middleware wrote it last decides. IAMSession writes the session's tenant; a deployment whose tenant arrives another way — a header a trusted gateway injects, a subdomain — installs its own middleware after IAMSession and before Authz and overwrites it. The value is trusted twice over — the authorization decision is made in that tenant, and every tenant-scoped row the request then reads or writes is scoped to it — so it must only ever be written from something the deployment vouches for, never from client input passed through as it stands: policies for the implicit authenticated role match in every tenant, so a request naming a forged tenant would pass those and act on that tenant's rows.
func BaseAuth ¶
func BaseAuth() gin.HandlerFunc
BaseAuth guards the documentation endpoints with HTTP Basic authentication.
Its refusal is gin's own: a bare 401 carrying WWW-Authenticate and no body, not the API envelope every other refusal answers in. That is the point — the header is what makes a browser open its credentials dialog, and these endpoints are opened by a person in a browser rather than by a client parsing responses.
func Builtin ¶
func Builtin() []gin.HandlerFunc
Builtin returns the middleware chain router.Init mounts ahead of every route, in mounting order. The chain is the framework's own and is not a menu: projects never mount these pieces themselves — mounting one twice double-counts metrics, double-writes logs or answers CORS twice — so the individual constructors are unexported and the file targets of the two loggers are fixed here rather than exposed as knobs.
Order carries the semantics: tracing and the access logger come first so every refusal downstream still carries a trace id and an access-log line, recovery turns panics from anything after it into enveloped responses, CORS and route-parameter capture prepare the request, and the strict-query gate runs last — nothing before it parses the query string, so the gate's parse is the request's first and, through the memo it fills, its only one.
func CircuitBreaker ¶
func CircuitBreaker() gin.HandlerFunc
func Delay ¶
func Delay(duration time.Duration) gin.HandlerFunc
Delay returns a middleware that adds a fixed delay before processing the request. This is primarily used for testing purposes to simulate network latency or slow responses.
Parameters:
- duration: The delay duration to add before processing the request
Returns:
- A gin.HandlerFunc that adds the specified delay
Example:
// Add a 100ms delay to all requests router.Use(middleware.Delay(100 * time.Millisecond)) // Add a 1 second delay router.Use(middleware.Delay(1 * time.Second))
func DelayRandom ¶
func DelayRandom(minDuration, maxDuration time.Duration) gin.HandlerFunc
DelayRandom returns a middleware that adds a random delay within the specified range before processing the request. This is primarily used for testing purposes to simulate variable network latency or slow responses.
Parameters:
- minDuration: The minimum delay duration
- maxDuration: The maximum delay duration
Returns:
- A gin.HandlerFunc that adds a random delay between minDuration and maxDuration
Example:
// Add a random delay between 0 and 3000ms router.Use(middleware.DelayRandom(0, 3000*time.Millisecond)) // Add a random delay between 100ms and 500ms router.Use(middleware.DelayRandom(100*time.Millisecond, 500*time.Millisecond))
func DelayWithConfig ¶
DelayWithConfig returns a middleware that adds a configurable delay based on request properties. This allows for more flexible testing scenarios, such as different delays for different paths or methods.
Parameters:
- delayFunc: A function that determines the delay duration based on the request context
Returns:
- A gin.HandlerFunc that adds the delay determined by delayFunc
Example:
// Add delay based on path
router.Use(middleware.DelayWithConfig(func(c *gin.Context) time.Duration {
if strings.HasPrefix(c.Request.URL.Path, "/api/slow") {
return 2 * time.Second
}
return 100 * time.Millisecond
}))
func GetSpanFromContext ¶
GetSpanFromContext retrieves the OpenTelemetry span from Gin context
func IAMSession ¶
func IAMSession() gin.HandlerFunc
func IPBlacklist ¶
func IPBlacklist(blacklist []string) gin.HandlerFunc
IPBlacklist returns a middleware that blocks requests from IP addresses in the blacklist.
Parameters:
- blacklist: List of blocked IP addresses or CIDR ranges (e.g., "192.168.1.100", "10.0.0.0/8")
Returns:
- A gin.HandlerFunc that enforces IP blacklist
Example:
// Block specific IPs
router.Use(middleware.IPBlacklist([]string{"192.168.1.100", "10.0.0.0/8"}))
// Block known malicious IPs
router.Use(middleware.IPBlacklist([]string{"1.2.3.4", "5.6.7.8"}))
func IPFilter ¶
func IPFilter(config *IPFilterConfig) gin.HandlerFunc
IPFilter returns a middleware that filters requests based on IP whitelist and blacklist. Blacklist takes precedence over whitelist.
The address filtered on is the one the engine reports: the peer of the connection, or the address a trusted proxy forwarded. Which proxies count is server.trusted_proxies, applied to the engine at startup — behind a proxy that is not named there, every request filters as the proxy's own address.
Parameters:
- config: Configuration for IP filtering
Returns:
- A gin.HandlerFunc that enforces IP filtering rules
Example:
// Use both whitelist and blacklist
router.Use(middleware.IPFilter(&middleware.IPFilterConfig{
Whitelist: []string{"192.168.0.0/16"},
Blacklist: []string{"192.168.1.100"},
}))
func IPWhitelist ¶
func IPWhitelist(whitelist []string) gin.HandlerFunc
IPWhitelist returns a middleware that only allows requests from IP addresses in the whitelist.
Parameters:
- whitelist: List of allowed IP addresses or CIDR ranges (e.g., "192.168.1.1", "10.0.0.0/8")
Returns:
- A gin.HandlerFunc that enforces IP whitelist
Example:
// Allow only specific IPs
router.Use(middleware.IPWhitelist([]string{"192.168.1.1", "10.0.0.0/8"}))
// Allow only localhost
router.Use(middleware.IPWhitelist([]string{"127.0.0.1", "::1"}))
func IsStreamingRoute ¶
IsStreamingRoute reports whether the route was marked as streaming.
func JwtAuth ¶
func JwtAuth() gin.HandlerFunc
JwtAuth authenticates a request from the bearer token in its Authorization header.
The token answers for itself: it is verified from its signature and claims, with nothing read from storage. Revoking one before it expires therefore is not something this middleware can do, which is the trade a stateless token makes and the reason IAM's own sessions are not built on it.
func MFAVerificationRateLimit ¶
func MFAVerificationRateLimit() gin.HandlerFunc
MFAVerificationRateLimit throttles the MFA endpoints that accept a guessable proof (a TOTP code or recovery code), per user and per endpoint: five attempts of burst with one attempt refilled every 12 seconds. Endpoints that accept no proof stay unthrottled.
It lives here rather than inside module/mfa so the add path and the copy path register the same handler: gg module copy carries middleware declared in module.json into the project and wires it into middleware/middleware.go, while a handler hidden in a module package would silently be add-only.
func MarkStreamingRoute ¶
func MarkStreamingRoute(method, path string)
MarkStreamingRoute registers a route as serving a long-lived streaming response. The path is the gin route pattern the handler is registered under, parameters included (e.g. "/api/items/:id/events").
func RecordError ¶
RecordError records an error in the current span
func Register ¶
func Register(middlewares ...gin.HandlerFunc)
Register adds global middlewares that apply to all routes. Must be called before router.Init. Middlewares are auto-wrapped for tracing; name is inferred via reflection.
func RegisterAuth ¶
func RegisterAuth(middlewares ...gin.HandlerFunc)
RegisterAuth adds authentication/authorization middlewares. Must be called before router.Init. Middlewares are auto-wrapped for tracing; name is inferred via reflection.
func RequestSizeLimit ¶
func RequestSizeLimit(maxSize int64) gin.HandlerFunc
RequestSizeLimit returns a middleware that limits the size of incoming request bodies. This helps prevent DoS attacks by limiting the amount of data that can be sent in a single request.
Parameters:
- maxSize: Maximum allowed size in bytes for the request body
Returns:
- A gin.HandlerFunc that enforces the request size limit
Example:
// Limit request body to 10MB router.Use(middleware.RequestSizeLimit(10 * 1024 * 1024)) // Limit request body to 1MB router.Use(middleware.RequestSizeLimit(1024 * 1024))
func SecurityHeaders ¶
func SecurityHeaders(config *SecurityHeadersConfig) gin.HandlerFunc
SecurityHeaders returns a middleware that sets security-related HTTP headers. This helps protect against various web vulnerabilities.
Parameters:
- config: Configuration for security headers. If nil, default secure headers will be used.
Returns:
- A gin.HandlerFunc that sets security headers
Example:
// Use default secure headers
router.Use(middleware.SecurityHeaders(nil))
// Use custom configuration
router.Use(middleware.SecurityHeaders(&middleware.SecurityHeadersConfig{
XFrameOptions: "DENY",
XContentTypeOptions: "nosniff",
XXSSProtection: "1; mode=block",
StrictTransportSecurity: "max-age=31536000; includeSubDomains",
ContentSecurityPolicy: "default-src 'self'",
ReferrerPolicy: "strict-origin-when-cross-origin",
}))
func SetApplyHandlers ¶
func SetApplyHandlers(commonHandler, authHandler func(gin.HandlerFunc))
SetApplyHandlers installs the handlers used to attach registered middlewares to router groups. Existing registered middlewares are applied immediately in registration order.
func Timeout ¶
func Timeout(timeout time.Duration) gin.HandlerFunc
Timeout returns a middleware that adds a timeout to the request context. If the request takes longer than the specified duration, it will be canceled.
Parameters:
- timeout: Maximum duration for the request to complete
Returns:
- A gin.HandlerFunc that enforces the timeout
Example:
// Set 30 second timeout for all requests router.Use(middleware.Timeout(30 * time.Second)) // Set 5 second timeout router.Use(middleware.Timeout(5 * time.Second))
Types ¶
type IPFilterConfig ¶
type IPFilterConfig struct {
// Whitelist contains allowed IP addresses or CIDR ranges
// If non-empty, only IPs in this list will be allowed
Whitelist []string
// Blacklist contains blocked IP addresses or CIDR ranges
// IPs in this list will always be blocked
Blacklist []string
}
IPFilterConfig holds configuration for IP filtering middleware
type RouteParamsManager ¶
type RouteParamsManager struct {
// contains filtered or unexported fields
}
RouteParamsManager holds parsed route path parameters for middleware.
var (
RouteManager *RouteParamsManager
)
func NewRouteParamsManager ¶
func NewRouteParamsManager() *RouteParamsManager
NewRouteParamsManager returns a new RouteParamsManager.
func (*RouteParamsManager) Add ¶
func (rpm *RouteParamsManager) Add(path string)
func (*RouteParamsManager) Get ¶
func (rpm *RouteParamsManager) Get(path string) []string
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// XFrameOptions controls the X-Frame-Options header
// Options: "DENY", "SAMEORIGIN", or empty string to disable
XFrameOptions string
// XContentTypeOptions controls the X-Content-Type-Options header
// Set to "nosniff" to enable, or empty string to disable
XContentTypeOptions string
// XXSSProtection controls the X-XSS-Protection header
// Set to "1; mode=block" to enable, or empty string to disable
XXSSProtection string
// StrictTransportSecurity controls the Strict-Transport-Security header
// Set to a value like "max-age=31536000; includeSubDomains" to enable, or empty string to disable
StrictTransportSecurity string
// ContentSecurityPolicy controls the Content-Security-Policy header
// Set to a CSP policy string to enable, or empty string to disable
ContentSecurityPolicy string
// ReferrerPolicy controls the Referrer-Policy header
// Options: "no-referrer", "no-referrer-when-downgrade", "origin", etc., or empty string to disable
ReferrerPolicy string
// PermissionsPolicy controls the Permissions-Policy header (formerly Feature-Policy)
// Set to a permissions policy string to enable, or empty string to disable
PermissionsPolicy string
}
SecurityHeadersConfig holds configuration for security headers middleware
Source Files
¶
- access_logger.go
- auth_marker.go
- authz.go
- baseauth.go
- builtin.go
- circuit_breaker.go
- cors.go
- delay.go
- http_body_logger.go
- iam_session.go
- ip_filter.go
- jwt.go
- mfa_verification.go
- middleware.go
- recovery.go
- request_size_limit.go
- routeparams_manager.go
- security_headers.go
- streaming_routes.go
- strict_query.go
- timeout.go
- tracing.go
- wrapper.go