82 lines
2.5 KiB
Go
82 lines
2.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"net/http"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
)
|
|
|
|
const SessionCookieName = "__Host-lincodex_session"
|
|
|
|
type sessionRequestMetadataKey struct{}
|
|
|
|
type sessionRequestMetadata struct {
|
|
origin string
|
|
originValid bool
|
|
incomingToken domain.SecretToken
|
|
}
|
|
|
|
// 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{}
|
|
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
|
|
}
|
|
|
|
// 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
|
|
}
|