Documentation
¶
Overview ¶
Package middleware provides middleware functionality for CheeseWAF.
Index ¶
- Constants
- func CSRFMiddleware(next http.Handler) http.Handler
- func CSRFTokenFromCookie(r *http.Request) string
- func CSRFTokenFromRequest(r *http.Request) string
- func ClearSessionCookies(w http.ResponseWriter, r *http.Request)
- func CookieSecure(r *http.Request) bool
- func EdgeOriginRequestID(r *http.Request) string
- func HashManagementAPIToken(raw string) string
- func HashManagementAPITokenLegacySHA256(raw string) string
- func ManagementAPIOrSessionMiddleware(manager *TokenManager, validator SessionValidator, ...) func(http.Handler) http.Handler
- func ManagementAPIOrSessionMiddlewareWithClock(manager *TokenManager, validator SessionValidator, ...) func(http.Handler) http.Handler
- func NewCSRFToken() (string, error)
- func NoStore(next http.Handler) http.Handler
- func RBAC(permissions PermissionMap, required string) func(http.Handler) http.Handler
- func RBACAny(permissions PermissionMap, required ...string) func(http.Handler) http.Handler
- func RBACAnyProvider(provider PermissionProvider, required ...string) func(http.Handler) http.Handler
- func RBACProvider(provider PermissionProvider, required string) func(http.Handler) http.Handler
- func Recovery(auditor *Auditor) func(http.Handler) http.Handler
- func RequiresCSRF(method string) bool
- func SessionFromCookie(r *http.Request) bool
- func SessionMiddleware(validator SessionValidator) func(http.Handler) http.Handler
- func SessionMiddlewareWithClock(validator SessionValidator, clock timekeeper.Clock) func(http.Handler) http.Handler
- func SessionToken(r *http.Request) string
- func ValidCSRFDoubleSubmit(r *http.Request) bool
- func VerifyEdgeOrigin(next http.Handler, secret []byte, clock timekeeper.Clock) http.Handler
- func VerifyEdgeOriginWithAccess(next http.Handler, secret []byte, accessClientID, accessClientSecret string, ...) http.Handler
- func VerifyEdgeOriginWithOptions(next http.Handler, options EdgeOriginOptions) http.Handler
- func WriteCookie(w http.ResponseWriter, r *http.Request, cookie *http.Cookie)
- func WriteSessionCookies(w http.ResponseWriter, r *http.Request, sessionJWT, csrf string, ...)
- type AIRequestLimitOptions
- type AIRequestLimiter
- type AuditEntry
- type Auditor
- func (a *Auditor) Middleware(next http.Handler) http.Handler
- func (a *Auditor) MiddlewareWithSource(next http.Handler, resolve func(*http.Request) (client, peer, source string)) http.Handler
- func (a *Auditor) Query(limit int) ([]AuditEntry, error)
- func (a *Auditor) Write(ctx context.Context, entry AuditEntry) error
- type Claims
- type EdgeOriginOptions
- type ManagementAPITokenAuthenticator
- type PermissionMap
- type PermissionProvider
- type SessionValidator
- type TokenManager
Constants ¶
const ( EdgeOriginRequestIDHeader = "X-CheeseSec-Edge-Request-Id" EdgeOriginTimestampHeader = "X-CheeseSec-Edge-Timestamp" EdgeOriginSignatureHeader = "X-CheeseSec-Edge-Signature" EdgeOriginPolicyHeader = "X-CheeseSec-Edge-Policy" EdgeOriginAccessIDHeader = "CF-Access-Client-Id" EdgeOriginAccessSecretHeader = "CF-Access-Client-Secret" )
const ( SessionCookieName = "cheesewaf_session" CSRFCookieName = "cheesewaf_csrf" SecureSessionCookieName = "__Host-cheesewaf_session" SecureCSRFCookieName = "__Host-cheesewaf_csrf" CSRFHeaderName = "X-CSRF-Token" )
Browser session cookie names (HttpOnly JWT + readable CSRF double-submit).
const ManagementAPITokenPrefix = "cwapi_"
const SessionCookieMaxAge = 24 * time.Hour
SessionCookieMaxAge mirrors default admin session TTL (24h) when unset.
const UserContextKey contextKey = "user"
Variables ¶
This section is empty.
Functions ¶
func CSRFMiddleware ¶
CSRFMiddleware enforces double-submit CSRF for cookie-authenticated browser sessions. Management API Bearer tokens (cwapi_*) and pure Authorization Bearer sessions without a session cookie are exempt. Safe methods are always allowed.
func CSRFTokenFromCookie ¶
CSRFTokenFromCookie returns the CSRF cookie value (readable by JS).
func CSRFTokenFromRequest ¶
CSRFTokenFromRequest returns the CSRF token from the double-submit header or a bounded URL-encoded form. Multipart bodies are never parsed here.
func ClearSessionCookies ¶
func ClearSessionCookies(w http.ResponseWriter, r *http.Request)
ClearSessionCookies expires session and CSRF cookies.
func CookieSecure ¶
CookieSecure is true for TLS requests, or for HTTPS declared by a trusted reverse proxy. X-Forwarded-Proto is only trusted when the socket peer is loopback or a private network (RFC1918 / IPv6 ULA); public peers must not be able to flip Secure on by supplying a header.
func EdgeOriginRequestID ¶ added in v0.4.0
EdgeOriginRequestID returns the validated Worker request ID for audit or tracing code downstream of VerifyEdgeOrigin.
func HashManagementAPIToken ¶
func HashManagementAPITokenLegacySHA256 ¶
HashManagementAPITokenLegacySHA256 is used only for tests that need deterministic digests.
func ManagementAPIOrSessionMiddleware ¶
func ManagementAPIOrSessionMiddleware(manager *TokenManager, validator SessionValidator, authenticate ManagementAPITokenAuthenticator) func(http.Handler) http.Handler
func ManagementAPIOrSessionMiddlewareWithClock ¶
func ManagementAPIOrSessionMiddlewareWithClock(manager *TokenManager, validator SessionValidator, authenticate ManagementAPITokenAuthenticator, clock timekeeper.Clock) func(http.Handler) http.Handler
func NewCSRFToken ¶
NewCSRFToken generates a random CSRF token for double-submit.
func NoStore ¶ added in v0.4.5
NoStore prevents browsers and intermediary caches retaining management data.
func RBACAnyProvider ¶
func RBACProvider ¶
func Recovery ¶
Recovery converts handler panics into a stable API error and correlates them with audit logs.
func RequiresCSRF ¶
RequiresCSRF reports whether the method mutates state and needs CSRF for cookie sessions.
func SessionFromCookie ¶
SessionFromCookie reports whether the request authenticated via the session cookie (as opposed to an Authorization Bearer header).
func SessionMiddleware ¶
func SessionMiddleware(validator SessionValidator) func(http.Handler) http.Handler
func SessionMiddlewareWithClock ¶
func SessionMiddlewareWithClock(validator SessionValidator, clock timekeeper.Clock) func(http.Handler) http.Handler
func SessionToken ¶
SessionToken extracts the browser session JWT from the HttpOnly cookie, or falls back to Authorization Bearer (management API / migration bootstrap).
func ValidCSRFDoubleSubmit ¶
ValidCSRFDoubleSubmit checks cookie CSRF matches header/form CSRF.
func VerifyEdgeOrigin ¶ added in v0.4.0
VerifyEdgeOrigin verifies the Worker HMAC envelope when secret is present. An empty secret leaves the middleware disabled so local loopback operation remains available until the deployment explicitly enables the tunnel trust boundary.
func VerifyEdgeOriginWithAccess ¶ added in v0.4.0
func VerifyEdgeOriginWithAccess(next http.Handler, secret []byte, accessClientID, accessClientSecret string, clock timekeeper.Clock) http.Handler
VerifyEdgeOriginWithAccess is the production form that also binds the request to the configured Cloudflare Access service identity.
func VerifyEdgeOriginWithOptions ¶ added in v0.4.0
func VerifyEdgeOriginWithOptions(next http.Handler, options EdgeOriginOptions) http.Handler
VerifyEdgeOriginWithOptions is exposed for deterministic tests and launchers that need a bounded replay cache.
func WriteCookie ¶
WriteCookie applies the request security policy then writes Set-Cookie. Host-prefixed cookies always retain Secure because browsers reject them otherwise.
func WriteSessionCookies ¶
func WriteSessionCookies(w http.ResponseWriter, r *http.Request, sessionJWT, csrf string, maxAge time.Duration)
WriteSessionCookies sets HttpOnly session JWT + non-HttpOnly CSRF cookies.
Types ¶
type AIRequestLimitOptions ¶
type AIRequestLimiter ¶
type AIRequestLimiter struct {
// contains filtered or unexported fields
}
AIRequestLimiter bounds paid AI work per authenticated principal. The map is TTL-pruned and capacity-bounded so arbitrary API-token subjects cannot grow it forever.
func NewAIRequestLimiter ¶
func NewAIRequestLimiter(options AIRequestLimitOptions) *AIRequestLimiter
func (*AIRequestLimiter) Middleware ¶
func (l *AIRequestLimiter) Middleware(next http.Handler) http.Handler
type AuditEntry ¶
type AuditEntry struct {
Timestamp time.Time `json:"timestamp"`
Subject string `json:"subject,omitempty"`
User string `json:"user"`
Role string `json:"role"`
Method string `json:"method"`
Path string `json:"path"`
Status int `json:"status"`
RemoteIP string `json:"remote_ip"`
PeerIP string `json:"peer_ip,omitempty"`
IPSource string `json:"ip_source,omitempty"`
SessionID string `json:"session_id,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
LatencyMS int64 `json:"latency_ms"`
Target string `json:"target,omitempty"`
Message string `json:"message,omitempty"`
}
type Auditor ¶
type Auditor struct {
// contains filtered or unexported fields
}
func NewAuditor ¶
func NewAuditorWithClock ¶
func NewAuditorWithClock(path string, clock timekeeper.Clock) *Auditor
func (*Auditor) MiddlewareWithSource ¶ added in v0.4.5
type Claims ¶
type Claims struct {
Subject string `json:"sub"`
ID string `json:"jti,omitempty"`
Username string `json:"username"`
Role string `json:"role"`
Scopes []string `json:"scope"`
IssuedAt int64 `json:"iat"`
NotBefore int64 `json:"nbf,omitempty"`
Expires int64 `json:"exp"`
}
type EdgeOriginOptions ¶ added in v0.4.0
type EdgeOriginOptions struct {
Secret []byte
AccessClientID string
AccessClientSecret string
Clock timekeeper.Clock
ReplayTTL time.Duration
MaxReplayIDs int
}
EdgeOriginOptions configures the transport trust check added by the Cloudflare Worker. The check never replaces user authentication or RBAC.
type ManagementAPITokenAuthenticator ¶
ManagementAPITokenAuthenticator may return an after-request callback for throttled bookkeeping that must run outside authentication/configuration locks. The middleware runs it even when the downstream handler panics.
type PermissionMap ¶
type PermissionProvider ¶
type PermissionProvider func() PermissionMap
type SessionValidator ¶
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
func NewTokenManager ¶
func NewTokenManager(secret string, ttl time.Duration) *TokenManager
func NewTokenManagerWithClock ¶
func NewTokenManagerWithClock(secret string, ttl time.Duration, clock timekeeper.Clock) *TokenManager
func (*TokenManager) Middleware ¶
func (m *TokenManager) Middleware(next http.Handler) http.Handler
func (*TokenManager) Sign ¶
func (m *TokenManager) Sign(subject, username, role string) (string, error)
func (*TokenManager) SignWithClaims ¶
func (m *TokenManager) SignWithClaims(subject, username, role string) (string, *Claims, error)