diff --git a/internal/server/bug3337_connection_authoritative_test.go b/internal/server/bug3337_connection_authoritative_test.go index 5c630aeb3..6fc4503cc 100644 --- a/internal/server/bug3337_connection_authoritative_test.go +++ b/internal/server/bug3337_connection_authoritative_test.go @@ -25,7 +25,9 @@ import ( // chain's request id. func legacyGrant(t *testing.T, srv *Server, sess oauthSession, extra []string) (string, string) { t.Helper() - tok, code := mintWithResource(t, srv, sess, "") + // The canonical resource: a grant without one is refused since TASK-3363 + // phase 2. A legacy chain was minted with the default, which is this. + tok, code := mintWithResource(t, srv, sess, testCanonicalAudience) if code != http.StatusOK { t.Fatalf("mint: %d", code) } diff --git a/internal/server/handlers_oauth.go b/internal/server/handlers_oauth.go index 80f9e959f..be81ec0f9 100644 --- a/internal/server/handlers_oauth.go +++ b/internal/server/handlers_oauth.go @@ -514,12 +514,24 @@ func writeDCRError(w http.ResponseWriter, status int, code, msg string) { // adopts RFC 8707." A future task tracks restoring the strict reject // once Claude / Cursor / ChatGPT all send `resource=`. // +// THAT TASK IS TASK-3363, and the reasoning above is now history. Phase 1 +// counted the defaults (cloud read #1: 0 of 322 requests omitted resource), +// and phase 2 refuses a missing resource at /authorize and +// /authorize/decide with invalid_target, which closes the replay above: +// no grant is made without the client naming its target. The token +// endpoint still defaults, because resource is optional there (RFC 8707 +// §2.2) and fosite holds the requested audience to the one granted +// (TestTASK3363_TokenExchangeWithoutResourceKeepsTheGrantedAudience). +// // Mutates r.Form in place. r MUST have ParseForm called before this; // the OAuth handlers below parse before invoking fosite. // // It reports whether it DEFAULTED a missing resource (TASK-3363): callers -// record that through noteResourceMissing, which phase 2 turns into a -// refusal. +// record that through noteResourceMissing and, since phase 2, refuse the +// request with invalid_target once fosite has parsed it. The default is still +// injected so fosite can parse the request far enough to return that error +// the way RFC 6749 says (a redirect to a registered redirect_uri at the +// authorize endpoint). func translateResourceToAudience(r *http.Request, canonical string) (defaulted bool) { if r == nil || r.Form == nil { return false @@ -549,12 +561,14 @@ func translateResourceToAudience(r *http.Request, canonical string) (defaulted b } // noteResourceMissing records a request that omitted the RFC 8707 -// resource parameter and was defaulted to the canonical audience (TASK-3363 -// phase 1, Dave's ruling on TASK-3345 #1). Phase 2, a release later, refuses -// such a request with invalid_target; until then this measures who would -// break: one log line naming the client (id and registered name) and one -// pad_oauth_resource_missing_total increment per endpoint. The defaulting is -// what lets a client registered through DCR replay a token cross-server. +// resource parameter (TASK-3363, Dave's ruling on TASK-3345 #1): one log line +// naming the client (id and registered name) and one +// pad_oauth_resource_missing_total increment per endpoint. Phase 1 measured +// who would break; phase 2 refuses the request (errInvalidTarget), so the +// counter counts refusals at authorize and decide, and the defaulted (still +// served) exchanges at the token endpoint. Defaulting the resource at +// authorization is what let a client registered through DCR replay a token +// cross-server. func (s *Server) noteResourceMissing(r *http.Request, endpoint string) { clientID := r.Form.Get("client_id") if clientID == "" { @@ -578,11 +592,23 @@ func (s *Server) noteResourceMissing(r *http.Request, endpoint string) { s.metrics.OAuthResourceMissingTotal.WithLabelValues(endpoint).Inc() } if s.resourceMissingWarnDue(clientID) { - slog.Warn("oauth: client omitted the RFC 8707 resource parameter; defaulted to the canonical audience (refused from the next phase). Logged once per client per hour; pad_oauth_resource_missing_total counts every request", + slog.Warn("oauth: client omitted the RFC 8707 resource parameter; refused with invalid_target at authorize and decide, defaulted at the token endpoint. Logged once per client per hour; pad_oauth_resource_missing_total counts every request", "endpoint", endpoint, "client_id", clientID, "client_name", clientName) } } +// errInvalidTarget is RFC 8707 §2's invalid_target, which fosite does not +// define: the request named no resource (TASK-3363 phase 2). A fresh value +// per call, because fosite's With* helpers copy but callers may not. +func errInvalidTarget() *fosite.RFC6749Error { + return &fosite.RFC6749Error{ + ErrorField: "invalid_target", + DescriptionField: "The requested resource is invalid, missing, unknown, or malformed.", + HintField: "Send the RFC 8707 resource parameter naming this server's MCP resource (see /.well-known/oauth-protected-resource).", + CodeField: http.StatusBadRequest, + } +} + // resourceMissingWarnInterval is how often noteResourceMissing logs one // client (TASK-3363). const resourceMissingWarnInterval = time.Hour @@ -652,7 +678,8 @@ func (s *Server) handleOAuthAuthorize(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid query string", http.StatusBadRequest) return } - if translateResourceToAudience(r, s.oauthServer.AllowedAudience()) { + resourceMissing := translateResourceToAudience(r, s.oauthServer.AllowedAudience()) + if resourceMissing { s.noteResourceMissing(r, "authorize") } @@ -700,6 +727,13 @@ func (s *Server) handleOAuthAuthorize(w http.ResponseWriter, r *http.Request) { s.oauthServer.Provider().WriteAuthorizeError(ctx, s.authorizeResponseWriter(w), ar, err) return } + // TASK-3363 phase 2: no resource, no grant. Refused after fosite parsed + // the request, so the error reaches the client at its redirect_uri. + if resourceMissing { + s.recordOAuthFlow("failed") + s.oauthServer.Provider().WriteAuthorizeError(ctx, s.authorizeResponseWriter(w), ar, errInvalidTarget()) + return + } // User must be logged in to grant consent. SessionAuth runs // in the parent middleware chain and falls through gracefully @@ -856,7 +890,8 @@ func (s *Server) handleOAuthAuthorizeDecide(w http.ResponseWriter, r *http.Reque } // RFC 8707 resource= → fosite audience= (Codex #372 round 1). - if translateResourceToAudience(r, s.oauthServer.AllowedAudience()) { + resourceMissing := translateResourceToAudience(r, s.oauthServer.AllowedAudience()) + if resourceMissing { s.noteResourceMissing(r, "decide") } @@ -871,6 +906,13 @@ func (s *Server) handleOAuthAuthorizeDecide(w http.ResponseWriter, r *http.Reque s.oauthServer.Provider().WriteAuthorizeError(ctx, s.authorizeResponseWriter(w), ar, err) return } + // TASK-3363 phase 2, as at /authorize: the decide POST rebuilds the + // request from the consent form, so it is refused here too. + if resourceMissing { + s.recordOAuthFlow("failed") + s.oauthServer.Provider().WriteAuthorizeError(ctx, s.authorizeResponseWriter(w), ar, errInvalidTarget()) + return + } choice := r.FormValue("decision") if choice == "deny" { @@ -1277,6 +1319,12 @@ func (s *Server) handleOAuthToken(w http.ResponseWriter, r *http.Request) { s.writeTokenError(ctx, w, fosite.ErrUnauthorizedClient.WithHint("client_credentials is for installed apps.")) return default: + // NOT refused here (TASK-3363 phase 2). RFC 8707 makes resource + // optional at the token endpoint: a code or refresh token is already + // bound to the audience its authorization granted, and that grant now + // requires resource (refused at /authorize and /authorize/decide). + // Defaulting here cannot widen a grant, because fosite holds the + // requested audience to the granted one. Still counted. if translateResourceToAudience(r, s.oauthServer.AllowedAudience()) { s.noteResourceMissing(r, "token") } diff --git a/internal/server/handlers_oauth_test.go b/internal/server/handlers_oauth_test.go index 2525850d7..267912729 100644 --- a/internal/server/handlers_oauth_test.go +++ b/internal/server/handlers_oauth_test.go @@ -682,30 +682,15 @@ func TestOAuth_Authorize_AcceptsResourceOnly(t *testing.T) { } } -// TestOAuth_Authorize_AcceptsNoResource_DefaultsToCanonical pins the -// fix for the "code: Field required" error Claude Desktop's MCP -// connector flow surfaces against pad: real MCP clients (Claude -// Desktop, Cursor as of 2026-05) don't send the RFC 8707 resource= -// parameter at all on /oauth/authorize. Before this fix, -// translateResourceToAudience only translated resource→audience when -// resource was present, so empty-resource requests reached fosite's -// audienceMatchingStrategy with an empty needle and got rejected -// with "resource parameter is required (RFC 8707)". fosite then -// redirected to the client's redirect_uri with ?error=invalid_request, -// and Claude's callback failed with a missing-`code`-field error -// (Anthropic's pydantic-style "code: Field required" envelope). -// -// RFC 8707 §2 marks the resource parameter OPTIONAL; servers with -// a single canonical audience are expected to default to it. This -// test sends NEITHER resource= NOR audience= and asserts the -// authorize request reaches the consent stub — proof that the -// translation injected the canonical audience instead of erroring. -// -// Pairs with TestOAuth_Authorize_AcceptsResourceOnly above (the -// resource-only path) and the existing TestOAuth_Authorize_* -// audience-mismatch tests (the wrong-audience path) to lock in the -// full matrix of what /authorize accepts for the audience parameter. -func TestOAuth_Authorize_AcceptsNoResource_DefaultsToCanonical(t *testing.T) { +// TestOAuth_Authorize_RefusesNoResource pins TASK-3363 phase 2 (Dave's +// ruling on TASK-3345 #1). From 2026-05 until phase 2, /oauth/authorize +// DEFAULTED a request with neither resource= nor audience= to the canonical +// audience, because Claude Desktop and Cursor did not send resource= then. +// That default let a client registered through DCR replay a token +// cross-server. Phase 1 measured who omitted it (cloud read #1: 0 of 322 +// requests), and phase 2 refuses it with RFC 8707's invalid_target, returned +// at the client's redirect_uri as RFC 6749 §4.1.2.1 requires. +func TestOAuth_Authorize_RefusesNoResource(t *testing.T) { t.Parallel() srv, _ := oauthEnabledTestServer(t) clientID := registerTestClient(t, srv, "https://app.test/cb") @@ -714,8 +699,7 @@ func TestOAuth_Authorize_AcceptsNoResource_DefaultsToCanonical(t *testing.T) { verifier := "verifier-the-quick-brown-fox-1234567890-abcdef" challenge := s256Challenge(verifier) - // Note: NO resource= AND NO audience= — exactly Claude Desktop's - // real-world authorize-request shape. + // NO resource= AND NO audience=. q := url.Values{ "client_id": {clientID}, "response_type": {"code"}, @@ -726,9 +710,21 @@ func TestOAuth_Authorize_AcceptsNoResource_DefaultsToCanonical(t *testing.T) { "state": {"no-resource-state"}, } rr := doAuthedRequest(srv, "GET", "/oauth/authorize?"+q.Encode(), nil, sessionToken) - if rr.Code != http.StatusOK { - t.Fatalf("expected 200 (consent stub) for no-resource request; got %d (Location: %s, Body: %s)", - rr.Code, rr.Header().Get("Location"), rr.Body.String()) + if rr.Code != http.StatusSeeOther && rr.Code != http.StatusFound { + t.Fatalf("expected a redirect carrying the error; got %d (Body: %s)", rr.Code, rr.Body.String()) + } + loc, err := url.Parse(rr.Header().Get("Location")) + if err != nil { + t.Fatal(err) + } + if got := loc.Scheme + "://" + loc.Host + loc.Path; got != "https://app.test/cb" { + t.Fatalf("the error went to %q, not the client's redirect_uri", got) + } + if loc.Query().Get("error") != "invalid_target" || loc.Query().Get("code") != "" { + t.Fatalf("want error=invalid_target and no code, got %s", loc.RawQuery) + } + if loc.Query().Get("state") != "no-resource-state" { + t.Fatalf("the error lost the client's state: %s", loc.RawQuery) } } @@ -770,6 +766,7 @@ func TestOAuth_ConsentScreen_NonceCSPLetsInlineScriptRun(t *testing.T) { "code_challenge": {challenge}, "code_challenge_method": {"S256"}, "state": {"nonce-csp-state"}, + "resource": {testCanonicalAudience}, } rr := doAuthedRequest(srv, "GET", "/oauth/authorize?"+q.Encode(), nil, sessionToken) if rr.Code != http.StatusOK { diff --git a/internal/server/task3321_u2a_audience_test.go b/internal/server/task3321_u2a_audience_test.go index 7264f4e2f..a5f77db74 100644 --- a/internal/server/task3321_u2a_audience_test.go +++ b/internal/server/task3321_u2a_audience_test.go @@ -184,9 +184,10 @@ func TestU2a_TokensAreBoundToOneResourceAndRefusedAtTheOther(t *testing.T) { if code != http.StatusOK { t.Fatalf("minting a ChatGPT token: %d", code) } - noResTok, code := mintWithResource(t, srv, sess, "") - if code != http.StatusOK { - t.Fatalf("minting a no-resource token: %d", code) + // No resource on the request: refused since TASK-3363 phase 2, so no + // token exists to be bound to a default. + if _, code := mintWithResource(t, srv, sess, ""); code == http.StatusOK { + t.Fatalf("minting a no-resource token succeeded; TASK-3363 phase 2 refuses it") } cases := []struct { @@ -199,11 +200,6 @@ func TestU2a_TokensAreBoundToOneResourceAndRefusedAtTheOther(t *testing.T) { {"/mcp token at the ChatGPT mount: refused", mcpTok, testChatGPTResource, http.StatusUnauthorized}, {"ChatGPT token at the ChatGPT mount", gptTok, testChatGPTResource, http.StatusOK}, {"ChatGPT token at /mcp: refused", gptTok, "", http.StatusUnauthorized}, - // No resource on the request: bound to /mcp's canonical (the - // documented default for clients that omit it), so it works at - // /mcp and is refused at the ChatGPT mount. ChatGPT always sends one. - {"no-resource token at /mcp", noResTok, "", http.StatusOK}, - {"no-resource token at the ChatGPT mount: refused", noResTok, testChatGPTResource, http.StatusUnauthorized}, } for _, c := range cases { if got := atMount(srv, c.resource, c.token); got != c.want { diff --git a/internal/server/task3363_resource_missing_test.go b/internal/server/task3363_resource_missing_test.go index 900445920..83c0a9929 100644 --- a/internal/server/task3363_resource_missing_test.go +++ b/internal/server/task3363_resource_missing_test.go @@ -15,10 +15,10 @@ import ( "github.com/PerpetualSoftware/pad/internal/metrics" ) -// TASK-3363 phase 1: a request that omits the RFC 8707 resource parameter is -// still defaulted to the canonical audience (phase 2 refuses it), and each -// one is now counted per endpoint, so the refusal can be measured first. -func TestTASK3363_MissingResourceIsCountedPerEndpoint(t *testing.T) { +// TASK-3363 phase 2: a consent decision that omits the RFC 8707 resource +// parameter is REFUSED with invalid_target, and counted. With resource it is +// served and nothing is counted. +func TestTASK3363_MissingResourceIsRefusedAndCounted(t *testing.T) { srv := twoResourceOAuthServer(t) m := metrics.New() srv.SetMetrics(m) @@ -31,7 +31,6 @@ func TestTASK3363_MissingResourceIsCountedPerEndpoint(t *testing.T) { } sess := newOAuthSession(t, srv) - // With resource on both legs: nothing is counted. if _, code := mintWithResource(t, srv, sess, testCanonicalAudience); code != 200 { t.Fatalf("mint with resource: %d", code) } @@ -39,18 +38,17 @@ func TestTASK3363_MissingResourceIsCountedPerEndpoint(t *testing.T) { t.Fatalf("a request WITH resource was counted: decide=%v token=%v", count("decide"), count("token")) } - // Without: still served (phase 1 changes no behaviour), and counted at - // both the consent decision and the token exchange. - if _, code := mintWithResource(t, srv, sess, ""); code != 200 { - t.Fatalf("mint without resource: %d (phase 1 must not refuse)", code) + // Without: refused at the decision, so no code and no token exchange. + if _, code := mintWithResource(t, srv, sess, ""); code == 200 { + t.Fatal("mint without resource was served; phase 2 refuses it") } - if count("decide") != 1 || count("token") != 1 { - t.Fatalf("a request WITHOUT resource: decide=%v token=%v, want 1 and 1", count("decide"), count("token")) + if count("decide") != 1 || count("token") != 0 { + t.Fatalf("a decision WITHOUT resource: decide=%v token=%v, want 1 and 0", count("decide"), count("token")) } } -// The authorize step (the consent page) counts too. -func TestTASK3363_AuthorizeWithoutResourceIsCounted(t *testing.T) { +// The authorize step refuses too, at the client's redirect_uri, and counts. +func TestTASK3363_AuthorizeWithoutResourceIsRefusedAndCounted(t *testing.T) { srv := twoResourceOAuthServer(t) m := metrics.New() srv.SetMetrics(m) @@ -60,8 +58,10 @@ func TestTASK3363_AuthorizeWithoutResourceIsCounted(t *testing.T) { "scope": {"pad:read"}, "code_challenge": {s256Challenge("verifier-3363-abcdefghijklmnopqrstuvwxyz0123456789")}, "code_challenge_method": {"S256"}, "state": {"state-3363-01"}, } - if rr := doRequestWithCookie(srv, "GET", "/oauth/authorize?"+q.Encode(), nil, sess.sessionToken); rr.Code != 200 { - t.Fatalf("consent page without resource: %d (phase 1 must not refuse)", rr.Code) + rr := doRequestWithCookie(srv, "GET", "/oauth/authorize?"+q.Encode(), nil, sess.sessionToken) + loc, _ := url.Parse(rr.Header().Get("Location")) + if (rr.Code != http.StatusSeeOther && rr.Code != http.StatusFound) || loc == nil || loc.Query().Get("error") != "invalid_target" { + t.Fatalf("authorize without resource: %d %s, want a redirect with error=invalid_target", rr.Code, rr.Header().Get("Location")) } var pb io_prometheus_client.Metric if err := m.OAuthResourceMissingTotal.WithLabelValues("authorize").Write(&pb); err != nil { @@ -72,6 +72,56 @@ func TestTASK3363_AuthorizeWithoutResourceIsCounted(t *testing.T) { } } +// The token endpoint is NOT refused (RFC 8707 makes resource optional there), +// and that is safe only because the grant binds the audience: a code granted +// for the ChatGPT resource, exchanged WITHOUT resource (so the request is +// defaulted to /mcp's canonical), still yields a token bound to the ChatGPT +// resource, refused at /mcp. The exchange is counted. +func TestTASK3363_TokenExchangeWithoutResourceKeepsTheGrantedAudience(t *testing.T) { + srv := twoResourceOAuthServer(t) + m := metrics.New() + srv.SetMetrics(m) + sess := newOAuthSession(t, srv) + + verifier := "verifier-3363-tok-abcdefghijklmnopqrstuvwxyz0123456789ABCDEF" + form := url.Values{ + "client_id": {sess.clientID}, "response_type": {"code"}, "redirect_uri": {"https://app.test/cb"}, + "code_challenge": {s256Challenge(verifier)}, "code_challenge_method": {"S256"}, + "scope": {"pad:read"}, "state": {"state-3363-tok-01"}, "decision": {"approve"}, + "csrf_token": {sess.csrfTok}, "capability_tier": {"read"}, "allowed_workspaces": {"*"}, + "resource": {testChatGPTResource}, + } + rr := postFormWithCookie(srv, "/oauth/authorize/decide", form, sess.sessionToken, sess.csrfTok) + cb, _ := url.Parse(rr.Header().Get("Location")) + code := cb.Query().Get("code") + if code == "" { + t.Fatalf("decide with resource: %d %s", rr.Code, rr.Header().Get("Location")) + } + trr := postOAuthForm(srv, "/oauth/token", url.Values{ + "grant_type": {"authorization_code"}, "code": {code}, "client_id": {sess.clientID}, + "redirect_uri": {"https://app.test/cb"}, "code_verifier": {verifier}, + }) + if trr.Code != http.StatusOK { + t.Fatalf("token exchange without resource: %d %s (RFC 8707: optional here)", trr.Code, trr.Body.String()) + } + var resp map[string]any + parseJSON(t, trr, &resp) + tok, _ := resp["access_token"].(string) + if got := atMount(srv, testChatGPTResource, tok); got != http.StatusOK { + t.Fatalf("the token is not served at its granted (ChatGPT) mount: %d", got) + } + if got := atMount(srv, "", tok); got != http.StatusUnauthorized { + t.Fatalf("the default widened the grant: the ChatGPT-granted token is served at /mcp (%d)", got) + } + var pb io_prometheus_client.Metric + if err := m.OAuthResourceMissingTotal.WithLabelValues("token").Write(&pb); err != nil { + t.Fatal(err) + } + if got := pb.GetCounter().GetValue(); got != 1 { + t.Fatalf("the token exchange without resource counted %v, want 1", got) + } +} + // The log line is half the phase-1 signal: it must name the endpoint and the // client, including a client that sends its id by HTTP Basic auth. Not // parallel: it swaps the default logger.