Help us shape the future of Go! Take the 2026 Go Developer Survey

middleware

package
v0.4.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package middleware provides middleware functionality for CheeseWAF.

Index

Constants

View Source
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"
)
View Source
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).

View Source
const ManagementAPITokenPrefix = "cwapi_"
View Source
const SessionCookieMaxAge = 24 * time.Hour

SessionCookieMaxAge mirrors default admin session TTL (24h) when unset.

View Source
const UserContextKey contextKey = "user"

Variables

This section is empty.

Functions

func CSRFMiddleware

func CSRFMiddleware(next http.Handler) http.Handler

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

func CSRFTokenFromCookie(r *http.Request) string

CSRFTokenFromCookie returns the CSRF cookie value (readable by JS).

func CSRFTokenFromRequest

func CSRFTokenFromRequest(r *http.Request) string

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

func CookieSecure(r *http.Request) bool

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

func EdgeOriginRequestID(r *http.Request) string

EdgeOriginRequestID returns the validated Worker request ID for audit or tracing code downstream of VerifyEdgeOrigin.

func HashManagementAPIToken

func HashManagementAPIToken(raw string) string

func HashManagementAPITokenLegacySHA256

func HashManagementAPITokenLegacySHA256(raw string) string

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

func NewCSRFToken() (string, error)

NewCSRFToken generates a random CSRF token for double-submit.

func NoStore added in v0.4.5

func NoStore(next http.Handler) http.Handler

NoStore prevents browsers and intermediary caches retaining management data.

func RBAC

func RBAC(permissions PermissionMap, required string) func(http.Handler) http.Handler

func RBACAny

func RBACAny(permissions PermissionMap, required ...string) func(http.Handler) http.Handler

func RBACAnyProvider

func RBACAnyProvider(provider PermissionProvider, required ...string) func(http.Handler) http.Handler

func RBACProvider

func RBACProvider(provider PermissionProvider, required string) func(http.Handler) http.Handler

func Recovery

func Recovery(auditor *Auditor) func(http.Handler) http.Handler

Recovery converts handler panics into a stable API error and correlates them with audit logs.

func RequiresCSRF

func RequiresCSRF(method string) bool

RequiresCSRF reports whether the method mutates state and needs CSRF for cookie sessions.

func SessionFromCookie

func SessionFromCookie(r *http.Request) bool

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

func SessionToken(r *http.Request) string

SessionToken extracts the browser session JWT from the HttpOnly cookie, or falls back to Authorization Bearer (management API / migration bootstrap).

func ValidCSRFDoubleSubmit

func ValidCSRFDoubleSubmit(r *http.Request) bool

ValidCSRFDoubleSubmit checks cookie CSRF matches header/form CSRF.

func VerifyEdgeOrigin added in v0.4.0

func VerifyEdgeOrigin(next http.Handler, secret []byte, clock timekeeper.Clock) http.Handler

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

func WriteCookie(w http.ResponseWriter, r *http.Request, cookie *http.Cookie)

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 AIRequestLimitOptions struct {
	MaxRequests int
	MaxInFlight int
	MaxSubjects int
	Window      time.Duration
	SubjectTTL  time.Duration
	Now         func() time.Time
}

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 NewAuditor(path string) *Auditor

func NewAuditorWithClock

func NewAuditorWithClock(path string, clock timekeeper.Clock) *Auditor

func (*Auditor) Middleware

func (a *Auditor) Middleware(next http.Handler) http.Handler

func (*Auditor) MiddlewareWithSource added in v0.4.5

func (a *Auditor) MiddlewareWithSource(next http.Handler, resolve func(*http.Request) (client, peer, source string)) http.Handler

func (*Auditor) Query

func (a *Auditor) Query(limit int) ([]AuditEntry, error)

func (*Auditor) Write

func (a *Auditor) Write(ctx context.Context, entry AuditEntry) error

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"`
}

func VerifyManagementAPIToken

func VerifyManagementAPIToken(raw string, cfg config.ManagementAPIConfig, now time.Time) (*Claims, bool)

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

type ManagementAPITokenAuthenticator func(raw string, at time.Time) (*Claims, func(), bool)

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 PermissionMap map[string][]string

type PermissionProvider

type PermissionProvider func() PermissionMap

type SessionValidator

type SessionValidator interface {
	IsSessionActive(ctx context.Context, id, userID string, now time.Time) (bool, error)
}

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)

func (*TokenManager) Verify

func (m *TokenManager) Verify(token string) (*Claims, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL