From db9c7130909aac753d29a49562e9b8173f633907 Mon Sep 17 00:00:00 2001 From: walsykerem Date: Sat, 21 Nov 2026 20:45:28 +0300 Subject: [PATCH 1/2] fix(api): reject unauthorized bodies before reading them --- cmd/api/main.go | 10 +--------- lib/middleware/oapi_auth.go | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index 636c28d88..9a9c0346a 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -17,7 +17,6 @@ import ( "time" "github.com/c2h5oh/datasize" - "github.com/getkin/kin-openapi/openapi3filter" "github.com/ghodss/yaml" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" @@ -41,7 +40,6 @@ import ( "github.com/kernel/hypeman/lib/scopes" "github.com/kernel/hypeman/lib/tokenrevocation" "github.com/kernel/hypeman/lib/vmm" - nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware" "github.com/riandyrn/otelchi" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/trace" @@ -509,13 +507,7 @@ func run() error { } // OpenAPI request validation with authentication - validatorOptions := &nethttpmiddleware.Options{ - Options: openapi3filter.Options{ - AuthenticationFunc: mw.OapiAuthenticationFunc(jwtVerifier, revokedTokens), - }, - ErrorHandler: mw.OapiErrorHandler, - } - r.Use(nethttpmiddleware.OapiRequestValidatorWithOptions(spec, validatorOptions)) + r.Use(mw.OapiRequestValidator(spec, jwtVerifier, revokedTokens)) // Scoped permissions — enforce per-route scope requirements r.Use(scopes.Middleware()) diff --git a/lib/middleware/oapi_auth.go b/lib/middleware/oapi_auth.go index 5f5cfa363..21b2ab9b1 100644 --- a/lib/middleware/oapi_auth.go +++ b/lib/middleware/oapi_auth.go @@ -10,6 +10,7 @@ import ( "strings" v2 "github.com/docker/distribution/registry/api/v2" + "github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3filter" "github.com/golang-jwt/jwt/v5" "github.com/gorilla/mux" @@ -17,6 +18,7 @@ import ( "github.com/kernel/hypeman/lib/logger" "github.com/kernel/hypeman/lib/scopes" "github.com/kernel/hypeman/lib/tokenrevocation" + nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware" ) // errRepoNotAllowed is returned when a valid token doesn't have access to the requested repository. @@ -57,6 +59,31 @@ type RegistryTokenClaims struct { Scope string `json:"scope,omitempty"` } +// OapiRequestValidator builds the OpenAPI request validation middleware, including +// bearer authentication. +func OapiRequestValidator(spec *openapi3.T, verifier *jwtauth.Verifier, revoked *tokenrevocation.List) func(http.Handler) http.Handler { + validate := nethttpmiddleware.OapiRequestValidatorWithOptions(spec, &nethttpmiddleware.Options{ + Options: openapi3filter.Options{ + AuthenticationFunc: OapiAuthenticationFunc(verifier, revoked), + }, + ErrorHandler: OapiErrorHandler, + }) + + return func(next http.Handler) http.Handler { + handler := validate(next) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // The validator reads the entire body into memory before calling the + // authentication function. A request without credentials is rejected + // regardless, so hide the body and keep anonymous clients from making + // the server buffer an arbitrarily large upload. + if r.Header.Get("Authorization") == "" { + r.Body = http.NoBody + } + handler.ServeHTTP(w, r) + }) + } +} + // OapiAuthenticationFunc creates an AuthenticationFunc compatible with nethttp-middleware // that validates JWT bearer tokens for endpoints with security requirements. func OapiAuthenticationFunc(verifier *jwtauth.Verifier, revoked *tokenrevocation.List) openapi3filter.AuthenticationFunc { From b654c4dd42b07615600766036c9667cfcd754216 Mon Sep 17 00:00:00 2001 From: walsykerem Date: Sat, 21 Nov 2026 22:03:05 +0300 Subject: [PATCH 2/2] fix(api): verify credentials before the request body is buffered The previous guard hid the body only when the Authorization header was absent, so any bogus header value (a non-bearer scheme, a malformed or revoked token) still drove the OpenAPI validator to read the whole body into memory before authentication rejected the request. The wrapper now authenticates first: it resolves the matched operation and, when that operation is secured, reuses the existing token extraction and validation path. A credential that cannot succeed hides the body before the validator runs; a credential that succeeds attaches the claims and passes the request through untouched. OapiAuthenticationFunc returns the pre-checked result instead of verifying the token again, so 401/403 bodies, messages, logs and revocation handling stay exactly as before. Requests with no body and unsecured operations are unchanged, and the registry routes are mounted outside this middleware. --- lib/middleware/oapi_auth.go | 101 +++++++++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 25 deletions(-) diff --git a/lib/middleware/oapi_auth.go b/lib/middleware/oapi_auth.go index 21b2ab9b1..17570d783 100644 --- a/lib/middleware/oapi_auth.go +++ b/lib/middleware/oapi_auth.go @@ -12,6 +12,8 @@ import ( v2 "github.com/docker/distribution/registry/api/v2" "github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3filter" + "github.com/getkin/kin-openapi/routers" + "github.com/getkin/kin-openapi/routers/gorillamux" "github.com/golang-jwt/jwt/v5" "github.com/gorilla/mux" "github.com/kernel/hypeman/lib/jwtauth" @@ -59,6 +61,16 @@ type RegistryTokenClaims struct { Scope string `json:"scope,omitempty"` } +// authenticatedRequestKey carries the outcome of an authentication check that ran +// before the request body was read. +const authenticatedRequestKey contextKey = "authenticated_request" + +// requestAuth is the result of pre-checking a request's credential. +type requestAuth struct { + claims jwt.MapClaims + err error +} + // OapiRequestValidator builds the OpenAPI request validation middleware, including // bearer authentication. func OapiRequestValidator(spec *openapi3.T, verifier *jwtauth.Verifier, revoked *tokenrevocation.List) func(http.Handler) http.Handler { @@ -69,27 +81,79 @@ func OapiRequestValidator(spec *openapi3.T, verifier *jwtauth.Verifier, revoked ErrorHandler: OapiErrorHandler, }) + router, err := gorillamux.NewRouter(spec) + if err != nil { + panic(err) // the validator above panics on the same spec + } + return func(next http.Handler) http.Handler { handler := validate(next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // The validator reads the entire body into memory before calling the - // authentication function. A request without credentials is rejected - // regardless, so hide the body and keep anonymous clients from making - // the server buffer an arbitrarily large upload. - if r.Header.Get("Authorization") == "" { - r.Body = http.NoBody + // authentication function, so a client whose credential cannot succeed + // could make the server buffer an arbitrarily large upload. Check the + // credential first and hide the body when it is unusable. + if r.Body != nil && r.Body != http.NoBody && routeRequiresAuth(router, r) { + auth := &requestAuth{} + auth.claims, auth.err = authenticateRequest(r.Context(), r, verifier, revoked) + if auth.err != nil { + r.Body = http.NoBody + } else { + r = r.WithContext(contextWithUserClaims(r.Context(), auth.claims)) + } + r = r.WithContext(context.WithValue(r.Context(), authenticatedRequestKey, auth)) } handler.ServeHTTP(w, r) }) } } +// routeRequiresAuth reports whether the request matches a secured operation, +// resolving operation and global security the way the validator does. +func routeRequiresAuth(router routers.Router, r *http.Request) bool { + route, _, err := router.FindRoute(r) + if err != nil { + return false + } + requirements := route.Operation.Security + if requirements == nil { + requirements = &route.Spec.Security + } + return len(*requirements) > 0 +} + +// authenticateRequest resolves the Authorization header to user claims. +func authenticateRequest(ctx context.Context, r *http.Request, verifier *jwtauth.Verifier, revoked *tokenrevocation.List) (jwt.MapClaims, error) { + log := logger.FromContext(ctx) + + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + log.DebugContext(ctx, "missing authorization header") + return nil, fmt.Errorf("authorization header required") + } + + token, err := extractBearerToken(authHeader) + if err != nil { + log.DebugContext(ctx, "invalid authorization header", "error", err) + return nil, fmt.Errorf("invalid authorization header format") + } + + claims, err := validateUserToken(ctx, token, verifier, revoked) + if err != nil { + logTokenValidationFailure(ctx, log, err, r) + if errors.Is(err, errInvalidTokenType) { + return nil, errInvalidTokenType + } + return nil, fmt.Errorf("invalid token") + } + + return claims, nil +} + // OapiAuthenticationFunc creates an AuthenticationFunc compatible with nethttp-middleware // that validates JWT bearer tokens for endpoints with security requirements. func OapiAuthenticationFunc(verifier *jwtauth.Verifier, revoked *tokenrevocation.List) openapi3filter.AuthenticationFunc { return func(ctx context.Context, input *openapi3filter.AuthenticationInput) error { - log := logger.FromContext(ctx) - // If no security requirements, allow the request if input.SecurityScheme == nil { return nil @@ -100,27 +164,14 @@ func OapiAuthenticationFunc(verifier *jwtauth.Verifier, revoked *tokenrevocation return fmt.Errorf("unsupported security scheme: %s", input.SecurityScheme.Type) } - // Extract token from Authorization header - authHeader := input.RequestValidationInput.Request.Header.Get("Authorization") - if authHeader == "" { - log.DebugContext(ctx, "missing authorization header") - return fmt.Errorf("authorization header required") + // Reuse the credential check that ran before the body was read, if any. + if auth, ok := ctx.Value(authenticatedRequestKey).(*requestAuth); ok { + return auth.err } - // Extract bearer token - token, err := extractBearerToken(authHeader) + claims, err := authenticateRequest(ctx, input.RequestValidationInput.Request, verifier, revoked) if err != nil { - log.DebugContext(ctx, "invalid authorization header", "error", err) - return fmt.Errorf("invalid authorization header format") - } - - claims, err := validateUserToken(ctx, token, verifier, revoked) - if err != nil { - logTokenValidationFailure(ctx, log, err, input.RequestValidationInput.Request) - if errors.Is(err, errInvalidTokenType) { - return errInvalidTokenType - } - return fmt.Errorf("invalid token") + return err } // Update the request with the authenticated user context.