From 248c78778aa76c65c500f386a63e72f661a66968 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 20 Nov 2026 01:25:28 +0800 Subject: [PATCH 1/9] fix!: bind DPoP proofs to the receiving endpoint RFC 9449 section 4.3 binds a DPoP proof to the URI of the request it is sent with. The authorization server accepted a proof naming either an endpoint's primary URL or its mTLS alias, and the resource server accepted one naming any configured origin covering the request path, so where the two routes keep separate replay records one unused captured proof could be spent once at each. Each DPoP request is now checked against one target. The authorization server takes it from the new FormRequest.EndpointRoute (PrimaryEndpoint or MTLSEndpointAlias; TokenEndpointRequest.SetEndpointRoute for a request read with TokenEndpointRequestFromHTTP) at PAR, the token endpoint, extension grants and the backchannel authentication endpoint. The resource server requires VerifyRequest.URL when several of Config.ResourceURLs cover a DPoP request's path, and the internal verifier no longer takes alternate URLs. The conformance server supplies both from the listener that accepted the connection. BREAKING CHANGE: a DPoP proof is accepted only for the one endpoint URL that received it. A server with a distinct mTLS alias must set FormRequest.EndpointRoute on DPoP requests, and a resource server whose configured origins overlap must set VerifyRequest.URL. See UPGRADING.md for the migration. Co-Authored-By: Claude Opus 5.5 --- GETTING_STARTED.md | 5 +- UPGRADING.md | 17 +++++ cmd/conformance-as/backchannel.go | 1 + cmd/conformance-as/main.go | 5 +- cmd/conformance-as/mtls_smoke_test.go | 4 +- cmd/conformance-as/par.go | 1 + cmd/conformance-as/resource.go | 21 +++++- cmd/conformance-as/router.go | 22 ++++++ cmd/conformance-as/token.go | 1 + cmd/conformance-as/wiring.go | 7 +- fapitest/authserver.go | 8 ++- internal/dpop/target_rules_test.go | 35 +++------- internal/dpop/verify.go | 24 +------ resource/config.go | 10 ++- resource/opaque_issuer_test.go | 2 +- resource/target.go | 32 ++++----- resource/target_test.go | 21 ++++-- resource/verifier_test.go | 2 +- resource/verify.go | 24 +++---- resource/verify_request_http.go | 3 +- server/backchannel_authentication.go | 2 +- server/backchannel_test.go | 4 +- server/backchannel_token.go | 2 +- server/ciba_assertion_audience_test.go | 6 +- server/client_auth_mtls_test.go | 16 ++--- server/client_credentials.go | 2 +- server/extension_grants.go | 4 +- server/extension_grants_test.go | 1 + server/http_requests.go | 9 +++ server/par.go | 20 +++--- server/refresh.go | 2 +- server/render_requests.go | 9 +-- server/render_requests_internal_test.go | 8 +-- server/token.go | 90 +++++++++++++++---------- server/token_request_dpop_test.go | 11 ++- 35 files changed, 254 insertions(+), 177 deletions(-) diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index c7589f17..0c793bb2 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -1456,8 +1456,9 @@ 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): set +`VerifyRequest.URL` from the trusted listener or proxy route when multiple +origins cover the same DPoP request path. 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..09d019c0 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -18,6 +18,23 @@ 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 + +### Bind DPoP proofs to the receiving endpoint + +Authorization servers advertising a distinct mTLS alias must identify which +route received each DPoP request at PAR, the token endpoint (including custom +grants), and the backchannel authentication endpoint. Set +`FormRequest.EndpointRoute` to `server.PrimaryEndpoint` or +`server.MTLSEndpointAlias` from the listener or trusted proxy route. For +`TokenEndpointRequestFromHTTP`, call `SetEndpointRoute` before dispatch. +A server with one endpoint URL can continue to omit the field. + +Resource servers with multiple configured origins covering the same path +must set `VerifyRequest.URL` to the actual public request URL for DPoP, +preserving the escaped path. Use trusted routing information for the +origin. An ambiguous target fails closed before replay or nonce processing. + ## v0.87.0 ### A JWT or UserInfo response may not repeat a claim with differing values (all packages) diff --git a/cmd/conformance-as/backchannel.go b/cmd/conformance-as/backchannel.go index 2619c95d..c2249152 100644 --- a/cmd/conformance-as/backchannel.go +++ b/cmd/conformance-as/backchannel.go @@ -60,6 +60,7 @@ func (h *backchannelHandler) handleAuthenticate(w http.ResponseWriter, r *http.R writeOAuthJSONError(w, err) return } + req.HTTP.EndpointRoute = receivingListener(r).route action, err := h.srv.BeginBackchannelAuthentication(r.Context(), req) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) diff --git a/cmd/conformance-as/main.go b/cmd/conformance-as/main.go index ffbd6d55..12b1ede5 100644 --- a/cmd/conformance-as/main.go +++ b/cmd/conformance-as/main.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "net/url" + "strings" "time" fapi "github.com/idfoundry/fapigo" @@ -117,7 +118,7 @@ func main() { httpServer := &http.Server{ Addr: resolved.ListenAddr, - Handler: mux, + Handler: listenerHandler(mux, server.PrimaryEndpoint, resolved.Issuer.String()), TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, CipherSuites: server.FAPIRWTLSCipherSuites}, ReadHeaderTimeout: readHeaderTimeout, } @@ -177,7 +178,7 @@ func newMTLSServer(resolved ResolvedConfig, mux http.Handler) (*http.Server, err } return &http.Server{ Addr: resolved.MTLSListenAddr, - Handler: mux, + Handler: listenerHandler(mux, server.MTLSEndpointAlias, strings.TrimSuffix(resolved.MTLSEndpoints.Token.String(), "/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..01766530 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.String())} go primaryServer.Serve(primaryTLS) t.Cleanup(func() { primaryServer.Close() }) - mtlsServer := &http.Server{Handler: mux} + mtlsServer := &http.Server{Handler: listenerHandler(mux, server.MTLSEndpointAlias, strings.TrimSuffix(mtlsEndpoints.Token.String(), "/token"))} go mtlsServer.Serve(mtlsTLS) t.Cleanup(func() { mtlsServer.Close() }) diff --git a/cmd/conformance-as/par.go b/cmd/conformance-as/par.go index d95fb0bc..dffd8567 100644 --- a/cmd/conformance-as/par.go +++ b/cmd/conformance-as/par.go @@ -13,6 +13,7 @@ func parHandler(srv *server.Server) http.HandlerFunc { writeOAuthJSONError(w, err) return } + req.HTTP.EndpointRoute = receivingListener(r).route result, err := srv.PushAuthorizationRequest(r.Context(), req) if err != nil { writeOAuthJSONError(w, err) diff --git a/cmd/conformance-as/resource.go b/cmd/conformance-as/resource.go index b036d2df..3ef31f30 100644 --- a/cmd/conformance-as/resource.go +++ b/cmd/conformance-as/resource.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "net/http" + "net/url" fapires "github.com/idfoundry/fapigo/resource" "github.com/idfoundry/fapigo/server" @@ -10,6 +11,22 @@ import ( "github.com/idfoundry/fapigo/storage" ) +// resourceRequest preserves the escaped path the client called and selects +// the origin from the listener. The request Host and forwarding headers +// cannot select the expected URI. +func resourceRequest(r *http.Request) fapires.VerifyRequest { + req := fapires.VerifyRequestFromHTTP(r) + if base := receivingListener(r).base; base != "" { + // base is a validated issuer or alias base and EscapedPath is URL-encoded. + target, err := url.Parse(base + r.URL.EscapedPath()) + if err != nil { + target = &url.URL{} // Verify rejects a relative target. + } + req.URL = target + } + return req +} + // contentTypeHeader is the HTTP header name every JSON/JWT response // this file writes sets. const contentTypeHeader = "Content-Type" @@ -58,7 +75,7 @@ func userinfoHandler(srv *server.Server, verifier *fapires.Verifier, identityCla } w.Header().Set(fapires.InteractionIDHeader, interactionID) - authCtx, err := verifier.Verify(r.Context(), fapires.VerifyRequestFromHTTP(r)) + authCtx, err := verifier.Verify(r.Context(), resourceRequest(r)) if err != nil { writeResourceError(w, err) return @@ -117,7 +134,7 @@ func accountsHandler(verifier *fapires.Verifier) http.HandlerFunc { } w.Header().Set(fapires.InteractionIDHeader, interactionID) - authCtx, err := verifier.Verify(r.Context(), fapires.VerifyRequestFromHTTP(r)) + authCtx, err := verifier.Verify(r.Context(), resourceRequest(r)) if err != nil { writeResourceError(w, err) return diff --git a/cmd/conformance-as/router.go b/cmd/conformance-as/router.go index 4ec713f8..35f789cc 100644 --- a/cmd/conformance-as/router.go +++ b/cmd/conformance-as/router.go @@ -1,6 +1,7 @@ package main import ( + "context" "net/http" "net/url" @@ -67,3 +68,24 @@ func newRouter(srv *server.Server, consent *consentHandler, backchannel *backcha } return mux } + +type listenerKey struct{} + +type publicListener struct { + route server.EndpointRoute + base string +} + +// listenerHandler supplies the advertised URL base of the listener that actually +// accepted the connection. Both listeners use the same ServeMux. +func listenerHandler(next http.Handler, route server.EndpointRoute, base string) http.Handler { + listener := publicListener{route: route, base: base} + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), listenerKey{}, listener))) + }) +} + +func receivingListener(r *http.Request) publicListener { + listener, _ := r.Context().Value(listenerKey{}).(publicListener) + return listener +} diff --git a/cmd/conformance-as/token.go b/cmd/conformance-as/token.go index b8518fcf..747ce788 100644 --- a/cmd/conformance-as/token.go +++ b/cmd/conformance-as/token.go @@ -14,6 +14,7 @@ func tokenHandler(srv *server.Server) http.HandlerFunc { return } + req.SetEndpointRoute(receivingListener(r).route) var result server.TokenResult switch req.GrantType() { case "authorization_code": diff --git a/cmd/conformance-as/wiring.go b/cmd/conformance-as/wiring.go index 76e7a693..af76477b 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" @@ -445,7 +446,11 @@ func newServerMux(resolved ResolvedConfig, allowLoopbackHTTP, dpopNonceChallenge // 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) + aliasAccounts, err := fapi.ParseEndpointURL(strings.TrimSuffix(mtlsUserinfoURL.String(), "/userinfo") + "/accounts") + if err != nil { + return nil, err + } + resourceOpts.ResourceURLs = append(resourceOpts.ResourceURLs, *mtlsUserinfoURL, aliasAccounts) } if dpopNonceChallenge { resourceOpts.Nonces = memstore.NewNonceStore() 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/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..7a6a9070 100644 --- a/resource/config.go +++ b/resource/config.go @@ -57,12 +57,10 @@ 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"). When several configured origins cover + // that path, a DPoP request requires VerifyRequest.URL from trusted + // listener or proxy routing. 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/target.go b/resource/target.go index 5709bfe5..5c6cb798 100644 --- a/resource/target.go +++ b/resource/target.go @@ -53,21 +53,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, 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 +73,35 @@ 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. DPoP needs +// one unambiguous URI. Certificate binding only requires a covered path. +func (v *Verifier) pathTarget(escapedPath 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 err == nil && t.Host == r.origin.Host && t.RawQuery == "" && t.Fragment == "" && r.covers(t) { - targets = append(targets, t) + if target != nil && dpop && canonical.URI(target) != canonical.URI(t) { + return nil, newError(ErrorServerError, 500, "ambiguous DPoP request target", errors.New("set VerifyRequest.URL from trusted routing metadata when multiple resource origins cover the request path")) + } + target = t } } - if len(targets) == 0 { + if target == nil { return nil, outsideResourceURLs(escapedPath) } - return targets, nil + return target, nil } // 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..17a654b2 100644 --- a/resource/verify.go +++ b/resource/verify.go @@ -36,7 +36,8 @@ 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 when one origin covers the path. + // For DPoP at overlapping origins, set URL from trusted routing. 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 @@ -313,14 +314,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 +547,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 +558,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..2895490d 100644 --- a/resource/verify_request_http.go +++ b/resource/verify_request_http.go @@ -23,7 +23,8 @@ 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 +// requires VerifyRequest.URL from the listener or trusted proxy route. // // Behind a proxy that terminates TLS, r carries no client certificate: // set PeerCertificate afterwards from however the proxy forwards it diff --git a/server/backchannel_authentication.go b/server/backchannel_authentication.go index 9a358a6d..48bb0d6c 100644 --- a/server/backchannel_authentication.go +++ b/server/backchannel_authentication.go @@ -181,7 +181,7 @@ func (s *Server) BeginBackchannelAuthentication(ctx context.Context, req BeginBa // 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) + 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..53dee3f8 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 { @@ -840,7 +832,7 @@ func TestExchangeAuthorizationCodeCertClientAuthAcceptsDPoPProofAtMTLSAlias(t *t 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), 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/extension_grants.go b/server/extension_grants.go index 3dcc3a6a..c6846299 100644 --- a/server/extension_grants.go +++ b/server/extension_grants.go @@ -142,7 +142,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 } @@ -207,7 +207,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/http_requests.go b/server/http_requests.go index 3db91aa1..3868a784 100644 --- a/server/http_requests.go +++ b/server/http_requests.go @@ -194,6 +194,15 @@ func TokenEndpointRequestFromHTTP(r *http.Request) (TokenEndpointRequest, error) // this package implements. func (t TokenEndpointRequest) GrantType() string { return t.parts.get().HTTP.Get("grant_type") } +// SetEndpointRoute records which configured public route received the request. +// Set this from trusted routing metadata when the token endpoint has an alias. +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..49a561e4 100644 --- a/server/par.go +++ b/server/par.go @@ -134,6 +134,11 @@ type FormParameter struct { // request itself, never its fields or their JSON. type FormRequest struct { Parameters []FormParameter + + // EndpointRoute identifies the public route that received a DPoP proof. + // Required when this endpoint advertises a distinct mTLS alias. Set it + // from trusted listener or proxy routing, never from the proof or a header. + EndpointRoute EndpointRoute } // Get returns the first value of name in f, or "" if absent — for an @@ -256,7 +261,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 +945,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 := 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..9a3341cd 100644 --- a/server/token.go +++ b/server/token.go @@ -25,6 +25,32 @@ import ( "github.com/idfoundry/fapigo/storage" ) +// EndpointRoute identifies the receiving route for a DPoP proof (RFC 9449 §4.3). +type EndpointRoute uint8 + +const ( + // PrimaryEndpoint selects the configured endpoint in Config.Endpoints. + PrimaryEndpoint EndpointRoute = iota + 1 + // MTLSEndpointAlias selects the corresponding Config.MTLSEndpoints URL. + 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)) + } +} + // AuthorizationCodeExchangeRequest is the input to // Server.ExchangeAuthorizationCode. type AuthorizationCodeExchangeRequest struct { @@ -231,7 +257,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 +897,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 +907,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 +928,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 := 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,37 +951,29 @@ 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 +// verifyEndpointDPoP matches htu to the one endpoint that received the request. +func verifyEndpointDPoP(ctx context.Context, req dpop.VerifyRequest, primary, alias fapi.URL, route EndpointRoute) (dpop.VerifiedProof, *Error) { + target := primary.URL() + switch route { + case PrimaryEndpoint: + case MTLSEndpointAlias: + if alias.IsZero() { + return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("no mTLS endpoint alias configured")) + } + target = alias.URL() + case 0: + if !alias.IsZero() && alias.String() != primary.String() { + return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("a DPoP request to an endpoint with an alias requires FormRequest.EndpointRoute")) + } + default: + return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("unknown DPoP endpoint route")) + } + req.URL = &target verified, err := dpop.Verify(ctx, req) - if err == nil || !errors.Is(err, dpop.ErrURIMismatch) || mtlsAlias.IsZero() { - return verified, err + if err != nil { + return dpop.VerifiedProof{}, storeFailure(ctx, err, "failed to check DPoP proof replay", newError(ErrorInvalidDPoPProof, 400, "DPoP proof verification failed", err)) } - aliasURL := mtlsAlias.URL() - req.URL = &aliasURL - return dpop.Verify(ctx, req) + return verified, nil } // withIdentityClaims merges whatever Dependencies.IdentityClaims diff --git a/server/token_request_dpop_test.go b/server/token_request_dpop_test.go index 572d82c6..fa77678b 100644 --- a/server/token_request_dpop_test.go +++ b/server/token_request_dpop_test.go @@ -184,7 +184,16 @@ func TestVerifyTokenRequestDPoPAtTheMTLSAlias(t *testing.T) { } cfg.MTLSEndpoints.Token = u }) - if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), alias, "", h.now))); err != nil { + req := clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), alias, "", h.now)) + if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); err == nil { + t.Fatal("accepted ambiguous route") + } + req.SetEndpointRoute(server.PrimaryEndpoint) + if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { + t.Fatalf("alias proof at primary endpoint: %v", err) + } + req.SetEndpointRoute(server.MTLSEndpointAlias) + if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); err != nil { t.Fatalf("VerifyTokenRequestDPoP(proof for the mTLS alias): %v", err) } } From 188aafa913c24aa42dc1dd1a2b2d13d98d5e3580 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:03:07 +0800 Subject: [PATCH 2/9] fix(server): check an unrouted DPoP proof against the primary endpoint A DPoP request with no endpoint route, at an endpoint with a distinct mTLS alias, was answered 500 server_error: every DPoP request to such a server failed until each listener set a route, including the ones that only ever serve the primary URL. Such a request is now checked against the endpoint's primary URL only, never either. A proof naming the alias, sent where no route was set, is refused like any other proof for another URL: 400 invalid_dpop_proof, with the generic public description and a cause that names the route setters for the deployment's logs. One target per request still holds, so a captured proof can't be spent once at each URL. The alias route at an endpoint configuring no alias of its own, on a server advertising aliases for others, is a URL the client wasn't given: 400 invalid_dpop_proof. The alias route on a server with no mTLS alias at all, or a route value the package doesn't define, stays a 500, and its cause now names FormRequest.EndpointRoute and TokenEndpointRequest.SetEndpointRoute. Co-Authored-By: Claude Opus 5.5 --- server/backchannel_authentication.go | 3 +- server/client_auth_mtls_test.go | 16 +++ server/endpoint_route.go | 114 +++++++++++++++++ server/endpoint_route_test.go | 180 +++++++++++++++++++++++++++ server/extension_grants.go | 7 +- server/http_requests.go | 6 +- server/par.go | 12 +- server/token.go | 53 +------- server/token_request_dpop_test.go | 24 ---- 9 files changed, 329 insertions(+), 86 deletions(-) create mode 100644 server/endpoint_route.go create mode 100644 server/endpoint_route_test.go diff --git a/server/backchannel_authentication.go b/server/backchannel_authentication.go index 48bb0d6c..a7162d2c 100644 --- a/server/backchannel_authentication.go +++ b/server/backchannel_authentication.go @@ -180,7 +180,8 @@ 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. + // 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/client_auth_mtls_test.go b/server/client_auth_mtls_test.go index 53dee3f8..ad44c0b4 100644 --- a/server/client_auth_mtls_test.go +++ b/server/client_auth_mtls_test.go @@ -826,6 +826,22 @@ 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 code := serverErrorCode(t, err); code != 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"}) diff --git a/server/endpoint_route.go b/server/endpoint_route.go new file mode 100644 index 00000000..bd498b2b --- /dev/null +++ b/server/endpoint_route.go @@ -0,0 +1,114 @@ +package server + +import ( + "context" + "errors" + "fmt" + "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. 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)) + } +} + +// endpointRouteSetters names everything that sets a request's +// EndpointRoute, for the errors a route this server can't serve gets. +const endpointRouteSetters = "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..407ebbd8 --- /dev/null +++ b/server/endpoint_route_test.go @@ -0,0 +1,180 @@ +package server_test + +import ( + "context" + "errors" + "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{"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) + } + } +} diff --git a/server/extension_grants.go b/server/extension_grants.go index c6846299..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 @@ -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: diff --git a/server/http_requests.go b/server/http_requests.go index 3868a784..e41bd2c0 100644 --- a/server/http_requests.go +++ b/server/http_requests.go @@ -194,8 +194,10 @@ func TokenEndpointRequestFromHTTP(r *http.Request) (TokenEndpointRequest, error) // this package implements. func (t TokenEndpointRequest) GrantType() string { return t.parts.get().HTTP.Get("grant_type") } -// SetEndpointRoute records which configured public route received the request. -// Set this from trusted routing metadata when the token endpoint has an alias. +// 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. 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 diff --git a/server/par.go b/server/par.go index 49a561e4..edcb80c0 100644 --- a/server/par.go +++ b/server/par.go @@ -135,9 +135,13 @@ type FormParameter struct { type FormRequest struct { Parameters []FormParameter - // EndpointRoute identifies the public route that received a DPoP proof. - // Required when this endpoint advertises a distinct mTLS alias. Set it - // from trusted listener or proxy routing, never from the proof or a header. + // 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. Left unset at an mTLS alias, a proof + // naming the alias is refused as invalid_dpop_proof. EndpointRoute EndpointRoute } @@ -949,7 +953,7 @@ func (s *Server) verifyOptionalDPoPProof(ctx context.Context, proof string, endp if proof == "" { return "", nil } - verified, err := verifyEndpointDPoP(ctx, dpop.VerifyRequest{ + verified, err := s.verifyEndpointDPoP(ctx, dpop.VerifyRequest{ Proof: proof, Method: "POST", Now: s.deps.Clock.Now(), diff --git a/server/token.go b/server/token.go index 9a3341cd..6c3960a7 100644 --- a/server/token.go +++ b/server/token.go @@ -25,32 +25,6 @@ import ( "github.com/idfoundry/fapigo/storage" ) -// EndpointRoute identifies the receiving route for a DPoP proof (RFC 9449 §4.3). -type EndpointRoute uint8 - -const ( - // PrimaryEndpoint selects the configured endpoint in Config.Endpoints. - PrimaryEndpoint EndpointRoute = iota + 1 - // MTLSEndpointAlias selects the corresponding Config.MTLSEndpoints URL. - 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)) - } -} - // AuthorizationCodeExchangeRequest is the input to // Server.ExchangeAuthorizationCode. type AuthorizationCodeExchangeRequest struct { @@ -932,7 +906,7 @@ func (s *Server) verifyTokenRequestDPoP(ctx context.Context, proof string, route if proof == "" { return dpop.VerifiedProof{}, newError(ErrorInvalidRequest, 400, "DPoP proof is required", nil) } - verified, err := verifyEndpointDPoP(ctx, dpop.VerifyRequest{ + verified, err := s.verifyEndpointDPoP(ctx, dpop.VerifyRequest{ Proof: proof, Method: "POST", Now: s.deps.Clock.Now(), @@ -951,31 +925,6 @@ func (s *Server) verifyTokenRequestDPoP(ctx context.Context, proof string, route return verified, nil } -// verifyEndpointDPoP matches htu to the one endpoint that received the request. -func verifyEndpointDPoP(ctx context.Context, req dpop.VerifyRequest, primary, alias fapi.URL, route EndpointRoute) (dpop.VerifiedProof, *Error) { - target := primary.URL() - switch route { - case PrimaryEndpoint: - case MTLSEndpointAlias: - if alias.IsZero() { - return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("no mTLS endpoint alias configured")) - } - target = alias.URL() - case 0: - if !alias.IsZero() && alias.String() != primary.String() { - return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("a DPoP request to an endpoint with an alias requires FormRequest.EndpointRoute")) - } - default: - return dpop.VerifiedProof{}, newError(ErrorServerError, 500, "cannot determine DPoP request target", errors.New("unknown DPoP endpoint route")) - } - 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", err)) - } - return verified, nil -} - // 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 fa77678b..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,26 +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 - }) - req := clientlessTokenRequest(t, dpopProofAt(t, generateKey(t), alias, "", h.now)) - if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); err == nil { - t.Fatal("accepted ambiguous route") - } - req.SetEndpointRoute(server.PrimaryEndpoint) - if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { - t.Fatalf("alias proof at primary endpoint: %v", err) - } - req.SetEndpointRoute(server.MTLSEndpointAlias) - if _, err := h.server.VerifyTokenRequestDPoP(context.Background(), req); err != nil { - t.Fatalf("VerifyTokenRequestDPoP(proof for the mTLS alias): %v", err) - } -} From 68fbe71f32babb8c5252a537b23a27c429039639 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:05:20 +0800 Subject: [PATCH 3/9] feat(server): add WithEndpointRoute to mark a listener's requests A deployment with mTLS aliases had to set FormRequest.EndpointRoute, or call TokenEndpointRequest.SetEndpointRoute, in every PAR, token and backchannel authentication handler, from listener state it had to carry through the request context itself. WithEndpointRoute(route, next) marks every request a listener receives with its route, and FormRequestFromHTTP, so every *FromHTTP request constructor, reads the route from that mark. Wrapping the handler of the listener serving Config.MTLSEndpoints in WithEndpointRoute(MTLSEndpointAlias, mux) is then the whole migration. A route set on a request after it is read still takes precedence. The 500 for a route the server can't serve now names WithEndpointRoute among the setters. The conformance server marks its two listeners this way instead of setting the route in each handler. Co-Authored-By: Claude Opus 5.5 --- cmd/conformance-as/backchannel.go | 1 - cmd/conformance-as/listener_test.go | 32 +++++++++++++ cmd/conformance-as/par.go | 1 - cmd/conformance-as/router.go | 15 +++--- cmd/conformance-as/token.go | 1 - server/endpoint_route.go | 43 ++++++++++++++++- server/endpoint_route_test.go | 71 ++++++++++++++++++++++++++++- server/formrequest.go | 5 +- server/http_requests.go | 4 +- server/par.go | 3 +- 10 files changed, 160 insertions(+), 16 deletions(-) create mode 100644 cmd/conformance-as/listener_test.go diff --git a/cmd/conformance-as/backchannel.go b/cmd/conformance-as/backchannel.go index c2249152..2619c95d 100644 --- a/cmd/conformance-as/backchannel.go +++ b/cmd/conformance-as/backchannel.go @@ -60,7 +60,6 @@ func (h *backchannelHandler) handleAuthenticate(w http.ResponseWriter, r *http.R writeOAuthJSONError(w, err) return } - req.HTTP.EndpointRoute = receivingListener(r).route action, err := h.srv.BeginBackchannelAuthentication(r.Context(), req) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) diff --git a/cmd/conformance-as/listener_test.go b/cmd/conformance-as/listener_test.go new file mode 100644 index 00000000..878b2e1a --- /dev/null +++ b/cmd/conformance-as/listener_test.go @@ -0,0 +1,32 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "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) { + 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, "https://as.example") + 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/par.go b/cmd/conformance-as/par.go index dffd8567..d95fb0bc 100644 --- a/cmd/conformance-as/par.go +++ b/cmd/conformance-as/par.go @@ -13,7 +13,6 @@ func parHandler(srv *server.Server) http.HandlerFunc { writeOAuthJSONError(w, err) return } - req.HTTP.EndpointRoute = receivingListener(r).route result, err := srv.PushAuthorizationRequest(r.Context(), req) if err != nil { writeOAuthJSONError(w, err) diff --git a/cmd/conformance-as/router.go b/cmd/conformance-as/router.go index 35f789cc..8bb88026 100644 --- a/cmd/conformance-as/router.go +++ b/cmd/conformance-as/router.go @@ -72,17 +72,18 @@ func newRouter(srv *server.Server, consent *consentHandler, backchannel *backcha type listenerKey struct{} type publicListener struct { - route server.EndpointRoute - base string + base string } -// listenerHandler supplies the advertised URL base of the listener that actually -// accepted the connection. Both listeners use the same ServeMux. +// listenerHandler marks each request with the listener that actually +// accepted the connection: its endpoint route, for the server's *FromHTTP +// request constructors (server.WithEndpointRoute), and its advertised URL +// base, for resourceRequest. Both listeners use the same ServeMux. func listenerHandler(next http.Handler, route server.EndpointRoute, base string) http.Handler { - listener := publicListener{route: route, base: base} - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + listener := publicListener{base: base} + return server.WithEndpointRoute(route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), listenerKey{}, listener))) - }) + })) } func receivingListener(r *http.Request) publicListener { diff --git a/cmd/conformance-as/token.go b/cmd/conformance-as/token.go index 747ce788..b8518fcf 100644 --- a/cmd/conformance-as/token.go +++ b/cmd/conformance-as/token.go @@ -14,7 +14,6 @@ func tokenHandler(srv *server.Server) http.HandlerFunc { return } - req.SetEndpointRoute(receivingListener(r).route) var result server.TokenResult switch req.GrantType() { case "authorization_code": diff --git a/server/endpoint_route.go b/server/endpoint_route.go index bd498b2b..19c93172 100644 --- a/server/endpoint_route.go +++ b/server/endpoint_route.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net/http" "net/url" fapi "github.com/idfoundry/fapigo" @@ -20,7 +21,8 @@ import ( // 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. The zero route (unset) is +// 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 @@ -47,9 +49,46 @@ func (r EndpointRoute) String() string { } } +// 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 = "FormRequest.EndpointRoute or TokenEndpointRequest.SetEndpointRoute" +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 diff --git a/server/endpoint_route_test.go b/server/endpoint_route_test.go index 407ebbd8..2c20587d 100644 --- a/server/endpoint_route_test.go +++ b/server/endpoint_route_test.go @@ -3,6 +3,8 @@ package server_test import ( "context" "errors" + "net/http" + "net/http/httptest" "strings" "testing" "time" @@ -15,7 +17,7 @@ import ( const testTokenAlias = "https://mtls.as.example/token" // routeSetterNames are the setters a route error's cause must name. -var routeSetterNames = []string{"FormRequest.EndpointRoute", "TokenEndpointRequest.SetEndpointRoute"} +var routeSetterNames = []string{"server.WithEndpointRoute", "FormRequest.EndpointRoute", "TokenEndpointRequest.SetEndpointRoute"} // newRouteHarness is a harness whose Config.MTLSEndpoints is set by // aliases (nil for none). @@ -178,3 +180,70 @@ func TestEndpointRouteString(t *testing.T) { } } } + +// 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) + } + token.SetEndpointRoute(server.PrimaryEndpoint) + if got := token.AuthorizationCodeExchange().HTTP.EndpointRoute; got != server.PrimaryEndpoint { + t.Errorf("route after SetEndpointRoute = %v, want %v", got, server.PrimaryEndpoint) + } + 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/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 e41bd2c0..90b3f4ea 100644 --- a/server/http_requests.go +++ b/server/http_requests.go @@ -196,7 +196,9 @@ func (t TokenEndpointRequest) GrantType() string { return t.parts.get().HTTP.Get // 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. Set it from the listener or +// 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() diff --git a/server/par.go b/server/par.go index edcb80c0..6e425a0f 100644 --- a/server/par.go +++ b/server/par.go @@ -140,7 +140,8 @@ type FormRequest struct { // 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. Left unset at an mTLS alias, a proof + // 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 } From c6bd0c5bde57b14dbfdf6b2ee3456ff6a83cf105 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:08:34 +0800 Subject: [PATCH 4/9] feat(resource): add WithResourceOrigin to mark a listener's origin A DPoP request whose path several of Config.ResourceURLs' origins cover is refused as a 500 unless the deployment says which origin received it, since the Host header the client sends can't. The only way to say so was VerifyRequest.URL, rebuilt by hand from the listener's origin and the escaped path in every handler, and the 500's cause named only that. WithResourceOrigin(origin, next) marks every request a listener receives with its origin, and VerifyRequestFromHTTP takes the mark: Verify then places the escaped path only under the ResourceURLs at that origin, keeping the path checks VerifyRequestFromHTTP's requests already get. A mark naming an origin none of ResourceURLs is at is the deployment's mistake, a 500; an explicit VerifyRequest.URL still takes precedence. The ambiguous-target 500 now names WithResourceOrigin and VerifyRequest.URL, and the request path it couldn't place. The conformance server marks each listener's origin this way instead of building VerifyRequest.URL itself. Co-Authored-By: Claude Opus 5.5 --- cmd/conformance-as/listener_test.go | 7 +- cmd/conformance-as/main.go | 5 +- cmd/conformance-as/mtls_smoke_test.go | 4 +- cmd/conformance-as/resource.go | 21 +--- cmd/conformance-as/router.go | 27 ++--- fapitest/testdata/redaction.golden | 1 + resource/render.go | 3 +- resource/render_internal_test.go | 4 +- resource/resource_origin.go | 48 +++++++++ resource/resource_origin_test.go | 139 ++++++++++++++++++++++++++ resource/target.go | 78 ++++++++++++--- resource/verify.go | 13 ++- resource/verify_request_http.go | 7 +- 13 files changed, 290 insertions(+), 67 deletions(-) create mode 100644 resource/resource_origin.go create mode 100644 resource/resource_origin_test.go diff --git a/cmd/conformance-as/listener_test.go b/cmd/conformance-as/listener_test.go index 878b2e1a..dcd27810 100644 --- a/cmd/conformance-as/listener_test.go +++ b/cmd/conformance-as/listener_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + fapi "github.com/idfoundry/fapigo" "github.com/idfoundry/fapigo/server" ) @@ -13,6 +14,10 @@ import ( // 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) { @@ -21,7 +26,7 @@ func TestListenerHandlerMarksTheRoute(t *testing.T) { t.Fatalf("PushAuthorizationRequestFromHTTP: %v", err) } got = req.HTTP.EndpointRoute - }), route, "https://as.example") + }), 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) diff --git a/cmd/conformance-as/main.go b/cmd/conformance-as/main.go index 12b1ede5..612f1624 100644 --- a/cmd/conformance-as/main.go +++ b/cmd/conformance-as/main.go @@ -8,7 +8,6 @@ import ( "net" "net/http" "net/url" - "strings" "time" fapi "github.com/idfoundry/fapigo" @@ -118,7 +117,7 @@ func main() { httpServer := &http.Server{ Addr: resolved.ListenAddr, - Handler: listenerHandler(mux, server.PrimaryEndpoint, resolved.Issuer.String()), + Handler: listenerHandler(mux, server.PrimaryEndpoint, resolved.Issuer), TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, CipherSuites: server.FAPIRWTLSCipherSuites}, ReadHeaderTimeout: readHeaderTimeout, } @@ -178,7 +177,7 @@ func newMTLSServer(resolved ResolvedConfig, mux http.Handler) (*http.Server, err } return &http.Server{ Addr: resolved.MTLSListenAddr, - Handler: listenerHandler(mux, server.MTLSEndpointAlias, strings.TrimSuffix(resolved.MTLSEndpoints.Token.String(), "/token")), + 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 01766530..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: listenerHandler(mux, server.PrimaryEndpoint, issuer.String())} + primaryServer := &http.Server{Handler: listenerHandler(mux, server.PrimaryEndpoint, issuer)} go primaryServer.Serve(primaryTLS) t.Cleanup(func() { primaryServer.Close() }) - mtlsServer := &http.Server{Handler: listenerHandler(mux, server.MTLSEndpointAlias, strings.TrimSuffix(mtlsEndpoints.Token.String(), "/token"))} + 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/resource.go b/cmd/conformance-as/resource.go index 3ef31f30..b036d2df 100644 --- a/cmd/conformance-as/resource.go +++ b/cmd/conformance-as/resource.go @@ -3,7 +3,6 @@ package main import ( "encoding/json" "net/http" - "net/url" fapires "github.com/idfoundry/fapigo/resource" "github.com/idfoundry/fapigo/server" @@ -11,22 +10,6 @@ import ( "github.com/idfoundry/fapigo/storage" ) -// resourceRequest preserves the escaped path the client called and selects -// the origin from the listener. The request Host and forwarding headers -// cannot select the expected URI. -func resourceRequest(r *http.Request) fapires.VerifyRequest { - req := fapires.VerifyRequestFromHTTP(r) - if base := receivingListener(r).base; base != "" { - // base is a validated issuer or alias base and EscapedPath is URL-encoded. - target, err := url.Parse(base + r.URL.EscapedPath()) - if err != nil { - target = &url.URL{} // Verify rejects a relative target. - } - req.URL = target - } - return req -} - // contentTypeHeader is the HTTP header name every JSON/JWT response // this file writes sets. const contentTypeHeader = "Content-Type" @@ -75,7 +58,7 @@ func userinfoHandler(srv *server.Server, verifier *fapires.Verifier, identityCla } w.Header().Set(fapires.InteractionIDHeader, interactionID) - authCtx, err := verifier.Verify(r.Context(), resourceRequest(r)) + authCtx, err := verifier.Verify(r.Context(), fapires.VerifyRequestFromHTTP(r)) if err != nil { writeResourceError(w, err) return @@ -134,7 +117,7 @@ func accountsHandler(verifier *fapires.Verifier) http.HandlerFunc { } w.Header().Set(fapires.InteractionIDHeader, interactionID) - authCtx, err := verifier.Verify(r.Context(), resourceRequest(r)) + authCtx, err := verifier.Verify(r.Context(), fapires.VerifyRequestFromHTTP(r)) if err != nil { writeResourceError(w, err) return diff --git a/cmd/conformance-as/router.go b/cmd/conformance-as/router.go index 8bb88026..e1adee46 100644 --- a/cmd/conformance-as/router.go +++ b/cmd/conformance-as/router.go @@ -1,7 +1,6 @@ package main import ( - "context" "net/http" "net/url" @@ -69,24 +68,12 @@ func newRouter(srv *server.Server, consent *consentHandler, backchannel *backcha return mux } -type listenerKey struct{} - -type publicListener struct { - base string -} - // listenerHandler marks each request with the listener that actually -// accepted the connection: its endpoint route, for the server's *FromHTTP -// request constructors (server.WithEndpointRoute), and its advertised URL -// base, for resourceRequest. Both listeners use the same ServeMux. -func listenerHandler(next http.Handler, route server.EndpointRoute, base string) http.Handler { - listener := publicListener{base: base} - return server.WithEndpointRoute(route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), listenerKey{}, listener))) - })) -} - -func receivingListener(r *http.Request) publicListener { - listener, _ := r.Context().Value(listenerKey{}).(publicListener) - return listener +// 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/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/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..32ee25a3 --- /dev/null +++ b/resource/resource_origin_test.go @@ -0,0 +1,139 @@ +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) +} + +// 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 5c6cb798..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 @@ -59,7 +65,7 @@ func (v *Verifier) requestTarget(req VerifyRequest, dpop bool) (*url.URL, *Error if req.URL != nil { return v.explicitTarget(req.URL) } - return v.pathTarget(req.requestPath, dpop) + return v.pathTarget(req.requestPath, req.requestOrigin, dpop) } // explicitTarget is target, once it is known to be an absolute http(s) @@ -79,31 +85,73 @@ func (v *Verifier) explicitTarget(target *url.URL) (*url.URL, *Error) { return nil, outsideResourceURLs(target.String()) } -// pathTarget resolves escapedPath under the configured prefixes. DPoP needs -// one unambiguous URI. Certificate binding only requires a covered path. -func (v *Verifier) pathTarget(escapedPath string, dpop bool) (*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 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) { - if target != nil && dpop && canonical.URI(target) != canonical.URI(t) { - return nil, newError(ErrorServerError, 500, "ambiguous DPoP request target", errors.New("set VerifyRequest.URL from trusted routing metadata when multiple resource origins cover the request path")) - } - target = t + if !covered { + continue } + if target != nil && dpop && canonical.URI(target) != canonical.URI(t) { + return nil, ambiguousTarget(escapedPath) + } + target = t } if target == nil { - return nil, outsideResourceURLs(escapedPath) + 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 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 // a DPoP htu is compared in: one with a dot segment ("/a/../b") or a // percent-encoded unreserved character ("/accounts/%31"). htu matching diff --git a/resource/verify.go b/resource/verify.go index 17a654b2..c9612b2a 100644 --- a/resource/verify.go +++ b/resource/verify.go @@ -36,8 +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 when one origin covers the path. - // For DPoP at overlapping origins, set URL from trusted routing. 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 @@ -94,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 diff --git a/resource/verify_request_http.go b/resource/verify_request_http.go index 2895490d..60c8c89c 100644 --- a/resource/verify_request_http.go +++ b/resource/verify_request_http.go @@ -23,8 +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. When several origins cover the path, a DPoP request -// requires VerifyRequest.URL from the listener or trusted proxy route. +// 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 @@ -40,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, } } From 9fc9e042f03a426048d594d2a00e42f20ade62e3 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:10:08 +0800 Subject: [PATCH 5/9] docs: describe the one-URL DPoP check and the listener marks UPGRADING.md's v0.88.0 section described the first cut of the change, under which an unrouted DPoP request at a server with mTLS aliases was a 500. It now says who is affected, what is refused and with which status, and that wrapping the alias listener in WithEndpointRoute, or each resource server listener in WithResourceOrigin, is the migration. GETTING_STARTED, the mTLS and DPoP guides and the doc comments on server.MTLSEndpoints and resource.Config.ResourceURLs show the listener marks, and the conformance notes record that the either-URL retry they describe was replaced. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 6 +- GETTING_STARTED.md | 24 +++++++- UPGRADING.md | 72 +++++++++++++++++++----- conformance/server/oidf-config/README.md | 5 +- docs/guides/dpop.md | 17 ++++-- docs/guides/mtls.md | 25 ++++++++ resource/config.go | 10 ++-- server/config.go | 7 ++- 8 files changed, 137 insertions(+), 29 deletions(-) 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 0c793bb2..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,9 +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): set -`VerifyRequest.URL` from the trusted listener or proxy route when multiple -origins cover the same DPoP request path. 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 09d019c0..623e069f 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -20,20 +20,64 @@ and `keys/ephemeral` needs only the steps not marked *production only*. ## v0.88.0 -### Bind DPoP proofs to the receiving endpoint - -Authorization servers advertising a distinct mTLS alias must identify which -route received each DPoP request at PAR, the token endpoint (including custom -grants), and the backchannel authentication endpoint. Set -`FormRequest.EndpointRoute` to `server.PrimaryEndpoint` or -`server.MTLSEndpointAlias` from the listener or trusted proxy route. For -`TokenEndpointRequestFromHTTP`, call `SetEndpointRoute` before dispatch. -A server with one endpoint URL can continue to omit the field. - -Resource servers with multiple configured origins covering the same path -must set `VerifyRequest.URL` to the actual public request URL for DPoP, -preserving the escaped path. Use trusted routing information for the -origin. An ambiguous target fails closed before replay or nonce processing. +### 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 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/resource/config.go b/resource/config.go index 7a6a9070..8be97c91 100644 --- a/resource/config.go +++ b/resource/config.go @@ -57,10 +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"). When several configured origins cover - // that path, a DPoP request requires VerifyRequest.URL from trusted - // listener or proxy routing. Verify checks an explicit URL against - // ResourceURLs too. 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/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 From de2a997cc1bd4c3451d5e728a47da1b75f3e9d27 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:12:29 +0800 Subject: [PATCH 6/9] test: cover the DPoP route at refresh and the listener marks' edges A refresh at the token endpoint's mTLS alias verifies a proof for the alias only on a request marked as received there. A copy of a token endpoint request made before SetEndpointRoute keeps its route, and an unmarked resource request no prefix covers is still the client's 400. Co-Authored-By: Claude Opus 5.5 --- resource/resource_origin_test.go | 7 +++++ server/client_auth_mtls_test.go | 44 ++++++++++++++++++++++++++++++++ server/endpoint_route_test.go | 4 +++ 3 files changed, 55 insertions(+) diff --git a/resource/resource_origin_test.go b/resource/resource_origin_test.go index 32ee25a3..dcf0e314 100644 --- a/resource/resource_origin_test.go +++ b/resource/resource_origin_test.go @@ -118,6 +118,13 @@ func TestWithResourceOriginOutsideResourceURLs(t *testing.T) { 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 diff --git a/server/client_auth_mtls_test.go b/server/client_auth_mtls_test.go index ad44c0b4..1b68eed1 100644 --- a/server/client_auth_mtls_test.go +++ b/server/client_auth_mtls_test.go @@ -865,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 code := serverErrorCode(t, err); code != 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/endpoint_route_test.go b/server/endpoint_route_test.go index 2c20587d..db731e0f 100644 --- a/server/endpoint_route_test.go +++ b/server/endpoint_route_test.go @@ -223,10 +223,14 @@ func TestWithEndpointRouteMarksFromHTTPRequests(t *testing.T) { 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) From 246cc54b9a36f366685f688d3539ab72e3ec4e1e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:18:34 +0800 Subject: [PATCH 7/9] refactor: build the conformance server's resource URLs in a helper Listing the protected endpoints at the mTLS alias origin added a parse and its error check to newServerMux, already the conformance server's most complex function. protectedResourceURLs now builds the list, and the comment saying why each listener marks its origin moves with it. Co-Authored-By: Claude Opus 5.5 --- cmd/conformance-as/wiring.go | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/cmd/conformance-as/wiring.go b/cmd/conformance-as/wiring.go index af76477b..26e6072b 100644 --- a/cmd/conformance-as/wiring.go +++ b/cmd/conformance-as/wiring.go @@ -441,17 +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 { - aliasAccounts, err := fapi.ParseEndpointURL(strings.TrimSuffix(mtlsUserinfoURL.String(), "/userinfo") + "/accounts") - if err != nil { - return nil, err - } - resourceOpts.ResourceURLs = append(resourceOpts.ResourceURLs, *mtlsUserinfoURL, aliasAccounts) + 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 @@ -509,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 +} From bff1057e2a9e1b32d9e8b8c31e73ffebb0c0745e Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 08:12:29 +0800 Subject: [PATCH 8/9] test: add mutants for the one-URL DPoP check and the listener marks Each new branch of the endpoint route check, the route hint, both listener marks and the route each DPoP call site passes has a mutant. Two existing mutants are re-anchored on code the change moved. Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 332 +++++++++++++++++++++++++++++++++- 1 file changed, 328 insertions(+), 4 deletions(-) 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" } ] From 078f01f7ff6623e9af3d2044fb211c7773ffb8a0 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Fri, 27 Nov 2026 09:06:38 +0800 Subject: [PATCH 9/9] test(server): compare the DPoP error code in the condition directly Co-Authored-By: Claude Opus 5.5 --- server/client_auth_mtls_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/client_auth_mtls_test.go b/server/client_auth_mtls_test.go index 1b68eed1..969821c5 100644 --- a/server/client_auth_mtls_test.go +++ b/server/client_auth_mtls_test.go @@ -837,7 +837,7 @@ func TestPushAuthorizationRequestRefusesAnUnroutedAliasProof(t *testing.T) { DPoPProofs: []string{dpopProofForURL(t, generateKey(t), mtlsPAR, h.now)}, PeerCertificate: cert, }) - if code := serverErrorCode(t, err); code != server.ErrorInvalidDPoPProof { + if serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { t.Fatalf("PushAuthorizationRequest(alias proof, no route) = %v, want invalid_dpop_proof", err) } } @@ -899,7 +899,7 @@ func TestRefreshAccessTokenCertClientAuthAtMTLSAlias(t *testing.T) { PeerCertificate: cert, }) if route == 0 { - if code := serverErrorCode(t, err); code != server.ErrorInvalidDPoPProof { + if serverErrorCode(t, err) != server.ErrorInvalidDPoPProof { t.Errorf("RefreshAccessToken(alias proof, no route) = %v, want invalid_dpop_proof", err) } continue