package middleware import ( "context" "crypto/subtle" "net/http" "lincodex/backend/internal/domain" ) const SessionCookieName = "__Host-lincodex_session" type sessionRequestMetadataKey struct{} // maxUserAgentBytes bounds the User-Agent that is kept for the request. A // browser sends a few hundred bytes; the rest is not a browser. const maxUserAgentBytes = 512 type sessionRequestMetadata struct { origin string originValid bool incomingToken domain.SecretToken userAgent string } // SessionRequestMetadata records the browser Origin and an optional incoming // session token for the handwritten identity operations. It never trusts // forwarded headers and rejects duplicate or malformed cookie values. func SessionRequestMetadata() func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { metadata := sessionRequestMetadata{userAgent: boundedUserAgent(r.Header.Get("User-Agent"))} origins := r.Header.Values("Origin") if len(origins) == 1 { metadata.origin = origins[0] metadata.originValid = true } cookieCount := 0 for _, cookie := range r.Cookies() { if cookie.Name != SessionCookieName { continue } cookieCount++ if token, err := domain.ParseSecretToken(cookie.Value); err == nil { metadata.incomingToken = token } } if cookieCount != 1 { metadata.incomingToken = domain.SecretToken{} } ctx := context.WithValue(r.Context(), sessionRequestMetadataKey{}, metadata) next.ServeHTTP(w, r.WithContext(ctx)) }) } } // RequestOrigin returns the sole Origin header value when one was provided. func RequestOrigin(ctx context.Context) (string, bool) { metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata) return metadata.origin, ok && metadata.originValid } // RequestUserAgent returns the User-Agent of the request, cut to a safe length, // or an empty string when it had none. It exists to be hashed with a key into a // signal of the attempt; callers never store or log it. func RequestUserAgent(ctx context.Context) string { metadata, _ := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata) return metadata.userAgent } func boundedUserAgent(value string) string { if len(value) > maxUserAgentBytes { return value[:maxUserAgentBytes] } return value } // IncomingSessionToken returns a parsed token from exactly one session cookie. // The zero value means missing, malformed, or duplicated input. func IncomingSessionToken(ctx context.Context) domain.SecretToken { metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata) if !ok { return domain.SecretToken{} } return metadata.incomingToken } // SessionCookieMatches reports whether the generated API parser's value is // the sole valid session cookie recorded at the HTTP boundary. func SessionCookieMatches(ctx context.Context, rawToken string) bool { stored := IncomingSessionToken(ctx) if stored.IsZero() { return false } provided, err := domain.ParseSecretToken(rawToken) if err != nil { return false } storedHash, providedHash := stored.Hash(), provided.Hash() return subtle.ConstantTimeCompare(storedHash[:], providedHash[:]) == 1 }