Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for the API layer.
Index ¶
- Constants
- func Auth(svc *auth.Service) gin.HandlerFunc
- func AuthLoginThrottle(l *SharedRateLimiter) gin.HandlerFunc
- func AuthLoginThrottleLocal(l *RateLimiter) gin.HandlerFunc
- func ClientCertFingerprint(c *gin.Context) string
- func ClientCertRequired(enabled bool) gin.HandlerFunc
- func ClientCertSubject(c *gin.Context) string
- func ComputeSignature(key []byte, method, path, timestamp string, body []byte) string
- func EnrichKVResourceLabels(resolver KVLabelResolver) gin.HandlerFunc
- func EnvironmentHeader() gin.HandlerFunc
- func EnvironmentHeaderWithConfig(cfg ABACHeaderConfig) gin.HandlerFunc
- func ErrorHandler() gin.HandlerFunc
- func KVCapability(c *gin.Context) string
- func MTLSForPaths(required bool, prefixes ...string) gin.HandlerFunc
- func MTLSRequired(required bool) gin.HandlerFunc
- func RequestID() gin.HandlerFunc
- func RequestLogger(log *zap.Logger) gin.HandlerFunc
- func RequireAnyPermission(svc *auth.Service, resourceActionPairs ...string) gin.HandlerFunc
- func RequireKVAccess(svc *auth.Service, capability string, audit *AuthzAudit) gin.HandlerFunc
- func RequirePKISignCapability(svc *auth.Service, defaultMount string) gin.HandlerFunc
- func RequirePathCapability(svc *auth.Service, baseResource, capability string, pathParam string, ...) gin.HandlerFunc
- func RequirePermission(svc *auth.Service, resource, action string) gin.HandlerFunc
- func SealGuard(checker SealChecker) gin.HandlerFunc
- func SecurityHeaders(cfg SecurityHeadersConfig) gin.HandlerFunc
- func SignExposurePayload(key, timestamp string, body []byte) string
- func SignRequest(req *http.Request, key []byte) error
- func TenantEnforcement(enabled bool) gin.HandlerFunc
- func TokenCreateThrottle(l *SharedRateLimiter) gin.HandlerFunc
- func TokenID(c *gin.Context) string
- type ABACHeaderConfig
- type AuthzAudit
- type AuthzAuditRecorder
- type CacheExposureReplayStore
- type ExposureReplayStore
- type ExposureSigning
- type KVLabelResolver
- type RateLimiter
- type RequestSigning
- type SealChecker
- type SecurityHeadersConfig
- type SharedRateLimiter
Constants ¶
const ( // MaxExposureSkew is the max absolute clock skew accepted for signed exposure reports (W50-24). MaxExposureSkew = 5 * time.Minute )
Variables ¶
This section is empty.
Functions ¶
func AuthLoginThrottle ¶
func AuthLoginThrottle(l *SharedRateLimiter) gin.HandlerFunc
AuthLoginThrottle wraps a shared (Valkey when configured) rate limiter with auth metrics (W43-03 / W86-10). Accepts *SharedRateLimiter or falls back via SharedRateLimiter.Local-compatible *RateLimiter through Shared wrapper.
func AuthLoginThrottleLocal ¶
func AuthLoginThrottleLocal(l *RateLimiter) gin.HandlerFunc
AuthLoginThrottleLocal is for tests that only construct a process-local limiter.
func ClientCertFingerprint ¶
ClientCertFingerprint returns the SHA-256 fingerprint (hex) of the leaf client cert.
func ClientCertRequired ¶
func ClientCertRequired(enabled bool) gin.HandlerFunc
ClientCertRequired optionally enforces mTLS on secured routes (W34-01).
func ClientCertSubject ¶
ClientCertSubject returns the first peer certificate subject CN, if present.
func ComputeSignature ¶
ComputeSignature returns the HMAC signature for a request (client helper).
func EnrichKVResourceLabels ¶
func EnrichKVResourceLabels(resolver KVLabelResolver) gin.HandlerFunc
EnrichKVResourceLabels loads KV metadata labels into the request context before path auth.
func EnvironmentHeader ¶
func EnvironmentHeader() gin.HandlerFunc
EnvironmentHeader sets request environment/cluster for ABAC (W44-02 / W86-12).
func EnvironmentHeaderWithConfig ¶
func EnvironmentHeaderWithConfig(cfg ABACHeaderConfig) gin.HandlerFunc
EnvironmentHeaderWithConfig applies ABAC header policy.
func ErrorHandler ¶
func ErrorHandler() gin.HandlerFunc
ErrorHandler maps domain errors to standardized API responses.
func KVCapability ¶
KVCapability picks read vs list for KV endpoints (W41-05).
func MTLSForPaths ¶
func MTLSForPaths(required bool, prefixes ...string) gin.HandlerFunc
MTLSForPaths applies mTLS requirement only to matching path prefixes.
func MTLSRequired ¶
func MTLSRequired(required bool) gin.HandlerFunc
MTLSRequired rejects requests without a verified client certificate when enabled.
func RequestLogger ¶
func RequestLogger(log *zap.Logger) gin.HandlerFunc
RequestLogger logs one line per HTTP request.
func RequireAnyPermission ¶
func RequireAnyPermission(svc *auth.Service, resourceActionPairs ...string) gin.HandlerFunc
RequireAnyPermission allows if any resource/action pair is authorized (W79). Pairs are resource, action alternating: "pki/ca", "write", "pki", "write". Prefer specific resources first; fall back to coarse "pki" for legacy policies.
func RequireKVAccess ¶
func RequireKVAccess(svc *auth.Service, capability string, audit *AuthzAudit) gin.HandlerFunc
RequireKVAccess enforces path-aware KV capabilities (W41-01, W41-05).
func RequirePKISignCapability ¶
func RequirePKISignCapability(svc *auth.Service, defaultMount string) gin.HandlerFunc
RequirePKISignCapability enforces path-scoped PKI sign capability (W50-29 / W52-04). Checks resource "{mount}/sign/{role}" first, then mount-level "{mount}/sign". Coarse "pki" write alone is NOT sufficient (removed compatibility fallback). Policies that need broad sign should grant "pki/sign/*" or "pki/*" path patterns.
func RequirePathCapability ¶
func RequirePathCapability(svc *auth.Service, baseResource, capability string, pathParam string, audit *AuthzAudit) gin.HandlerFunc
RequirePathCapability enforces path-aware RBAC (W41-01).
func RequirePermission ¶
func RequirePermission(svc *auth.Service, resource, action string) gin.HandlerFunc
RequirePermission enforces RBAC for a resource/action pair.
func SealGuard ¶
func SealGuard(checker SealChecker) gin.HandlerFunc
SealGuard blocks the data plane when the vault is sealed (W50-03). Unlike write-only sealing, authenticated secret/PKI/audit reads are also denied so incident seal stops exfiltration. Unseal and liveness routes are registered outside groups that use this middleware.
func SecurityHeaders ¶
func SecurityHeaders(cfg SecurityHeadersConfig) gin.HandlerFunc
SecurityHeaders applies Helmet-like headers and optional CORS.
func SignExposurePayload ¶
SignExposurePayload computes the HMAC for body + timestamp (tests / clients). MAC = HMAC-SHA256(key, timestamp + "\n" + body).
func SignRequest ¶
SignRequest adds signature headers to an HTTP request.
func TenantEnforcement ¶
func TenantEnforcement(enabled bool) gin.HandlerFunc
TenantEnforcement requires namespace on mutating routes when tenant mode is enabled (W32-02).
func TokenCreateThrottle ¶
func TokenCreateThrottle(l *SharedRateLimiter) gin.HandlerFunc
TokenCreateThrottle wraps token create rate limiting (W43-05 / W86-10).
Types ¶
type ABACHeaderConfig ¶
type ABACHeaderConfig struct {
// TrustClient when true accepts X-KNX-Environment / X-KNX-Cluster from the client (lab).
// Production sets TrustClient=false so policies cannot be spoofed via headers alone.
TrustClient bool
// ServerEnvironment / ServerCluster are authoritative values when TrustClient is false
// (injected by the platform, not the caller).
ServerEnvironment string
ServerCluster string
}
ABACHeaderConfig controls whether client-asserted environment/cluster headers are trusted (W86-12).
type AuthzAudit ¶
type AuthzAudit struct {
// contains filtered or unexported fields
}
AuthzAudit records authorization denials.
func NewAuthzAudit ¶
func NewAuthzAudit(recorder AuthzAuditRecorder) *AuthzAudit
NewAuthzAudit constructs an authorization denial audit helper.
type AuthzAuditRecorder ¶
type AuthzAuditRecorder interface {
Record(ctx context.Context, actor, action, resource, status string, details map[string]any) error
}
AuthzAuditRecorder logs authz.denied events (W41-06).
type CacheExposureReplayStore ¶
type CacheExposureReplayStore struct {
// contains filtered or unexported fields
}
CacheExposureReplayStore uses cache.IncrStore (Valkey or memory) for HA-safe replay (W80-06). First MarkSeen returns true (Incr==1); subsequent calls return false.
func NewCacheExposureReplayStore ¶
func NewCacheExposureReplayStore(store cache.Store) *CacheExposureReplayStore
NewCacheExposureReplayStore wraps a cache.Store. Returns nil when store is nil.
type ExposureReplayStore ¶
type ExposureReplayStore interface {
MarkSeen(ctx context.Context, key string, ttl time.Duration) bool
}
ExposureReplayStore marks a replay key as seen. Returns false if the key was already present. Used for HA-safe exposure report anti-replay when backed by Valkey (W80-06).
type ExposureSigning ¶
type ExposureSigning struct {
// contains filtered or unexported fields
}
ExposureSigning verifies HMAC signatures on exposure reports.
func NewExposureSigning ¶
func NewExposureSigning(key string) *ExposureSigning
NewExposureSigning constructs exposure report signing middleware.
func (*ExposureSigning) Middleware ¶
func (s *ExposureSigning) Middleware() gin.HandlerFunc
Middleware validates the exposure report signature when configured.
func (*ExposureSigning) SetReplayStore ¶
func (s *ExposureSigning) SetReplayStore(store ExposureReplayStore)
SetReplayStore installs a shared (HA) replay store. Nil keeps process-local only.
type KVLabelResolver ¶
type KVLabelResolver interface {
LabelsForPath(ctx context.Context, path string) (map[string]string, error)
}
KVLabelResolver returns metadata labels for a secret path (W44-01).
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter enforces per-client request limits (W19) with bounded bucket map (W50-21).
func NewRateLimiter ¶
func NewRateLimiter(requestsPerMinute int, enabled bool) *RateLimiter
NewRateLimiter constructs a token-bucket rate limiter.
func (*RateLimiter) BucketCount ¶
func (l *RateLimiter) BucketCount() int
BucketCount returns the number of tracked client buckets (tests).
func (*RateLimiter) Middleware ¶
func (l *RateLimiter) Middleware() gin.HandlerFunc
Middleware returns a Gin handler that enforces rate limits.
func (*RateLimiter) SetMaxBuckets ¶
func (l *RateLimiter) SetMaxBuckets(n int)
SetMaxBuckets overrides the maximum number of client buckets retained (tests/ops).
type RequestSigning ¶
type RequestSigning struct {
// contains filtered or unexported fields
}
RequestSigning verifies optional HMAC request signatures (W19).
func NewRequestSigning ¶
func NewRequestSigning(key string, required bool) *RequestSigning
NewRequestSigning constructs request signing middleware settings.
func (*RequestSigning) Middleware ¶
func (s *RequestSigning) Middleware() gin.HandlerFunc
Middleware validates signed requests when configured.
type SealChecker ¶
type SealChecker interface {
Sealed() bool
}
SealChecker reports operational seal status.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
CORSAllowedOrigins []string
}
SecurityHeadersConfig configures CORS and security headers.
type SharedRateLimiter ¶
type SharedRateLimiter struct {
// contains filtered or unexported fields
}
SharedRateLimiter enforces per-key RPM using cache.Store when available (cluster-wide).
func NewSharedRateLimiter ¶
func NewSharedRateLimiter(rpm int, enabled bool, store cache.Store) *SharedRateLimiter
NewSharedRateLimiter wraps a local limiter with optional Valkey-backed counters.
func NewSharedRateLimiterPrefixed ¶
func NewSharedRateLimiterPrefixed(rpm int, enabled bool, store cache.Store, prefix string) *SharedRateLimiter
NewSharedRateLimiterPrefixed is like NewSharedRateLimiter with a custom key prefix so login/unseal/API counters do not collide (W86-10).
func (*SharedRateLimiter) Local ¶
func (l *SharedRateLimiter) Local() *RateLimiter
Local returns the underlying process-local limiter (for tests).
func (*SharedRateLimiter) Middleware ¶
func (l *SharedRateLimiter) Middleware() gin.HandlerFunc
Middleware enforces shared then local limits.