package mcp import ( "crypto/subtle" "net/http" "strings" "github.com/mathiasbq/hyperguild/ingestion/internal/auth" ) // BearerAuth returns a middleware that enforces authentication on every request. // It tries a valid Dex JWT first (when v is non-nil), then falls back to the // static token. Rejects if token is empty and no valid JWT is presented. func BearerAuth(token string, v *auth.Validator, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rawToken, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok { http.Error(w, "unauthorized", http.StatusUnauthorized) return } if v != nil { if _, err := v.Validate(r.Context(), rawToken); err == nil { next.ServeHTTP(w, r) return } } if token != "" && subtle.ConstantTimeCompare([]byte(rawToken), []byte(token)) == 1 { next.ServeHTTP(w, r) return } http.Error(w, "unauthorized", http.StatusUnauthorized) }) }