diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 8c1546ac..794bb85f 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -3794,8 +3794,8 @@ { "id": "server-token-endpoint-request-set-certificate-copy", "file": "server/http_requests.go", - "old": "\tt.parts = holdParts(parts)", - "new": "\t**t.parts.p = parts", + "old": "parts by value.\n\tt.parts = holdParts(parts)", + "new": "parts by value.\n\t**t.parts.p = parts", "module": "root", "packages": [ "./server" @@ -4082,8 +4082,8 @@ { "id": "resource-request-path-normal-path", "file": "resource/target.go", - "old": "if err == nil && !canonical.HasNormalPath(t) {", - "new": "if false && err == nil && !canonical.HasNormalPath(t) {", + "old": "if !canonical.HasNormalPath(t) {", + "new": "if false && !canonical.HasNormalPath(t) {", "module": "root", "packages": [ "./resource" @@ -6043,5 +6043,329 @@ ], "run": "^TestEmbedderUISealsTheHandleUnlessToldNotTo$", "why": "EmbedderUI without UnsafeRawHandleCookie completes an interaction from the raw handle in a plain cookie" + }, + { + "id": "server-dpop-route-unset-is-primary", + "file": "server/endpoint_route.go", + "old": "\tcase 0, PrimaryEndpoint:", + "new": "\tcase PrimaryEndpoint:", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestDPoPAtTheMTLSAlias$", + "why": "a DPoP request with no endpoint route is checked against the primary endpoint, not refused as a 500" + }, + { + "id": "server-dpop-route-alias-target", + "file": "server/endpoint_route.go", + "old": "\t\t\treturn alias.URL(), nil", + "new": "\t\t\treturn primary.URL(), nil", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestDPoPAtTheMTLSAlias$", + "why": "a request on the mTLS alias route is checked against the alias, and only the alias" + }, + { + "id": "server-dpop-route-alias-without-any-alias-500", + "file": "server/endpoint_route.go", + "old": "\t\tif s.cfg.MTLSEndpoints.IsZero() {", + "new": "\t\tif false && s.cfg.MTLSEndpoints.IsZero() {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestDPoPRefusesARouteWithNoTarget$", + "why": "the alias route on a server configuring no mTLS alias is the deployment's mistake: 500 naming the setters" + }, + { + "id": "server-dpop-route-unadvertised-alias-400", + "file": "server/endpoint_route.go", + "old": "\t\tif s.cfg.MTLSEndpoints.IsZero() {", + "new": "\t\tif true || s.cfg.MTLSEndpoints.IsZero() {", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestAliasRouteAtAnEndpointWithoutAlias$", + "why": "the alias route at an endpoint without an alias, on a server advertising others, is the client's mistake: 400" + }, + { + "id": "server-dpop-route-unknown-500", + "file": "server/endpoint_route.go", + "old": "\tdefault:\n\t\treturn url.URL{}, newError(ErrorServerError, 500", + "new": "\tdefault:\n\t\tif route > 0 {\n\t\t\treturn primary.URL(), nil\n\t\t}\n\t\treturn url.URL{}, newError(ErrorServerError, 500", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestDPoPRefusesARouteWithNoTarget$", + "why": "a route value the package doesn't define is refused as a 500, not treated as primary" + }, + { + "id": "server-dpop-route-replay-outage-500", + "file": "server/endpoint_route.go", + "old": "storeFailure(ctx, err, \"failed to check DPoP proof replay\"", + "new": "storeFailure(context.Background(), errors.New(\"refused\"), \"failed to check DPoP proof replay\"", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestStoreOutageAtReplayCheck$", + "why": "a replay store outage during the one-target DPoP check is still a 500, not invalid_dpop_proof" + }, + { + "id": "server-dpop-route-hint-shown", + "file": "server/endpoint_route.go", + "old": "\tif route != 0 || !errors.Is(err, dpop.ErrURIMismatch)", + "new": "\tif true || route != 0 || !errors.Is(err, dpop.ErrURIMismatch)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestUnroutedAliasProofNamesTheRouteSetters$", + "why": "an unrouted proof refused for its htu at an endpoint with an alias names the route setters in its cause" + }, + { + "id": "server-dpop-route-hint-only-unrouted", + "file": "server/endpoint_route.go", + "old": "\tif route != 0 || !errors.Is(err, dpop.ErrURIMismatch)", + "new": "\tif !errors.Is(err, dpop.ErrURIMismatch)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestRoutedOrAliaslessMismatchHasNoRouteHint$", + "why": "a routed request's refusal carries no route hint" + }, + { + "id": "server-dpop-route-hint-only-htu", + "file": "server/endpoint_route.go", + "old": "route != 0 || !errors.Is(err, dpop.ErrURIMismatch) || alias.IsZero()", + "new": "route != 0 || alias.IsZero()", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestRoutedOrAliaslessMismatchHasNoRouteHint$", + "why": "a proof refused for something other than its htu carries no route hint" + }, + { + "id": "server-dpop-route-hint-only-with-alias", + "file": "server/endpoint_route.go", + "old": "|| alias.IsZero() || alias.String() == primary.String()", + "new": "|| alias.String() == primary.String()", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestRoutedOrAliaslessMismatchHasNoRouteHint$", + "why": "an endpoint without an alias gives no route hint" + }, + { + "id": "server-dpop-route-hint-only-distinct-alias", + "file": "server/endpoint_route.go", + "old": "|| alias.IsZero() || alias.String() == primary.String()", + "new": "|| alias.IsZero()", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestRoutedOrAliaslessMismatchHasNoRouteHint$", + "why": "an alias equal to the endpoint's URL gives no route hint" + }, + { + "id": "server-with-endpoint-route-marks", + "file": "server/endpoint_route.go", + "old": "endpointRouteKey{}, route)))", + "new": "endpointRouteKey{}, route-route)))", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestWithEndpointRouteMarksFromHTTPRequests|TestWithEndpointRouteVerifiesAliasProofs)$", + "why": "WithEndpointRoute marks each request with its route" + }, + { + "id": "server-form-request-from-http-route", + "file": "server/formrequest.go", + "old": "EndpointRoute: endpointRouteOf(r)}", + "new": "EndpointRoute: 0 * endpointRouteOf(r)}", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestWithEndpointRouteMarksFromHTTPRequests|TestWithEndpointRouteVerifiesAliasProofs)$", + "why": "FormRequestFromHTTP, and every *FromHTTP constructor, takes the route WithEndpointRoute marked" + }, + { + "id": "server-set-endpoint-route", + "file": "server/http_requests.go", + "old": "\tparts.HTTP.EndpointRoute = route", + "new": "\tparts.HTTP.EndpointRoute = route - route", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestWithEndpointRouteMarksFromHTTPRequests|TestVerifyTokenRequestDPoPAtTheMTLSAlias)$", + "why": "SetEndpointRoute sets the request's route" + }, + { + "id": "server-set-endpoint-route-copy", + "file": "server/http_requests.go", + "old": "SetPeerCertificate makes.\n\tt.parts = holdParts(parts)", + "new": "SetPeerCertificate makes.\n\t**t.parts.p = parts", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestWithEndpointRouteMarksFromHTTPRequests$", + "why": "SetEndpointRoute gives the request a holder of its own, so a copy made before keeps its route" + }, + { + "id": "server-par-passes-route", + "file": "server/par.go", + "old": "s.cfg.MTLSEndpoints.PushedAuthorizationRequest, req.HTTP.EndpointRoute)", + "new": "s.cfg.MTLSEndpoints.PushedAuthorizationRequest, 0*req.HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestPushAuthorizationRequestCertClientAuthAcceptsDPoPProofAtMTLSAlias$", + "why": "PAR checks a DPoP proof against the URL its request's route names" + }, + { + "id": "server-ciba-begin-passes-route", + "file": "server/backchannel_authentication.go", + "old": "s.cfg.MTLSEndpoints.BackchannelAuthentication, req.HTTP.EndpointRoute)", + "new": "s.cfg.MTLSEndpoints.BackchannelAuthentication, 0*req.HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestBeginBackchannelAuthenticationAcceptsDPoPProofForTheMTLSAlias$", + "why": "the backchannel authentication endpoint checks a DPoP proof against the URL its request's route names" + }, + { + "id": "server-code-exchange-passes-route", + "file": "server/token.go", + "old": "dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute)", + "new": "dpopProof, req.PeerCertificate, 0*req.HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestExchangeAuthorizationCodeCertClientAuthAcceptsDPoPProofAtMTLSAlias$", + "why": "a code exchange checks a DPoP proof against the URL its request's route names" + }, + { + "id": "server-refresh-passes-route", + "file": "server/refresh.go", + "old": "dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute)", + "new": "dpopProof, req.PeerCertificate, 0*req.HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestRefreshAccessTokenCertClientAuthAtMTLSAlias$", + "why": "a refresh checks a DPoP proof against the URL its request's route names" + }, + { + "id": "server-extension-binding-passes-route", + "file": "server/extension_grants.go", + "old": "parts.PeerCertificate, parts.HTTP.EndpointRoute)", + "new": "parts.PeerCertificate, 0*parts.HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestBindingAtTheMTLSAlias$", + "why": "VerifyTokenRequestBinding checks a DPoP proof against the URL its request's route names" + }, + { + "id": "server-clientless-dpop-passes-route", + "file": "server/extension_grants.go", + "old": "proof, req.parts.get().HTTP.EndpointRoute)", + "new": "proof, 0*req.parts.get().HTTP.EndpointRoute)", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestVerifyTokenRequestDPoPAtTheMTLSAlias$", + "why": "VerifyTokenRequestDPoP checks a DPoP proof against the URL its request's route names" + }, + { + "id": "resource-origin-filters-resource-urls", + "file": "resource/target.go", + "old": "if origin != \"\" && r.originKey != origin {", + "new": "if false && origin != \"\" && r.originKey != origin {", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestWithResourceOriginSelectsTheTarget$", + "why": "under WithResourceOrigin, only the ResourceURLs at the marked origin place the request" + }, + { + "id": "resource-origin-unconfigured-500", + "file": "resource/target.go", + "old": "\t\tif r.originKey == origin {", + "new": "\t\tif true || r.originKey == origin {", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestWithResourceOriginOutsideResourceURLs$", + "why": "a mark naming an origin none of ResourceURLs is at is the deployment's mistake: 500" + }, + { + "id": "resource-origin-unmarked-outside-400", + "file": "resource/target.go", + "old": "\tif origin == \"\" {\n\t\treturn outsideResourceURLs(escapedPath)", + "new": "\tif false {\n\t\treturn outsideResourceURLs(escapedPath)", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestWithResourceOriginOutsideResourceURLs$", + "why": "an unmarked request no prefix covers is still the client's 400" + }, + { + "id": "resource-verify-request-from-http-origin", + "file": "resource/verify_request_http.go", + "old": "requestOrigin: resourceOriginOf(r),", + "new": "requestOrigin: resourceOriginOf(r)[:0],", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestWithResourceOriginSelectsTheTarget$", + "why": "VerifyRequestFromHTTP takes the origin WithResourceOrigin marked" + }, + { + "id": "resource-with-resource-origin-ignores-path", + "file": "resource/resource_origin.go", + "old": "key := canonical.URI(&url.URL{Scheme: u.Scheme, Host: u.Host})", + "new": "key := canonical.URI(&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path})", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^TestWithResourceOriginSelectsTheTarget$", + "why": "WithResourceOrigin keys on the origin's scheme and host, ignoring its path" + }, + { + "id": "resource-ambiguous-target-names-fix", + "file": "resource/target.go", + "old": "\t\t\treturn nil, ambiguousTarget(escapedPath)", + "new": "\t\t\treturn nil, outsideResourceURLs(escapedPath)", + "module": "root", + "packages": [ + "./resource" + ], + "run": "^(TestAmbiguousDPoPTargetNamesTheFix|TestVerifyDPoPTargetWithOverlappingOrigins)$", + "why": "an ambiguous DPoP target is a 500 naming WithResourceOrigin and VerifyRequest.URL" } ] diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 524cf78b..afcb21c3 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1324,7 +1324,11 @@ confirmed live via the token endpoint's `dpop: htu does not match request URI` rejection. Fixed by `verifyDPoPAtEitherEndpoint`, which retries once against the alias on a pure `htu` mismatch — safe since `internal/dpop.Verify` checks `htu` strictly before consuming replay -state. Full breakdown, including a genuine suite-config quirk this +state. (Since v0.88.0 the proof is checked against one URL only, the one +the request's `server.EndpointRoute` names: accepting either let one +unused proof be spent once at each where the two routes keep separate +replay records. `cmd/conformance-as` marks its alias listener with +`server.WithEndpointRoute`.) Full breakdown, including a genuine suite-config quirk this surfaced (unrelated to either fix) and the one apparent failure traced to a suite-side timing artifact rather than this server, in `conformance/server/oidf-config/README.md`'s own client-authentication diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index c7589f17..e99858ed 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -1326,6 +1326,21 @@ Add `POST /authorize/complete` (or wherever your login page posts) for `CompleteAuthorization` from step 5, and the CIBA, client credentials and revocation routes when you enable them. +With `Config.MTLSEndpoints` set, serve the same mux on a second listener +that asks for a client certificate, and mark it as the alias: + +```go +mux := routes(srv, login) +primary := &http.Server{Addr: ":8443", Handler: mux} +alias := &http.Server{Addr: ":8444", Handler: server.WithEndpointRoute(server.MTLSEndpointAlias, mux)} +``` + +A DPoP proof names the one URL it was sent to (RFC 9449 §4.3), so the +server checks it against the alias only for a request so marked (the +`*FromHTTP` constructors read the mark), and against `Config.Endpoints` +for any other. Without the mark, a proof for the alias is refused as +`invalid_dpop_proof`. See the [mutual TLS guide](docs/guides/mtls.md). + **What the HTTP layer owes FAPI 2.0.** These are yours, not the package's (FAPI 2.0 Security Profile §5.2): @@ -1456,8 +1471,12 @@ sent to, and only you know yours: the `Host` header, and whatever path a front end forwards, are the client's to choose. `Verify` takes the request's target to be its escaped path at one of these origins, and refuses a request no `ResourceURLs` prefix covers. List more than one -for an API reachable under several names (an mTLS alias host, say): a -proof naming any of them is accepted. As with the server, +for an API reachable under several names (an mTLS alias host, say), +and wrap each listener's handler in `resource.WithResourceOrigin(origin, +mux)`: when several origins cover a DPoP request's path, `Verify` needs +the one that received it, and refuses the request with `500 +server_error` without it (or an explicit `VerifyRequest.URL` from a +trusted proxy route). As with the server, `resource.AssuranceProduction` refuses `memstore`'s stores and `keys/ephemeral`'s key sources: it requires the issuer key source to declare `keys.KeySourceAssurance` (`keys.LocalIssuerKeys` does, and so diff --git a/UPGRADING.md b/UPGRADING.md index a4ad6153..623e069f 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,67 @@ Most production-assurance changes only affect `Config.Assurance = AssuranceProduction`. A development-assurance setup built on `memstore` and `keys/ephemeral` needs only the steps not marked *production only*. +## v0.88.0 + +### A DPoP proof is accepted only for the URL that received it (server) + +**Affects:** an authorization server with `Config.MTLSEndpoints` set +whose clients send DPoP proofs to an mTLS alias: typically a client +that authenticates with its certificate (`tls_client_auth`, +`self_signed_tls_client_auth`) but binds its tokens with DPoP, at PAR, +the token endpoint (extension grants included, through +`VerifyTokenRequestBinding` and `VerifyTokenRequestDPoP`) or the +backchannel authentication endpoint. A server without aliases, or whose +alias traffic is all mTLS-bound, is unaffected. + +**Why:** RFC 9449 §4.3 binds a proof to the URL of the request it is +sent with. The server accepted a proof naming either an endpoint's +`Config.Endpoints` URL or its alias, wherever it arrived, so where the +two routes keep separate replay records one unused captured proof could +be used once at each. + +**What fails:** each proof is now checked against one URL, chosen by the +request's new `FormRequest.EndpointRoute`: the alias for +`server.MTLSEndpointAlias`, the `Config.Endpoints` URL for +`server.PrimaryEndpoint` or no route at all. A request received at the +alias without a route, carrying a proof for the alias, is refused with +400 `invalid_dpop_proof` ("DPoP proof verification failed"); the +error's cause, in your logs but not the response, names the route +setters. A request on the alias route at an endpoint with no alias of +its own, on a server advertising others, gets the same 400. The alias +route on a server with no `MTLSEndpoints` at all, or a route value the +package doesn't define, is a deployment mistake: 500 `server_error`, +whose cause names the setters. + +**What to change:** wrap the handler of the listener serving the aliases +in `server.WithEndpointRoute(server.MTLSEndpointAlias, mux)`. The +`*FromHTTP` request constructors read the mark, so no handler changes. +Behind a front end that routes both URLs to one listener, set +`FormRequest.EndpointRoute`, or call +`TokenEndpointRequest.SetEndpointRoute`, from its trusted routing, +never from the `Host` header. The primary listener needs nothing. + +### A DPoP request needs its origin when several ResourceURLs cover its path (resource) + +**Affects:** a resource server whose `Config.ResourceURLs` (or +`serverresource.Options.ResourceURLs`) cover the same path at more than +one origin, such as an API also served at an mTLS alias host, serving +DPoP-bound tokens with requests built by `VerifyRequestFromHTTP`. + +**Why:** a proof naming any covering origin was accepted, with the same +consequence as at the authorization server. + +**What fails:** such a DPoP request is refused with 500 `server_error` +("ambiguous DPoP request target"), whose cause names the request path +and the fix. mTLS-bound requests, and paths only one origin covers, are +unaffected. + +**What to change:** wrap each listener's handler in +`resource.WithResourceOrigin(origin, mux)` with the origin it serves, +or set `VerifyRequest.URL` from a trusted proxy route, keeping the +escaped path the client sent. Never build either from the `Host` +header. An origin none of `ResourceURLs` is at is refused as a 500. + ## v0.87.0 ### A JWT or UserInfo response may not repeat a claim with differing values (all packages) diff --git a/cmd/conformance-as/listener_test.go b/cmd/conformance-as/listener_test.go new file mode 100644 index 00000000..dcd27810 --- /dev/null +++ b/cmd/conformance-as/listener_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/server" +) + +// TestListenerHandlerMarksTheRoute: a request each listener accepts is +// read with that listener's endpoint route, which decides the URL its +// DPoP proof must name. +func TestListenerHandlerMarksTheRoute(t *testing.T) { + origin, err := fapi.ParseEndpointURL("https://as.example") + if err != nil { + t.Fatal(err) + } + for _, route := range []server.EndpointRoute{server.PrimaryEndpoint, server.MTLSEndpointAlias} { + var got server.EndpointRoute + h := listenerHandler(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + req, err := server.PushAuthorizationRequestFromHTTP(r) + if err != nil { + t.Fatalf("PushAuthorizationRequestFromHTTP: %v", err) + } + got = req.HTTP.EndpointRoute + }), route, origin) + r := httptest.NewRequest(http.MethodPost, "/par", strings.NewReader("client_id=c")) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + h.ServeHTTP(httptest.NewRecorder(), r) + if got != route { + t.Errorf("listener %v: request read with route %v", route, got) + } + } +} diff --git a/cmd/conformance-as/main.go b/cmd/conformance-as/main.go index ffbd6d55..612f1624 100644 --- a/cmd/conformance-as/main.go +++ b/cmd/conformance-as/main.go @@ -117,7 +117,7 @@ func main() { httpServer := &http.Server{ Addr: resolved.ListenAddr, - Handler: mux, + Handler: listenerHandler(mux, server.PrimaryEndpoint, resolved.Issuer), TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, CipherSuites: server.FAPIRWTLSCipherSuites}, ReadHeaderTimeout: readHeaderTimeout, } @@ -177,7 +177,7 @@ func newMTLSServer(resolved ResolvedConfig, mux http.Handler) (*http.Server, err } return &http.Server{ Addr: resolved.MTLSListenAddr, - Handler: mux, + Handler: listenerHandler(mux, server.MTLSEndpointAlias, resolved.MTLSEndpoints.Token), TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, CipherSuites: server.FAPIRWTLSCipherSuites, diff --git a/cmd/conformance-as/mtls_smoke_test.go b/cmd/conformance-as/mtls_smoke_test.go index 57e7e391..65e850d6 100644 --- a/cmd/conformance-as/mtls_smoke_test.go +++ b/cmd/conformance-as/mtls_smoke_test.go @@ -166,10 +166,10 @@ func TestSmokeMTLSFlow(t *testing.T) { if err != nil { t.Fatalf("build server mux: %v", err) } - primaryServer := &http.Server{Handler: mux} + primaryServer := &http.Server{Handler: listenerHandler(mux, server.PrimaryEndpoint, issuer)} go primaryServer.Serve(primaryTLS) t.Cleanup(func() { primaryServer.Close() }) - mtlsServer := &http.Server{Handler: mux} + mtlsServer := &http.Server{Handler: listenerHandler(mux, server.MTLSEndpointAlias, mtlsEndpoints.Token)} go mtlsServer.Serve(mtlsTLS) t.Cleanup(func() { mtlsServer.Close() }) diff --git a/cmd/conformance-as/router.go b/cmd/conformance-as/router.go index 4ec713f8..e1adee46 100644 --- a/cmd/conformance-as/router.go +++ b/cmd/conformance-as/router.go @@ -67,3 +67,13 @@ func newRouter(srv *server.Server, consent *consentHandler, backchannel *backcha } return mux } + +// listenerHandler marks each request with the listener that actually +// accepted the connection: its endpoint route, which the server's +// *FromHTTP request constructors take (server.WithEndpointRoute), and +// its public origin, which resource.VerifyRequestFromHTTP takes +// (resource.WithResourceOrigin). Both listeners use the same ServeMux, +// and both decide which URL a DPoP proof sent there must name. +func listenerHandler(next http.Handler, route server.EndpointRoute, origin fapi.URL) http.Handler { + return server.WithEndpointRoute(route, fapires.WithResourceOrigin(origin, next)) +} diff --git a/cmd/conformance-as/wiring.go b/cmd/conformance-as/wiring.go index 76e7a693..26e6072b 100644 --- a/cmd/conformance-as/wiring.go +++ b/cmd/conformance-as/wiring.go @@ -7,6 +7,7 @@ import ( "net/http" "net/url" "os" + "strings" "time" fapi "github.com/idfoundry/fapigo" @@ -440,13 +441,11 @@ func newServerMux(resolved ResolvedConfig, allowLoopbackHTTP, dpopNonceChallenge // with a store of the resource side's own; with it off, // serverresource.NewVerifier follows the server's // server.NoDPoPNonces{} and declines too. - // Its URLs are the two protected endpoints', and the mTLS alias of - // UserInfo's when there is one: a DPoP proof names the URL its client - // called, never one taken from the request's Host header. - resourceOpts := serverresource.Options{ResourceURLs: []fapi.URL{userinfoURL, accountsURL}} - if mtlsUserinfoURL != nil { - resourceOpts.ResourceURLs = append(resourceOpts.ResourceURLs, *mtlsUserinfoURL) + resourceURLs, err := protectedResourceURLs(userinfoURL, accountsURL, mtlsUserinfoURL) + if err != nil { + return nil, err } + resourceOpts := serverresource.Options{ResourceURLs: resourceURLs} if dpopNonceChallenge { resourceOpts.Nonces = memstore.NewNonceStore() resourceOpts.NonceLifetime = dpopNonceLifetime @@ -504,3 +503,21 @@ func pairwiseSubjects(enabled bool) (server.SubjectConfig, pairwise.Deriver, err Prefix: prefix, }, deriver, nil } + +// protectedResourceURLs are the resource verifier's URLs: the two +// protected endpoints', and both again at the mTLS alias origin when +// there is one (mtlsUserinfoURL non-nil), since the alias listener +// serves the same mux. A DPoP proof names the URL its client called, +// never one taken from the request's Host header: each listener marks +// its origin (listenerHandler). +func protectedResourceURLs(userinfoURL, accountsURL fapi.URL, mtlsUserinfoURL *fapi.URL) ([]fapi.URL, error) { + urls := []fapi.URL{userinfoURL, accountsURL} + if mtlsUserinfoURL == nil { + return urls, nil + } + aliasAccounts, err := fapi.ParseEndpointURL(strings.TrimSuffix(mtlsUserinfoURL.String(), "/userinfo") + "/accounts") + if err != nil { + return nil, err + } + return append(urls, *mtlsUserinfoURL, aliasAccounts), nil +} diff --git a/conformance/server/oidf-config/README.md b/conformance/server/oidf-config/README.md index 932c0dbf..98753b5d 100644 --- a/conformance/server/oidf-config/README.md +++ b/conformance/server/oidf-config/README.md @@ -336,7 +336,10 @@ run: token endpoint rejected the suite's very first token request with `invalid_request: DPoP proof verification failed` / `dpop: htu does not match request URI`. Fixed by - `verifyDPoPAtEitherEndpoint` (`server/token.go`), which retries once + `verifyDPoPAtEitherEndpoint` (`server/token.go`; since v0.88.0 + replaced by a check against the one URL the request's + `server.EndpointRoute` names, which `cmd/conformance-as`'s alias + listener sets with `server.WithEndpointRoute`), which retries once against the mTLS-alias URL on a pure `htu` mismatch — safe because `internal/dpop.Verify`'s own `htu` check runs strictly before its replay check, so a mismatched first attempt never touches replay diff --git a/docs/guides/dpop.md b/docs/guides/dpop.md index 91ae58f9..53bc3b30 100644 --- a/docs/guides/dpop.md +++ b/docs/guides/dpop.md @@ -45,9 +45,13 @@ Register the client with `storage.SenderConstrainDPoP` (the default). endpoints, and binds the access token to the key (`cnf.jkt`). The checks are the ones RFC 9449 §4.3 lists, plus the ones that are easy to miss: -- the proof's `htu` is checked against your configured endpoint URLs - (`Config.Endpoints`, or their `MTLSEndpoints` aliases), never against - the request's `Host` header; +- the proof's `htu` is checked against one configured endpoint URL, + never against the request's `Host` header: the `Config.Endpoints` URL, + or its `MTLSEndpoints` alias for a request received there, which the + alias listener says by wrapping its handler in + `server.WithEndpointRoute(server.MTLSEndpointAlias, mux)` (see the + mutual TLS guide). A proof accepted at both could be used once at + each; - `iat` must fall within `Limits.MaxDPoPProofAge`, and a proof's `jti` can be used once (`Dependencies.Replay`); - a key committed at PAR must match the key at the token endpoint. @@ -97,7 +101,12 @@ the request describes), `ath` against the token, the key against `resource.Config.ResourceURLs` (or `serverresource.Options.ResourceURLs`): an origin, optionally with a path prefix. A request whose path no prefix covers is refused, and so is a proof whose `htu` is relative or names -another scheme. +another scheme. List every origin the API is reached at; if two of +them cover the same path (an mTLS alias host, say), wrap each +listener's handler in `resource.WithResourceOrigin(origin, mux)`, or set +`VerifyRequest.URL`, so a proof is checked against the one origin that +received it. Without either, such a DPoP request is refused with `500` +`server_error`, since the `Host` header can't be trusted to say. Nonces work as at the authorization server ([RFC 9449] §9, answered `401` with a `WWW-Authenticate: DPoP error="use_dpop_nonce"` challenge): diff --git a/docs/guides/mtls.md b/docs/guides/mtls.md index c3b87f1d..efc85eb6 100644 --- a/docs/guides/mtls.md +++ b/docs/guides/mtls.md @@ -117,6 +117,31 @@ srv, err := server.New(server.Config{ `Client-Cert` header, `fapihttp.ForwardedClientCertificate(r, fapihttp.ClientCertHeader, fapihttp.RemoteAddrIn(proxyPrefix))` reads it, and refuses a request that didn't come from the proxy's address. +- **The alias listener.** Serve `MTLSEndpoints` from a listener that + asks for a client certificate, and wrap its handler in + `server.WithEndpointRoute(server.MTLSEndpointAlias, mux)`. A DPoP + proof names the one URL its request was sent to (RFC 9449 §4.3), so + the server checks it against the alias only for a request marked as + received there, and against `Config.Endpoints` otherwise; the + `…FromHTTP` constructors take the mark. Unmarked, a client that + authenticates with its certificate but binds its tokens with DPoP + (`private_key_jwt` is not the only way to pair them) has its proof for + the alias refused as `invalid_dpop_proof`. Behind a front end that + routes both URLs to one listener, set `FormRequest.EndpointRoute` (or + `TokenEndpointRequest.SetEndpointRoute`) from its trusted routing + instead, never from the `Host` header: + + ```go + primary := &http.Server{Handler: mux} + alias := &http.Server{ + Handler: server.WithEndpointRoute(server.MTLSEndpointAlias, mux), + TLSConfig: &tls.Config{ClientAuth: tls.RequestClientCert /* ... */}, + } + ``` + + A resource server reachable at the alias host too lists both origins + in `ResourceURLs` and wraps each listener in + `resource.WithResourceOrigin(origin, mux)`; see the DPoP guide. - **Metadata** advertises `mtls_endpoint_aliases` once `MTLSEndpoints` is set, and `tls_client_certificate_bound_access_tokens` and the mTLS authentication methods once a client can do mutual TLS diff --git a/fapitest/authserver.go b/fapitest/authserver.go index bf0e271f..92156381 100644 --- a/fapitest/authserver.go +++ b/fapitest/authserver.go @@ -296,7 +296,13 @@ func (a *authServer) handleToken(w http.ResponseWriter, r *http.Request) { // client/userinfo_test.go, and this handler's job is the transport, not // re-proving that. func (a *authServer) handleUserInfo(w http.ResponseWriter, r *http.Request) { - authz, err := a.resource.Verify(r.Context(), resource.VerifyRequestFromHTTP(r)) + req := resource.VerifyRequestFromHTTP(r) + target, err := url.Parse(a.ts.URL + r.URL.EscapedPath()) + if err != nil { + a.t.Fatalf("fapitest: build UserInfo target: %v", err) + } + req.URL = target + authz, err := a.resource.Verify(r.Context(), req) if err != nil { a.writeResourceError(w, err) return diff --git a/fapitest/testdata/redaction.golden b/fapitest/testdata/redaction.golden index a288b4ea..adc6cbcf 100644 --- a/fapitest/testdata/redaction.golden +++ b/fapitest/testdata/redaction.golden @@ -314,6 +314,7 @@ resource.ResolvedAccessToken.Thumbprint encoding,fallback,log resource.VerifyRequest.Authorization encoding,fallback resource.VerifyRequest.DPoPProofs[0] encoding,fallback resource.VerifyRequest.Method encoding,fallback,log +resource.VerifyRequest.requestOrigin fallback,log resource.VerifyRequest.requestPath fallback,log server.AccessTokenParams.Audience encoding,fallback,log server.AccessTokenParams.Audiences[0] encoding,fallback,log diff --git a/internal/dpop/target_rules_test.go b/internal/dpop/target_rules_test.go index 991f37e8..c381f539 100644 --- a/internal/dpop/target_rules_test.go +++ b/internal/dpop/target_rules_test.go @@ -32,10 +32,10 @@ func signClaims(t *testing.T, htm, htu string, now time.Time) string { return proof } -func verifyAt(t *testing.T, proof, method string, target *url.URL, alternates []*url.URL, now time.Time) error { +func verifyAt(t *testing.T, proof, method string, target *url.URL, now time.Time) error { t.Helper() _, err := Verify(context.Background(), VerifyRequest{ - Proof: proof, Method: method, URL: target, AlternateURLs: alternates, + Proof: proof, Method: method, URL: target, Now: now, MaxProofAge: time.Minute, }) return err @@ -49,11 +49,11 @@ func TestVerifyRefusesRelativeOrNonHTTPHTU(t *testing.T) { now := time.Now() target := mustURL(t, "https://rs.example/accounts") for _, htu := range []string{"/accounts", "//rs.example/accounts", "ftp://rs.example/accounts", "FTP://RS.example/accounts", "urn:x:accounts", "https:///accounts"} { - if err := verifyAt(t, signClaims(t, "GET", htu, now), "GET", target, nil, now); !errors.Is(err, ErrURIMismatch) { + if err := verifyAt(t, signClaims(t, "GET", htu, now), "GET", target, now); !errors.Is(err, ErrURIMismatch) { t.Errorf("htu %q at %s: err = %v, want ErrURIMismatch", htu, target, err) } } - if err := verifyAt(t, signClaims(t, "GET", "HTTPS://RS.example/accounts", now), "GET", target, nil, now); err != nil { + if err := verifyAt(t, signClaims(t, "GET", "HTTPS://RS.example/accounts", now), "GET", target, now); err != nil { t.Errorf("htu differing only in ASCII case: err = %v, want nil", err) } } @@ -66,13 +66,10 @@ func TestVerifyRefusesRelativeOrNonHTTPTarget(t *testing.T) { now := time.Now() for _, target := range []string{"/accounts", "ftp://rs.example/accounts", "rs.example/accounts", "https:///accounts", "mailto:a@rs.example"} { u := mustURL(t, target) - if err := verifyAt(t, signClaims(t, "GET", target, now), "GET", u, nil, now); err == nil || errors.Is(err, ErrURIMismatch) { + if err := verifyAt(t, signClaims(t, "GET", target, now), "GET", u, now); err == nil || errors.Is(err, ErrURIMismatch) { t.Errorf("target %q: err = %v, want a refused target", target, err) } - good := mustURL(t, "https://rs.example/accounts") - if err := verifyAt(t, signClaims(t, "GET", good.String(), now), "GET", good, []*url.URL{u}, now); err == nil || errors.Is(err, ErrURIMismatch) { - t.Errorf("alternate target %q: err = %v, want a refused target", target, err) - } + } } @@ -93,7 +90,7 @@ func TestVerifyComparesMethodExactly(t *testing.T) { {"get", "get", true}, } for _, c := range cases { - err := verifyAt(t, signClaims(t, c.htm, target.String(), now), c.method, target, nil, now) + err := verifyAt(t, signClaims(t, c.htm, target.String(), now), c.method, target, now) if c.ok != (err == nil) || (!c.ok && !errors.Is(err, ErrMethodMismatch)) { t.Errorf("htm %q, method %q: err = %v, want ok=%v", c.htm, c.method, err, c.ok) } @@ -110,24 +107,10 @@ func TestCreateProofKeepsMethodAsGiven(t *testing.T) { if err != nil { t.Fatal(err) } - if err := verifyAt(t, proof, "get", target, nil, now); err != nil { + if err := verifyAt(t, proof, "get", target, now); err != nil { t.Errorf("verify at get: %v", err) } - if err := verifyAt(t, proof, "GET", target, nil, now); !errors.Is(err, ErrMethodMismatch) { + if err := verifyAt(t, proof, "GET", target, now); !errors.Is(err, ErrMethodMismatch) { t.Errorf("verify at GET: err = %v, want ErrMethodMismatch", err) } } - -// TestVerifyAcceptsAnAlternateTarget: an htu naming any one of the -// targets verifies; one naming none of them doesn't. -func TestVerifyAcceptsAnAlternateTarget(t *testing.T) { - now := time.Now() - primary := mustURL(t, "https://rs.example/accounts") - alternates := []*url.URL{mustURL(t, "https://mtls.rs.example/accounts")} - if err := verifyAt(t, signClaims(t, "GET", "https://mtls.rs.example/accounts", now), "GET", primary, alternates, now); err != nil { - t.Errorf("htu naming the alternate: %v", err) - } - if err := verifyAt(t, signClaims(t, "GET", "https://other.example/accounts", now), "GET", primary, alternates, now); !errors.Is(err, ErrURIMismatch) { - t.Errorf("htu naming neither: err = %v, want ErrURIMismatch", err) - } -} diff --git a/internal/dpop/verify.go b/internal/dpop/verify.go index 67bca04a..330219ac 100644 --- a/internal/dpop/verify.go +++ b/internal/dpop/verify.go @@ -39,11 +39,6 @@ type VerifyRequest struct { Method string URL *url.URL - // AlternateURLs are further target URIs the proof's "htu" may name - // instead of URL, for a resource reachable at more than one origin; - // each is held to URL's own rules. Empty, the htu must name URL. - AlternateURLs []*url.URL - // AccessToken, if non-empty, is the access token presented alongside // this proof. When set, the proof's "ath" claim must match its hash; // when empty, the proof must not carry an "ath" claim at all. @@ -105,10 +100,8 @@ func Verify(ctx context.Context, req VerifyRequest) (VerifiedProof, error) { if req.URL == nil { return VerifiedProof{}, fmt.Errorf("dpop: url is nil") } - for _, u := range append([]*url.URL{req.URL}, req.AlternateURLs...) { - if !isAbsoluteHTTP(u) { - return VerifiedProof{}, fmt.Errorf("dpop: url must be an absolute http or https URL with a host") - } + if !isAbsoluteHTTP(req.URL) { + return VerifiedProof{}, fmt.Errorf("dpop: url must be an absolute http or https URL with a host") } if req.Now.IsZero() { return VerifiedProof{}, fmt.Errorf("dpop: now is zero") @@ -169,17 +162,6 @@ func isAbsoluteHTTP(u *url.URL) bool { return scheme == "https" || scheme == "http" } -// namesTarget reports whether htu, canonicalized, names req.URL or one -// of req.AlternateURLs. A target whose host isn't ASCII never matches. -func namesTarget(htu string, req VerifyRequest) bool { - for _, u := range append([]*url.URL{req.URL}, req.AlternateURLs...) { - if canonical.IsASCII(u.Host) && canonical.URI(u) == htu { - return true - } - } - return false -} - // checkProofTimes holds the proof to its iat: no further in the future // than MaxClockSkew and no older than MaxProofAge. An nbf or exp the // proof carries counts too (RFC 7519 §4.1.4-§4.1.5): FAPI 2.0 Security @@ -230,7 +212,7 @@ func verifyProofClaims(c claims, req VerifyRequest, iat time.Time) error { if err != nil || !isAbsoluteHTTP(htu) || !canonical.IsASCII(htu.Host) { return ErrURIMismatch } - if !namesTarget(canonical.URI(htu), req) { + if !canonical.IsASCII(req.URL.Host) || canonical.URI(htu) != canonical.URI(req.URL) { return ErrURIMismatch } diff --git a/resource/config.go b/resource/config.go index af535b5e..8be97c91 100644 --- a/resource/config.go +++ b/resource/config.go @@ -57,12 +57,12 @@ type Config struct { // are the client's to choose. For a request built by // VerifyRequestFromHTTP, Verify takes the target to be the request's // escaped path (never its decoded one, which names another resource - // when a segment holds "%2F") at each origin here whose path prefix - // covers it, and refuses a request no prefix covers. An explicit - // VerifyRequest.URL must be under one of them too. Several origins - // serve one resource server reachable under more than one name, an - // mTLS alias host among them; a proof naming any of them is - // accepted. A URL parsed with fapi.AllowLoopbackHTTP is refused + // when a segment holds "%2F") at the origin WithResourceOrigin marked + // the request with, or else at whichever configured origin covers + // it. When several do, a DPoP request needs that mark, or + // VerifyRequest.URL, from trusted listener or proxy routing: without + // either it is refused as a 500. Verify checks an explicit URL + // against ResourceURLs too. A URL parsed with fapi.AllowLoopbackHTTP is refused // under AssuranceProduction. ResourceURLs []fapi.URL diff --git a/resource/opaque_issuer_test.go b/resource/opaque_issuer_test.go index 874334fe..96759319 100644 --- a/resource/opaque_issuer_test.go +++ b/resource/opaque_issuer_test.go @@ -28,7 +28,7 @@ func TestOpaqueAccessTokenFromAnotherIssuerIsRefused(t *testing.T) { const ( issuerA = "https://idp.example/tenant-a" issuerB = "https://idp.example/tenant-b" - api = "https://rs.example" + api = "https://rs.example.com" ) now := time.Now() shared := memstore.NewAccessTokenStore() diff --git a/resource/render.go b/resource/render.go index 7c25728d..e6592325 100644 --- a/resource/render.go +++ b/resource/render.go @@ -24,13 +24,14 @@ type verifyRequestShadow struct { DPoPProofs []redact.Hidden PeerCertificate string requestPath string + requestOrigin string repeatedAuthorization bool } func (r VerifyRequest) shadow() verifyRequestShadow { shadow := verifyRequestShadow{ Method: r.Method, Authorization: authorizationSummary(r.Authorization), DPoPProofs: redact.MaskStrings(r.DPoPProofs), - PeerCertificate: certificateSummary(r.PeerCertificate), requestPath: r.requestPath, repeatedAuthorization: r.repeatedAuthorization, + PeerCertificate: certificateSummary(r.PeerCertificate), requestPath: r.requestPath, requestOrigin: r.requestOrigin, repeatedAuthorization: r.repeatedAuthorization, } if r.URL != nil { shadow.URL = redact.URL(*r.URL) diff --git a/resource/render_internal_test.go b/resource/render_internal_test.go index 53bba016..7e255ffb 100644 --- a/resource/render_internal_test.go +++ b/resource/render_internal_test.go @@ -32,14 +32,14 @@ func TestVerifyRequestPrintsNoToken(t *testing.T) { r.Header.Set("DPoP", renderProof) req := VerifyRequestFromHTTP(r) rendertest.Check(t, req, []string{renderAccessToken, renderProof}, exportedResidual) - if got := fmt.Sprintf("%+v", req); got != "{Method:GET URL: Authorization:DPoP [REDACTED] DPoPProofs:[[REDACTED]] PeerCertificate: requestPath:/accounts repeatedAuthorization:false}" { + if got := fmt.Sprintf("%+v", req); got != "{Method:GET URL: Authorization:DPoP [REDACTED] DPoPProofs:[[REDACTED]] PeerCertificate: requestPath:/accounts requestOrigin: repeatedAuthorization:false}" { t.Errorf("%%+v = %s", got) } withURL := VerifyRequest{Method: "POST", URL: r.URL, Authorization: "Bearer " + renderAccessToken, PeerCertificate: &x509.Certificate{Subject: pkix.Name{CommonName: "client-1"}}} rendertest.Check(t, withURL, []string{renderAccessToken, renderQueryValue}, exportedResidual) - if got := fmt.Sprint(withURL); got != "{POST https://rs.example/accounts?filter=[REDACTED] Bearer [REDACTED] [] CN=client-1 false}" { + if got := fmt.Sprint(withURL); got != "{POST https://rs.example/accounts?filter=[REDACTED] Bearer [REDACTED] [] CN=client-1 false}" { t.Errorf("%%v = %s", got) } if got := logged(withURL); !strings.Contains(got, `k.Authorization="Bearer [REDACTED]"`) || !strings.Contains(got, `k.PeerCertificate="CN=client-1"`) { diff --git a/resource/resource_origin.go b/resource/resource_origin.go new file mode 100644 index 00000000..0049408d --- /dev/null +++ b/resource/resource_origin.go @@ -0,0 +1,48 @@ +package resource + +import ( + "context" + "net/http" + "net/url" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/canonical" +) + +// resourceOriginKey is the context key WithResourceOrigin marks a +// request's origin under. +type resourceOriginKey struct{} + +// WithResourceOrigin returns a handler that serves each request with +// next, marked as received at origin's scheme and host (its path, if +// any, is ignored). VerifyRequestFromHTTP takes the mark, and Verify +// then places the request's escaped path only under the +// Config.ResourceURLs at that origin. A resource server reachable under +// more than one origin, such as an mTLS alias host, whose ResourceURLs +// cover one path at several of them, needs the mark (or +// VerifyRequest.URL) for each DPoP request: a proof names one URL (RFC +// 9449 §4.3), and the Host header the client sends can't say which, or +// a proof captured at one origin could be spent again at another. Wrap +// each listener's handler with its own origin: +// +// primary := &http.Server{Handler: resource.WithResourceOrigin(apiURL, mux)} +// alias := &http.Server{Handler: resource.WithResourceOrigin(mtlsAPIURL, mux)} +// +// origin must be the origin of one of Config.ResourceURLs, or Verify +// refuses every request marked with it as a 500. An explicit +// VerifyRequest.URL takes precedence over the mark, and the innermost +// WithResourceOrigin wins. +func WithResourceOrigin(origin fapi.URL, next http.Handler) http.Handler { + u := origin.URL() + key := canonical.URI(&url.URL{Scheme: u.Scheme, Host: u.Host}) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), resourceOriginKey{}, key))) + }) +} + +// resourceOriginOf is the canonical origin WithResourceOrigin marked r +// with, or "". +func resourceOriginOf(r *http.Request) string { + origin, _ := r.Context().Value(resourceOriginKey{}).(string) + return origin +} diff --git a/resource/resource_origin_test.go b/resource/resource_origin_test.go new file mode 100644 index 00000000..dcf0e314 --- /dev/null +++ b/resource/resource_origin_test.go @@ -0,0 +1,146 @@ +package resource_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/resource" +) + +// overlappingFixture is newFixture with both of testResourceURLs' +// origins covering every path, plus extra. +func overlappingFixture(t *testing.T, extra ...string) fixture { + t.Helper() + f := newFixture(t) + cfg := validConfig(t) + cfg.ResourceURLs = testResourceURLs(t) + for _, raw := range extra { + cfg.ResourceURLs = append(cfg.ResourceURLs, mustEndpointURL(t, raw)) + } + f.verifier = newVerifierLike(t, f, cfg) + return f +} + +func mustEndpointURL(t *testing.T, raw string) fapi.URL { + t.Helper() + u, err := fapi.ParseEndpointURL(raw) + if err != nil { + t.Fatalf("ParseEndpointURL(%q): %v", raw, err) + } + return u +} + +// verifyAtOrigin verifies a DPoP GET of path, with a proof naming htu, +// read by VerifyRequestFromHTTP under WithResourceOrigin(origin) — or +// unmarked for origin "". +func verifyAtOrigin(t *testing.T, f fixture, origin, path, htu string) error { + t.Helper() + r := httptest.NewRequest(http.MethodGet, path, nil) + r.Header.Set("Authorization", "DPoP "+f.accessToken) + r.Header.Set("DPoP", f.proofFor(t, "GET", htu)) + var err error + var h http.Handler = http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + _, err = f.verifier.Verify(r.Context(), resource.VerifyRequestFromHTTP(r)) + }) + if origin != "" { + h = resource.WithResourceOrigin(mustEndpointURL(t, origin), h) + } + h.ServeHTTP(httptest.NewRecorder(), r) + return err +} + +// wantResourceError checks err is a *resource.Error with code and +// status whose message names each of causes. +func wantResourceError(t *testing.T, name string, err error, code resource.ErrorCode, status int, causes ...string) { + t.Helper() + var rerr *resource.Error + if !errors.As(err, &rerr) || rerr.Code() != code || rerr.HTTPStatus() != status { + t.Errorf("%s: err = %v, want %d %s", name, err, status, code) + return + } + for _, c := range causes { + if !strings.Contains(err.Error(), c) { + t.Errorf("%s: err = %v, want it to name %q", name, err, c) + } + } +} + +// TestAmbiguousDPoPTargetNamesTheFix: a DPoP request whose path two +// configured origins cover, with nothing to say which received it, is +// the deployment's to fix: a 500 naming WithResourceOrigin and +// VerifyRequest.URL. +func TestAmbiguousDPoPTargetNamesTheFix(t *testing.T) { + f := overlappingFixture(t) + err := verifyAtOrigin(t, f, "", "/accounts/1", "https://rs.example/accounts/1") + wantResourceError(t, "ambiguous", err, resource.ErrorServerError, 500, "resource.WithResourceOrigin", "VerifyRequest.URL") +} + +// TestWithResourceOriginSelectsTheTarget: under WithResourceOrigin, a +// proof must name the marked origin, whatever other configured origin +// covers the path too. +func TestWithResourceOriginSelectsTheTarget(t *testing.T) { + f := overlappingFixture(t) + for _, c := range []struct { + origin, htu string + ok bool + }{ + {"https://rs.example", "https://rs.example/accounts/1", true}, + {"https://rs.example", "https://rs.example.com/accounts/1", false}, + {"https://rs.example.com", "https://rs.example.com/accounts/1", true}, + {"https://rs.example.com", "https://rs.example/accounts/1", false}, + {"https://rs.example.com/ignored/path", "https://rs.example.com/accounts/1", true}, + } { + err := verifyAtOrigin(t, f, c.origin, "/accounts/1", c.htu) + if c.ok { + if err != nil { + t.Errorf("at %s, proof for %s: %v", c.origin, c.htu, err) + } + continue + } + wantResourceError(t, "at "+c.origin+", proof for "+c.htu, err, resource.ErrorInvalidDPoPProof, 401) + } +} + +// TestWithResourceOriginOutsideResourceURLs: a mark naming an origin +// none of Config.ResourceURLs is at is the deployment's mistake, a 500 +// naming WithResourceOrigin; a path not covered at a configured origin +// is still the client's, 400. +func TestWithResourceOriginOutsideResourceURLs(t *testing.T) { + f := overlappingFixture(t, "https://api.example/v1") + err := verifyAtOrigin(t, f, "https://other.example", "/accounts/1", "https://other.example/accounts/1") + wantResourceError(t, "unconfigured origin", err, resource.ErrorServerError, 500, "resource.WithResourceOrigin", "https://other.example/") + err = verifyAtOrigin(t, f, "https://api.example", "/v2/accounts", "https://api.example/v2/accounts") + wantResourceError(t, "uncovered path", err, resource.ErrorInvalidRequest, 400) + err = verifyAtOrigin(t, f, "", "/", "https://rs.example/") + wantResourceError(t, "ambiguous root", err, resource.ErrorServerError, 500) + + prefixed := newFixture(t) + cfg := validConfig(t) + cfg.ResourceURLs = []fapi.URL{mustEndpointURL(t, "https://api.example/v1")} + prefixed.verifier = newVerifierLike(t, prefixed, cfg) + err = verifyAtOrigin(t, prefixed, "", "/v2/accounts", "https://api.example/v2/accounts") + wantResourceError(t, "uncovered path, unmarked", err, resource.ErrorInvalidRequest, 400) +} + +// TestExplicitURLOverridesWithResourceOrigin: VerifyRequest.URL, set +// after VerifyRequestFromHTTP, takes precedence over the mark. +func TestExplicitURLOverridesWithResourceOrigin(t *testing.T) { + f := overlappingFixture(t) + r := httptest.NewRequest(http.MethodGet, "/accounts/1", nil) + r.Header.Set("Authorization", "DPoP "+f.accessToken) + r.Header.Set("DPoP", f.proofFor(t, "GET", "https://rs.example.com/accounts/1")) + var err error + resource.WithResourceOrigin(mustEndpointURL(t, "https://rs.example"), http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + req := resource.VerifyRequestFromHTTP(r) + req.URL, _ = url.Parse("https://rs.example.com/accounts/1") + _, err = f.verifier.Verify(r.Context(), req) + })).ServeHTTP(httptest.NewRecorder(), r) + if err != nil { + t.Fatalf("explicit URL under another origin's mark: %v", err) + } +} diff --git a/resource/target.go b/resource/target.go index 5709bfe5..a0a91c74 100644 --- a/resource/target.go +++ b/resource/target.go @@ -16,6 +16,10 @@ import ( type resourceURL struct { origin url.URL prefix string + + // originKey is canonical.URI(&origin), which a request's + // requestOrigin is compared to. + originKey string } // prepareResourceURLs checks Config.ResourceURLs and prepares each for @@ -38,9 +42,11 @@ func prepareResourceURLs(cfg Config) ([]resourceURL, error) { case !canonical.HasNormalPath(&u): return nil, fmt.Errorf("resource: config: resource_urls[%d] has a path with dot segments or percent-encoded unreserved characters", i) } + origin := url.URL{Scheme: u.Scheme, Host: u.Host} out = append(out, resourceURL{ - origin: url.URL{Scheme: u.Scheme, Host: u.Host}, - prefix: strings.TrimSuffix(canonical.URI(&u), "/"), + origin: origin, + prefix: strings.TrimSuffix(canonical.URI(&u), "/"), + originKey: canonical.URI(&origin), }) } return out, nil @@ -53,21 +59,18 @@ func (r resourceURL) covers(target *url.URL) bool { return c == r.prefix || strings.HasPrefix(c, r.prefix+"/") } -// requestTargets returns the URLs a DPoP proof's htu may name for req: -// for a request built by VerifyRequestFromHTTP, its escaped path at each -// configured origin whose path prefix covers it; for an explicit -// req.URL, that URL, once it is known to be under one of -// Config.ResourceURLs. -func (v *Verifier) requestTargets(req VerifyRequest) ([]*url.URL, *Error) { +// requestTarget checks an explicit target or resolves the received path +// against the configured origins. +func (v *Verifier) requestTarget(req VerifyRequest, dpop bool) (*url.URL, *Error) { if req.URL != nil { return v.explicitTarget(req.URL) } - return v.pathTargets(req.requestPath) + return v.pathTarget(req.requestPath, req.requestOrigin, dpop) } // explicitTarget is target, once it is known to be an absolute http(s) // URL under one of Config.ResourceURLs. -func (v *Verifier) explicitTarget(target *url.URL) ([]*url.URL, *Error) { +func (v *Verifier) explicitTarget(target *url.URL) (*url.URL, *Error) { if !target.IsAbs() || target.Host == "" || (target.Scheme != "https" && target.Scheme != "http") { return nil, newError(ErrorServerError, 500, "failed to verify request", errors.New("resource: VerifyRequest.URL must be an absolute http(s) URL, or left nil with a request built by VerifyRequestFromHTTP")) } @@ -76,32 +79,77 @@ func (v *Verifier) explicitTarget(target *url.URL) ([]*url.URL, *Error) { } for _, r := range v.resourceURLs { if r.covers(target) { - return []*url.URL{target}, nil + return target, nil } } return nil, outsideResourceURLs(target.String()) } -// pathTargets is escapedPath at each configured origin whose path -// prefix covers it. -func (v *Verifier) pathTargets(escapedPath string) ([]*url.URL, *Error) { +// pathTarget resolves escapedPath under the configured prefixes at +// origin (WithResourceOrigin's mark), or at every configured origin for +// none. DPoP needs one unambiguous URI; certificate binding only +// requires a covered path. +func (v *Verifier) pathTarget(escapedPath, origin string, dpop bool) (*url.URL, *Error) { if !strings.HasPrefix(escapedPath, "/") { return nil, outsideResourceURLs(escapedPath) } - var targets []*url.URL + var target *url.URL for _, r := range v.resourceURLs { - t, err := url.Parse(r.origin.String() + escapedPath) - if err == nil && !canonical.HasNormalPath(t) { - return nil, nonNormalPath(escapedPath) + if origin != "" && r.originKey != origin { + continue + } + t, covered, perr := r.pathAt(escapedPath) + if perr != nil { + return nil, perr } - if err == nil && t.Host == r.origin.Host && t.RawQuery == "" && t.Fragment == "" && r.covers(t) { - targets = append(targets, t) + if !covered { + continue } + if target != nil && dpop && canonical.URI(target) != canonical.URI(t) { + return nil, ambiguousTarget(escapedPath) + } + target = t } - if len(targets) == 0 { - return nil, outsideResourceURLs(escapedPath) + if target == nil { + return nil, v.uncoveredPath(escapedPath, origin) + } + return target, nil +} + +// pathAt is escapedPath at r's origin, and whether r covers it there. +// A path not in normal form is refused whichever origin it is at. +func (r resourceURL) pathAt(escapedPath string) (*url.URL, bool, *Error) { + t, err := url.Parse(r.origin.String() + escapedPath) + if err != nil { + return nil, false, nil + } + if !canonical.HasNormalPath(t) { + return nil, false, nonNormalPath(escapedPath) + } + return t, t.Host == r.origin.Host && t.RawQuery == "" && t.Fragment == "" && r.covers(t), nil +} + +// ambiguousTarget refuses a DPoP request whose path is covered at more +// than one configured origin, with nothing to say which it was received +// at: the deployment's to fix, so a 500. +func ambiguousTarget(escapedPath string) *Error { + return newError(ErrorServerError, 500, "ambiguous DPoP request target", fmt.Errorf("resource: several of Config.ResourceURLs' origins cover the request path %q: wrap the listener's handler in resource.WithResourceOrigin, or set VerifyRequest.URL, from the listener or a trusted proxy route (never the Host header)", escapedPath)) +} + +// uncoveredPath refuses a request no configured prefix at origin covers: +// outsideResourceURLs, unless no ResourceURLs entry is at origin at all, +// so that WithResourceOrigin marks the listener with an origin this +// resource server doesn't serve, which is the deployment's to fix. +func (v *Verifier) uncoveredPath(escapedPath, origin string) *Error { + if origin == "" { + return outsideResourceURLs(escapedPath) + } + for _, r := range v.resourceURLs { + if r.originKey == origin { + return outsideResourceURLs(escapedPath) + } } - return targets, nil + return newError(ErrorServerError, 500, "failed to verify request", fmt.Errorf("resource: resource.WithResourceOrigin marks the request with origin %q, which none of Config.ResourceURLs is at", origin)) } // nonNormalPath refuses a request whose path isn't in the normal form diff --git a/resource/target_test.go b/resource/target_test.go index 5b481676..43ad7071 100644 --- a/resource/target_test.go +++ b/resource/target_test.go @@ -102,12 +102,23 @@ func TestVerifyRequestFromHTTPIgnoresHost(t *testing.T) { } } -// TestVerifyRequestFromHTTPAcceptsEachConfiguredOrigin: a proof naming -// any of Config.ResourceURLs' origins verifies. -func TestVerifyRequestFromHTTPAcceptsEachConfiguredOrigin(t *testing.T) { +func TestVerifyDPoPTargetWithOverlappingOrigins(t *testing.T) { f := newFixture(t) - if got := serveThroughMux(t, f, "/accounts/1", "", f.proofFor(t, "GET", "https://rs.example/accounts/1")); got != http.StatusOK { - t.Errorf("proof naming the second origin: status %d, want 200", got) + cfg := validConfig(t) + cfg.ResourceURLs = testResourceURLs(t) + f.verifier = newVerifierLike(t, f, cfg) + r := httptest.NewRequest(http.MethodGet, "/accounts/1", nil) + r.Header.Set("Authorization", "DPoP "+f.accessToken) + r.Header.Set("DPoP", f.proofFor(t, "GET", "https://rs.example/accounts/1")) + req := resource.VerifyRequestFromHTTP(r) + _, err := f.verifier.Verify(r.Context(), req) + assertCode(t, "ambiguous route", err, resource.ErrorServerError) + req.URL, _ = url.Parse("https://rs.example.com/accounts/1") + _, err = f.verifier.Verify(r.Context(), req) + assertCode(t, "different origin", err, resource.ErrorInvalidDPoPProof) + req.URL, _ = url.Parse("https://rs.example/accounts/1") + if _, err := f.verifier.Verify(r.Context(), req); err != nil { + t.Fatalf("receiving origin: %v", err) } } diff --git a/resource/verifier_test.go b/resource/verifier_test.go index 992ab079..4cccfaa9 100644 --- a/resource/verifier_test.go +++ b/resource/verifier_test.go @@ -97,7 +97,7 @@ func validConfig(t *testing.T) resource.Config { MaxClockSkew: 5 * time.Second, }, Assurance: resource.AssuranceDevelopment, - ResourceURLs: testResourceURLs(t), + ResourceURLs: testResourceURLs(t)[:1], } } diff --git a/resource/verify.go b/resource/verify.go index 72c92fc0..c9612b2a 100644 --- a/resource/verify.go +++ b/resource/verify.go @@ -36,7 +36,11 @@ type VerifyRequest struct { // URL is the absolute URL the client called, which a DPoP proof's // htu must name. Leave it nil with a request built by // VerifyRequestFromHTTP: Verify then builds it from the request's - // escaped path and Config.ResourceURLs. Set, it must be an absolute + // escaped path and Config.ResourceURLs: at the origin + // WithResourceOrigin marked the request with, or else at the one + // origin whose ResourceURLs cover the path. A DPoP request whose path + // several origins cover, with neither, is refused as a 500: the + // deployment must say which it was received at. Set, it must be an absolute // http(s) URL under one of Config.ResourceURLs, or Verify refuses // the request — so one built from the request's Host header, which // the client controls, can name no other resource server. A path @@ -93,6 +97,12 @@ type VerifyRequest struct { // under Config.ResourceURLs when URL is nil. requestPath string + // requestOrigin is the canonical origin (canonical.URI of its scheme + // and host) WithResourceOrigin marked the request with, "" for none: + // Verify then places requestPath only under the ResourceURLs at that + // origin. + requestOrigin string + // repeatedAuthorization is VerifyRequestFromHTTP's mark of a request // with more than one Authorization header. repeatedAuthorization bool @@ -313,14 +323,14 @@ func (v *Verifier) verify(ctx context.Context, req VerifyRequest) (Authorization if perr != nil { return AuthorizationContext{}, usedDPoP, perr } - targets, terr := v.requestTargets(req) + target, terr := v.requestTarget(req, usedDPoP) if terr != nil { return AuthorizationContext{}, usedDPoP, terr } now := v.deps.Clock.Now() - senderConstrain, verifiedProof, certThumbprint, verr := v.resolveCredential(ctx, req, targets, dpopProof, raw, usedDPoP, now) + senderConstrain, verifiedProof, certThumbprint, verr := v.resolveCredential(ctx, req, target, dpopProof, raw, usedDPoP, now) if verr != nil { return AuthorizationContext{}, usedDPoP, verr } @@ -546,7 +556,7 @@ func tokenRevocationKeys(resolved ResolvedAccessToken) []string { // the resolved access token against. Split out of Verify purely to keep // that method's own token-resolution/binding/revocation pipeline // readable — this is the one genuinely separable sub-task within it. -func (v *Verifier) resolveCredential(ctx context.Context, req VerifyRequest, targets []*url.URL, dpopProof, raw string, usedDPoP bool, now time.Time) (storage.SenderConstrain, dpop.VerifiedProof, string, *Error) { +func (v *Verifier) resolveCredential(ctx context.Context, req VerifyRequest, target *url.URL, dpopProof, raw string, usedDPoP bool, now time.Time) (storage.SenderConstrain, dpop.VerifiedProof, string, *Error) { if usedDPoP { if dpopProof == "" { return 0, dpop.VerifiedProof{}, "", newError(ErrorInvalidRequest, 400, "DPoP header is required", nil) @@ -557,14 +567,13 @@ func (v *Verifier) resolveCredential(ctx context.Context, req VerifyRequest, tar // proof's key. A proof anyone can sign with their own key and a // made-up token must not be able to write to either store. verifiedProof, err := dpop.Verify(ctx, dpop.VerifyRequest{ - Proof: dpopProof, - Method: req.Method, - URL: targets[0], - AlternateURLs: targets[1:], - AccessToken: raw, - Now: now, - MaxProofAge: v.cfg.Limits.MaxDPoPProofAge, - MaxClockSkew: v.cfg.Limits.MaxClockSkew, + Proof: dpopProof, + Method: req.Method, + URL: target, + AccessToken: raw, + Now: now, + MaxProofAge: v.cfg.Limits.MaxDPoPProofAge, + MaxClockSkew: v.cfg.Limits.MaxClockSkew, }) if err != nil { return 0, dpop.VerifiedProof{}, "", newError(ErrorInvalidDPoPProof, 401, "DPoP proof verification failed", err) diff --git a/resource/verify_request_http.go b/resource/verify_request_http.go index cb77e327..60c8c89c 100644 --- a/resource/verify_request_http.go +++ b/resource/verify_request_http.go @@ -23,7 +23,10 @@ import ( // request refused, and so is a path with a dot segment ("/a/../b") or a // percent-encoded unreserved character ("/accounts/%31"): htu matching // would resolve it, while a router dispatching on the path as sent -// wouldn't. +// wouldn't. When several origins cover the path, a DPoP request needs +// the one it was received at: wrap the listener's handler in +// WithResourceOrigin, or set VerifyRequest.URL, from the listener or a +// trusted proxy route. // // Behind a proxy that terminates TLS, r carries no client certificate: // set PeerCertificate afterwards from however the proxy forwards it @@ -39,6 +42,7 @@ func VerifyRequestFromHTTP(r *http.Request) VerifyRequest { PeerCertificate: PeerCertificateFromHTTP(r), requestPath: r.URL.EscapedPath(), + requestOrigin: resourceOriginOf(r), repeatedAuthorization: len(r.Header.Values("Authorization")) > 1, } } diff --git a/server/backchannel_authentication.go b/server/backchannel_authentication.go index 9a358a6d..a7162d2c 100644 --- a/server/backchannel_authentication.go +++ b/server/backchannel_authentication.go @@ -180,8 +180,9 @@ func (s *Server) BeginBackchannelAuthentication(ctx context.Context, req BeginBa // Before the signed authentication request, which records its jti: // see verifyOptionalDPoPProof. A client authenticating with its // certificate calls the mTLS alias (RFC 8705 §5), and its proof names - // that URL, as at PAR and the token endpoint. - dpopThumbprint, dpopErr := s.verifyOptionalDPoPProof(ctx, dpopProof, s.cfg.Endpoints.BackchannelAuthentication, s.cfg.MTLSEndpoints.BackchannelAuthentication) + // that URL, as at PAR and the token endpoint: req.HTTP.EndpointRoute + // says which of the two received it. + dpopThumbprint, dpopErr := s.verifyOptionalDPoPProof(ctx, dpopProof, s.cfg.Endpoints.BackchannelAuthentication, s.cfg.MTLSEndpoints.BackchannelAuthentication, req.HTTP.EndpointRoute) if dpopErr != nil { return s.backchannelBeginFail(ctx, client.ID(), dpopErr), nil } diff --git a/server/backchannel_test.go b/server/backchannel_test.go index b5141e82..d8d470ac 100644 --- a/server/backchannel_test.go +++ b/server/backchannel_test.go @@ -2064,7 +2064,7 @@ func TestBeginBackchannelAuthenticationAcceptsDPoPProofForTheMTLSAlias(t *testin } cfg.MTLSEndpoints.BackchannelAuthentication = u }) - for htu, wantOK := range map[string]bool{alias: true, testBackchannelAuthenticationEndpoint: true, "https://other.example/backchannel-authenticate": false} { + for htu, wantOK := range map[string]bool{alias: true, testBackchannelAuthenticationEndpoint: false, "https://other.example/backchannel-authenticate": false} { target, err := url.Parse(htu) if err != nil { t.Fatal(err) @@ -2074,7 +2074,7 @@ func TestBeginBackchannelAuthenticationAcceptsDPoPProofForTheMTLSAlias(t *testin t.Fatal(err) } action, err := h.server.BeginBackchannelAuthentication(context.Background(), server.BeginBackchannelAuthenticationRequest{ - HTTP: server.FormRequest{Parameters: backchannelFormParams(h.clientAssertion(t), h.backchannelRequestObject(t, standardBackchannelParams(t)))}, + HTTP: server.FormRequest{EndpointRoute: server.MTLSEndpointAlias, Parameters: backchannelFormParams(h.clientAssertion(t), h.backchannelRequestObject(t, standardBackchannelParams(t)))}, DPoPProofs: []string{proof}, }) if err != nil { diff --git a/server/backchannel_token.go b/server/backchannel_token.go index a63144e9..c4c68ff2 100644 --- a/server/backchannel_token.go +++ b/server/backchannel_token.go @@ -109,7 +109,7 @@ func (s *Server) ExchangeBackchannelAuthentication(ctx context.Context, req Back return s.tokenFail(ctx, AuditEventExchangeBackchannelAuthentication, client.ID(), paramErr) } - thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate) + thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute) if bindingErr != nil { return s.tokenFail(ctx, AuditEventExchangeBackchannelAuthentication, client.ID(), bindingErr) } diff --git a/server/ciba_assertion_audience_test.go b/server/ciba_assertion_audience_test.go index 3da9e337..1ba7d0f2 100644 --- a/server/ciba_assertion_audience_test.go +++ b/server/ciba_assertion_audience_test.go @@ -139,7 +139,7 @@ func beginOutcome(t *testing.T, h harness, assertion string) server.ErrorCode { func pollBackchannelWith(t *testing.T, h harness, authReqID, assertion string, b senderBinding) (server.TokenResult, error) { t.Helper() return h.server.ExchangeBackchannelAuthentication(context.Background(), server.BackchannelTokenExchangeRequest{ - HTTP: server.FormRequest{Parameters: []server.FormParameter{ + HTTP: server.FormRequest{EndpointRoute: server.PrimaryEndpoint, Parameters: []server.FormParameter{ formParam("client_assertion", assertion), formParam("client_assertion_type", clientassertion.AssertionType), formParam("grant_type", server.CIBAGrantType), @@ -155,7 +155,7 @@ func pollBackchannelWith(t *testing.T, h harness, authReqID, assertion string, b func refreshWithAssertion(t *testing.T, h harness, assertion, refreshToken string, b senderBinding) error { t.Helper() _, err := h.server.RefreshAccessToken(context.Background(), server.RefreshTokenRequest{ - HTTP: server.FormRequest{Parameters: refreshFormParams(assertion, refreshToken, "")}, + HTTP: server.FormRequest{EndpointRoute: server.PrimaryEndpoint, Parameters: refreshFormParams(assertion, refreshToken, "")}, DPoPProofs: b.dpopProofs(t, h), PeerCertificate: b.cert, }) @@ -169,7 +169,7 @@ func codeGrantRefreshToken(t *testing.T, h harness, b senderBinding) string { t.Helper() code := completeSuccessfulAuthorization(t, h, []string{"openid", "accounts", "offline_access"}) tokens, err := h.server.ExchangeAuthorizationCode(context.Background(), server.AuthorizationCodeExchangeRequest{ - HTTP: server.FormRequest{Parameters: exchangeFormParams(h.clientAssertion(t), code, testRedirectURI, testCodeVerifier)}, + HTTP: server.FormRequest{EndpointRoute: server.PrimaryEndpoint, Parameters: exchangeFormParams(h.clientAssertion(t), code, testRedirectURI, testCodeVerifier)}, DPoPProofs: b.dpopProofs(t, h), PeerCertificate: b.cert, }) diff --git a/server/client_auth_mtls_test.go b/server/client_auth_mtls_test.go index 7d856d0b..969821c5 100644 --- a/server/client_auth_mtls_test.go +++ b/server/client_auth_mtls_test.go @@ -709,10 +709,7 @@ func TestBeginBackchannelAuthenticationCertClientAuthReachesPeerCertificate(t *t // sender_constrain=dpop plan): a client authenticating via certificate // must reach the mTLS-alias URL to present it at all, so its DPoP // proof's own "htu" legitimately names that alias rather than the plain -// endpoint. Config.MTLSEndpoints uses deliberately different URLs from -// testEndpoints(t)'s plain ones, so a test here genuinely exercises -// verifyDPoPAtEitherEndpoint's fallback rather than happening to match -// by coincidence. +// endpoint. The two configured URLs are distinct. func newHarnessWithClientAuthMTLSAndDPoP(t *testing.T) (harness, *x509.Certificate, string, string) { t.Helper() now := time.Now() @@ -815,18 +812,13 @@ func dpopProofForURL(t *testing.T, key *ecdsa.PrivateKey, rawURL string, now tim // registered for certificate-based authentication but plain DPoP // sender-constraining must call the mTLS-alias URL to present its // certificate at all, so its DPoP proof's own "htu" legitimately names -// that alias rather than this server's plain endpoint. Before -// verifyDPoPAtEitherEndpoint, this server rejected such a proof -// outright with ErrURIMismatch, wrapped as "DPoP proof verification -// failed" — confirmed live, not just reasoned about (see -// ARCHITECTURE.md's conformance strategy section for the exact -// suite-side failure this reproduces). +// the mTLS alias route. func TestPushAuthorizationRequestCertClientAuthAcceptsDPoPProofAtMTLSAlias(t *testing.T) { h, cert, _, mtlsPAR := newHarnessWithClientAuthMTLSAndDPoP(t) dpopKey := generateKey(t) if _, err := h.server.PushAuthorizationRequest(context.Background(), server.PushAuthorizationRequest{ - HTTP: server.FormRequest{Parameters: certFormParameters(nil)}, + HTTP: server.FormRequest{EndpointRoute: server.MTLSEndpointAlias, Parameters: certFormParameters(nil)}, DPoPProofs: []string{dpopProofForURL(t, dpopKey, mtlsPAR, h.now)}, PeerCertificate: cert, }); err != nil { @@ -834,13 +826,29 @@ func TestPushAuthorizationRequestCertClientAuthAcceptsDPoPProofAtMTLSAlias(t *te } } +// TestPushAuthorizationRequestRefusesAnUnroutedAliasProof: without a +// route, PAR checks a proof against its primary URL only, so one naming +// the mTLS alias is refused as invalid_dpop_proof (not a 500), as at +// the token endpoint. +func TestPushAuthorizationRequestRefusesAnUnroutedAliasProof(t *testing.T) { + h, cert, _, mtlsPAR := newHarnessWithClientAuthMTLSAndDPoP(t) + _, err := h.server.PushAuthorizationRequest(context.Background(), server.PushAuthorizationRequest{ + HTTP: server.FormRequest{Parameters: certFormParameters(nil)}, + DPoPProofs: []string{dpopProofForURL(t, generateKey(t), mtlsPAR, h.now)}, + PeerCertificate: cert, + }) + if serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { + t.Fatalf("PushAuthorizationRequest(alias proof, no route) = %v, want invalid_dpop_proof", err) + } +} + func TestExchangeAuthorizationCodeCertClientAuthAcceptsDPoPProofAtMTLSAlias(t *testing.T) { h, cert, mtlsToken, _ := newHarnessWithClientAuthMTLSAndDPoP(t) code := completeSuccessfulCertAuthorization(t, h, cert, []string{"openid", "accounts"}) dpopKey := generateKey(t) result, err := h.server.ExchangeAuthorizationCode(context.Background(), server.AuthorizationCodeExchangeRequest{ - HTTP: server.FormRequest{Parameters: []server.FormParameter{ + HTTP: server.FormRequest{EndpointRoute: server.MTLSEndpointAlias, Parameters: []server.FormParameter{ formParam("client_id", testClientID.String()), formParam("grant_type", "authorization_code"), formParam("code", code), @@ -857,3 +865,47 @@ func TestExchangeAuthorizationCodeCertClientAuthAcceptsDPoPProofAtMTLSAlias(t *t t.Fatalf("TokenType = %q, want %q", result.TokenType, "DPoP") } } + +// TestRefreshAccessTokenCertClientAuthAtMTLSAlias: a refresh request +// is checked against the URL its route names, as a code exchange is: +// a proof for the token endpoint's alias verifies only on a request +// received there. +func TestRefreshAccessTokenCertClientAuthAtMTLSAlias(t *testing.T) { + h, cert, mtlsToken, _ := newHarnessWithClientAuthMTLSAndDPoP(t) + code := completeSuccessfulCertAuthorization(t, h, cert, []string{"openid", "accounts", "offline_access"}) + dpopKey := generateKey(t) + tokens, err := h.server.ExchangeAuthorizationCode(context.Background(), server.AuthorizationCodeExchangeRequest{ + HTTP: server.FormRequest{EndpointRoute: server.MTLSEndpointAlias, Parameters: []server.FormParameter{ + formParam("client_id", testClientID.String()), + formParam("grant_type", "authorization_code"), + formParam("code", code), + formParam("redirect_uri", testRedirectURI), + formParam("code_verifier", testCodeVerifier), + }}, + DPoPProofs: []string{dpopProofForURL(t, dpopKey, mtlsToken, h.now)}, + PeerCertificate: cert, + }) + if err != nil || !tokens.HasRefreshToken { + t.Fatalf("ExchangeAuthorizationCode = %v (refresh token %v), want a refresh token", err, tokens.HasRefreshToken) + } + for _, route := range []server.EndpointRoute{0, server.MTLSEndpointAlias} { + _, err := h.server.RefreshAccessToken(context.Background(), server.RefreshTokenRequest{ + HTTP: server.FormRequest{EndpointRoute: route, Parameters: []server.FormParameter{ + formParam("client_id", testClientID.String()), + formParam("grant_type", "refresh_token"), + formParam("refresh_token", tokens.RefreshToken.Reveal()), + }}, + DPoPProofs: []string{dpopProofForURL(t, dpopKey, mtlsToken, h.now)}, + PeerCertificate: cert, + }) + if route == 0 { + if serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { + t.Errorf("RefreshAccessToken(alias proof, no route) = %v, want invalid_dpop_proof", err) + } + continue + } + if err != nil { + t.Errorf("RefreshAccessToken(alias proof, alias route): %v", err) + } + } +} diff --git a/server/client_credentials.go b/server/client_credentials.go index ebc33dcd..6564703a 100644 --- a/server/client_credentials.go +++ b/server/client_credentials.go @@ -95,7 +95,7 @@ func (s *Server) RequestClientCredentialsToken(ctx context.Context, req ClientCr return s.tokenFail(ctx, AuditEventRequestClientCredentialsToken, client.ID(), grantErr) } - thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate) + thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute) if bindingErr != nil { return s.tokenFail(ctx, AuditEventRequestClientCredentialsToken, client.ID(), bindingErr) } diff --git a/server/config.go b/server/config.go index a5c2552c..cf554988 100644 --- a/server/config.go +++ b/server/config.go @@ -204,8 +204,11 @@ type Endpoints struct { // one of these URLs actually arrived over a connection that presented // a certificate — every SenderConstrainMTLS check already happens // per-request via PeerCertificate on the relevant request struct, -// regardless of which URL it arrived at. Zero value (every field -// zero) omits mtls_endpoint_aliases from Metadata entirely. +// regardless of which URL it arrived at. Which URL it arrived at +// matters for a DPoP proof sent with it, whose htu names one of the +// two (RFC 9449 §4.3): mark the alias listener's requests with +// WithEndpointRoute (see EndpointRoute). Zero value (every field zero) +// omits mtls_endpoint_aliases from Metadata entirely. type MTLSEndpoints struct { Token fapi.URL PushedAuthorizationRequest fapi.URL diff --git a/server/endpoint_route.go b/server/endpoint_route.go new file mode 100644 index 00000000..19c93172 --- /dev/null +++ b/server/endpoint_route.go @@ -0,0 +1,153 @@ +package server + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/dpop" +) + +// EndpointRoute is the public route a request to one of this server's +// endpoints was received at: the endpoint's URL in Config.Endpoints, or +// its RFC 8705 §5 alias in Config.MTLSEndpoints. A DPoP proof names the +// URL of the request it is sent with (RFC 9449 §4.3), so the route +// decides which of the two its htu must name; it never matters for a +// request without a proof. +// +// Set it from the listener or trusted proxy route that received the +// request, never from anything the client sends (the Host header, the +// proof itself): FormRequest.EndpointRoute, or +// TokenEndpointRequest.SetEndpointRoute, or for every request a +// listener receives, WithEndpointRoute. The zero route (unset) is +// PrimaryEndpoint, so a server without mTLS aliases needs none of this. +type EndpointRoute uint8 + +const ( + // PrimaryEndpoint is the endpoint's URL in Config.Endpoints. + PrimaryEndpoint EndpointRoute = iota + 1 + // MTLSEndpointAlias is the endpoint's alias in Config.MTLSEndpoints. + MTLSEndpointAlias +) + +// String is the route's name: "primary", "mtls_alias", "unset" for the +// zero route, or EndpointRoute(n) for a value this package doesn't +// define. +func (r EndpointRoute) String() string { + switch r { + case 0: + return "unset" + case PrimaryEndpoint: + return "primary" + case MTLSEndpointAlias: + return "mtls_alias" + default: + return fmt.Sprintf("EndpointRoute(%d)", uint8(r)) + } +} + +// endpointRouteKey is the context key WithEndpointRoute marks a +// request's route under. +type endpointRouteKey struct{} + +// WithEndpointRoute returns a handler that serves each request with +// next, marked as received at route. FormRequestFromHTTP, and so each +// of this package's *FromHTTP request constructors, takes +// FormRequest.EndpointRoute from the mark, so wrapping the handler of +// the listener serving Config.MTLSEndpoints is all a deployment with +// mTLS aliases needs: +// +// mtlsListener := &http.Server{ +// Handler: server.WithEndpointRoute(server.MTLSEndpointAlias, mux), +// TLSConfig: ..., // asks for a client certificate +// } +// +// The listener serving Config.Endpoints needs no mark, since an unset +// route is PrimaryEndpoint, though WithEndpointRoute(PrimaryEndpoint, +// mux) says so explicitly. A route set on a request after it is read +// (FormRequest.EndpointRoute, TokenEndpointRequest.SetEndpointRoute) +// takes precedence, and the innermost WithEndpointRoute wins. Mark only +// what the listener or a trusted front end knows: one listener serving +// both routes, told apart by the Host header the client sends, can't +// use this. +func WithEndpointRoute(route EndpointRoute, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), endpointRouteKey{}, route))) + }) +} + +// endpointRouteOf is the route WithEndpointRoute marked r with, or the +// zero route. +func endpointRouteOf(r *http.Request) EndpointRoute { + route, _ := r.Context().Value(endpointRouteKey{}).(EndpointRoute) + return route +} + +// endpointRouteSetters names everything that sets a request's +// EndpointRoute, for the errors a route this server can't serve gets. +const endpointRouteSetters = "server.WithEndpointRoute on the listener, FormRequest.EndpointRoute or TokenEndpointRequest.SetEndpointRoute" + +// verifyEndpointDPoP verifies req's proof for the one URL of an +// endpoint that received it — primary, or alias, its mTLS alias, by +// route — never for either (RFC 9449 §4.3): where the two routes keep +// separate replay records, a proof accepted at both could be used once +// at each. See endpointDPoPTarget for the URL each route names. +// +// A proof refused is a 400 invalid_dpop_proof, or a 500 when the +// replay store couldn't answer. +func (s *Server) verifyEndpointDPoP(ctx context.Context, req dpop.VerifyRequest, primary, alias fapi.URL, route EndpointRoute) (dpop.VerifiedProof, *Error) { + target, targetErr := s.endpointDPoPTarget(primary, alias, route) + if targetErr != nil { + return dpop.VerifiedProof{}, targetErr + } + req.URL = &target + verified, err := dpop.Verify(ctx, req) + if err != nil { + return dpop.VerifiedProof{}, storeFailure(ctx, err, "failed to check DPoP proof replay", newError(ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", unroutedMismatch(err, primary, alias, route))) + } + return verified, nil +} + +// endpointDPoPTarget is the URL a DPoP proof received at route must +// name: +// - PrimaryEndpoint, or no route at all: primary. A proof naming the +// alias, sent without a route, is refused as any other proof for +// another URL is (see unroutedMismatch). +// - MTLSEndpointAlias: alias. An endpoint with none, on a server +// advertising aliases for others, was called at a URL this server +// doesn't advertise: the client's mistake, 400 invalid_dpop_proof. +// On a server advertising no alias at all, no request can arrive +// at one, so the route is the deployment's mistake: 500. +// - any other value: the deployment's mistake, 500. +func (s *Server) endpointDPoPTarget(primary, alias fapi.URL, route EndpointRoute) (url.URL, *Error) { + switch route { + case 0, PrimaryEndpoint: + return primary.URL(), nil + case MTLSEndpointAlias: + if !alias.IsZero() { + return alias.URL(), nil + } + if s.cfg.MTLSEndpoints.IsZero() { + return url.URL{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("the request's endpoint route is MTLSEndpointAlias, but Config.MTLSEndpoints configures no alias: set that route, with "+endpointRouteSetters+", only for requests received at an mTLS alias")) + } + return url.URL{}, newError(ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", errors.New("the request was received at the mTLS alias route, but Config.MTLSEndpoints configures no alias for this endpoint, so no URL there is one a DPoP proof can name")) + default: + return url.URL{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", fmt.Errorf("the request's endpoint route %v is not one this package defines: set PrimaryEndpoint or MTLSEndpointAlias with %s", route, endpointRouteSetters)) + } +} + +// unroutedMismatch is err, the reason dpop.Verify refused a proof, +// with a hint for the deployment when the request carried no route, +// the proof named another URL, and the endpoint has a distinct mTLS +// alias: a proof for the alias fails so when the listener serving it +// doesn't mark its requests. The hint is in the error's cause only, +// which the response doesn't carry. +func unroutedMismatch(err error, primary, alias fapi.URL, route EndpointRoute) error { + if route != 0 || !errors.Is(err, dpop.ErrURIMismatch) || alias.IsZero() || alias.String() == primary.String() { + return err + } + return fmt.Errorf("%w (the request had no endpoint route, so the proof was checked against %s; if it was received at the mTLS alias %s, set its route with %s)", err, primary.String(), alias.String(), endpointRouteSetters) +} diff --git a/server/endpoint_route_test.go b/server/endpoint_route_test.go new file mode 100644 index 00000000..db731e0f --- /dev/null +++ b/server/endpoint_route_test.go @@ -0,0 +1,253 @@ +package server_test + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/storage" +) + +const testTokenAlias = "https://mtls.as.example/token" + +// routeSetterNames are the setters a route error's cause must name. +var routeSetterNames = []string{"server.WithEndpointRoute", "FormRequest.EndpointRoute", "TokenEndpointRequest.SetEndpointRoute"} + +// newRouteHarness is a harness whose Config.MTLSEndpoints is set by +// aliases (nil for none). +func newRouteHarness(t *testing.T, aliases func(*server.MTLSEndpoints, func(string) fapi.URL)) harness { + t.Helper() + return newAttestationHarness(t, time.Now(), generateKey(t), server.RegisteredAttesterKeys{}, func(cfg *server.Config, _ *storage.RegisteredClientConfig) { + if aliases != nil { + aliases(&cfg.MTLSEndpoints, func(raw string) fapi.URL { + u, err := fapi.ParseEndpointURL(raw) + if err != nil { + t.Fatal(err) + } + return u + }) + } + }) +} + +func withTokenAlias(raw string) func(*server.MTLSEndpoints, func(string) fapi.URL) { + return func(e *server.MTLSEndpoints, parse func(string) fapi.URL) { e.Token = parse(raw) } +} + +// verifyRouted is VerifyTokenRequestDPoP for a fresh proof naming htu, +// received at route. +func verifyRouted(t *testing.T, h harness, htu string, route server.EndpointRoute) error { + t.Helper() + req := clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), htu, "", h.now)) + req.SetEndpointRoute(route) + _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req) + return err +} + +// wantRouteError checks err is a *server.Error with code and status, +// whose public description is description and whose message contains +// each of causes. +func wantRouteError(t *testing.T, name string, err error, code server.ErrorCode, status int, description string, causes ...string) { + t.Helper() + var serr *server.Error + if !errors.As(err, &serr) { + t.Fatalf("%s: err = %v, want a *server.Error", name, err) + } + if serr.Code() != code || serr.HTTPStatus() != status || serr.PublicDescription() != description { + t.Errorf("%s: err = %d %s %q, want %d %s %q", name, serr.HTTPStatus(), serr.Code(), serr.PublicDescription(), status, code, description) + } + for _, c := range causes { + if !strings.Contains(err.Error(), c) { + t.Errorf("%s: err = %v, want it to name %q", name, err, c) + } + } +} + +// TestVerifyTokenRequestDPoPAtTheMTLSAlias: a proof is checked against +// the one URL its route names. A request received at the alias, so +// marked, verifies a proof naming the alias and refuses one naming the +// primary URL or another server; one marked primary, or not marked at +// all, refuses a proof naming the alias. +func TestVerifyTokenRequestDPoPAtTheMTLSAlias(t *testing.T) { + h := newRouteHarness(t, withTokenAlias(testTokenAlias)) + for _, c := range []struct { + htu string + route server.EndpointRoute + ok bool + }{ + {testTokenAlias, server.MTLSEndpointAlias, true}, + {testTokenEndpoint, server.MTLSEndpointAlias, false}, + {"https://other.example/token", server.MTLSEndpointAlias, false}, + {testTokenEndpoint, server.PrimaryEndpoint, true}, + {testTokenAlias, server.PrimaryEndpoint, false}, + {testTokenEndpoint, 0, true}, + {testTokenAlias, 0, false}, + {"https://other.example/token", 0, false}, + } { + err := verifyRouted(t, h, c.htu, c.route) + if c.ok { + if err != nil { + t.Errorf("proof for %s at route %v: %v", c.htu, c.route, err) + } + continue + } + wantRouteError(t, "proof for "+c.htu+" at route "+c.route.String(), err, server.ErrorInvalidDPoPProof, 400, "DPoP proof verification failed") + } +} + +// TestUnroutedAliasProofNamesTheRouteSetters: a proof naming another +// URL, on a request with no route at an endpoint with a distinct mTLS +// alias, is refused with a cause naming the route setters, for the +// deployment whose alias listener doesn't set one; the public +// description stays the generic one. +func TestUnroutedAliasProofNamesTheRouteSetters(t *testing.T) { + h := newRouteHarness(t, withTokenAlias(testTokenAlias)) + err := verifyRouted(t, h, testTokenAlias, 0) + wantRouteError(t, "unrouted alias proof", err, server.ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", append([]string{testTokenAlias, "no endpoint route"}, routeSetterNames...)...) +} + +// TestRoutedOrAliaslessMismatchHasNoRouteHint: the route hint is only +// for a request with no route at an endpoint whose alias differs from +// its URL. With a route, with no alias or one equal to the endpoint's +// URL, or for a proof refused for something other than its htu, a +// refusal carries none. +func TestRoutedOrAliaslessMismatchHasNoRouteHint(t *testing.T) { + aliased := newRouteHarness(t, withTokenAlias(testTokenAlias)) + for name, c := range map[string]struct { + h harness + htu string + route server.EndpointRoute + at time.Duration + }{ + "routed primary": {aliased, testTokenAlias, server.PrimaryEndpoint, 0}, + "no alias": {newRouteHarness(t, nil), "https://other.example/token", 0, 0}, + "alias is the URL": {newRouteHarness(t, withTokenAlias(testTokenEndpoint)), "https://other.example/token", 0, 0}, + "stale proof": {aliased, testTokenEndpoint, 0, -time.Hour}, + } { + req := clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), c.htu, "", c.h.now.Add(c.at))) + req.SetEndpointRoute(c.route) + _, err := c.h.server.VerifyTokenRequestDPoP(context.Background(), req) + wantRouteError(t, name, err, server.ErrorInvalidDPoPProof, 400, "DPoP proof verification failed") + if strings.Contains(err.Error(), "no endpoint route") { + t.Errorf("%s: err = %v, want no route hint", name, err) + } + } +} + +// TestVerifyTokenRequestDPoPRefusesARouteWithNoTarget: the alias route +// on a server configuring no mTLS alias at all, or a route this package +// doesn't define, is the deployment's routing at fault: a 500 naming +// the setters, not a verdict on the proof. +func TestVerifyTokenRequestDPoPRefusesARouteWithNoTarget(t *testing.T) { + h := newRouteHarness(t, nil) + for name, route := range map[string]server.EndpointRoute{ + "alias route, no alias": server.MTLSEndpointAlias, + "unknown route": server.EndpointRoute(99), + } { + err := verifyRouted(t, h, testTokenEndpoint, route) + wantRouteError(t, name, err, server.ErrorServerError, 500, "cannot determine DPoP request target", routeSetterNames...) + } +} + +// TestAliasRouteAtAnEndpointWithoutAlias: a request received at the +// alias route for an endpoint with no alias of its own, on a server +// advertising aliases for others, called a URL this server doesn't +// advertise: the client's mistake, refused as invalid_dpop_proof. +func TestAliasRouteAtAnEndpointWithoutAlias(t *testing.T) { + h := newRouteHarness(t, func(e *server.MTLSEndpoints, parse func(string) fapi.URL) { + e.PushedAuthorizationRequest = parse("https://mtls.as.example/par") + }) + err := verifyRouted(t, h, testTokenAlias, server.MTLSEndpointAlias) + wantRouteError(t, "unadvertised alias", err, server.ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", "configures no alias for this endpoint") +} + +// TestEndpointRouteString pins each route's name, as logs show it. +func TestEndpointRouteString(t *testing.T) { + for route, want := range map[server.EndpointRoute]string{ + 0: "unset", + server.PrimaryEndpoint: "primary", + server.MTLSEndpointAlias: "mtls_alias", + server.EndpointRoute(7): "EndpointRoute(7)", + } { + if got := route.String(); got != want { + t.Errorf("EndpointRoute(%d).String() = %q, want %q", uint8(route), got, want) + } + } +} + +// formPost is a form-encoded POST of body, as a client sends it. +func formPost(body string, header http.Header) *http.Request { + r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for name, values := range header { + r.Header[name] = values + } + return r +} + +// routedRead serves r through WithEndpointRoute(route, ...) and returns +// what read made of it. +func routedRead[T any](t *testing.T, route server.EndpointRoute, r *http.Request, read func(*http.Request) (T, error)) T { + t.Helper() + var got T + server.WithEndpointRoute(route, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + var err error + if got, err = read(r); err != nil { + t.Fatalf("read: %v", err) + } + })).ServeHTTP(httptest.NewRecorder(), r) + return got +} + +// TestWithEndpointRouteMarksFromHTTPRequests: every *FromHTTP request +// read under WithEndpointRoute carries its route; one read without it +// carries none; and a route set afterwards replaces the mark. +func TestWithEndpointRouteMarksFromHTTPRequests(t *testing.T) { + const alias = server.MTLSEndpointAlias + if got := routedRead(t, alias, formPost("a=b", nil), server.FormRequestFromHTTP); got.EndpointRoute != alias { + t.Errorf("FormRequestFromHTTP route = %v, want %v", got.EndpointRoute, alias) + } + if got := routedRead(t, alias, formPost("client_id=c", nil), server.PushAuthorizationRequestFromHTTP); got.HTTP.EndpointRoute != alias { + t.Errorf("PushAuthorizationRequestFromHTTP route = %v, want %v", got.HTTP.EndpointRoute, alias) + } + if got := routedRead(t, alias, formPost("client_id=c", nil), server.BeginBackchannelAuthenticationRequestFromHTTP); got.HTTP.EndpointRoute != alias { + t.Errorf("BeginBackchannelAuthenticationRequestFromHTTP route = %v, want %v", got.HTTP.EndpointRoute, alias) + } + token := routedRead(t, alias, formPost("grant_type=refresh_token", nil), server.TokenEndpointRequestFromHTTP) + if got := token.RefreshToken().HTTP.EndpointRoute; got != alias { + t.Errorf("TokenEndpointRequestFromHTTP route = %v, want %v", got, alias) + } + before := token + token.SetEndpointRoute(server.PrimaryEndpoint) + if got := token.AuthorizationCodeExchange().HTTP.EndpointRoute; got != server.PrimaryEndpoint { + t.Errorf("route after SetEndpointRoute = %v, want %v", got, server.PrimaryEndpoint) + } + if got := before.ClientCredentials().HTTP.EndpointRoute; got != alias { + t.Errorf("a copy made before SetEndpointRoute has route %v, want %v", got, alias) + } + unmarked, err := server.FormRequestFromHTTP(formPost("a=b", nil)) + if err != nil || unmarked.EndpointRoute != 0 { + t.Errorf("FormRequestFromHTTP without WithEndpointRoute = %v, %v, want the zero route", unmarked.EndpointRoute, err) + } +} + +// TestWithEndpointRouteVerifiesAliasProofs: a token request read at a +// listener marked MTLSEndpointAlias verifies a proof for the alias, +// which the same request read unmarked doesn't. +func TestWithEndpointRouteVerifiesAliasProofs(t *testing.T) { + h := newRouteHarness(t, withTokenAlias(testTokenAlias)) + for route, ok := range map[server.EndpointRoute]bool{server.MTLSEndpointAlias: true, 0: false} { + r := formPost(preAuthorizedForm().Encode(), dpopHeader(dpopProofAt(t, generateKey(t), testTokenAlias, "", h.now))) + req := routedRead(t, route, r, server.TokenEndpointRequestFromHTTP) + _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req) + if ok != (err == nil) { + t.Errorf("alias proof at route %v: err = %v, want ok=%v", route, err, ok) + } + } +} diff --git a/server/extension_grants.go b/server/extension_grants.go index 3dcc3a6a..0957100f 100644 --- a/server/extension_grants.go +++ b/server/extension_grants.go @@ -112,7 +112,8 @@ type TokenBinding struct { // constraint decides the check: // // - SenderConstrainDPoP: exactly one DPoP proof, for POST to -// Endpoints.Token or its MTLSEndpoints alias, within +// Endpoints.Token, or its MTLSEndpoints alias for a request +// received there (TokenEndpointRequest.SetEndpointRoute), within // Limits.MaxDPoPProofAge and MaxClockSkew, not seen before — one // replay record with this server's own token requests — and, when // Dependencies.Nonces is set, carrying a current nonce: otherwise @@ -142,7 +143,7 @@ func (s *Server) verifyExtensionGrantBinding(ctx context.Context, client storage if err != nil { return TokenBinding{}, err } - thumbprint, err := s.verifyTokenRequestBinding(ctx, client, proof, parts.PeerCertificate) + thumbprint, err := s.verifyTokenRequestBinding(ctx, client, proof, parts.PeerCertificate, parts.HTTP.EndpointRoute) if err != nil { return TokenBinding{}, err } @@ -177,8 +178,8 @@ type DPoPProofBinding struct { // authenticated client — OpenID4VCI 1.0 §6.1's pre-authorized code // grant without client authentication, for example, outside FAPI. It // is VerifyTokenRequestBinding's DPoP check without a client: exactly -// one DPoP proof, for POST to Endpoints.Token or its MTLSEndpoints -// alias, within Limits.MaxDPoPProofAge and MaxClockSkew, not seen +// one DPoP proof, for POST to Endpoints.Token, or its MTLSEndpoints +// alias for a request received there (TokenEndpointRequest.SetEndpointRoute), within Limits.MaxDPoPProofAge and MaxClockSkew, not seen // before — one replay record with this server's own token requests and // VerifyTokenRequestBinding, so a proof is accepted at only one of them // — and, when Dependencies.Nonces is set, carrying a current nonce: @@ -207,7 +208,7 @@ func (s *Server) verifyClientlessDPoP(ctx context.Context, req TokenEndpointRequ if err != nil { return DPoPProofBinding{}, err } - verified, err := s.verifyTokenRequestDPoP(ctx, proof) + verified, err := s.verifyTokenRequestDPoP(ctx, proof, req.parts.get().HTTP.EndpointRoute) if err != nil { return DPoPProofBinding{}, err } diff --git a/server/extension_grants_test.go b/server/extension_grants_test.go index 15bc8233..de6a32c8 100644 --- a/server/extension_grants_test.go +++ b/server/extension_grants_test.go @@ -201,6 +201,7 @@ func TestVerifyTokenRequestBindingAtTheMTLSAlias(t *testing.T) { cfg.MTLSEndpoints.Token = u }) req := extensionTokenRequest(t, preAuthorizedForm(), dpopHeader(dpopProofAt(t, generateKey(t), alias, "", h.now)), nil) + req.SetEndpointRoute(server.MTLSEndpointAlias) if _, err := h.server.VerifyTokenRequestBinding(context.Background(), registeredClient(t, h), req); err != nil { t.Fatalf("VerifyTokenRequestBinding(proof for the mTLS alias): %v", err) } diff --git a/server/formrequest.go b/server/formrequest.go index cab4df8c..e559d573 100644 --- a/server/formrequest.go +++ b/server/formrequest.go @@ -39,6 +39,9 @@ const maxFormRequestBytes = 1 << 20 // BeginBackchannelAuthenticationRequestFromHTTP, // TokenRevocationRequestFromHTTP, and BeginAuthorizationRequestFromHTTP // for a POST). +// +// EndpointRoute is the route WithEndpointRoute marked r with, if any: +// see WithEndpointRoute. func FormRequestFromHTTP(r *http.Request) (FormRequest, error) { // RFC 9110 §8.3.1: the media type is case-insensitive, and may carry // parameters ("; charset=UTF-8"); "application/x-www-form-urlencodedx" @@ -58,7 +61,7 @@ func FormRequestFromHTTP(r *http.Request) (FormRequest, error) { if err != nil { return FormRequest{}, err } - return FormRequest{Parameters: params}, nil + return FormRequest{Parameters: params, EndpointRoute: endpointRouteOf(r)}, nil } // decodeFormParameters decodes encoded — name=value pairs joined by diff --git a/server/http_requests.go b/server/http_requests.go index 3db91aa1..90b3f4ea 100644 --- a/server/http_requests.go +++ b/server/http_requests.go @@ -194,6 +194,19 @@ func TokenEndpointRequestFromHTTP(r *http.Request) (TokenEndpointRequest, error) // this package implements. func (t TokenEndpointRequest) GrantType() string { return t.parts.get().HTTP.Get("grant_type") } +// SetEndpointRoute sets the public route the request was received at +// (FormRequest.EndpointRoute), which decides the URL its DPoP proof must +// name: needed at the token endpoint's mTLS alias, unless the listener +// there is wrapped in WithEndpointRoute, which TokenEndpointRequestFromHTTP +// takes it from. Set it from the listener or +// trusted proxy route, never from anything the client sends. +func (t *TokenEndpointRequest) SetEndpointRoute(route EndpointRoute) { + parts := t.parts.get() + parts.HTTP.EndpointRoute = route + // A holder of its own, as SetPeerCertificate makes. + t.parts = holdParts(parts) +} + // SetPeerCertificate sets the TLS client certificate, for a server // behind a proxy that terminates TLS and forwards the certificate itself. // Set it only from your own proxy's forwarding, never from anything the diff --git a/server/par.go b/server/par.go index dfba202c..6e425a0f 100644 --- a/server/par.go +++ b/server/par.go @@ -134,6 +134,16 @@ type FormParameter struct { // request itself, never its fields or their JSON. type FormRequest struct { Parameters []FormParameter + + // EndpointRoute is the public route the request was received at, + // which decides the URL a DPoP proof sent with it must name: the + // endpoint's Config.Endpoints URL for PrimaryEndpoint or the zero + // route, its Config.MTLSEndpoints alias for MTLSEndpointAlias (see + // EndpointRoute). Set it from the listener or trusted proxy route, + // never from the proof or a header; FormRequestFromHTTP takes it + // from WithEndpointRoute. Left unset at an mTLS alias, a proof + // naming the alias is refused as invalid_dpop_proof. + EndpointRoute EndpointRoute } // Get returns the first value of name in f, or "" if absent — for an @@ -256,7 +266,7 @@ func (s *Server) PushAuthorizationRequest(ctx context.Context, req PushAuthoriza } // Before the request object, which records its jti: see // verifyOptionalDPoPProof. - dpopThumbprint, dpopErr := s.verifyOptionalDPoPProof(ctx, dpopProof, s.cfg.Endpoints.PushedAuthorizationRequest, s.cfg.MTLSEndpoints.PushedAuthorizationRequest) + dpopThumbprint, dpopErr := s.verifyOptionalDPoPProof(ctx, dpopProof, s.cfg.Endpoints.PushedAuthorizationRequest, s.cfg.MTLSEndpoints.PushedAuthorizationRequest, req.HTTP.EndpointRoute) if dpopErr != nil { return s.parFail(ctx, client.ID(), dpopErr) } @@ -940,25 +950,20 @@ func validatePKCEParameters(params map[string]json.RawMessage) *Error { // issued after it would make the client's legitimate retry of the same // signed request fail as a replay (§8 asks the client only to retry with // the nonce, not to re-sign its request). -// -// The proof's htu is checked against either the endpoint's plain URL -// or its mTLS alias (RFC 8705 §5) — see verifyDPoPAtEitherEndpoint's own -// doc comment for why a DPoP-sender-constrained client may legitimately -// call the alias here too. -func (s *Server) verifyOptionalDPoPProof(ctx context.Context, proof string, endpoint, mtlsAlias fapi.URL) (string, *Error) { +func (s *Server) verifyOptionalDPoPProof(ctx context.Context, proof string, endpoint, mtlsAlias fapi.URL, route EndpointRoute) (string, *Error) { if proof == "" { return "", nil } - verified, err := verifyDPoPAtEitherEndpoint(ctx, dpop.VerifyRequest{ + verified, err := s.verifyEndpointDPoP(ctx, dpop.VerifyRequest{ Proof: proof, Method: "POST", Now: s.deps.Clock.Now(), MaxProofAge: s.cfg.Limits.MaxDPoPProofAge, MaxClockSkew: s.cfg.Limits.MaxClockSkew, Replay: s.dpopReplayChecker(), - }, endpoint, mtlsAlias) + }, endpoint, mtlsAlias, route) if err != nil { - return "", storeFailure(ctx, err, "failed to check DPoP proof replay", newError(ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", err)) + return "", err } if s.deps.Nonces != nil { if challenge := s.checkDPoPNonce(ctx, verified.Nonce, s.deps.Clock.Now()); challenge != nil { diff --git a/server/refresh.go b/server/refresh.go index e5d01f65..79f25136 100644 --- a/server/refresh.go +++ b/server/refresh.go @@ -117,7 +117,7 @@ func (s *Server) RefreshAccessToken(ctx context.Context, req RefreshTokenRequest return s.tokenFail(ctx, AuditEventRefreshAccessToken, client.ID(), paramErr) } - thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate) + thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute) if bindingErr != nil { return s.tokenFail(ctx, AuditEventRefreshAccessToken, client.ID(), bindingErr) } diff --git a/server/render_requests.go b/server/render_requests.go index 5028dc25..475edd04 100644 --- a/server/render_requests.go +++ b/server/render_requests.go @@ -86,14 +86,15 @@ func (p FormParameter) LogValue() slog.Value { } type formRequestShadow struct { - Parameters []formParameterShadow + Parameters []formParameterShadow + EndpointRoute EndpointRoute } func (f FormRequest) shadow() formRequestShadow { if f.Parameters == nil { - return formRequestShadow{} + return formRequestShadow{EndpointRoute: f.EndpointRoute} } - shadow := formRequestShadow{Parameters: make([]formParameterShadow, len(f.Parameters))} + shadow := formRequestShadow{Parameters: make([]formParameterShadow, len(f.Parameters)), EndpointRoute: f.EndpointRoute} for i, p := range f.Parameters { shadow.Parameters[i] = p.shadow() } @@ -116,7 +117,7 @@ func (f FormRequest) LogValue() slog.Value { for i, p := range f.Parameters { params[i] = p.LogValue().String() } - return slog.GroupValue(slog.Any("Parameters", params)) + return slog.GroupValue(slog.Any("Parameters", params), slog.String("EndpointRoute", f.EndpointRoute.String())) } // certificateSummary is cert as a rendering shows it: its subject, or "" diff --git a/server/render_requests_internal_test.go b/server/render_requests_internal_test.go index 86e40ce6..55601d30 100644 --- a/server/render_requests_internal_test.go +++ b/server/render_requests_internal_test.go @@ -86,13 +86,13 @@ func TestFormParameterPrintsOnlyAllowedValues(t *testing.T) { func TestFormRequestPrintsNoCredential(t *testing.T) { rendertest.Check(t, renderForm, renderFormSecrets, exportedResidual) - if got := fmt.Sprintf("%#v", FormRequest{Parameters: []FormParameter{{Name: "code", Value: renderCode}}}); got != `server.FormRequest{Parameters:[]server.FormParameter{server.FormParameter{Name:"code", Value:"[REDACTED]"}}}` { + if got := fmt.Sprintf("%#v", FormRequest{Parameters: []FormParameter{{Name: "code", Value: renderCode}}}); got != `server.FormRequest{Parameters:[]server.FormParameter{server.FormParameter{Name:"code", Value:"[REDACTED]"}}, EndpointRoute:0x0}` { t.Errorf("%%#v = %s", got) } if got := logged(renderForm); !strings.Contains(got, `k.Parameters="[grant_type=authorization_code code=[REDACTED]`) { t.Errorf("slog = %s", got) } - if got := fmt.Sprint(FormRequest{}); got != "{[]}" { + if got := fmt.Sprint(FormRequest{}); got != "{[] unset}" { t.Errorf("an empty form prints %s", got) } } @@ -158,7 +158,7 @@ func TestTokenEndpointRequestPrintsNoCredential(t *testing.T) { t.Errorf("%s prints %s, want an address and no value", name, got) } } - if got := fmt.Sprintf("%+v", req); got != "{parts:{HTTP:{Parameters:[{Name:grant_type Value:refresh_token} {Name:refresh_token Value:[REDACTED]} {Name:client_assertion_type Value:x} {Name:client_assertion Value:[REDACTED]}]} DPoPProofs:[[REDACTED]] ClientAttestations:[] ClientAttestationPoPs:[] PeerCertificate:}}" { + if got := fmt.Sprintf("%+v", req); got != "{parts:{HTTP:{Parameters:[{Name:grant_type Value:refresh_token} {Name:refresh_token Value:[REDACTED]} {Name:client_assertion_type Value:x} {Name:client_assertion Value:[REDACTED]}] EndpointRoute:0} DPoPProofs:[[REDACTED]] ClientAttestations:[] ClientAttestationPoPs:[] PeerCertificate:}}" { t.Errorf("%%+v = %s", got) } if got := fmt.Sprintf("%#v", req); !strings.HasPrefix(got, "server.TokenEndpointRequest{parts:server.httpRequestParts{HTTP:server.FormRequest{") { @@ -207,7 +207,7 @@ func TestOtherRequestsPrintNoCredential(t *testing.T) { ClientAttestations: []string{renderAttestation}, ClientAttestationPoPs: []string{renderAttestation + "-POP"}, } rendertest.Check(t, revocation, []string{renderToken, renderAttestation}, exportedResidual) - if got := fmt.Sprintf("%+v", revocation); got != "{HTTP:{Parameters:[{Name:token Value:[REDACTED]} {Name:token_type_hint Value:refresh_token}]} ClientAttestations:[[REDACTED]] ClientAttestationPoPs:[[REDACTED]] PeerCertificate:}" { + if got := fmt.Sprintf("%+v", revocation); got != "{HTTP:{Parameters:[{Name:token Value:[REDACTED]} {Name:token_type_hint Value:refresh_token}] EndpointRoute:unset} ClientAttestations:[[REDACTED]] ClientAttestationPoPs:[[REDACTED]] PeerCertificate:}" { t.Errorf("%%+v = %s", got) } if got := logged(revocation); !strings.Contains(got, "k.ClientAttestations=[[REDACTED]]") || strings.Contains(got, renderToken) { diff --git a/server/token.go b/server/token.go index 41596d5c..6c3960a7 100644 --- a/server/token.go +++ b/server/token.go @@ -231,7 +231,7 @@ func (s *Server) ExchangeAuthorizationCode(ctx context.Context, req Authorizatio return s.tokenFail(ctx, AuditEventExchangeAuthorizationCode, client.ID(), paramErr) } - thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate) + thumbprint, bindingErr := s.verifyTokenRequestBinding(ctx, client, dpopProof, req.PeerCertificate, req.HTTP.EndpointRoute) if bindingErr != nil { return s.tokenFail(ctx, AuditEventExchangeAuthorizationCode, client.ID(), bindingErr) } @@ -871,7 +871,7 @@ func resolveDPoPProof(proofs []string) (string, *Error) { // AccessTokenParams.Thumbprint (and, for a DPoP-bound client, the same // value stored authorization-code/backchannel-request bindings are // checked against). -func (s *Server) verifyTokenRequestBinding(ctx context.Context, client storage.RegisteredClient, dpopProof string, peerCert *x509.Certificate) (string, *Error) { +func (s *Server) verifyTokenRequestBinding(ctx context.Context, client storage.RegisteredClient, dpopProof string, peerCert *x509.Certificate, route EndpointRoute) (string, *Error) { if client.SenderConstrain() == storage.SenderConstrainMTLS { if peerCert == nil { return "", newError(ErrorInvalidRequest, 400, "a client certificate is required", nil) @@ -881,7 +881,7 @@ func (s *Server) verifyTokenRequestBinding(ctx context.Context, client storage.R } return mtls.Thumbprint(peerCert), nil } - verified, err := s.verifyTokenRequestDPoP(ctx, dpopProof) + verified, err := s.verifyTokenRequestDPoP(ctx, dpopProof, route) if err != nil { return "", err } @@ -902,20 +902,20 @@ func tokenTypeFor(senderConstrain storage.SenderConstrain) string { return "DPoP" } -func (s *Server) verifyTokenRequestDPoP(ctx context.Context, proof string) (dpop.VerifiedProof, *Error) { +func (s *Server) verifyTokenRequestDPoP(ctx context.Context, proof string, route EndpointRoute) (dpop.VerifiedProof, *Error) { if proof == "" { return dpop.VerifiedProof{}, newError(ErrorInvalidRequest, 400, "DPoP proof is required", nil) } - verified, err := verifyDPoPAtEitherEndpoint(ctx, dpop.VerifyRequest{ + verified, err := s.verifyEndpointDPoP(ctx, dpop.VerifyRequest{ Proof: proof, Method: "POST", Now: s.deps.Clock.Now(), MaxProofAge: s.cfg.Limits.MaxDPoPProofAge, MaxClockSkew: s.cfg.Limits.MaxClockSkew, Replay: s.dpopReplayChecker(), - }, s.cfg.Endpoints.Token, s.cfg.MTLSEndpoints.Token) + }, s.cfg.Endpoints.Token, s.cfg.MTLSEndpoints.Token, route) if err != nil { - return dpop.VerifiedProof{}, storeFailure(ctx, err, "failed to check DPoP proof replay", newError(ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", err)) + return dpop.VerifiedProof{}, err } if s.deps.Nonces != nil { if challenge := s.checkDPoPNonce(ctx, verified.Nonce, s.deps.Clock.Now()); challenge != nil { @@ -925,39 +925,6 @@ func (s *Server) verifyTokenRequestDPoP(ctx context.Context, proof string) (dpop return verified, nil } -// verifyDPoPAtEitherEndpoint verifies a DPoP proof's "htm"/"htu" against -// primary, retrying once against mtlsAlias (RFC 8705 §5) on a pure htu -// mismatch — never on any other failure, and never once req.Replay has -// actually been consulted (dpop.Verify's own htu check runs strictly -// before its replay check, confirmed by reading its source — so a -// mismatched first attempt never touches replay state, making the -// retry safe rather than a second, distinct use of the same jti). -// -// This is not sender-constraining-specific: a DPoP-sender-constrained -// client that is *also* registered for RFC 8705 §2 certificate-based -// authentication (storage.ClientAuthMethodSelfSignedTLSClientAuth/ -// TLSClientAuth) must call this endpoint's mTLS-alias URL to present -// its certificate at all — its DPoP proof's own htu then legitimately -// names that alias, not the plain endpoint. Confirmed live: the OIDF -// conformance suite's own FAPI2SPFinal driver does exactly this once it -// discovers mtls_endpoint_aliases, for a client_auth_type=mtls client -// that is otherwise plain sender_constrain=dpop. Both URLs -// unambiguously identify this same authorization server, so accepting -// either is interoperability, not a security relaxation — and -// unconditional on which client, unlike acceptableClientAssertionAudiences's -// CIBA-only "aud" widening: any client may legitimately reach either URL. -func verifyDPoPAtEitherEndpoint(ctx context.Context, req dpop.VerifyRequest, primary, mtlsAlias fapi.URL) (dpop.VerifiedProof, error) { - primaryURL := primary.URL() - req.URL = &primaryURL - verified, err := dpop.Verify(ctx, req) - if err == nil || !errors.Is(err, dpop.ErrURIMismatch) || mtlsAlias.IsZero() { - return verified, err - } - aliasURL := mtlsAlias.URL() - req.URL = &aliasURL - return dpop.Verify(ctx, req) -} - // withIdentityClaims merges whatever Dependencies.IdentityClaims // resolves for subject on top of base (identity claims win on collision // — they are authoritative, server-resolved values, and must not be diff --git a/server/token_request_dpop_test.go b/server/token_request_dpop_test.go index 572d82c6..c3be3833 100644 --- a/server/token_request_dpop_test.go +++ b/server/token_request_dpop_test.go @@ -11,7 +11,6 @@ import ( fapi "github.com/idfoundry/fapigo" "github.com/idfoundry/fapigo/internal/dpop" "github.com/idfoundry/fapigo/server" - "github.com/idfoundry/fapigo/storage" ) // clientlessTokenRequest is a pre-authorized code token request without @@ -174,17 +173,3 @@ func TestVerifyTokenRequestDPoPNonces(t *testing.T) { t.Error("NextDPoPNonce is empty, want the nonce to use next") } } - -func TestVerifyTokenRequestDPoPAtTheMTLSAlias(t *testing.T) { - const alias = "https://mtls.as.example/token" - h := newAttestationHarness(t, time.Now(), generateKey(t), server.RegisteredAttesterKeys{}, func(cfg *server.Config, _ *storage.RegisteredClientConfig) { - u, err := fapi.ParseEndpointURL(alias) - if err != nil { - t.Fatal(err) - } - cfg.MTLSEndpoints.Token = u - }) - if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), alias, "", h.now))); err != nil { - t.Fatalf("VerifyTokenRequestDPoP(proof for the mTLS alias): %v", err) - } -}