From 77425dcd6842db541746107b5ba4e82b3206ef4d Mon Sep 17 00:00:00 2001 From: Chris Burns <29541485+ChrisJBurns@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:47:21 +0000 Subject: [PATCH 1/2] test(identityharness): retire the fake AS-1; identity tests use the real AS-1 Every identity test that needs an AS-1 now runs against ToolHive's embedded authorization server hosted by as1server: mecak8s session ownership, TUI and clientauth sign-in, session-open checks, AS-2 redemption, and AS-1's own revoked answer. Forged tokens come from as1servertest.Forge, RFC 7009 client authentication is tested against a stub until AS-1 serves the route (stacklok/toolhive#6966), and a test-only RevokeGrant, which forbidigo keeps out of production, lets tests see AS-1 refuse a revoked grant. The fake AS-1, its self-tests, and the harness revocation fixture are deleted; the harness keeps the upstream IdP, the consent helper, the fault transport, the CA and key helpers, and the gateway stand-in. Closes #2858. Co-authored-by: Mecatl --- .golangci.yml | 21 +- cmd/mecak8s/identity_broker_harness_test.go | 227 +++---- cmd/mecak8s/identity_broker_real_as1_test.go | 53 +- cmd/mecak8s/tui_sign_in_harness_test.go | 34 +- .../adapter/clientauth/as1_signin_test.go | 40 +- internal/adapter/mcp/gatewaycall_test.go | 20 +- internal/adapter/mcpbroker/as2_test.go | 137 ++-- internal/app/build.go | 4 +- .../adapter/as1server/as1server.go | 36 +- .../as1server/as1servertest/actorvalidator.go | 34 - .../as1server/as1servertest/as1servertest.go | 64 +- .../adapter/as1server/revoke_test.go | 49 ++ .../adapter/authserverclient/client_test.go | 213 +++--- .../authorize_integration_test.go | 139 ++-- internal/identitybroker/sessionopen_test.go | 43 +- internal/testutil/identityharness/as1.go | 616 ------------------ internal/testutil/identityharness/broker.go | 82 --- internal/testutil/identityharness/browser.go | 6 +- .../testutil/identityharness/clientauth.go | 202 ------ .../identityharness/clientauth_test.go | 212 ------ .../identityharness/faulttransport.go | 23 +- .../identityharness/faulttransport_test.go | 163 +++-- .../testutil/identityharness/gateway_test.go | 28 +- internal/testutil/identityharness/harness.go | 253 ++----- .../testutil/identityharness/harness_test.go | 499 -------------- internal/testutil/identityharness/idjag.go | 222 ------- .../testutil/identityharness/idjag_test.go | 256 -------- internal/testutil/identityharness/idp.go | 44 +- internal/testutil/identityharness/idp_test.go | 171 +++++ internal/testutil/identityharness/oauth.go | 47 +- internal/testutil/identityharness/revoke.go | 37 -- .../testutil/identityharness/sessionopen.go | 333 ---------- .../identityharness/sessionopen_test.go | 383 ----------- internal/testutil/identityharness/signin.go | 168 ----- 34 files changed, 1041 insertions(+), 3818 deletions(-) delete mode 100644 internal/identitybroker/adapter/as1server/as1servertest/actorvalidator.go create mode 100644 internal/identitybroker/adapter/as1server/revoke_test.go delete mode 100644 internal/testutil/identityharness/as1.go delete mode 100644 internal/testutil/identityharness/broker.go delete mode 100644 internal/testutil/identityharness/clientauth.go delete mode 100644 internal/testutil/identityharness/clientauth_test.go delete mode 100644 internal/testutil/identityharness/harness_test.go delete mode 100644 internal/testutil/identityharness/idjag.go delete mode 100644 internal/testutil/identityharness/idjag_test.go create mode 100644 internal/testutil/identityharness/idp_test.go delete mode 100644 internal/testutil/identityharness/revoke.go delete mode 100644 internal/testutil/identityharness/sessionopen.go delete mode 100644 internal/testutil/identityharness/sessionopen_test.go delete mode 100644 internal/testutil/identityharness/signin.go diff --git a/.golangci.yml b/.golangci.yml index 47f006f54a..4542101a61 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1045,9 +1045,9 @@ linters: - github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server$ - github.com/stacklok/mecatl/internal/identitybroker/adapter/authserverclient$ - github.com/stacklok/mecatl/internal/testutil/identityharness$ - # The identity harness stands in for the IdP, AS-1, AS-2, and the - # gateway; it never imports the code under test, so a broker bug - # cannot also bend the stand-in. Its external tests import the harness + # The identity harness stands in for the IdP and the gateway; it + # never imports the code under test, so a broker bug cannot also bend + # the stand-in. Its external tests import the harness # itself, the one Mecatl package allowed. internal-testutil-identityharness: list-mode: lax @@ -1287,6 +1287,13 @@ linters: msg: 'global slog is banned in engine/ and internal/: only cmd/ mains may install a slog default (the third-party-slog bridge). Everything else must take a port.Diagnostics.' - pattern: 'slog\.(Info|Warn|Debug|Error)(Context)?\b' msg: 'package-level slog.* is banned in engine/ and internal/: log through the injected port.Diagnostics seam, not the global logger.' + # as1server.Server.RevokeGrant revokes in AS-1's storage, past AS-1's + # handler, client authentication, and ownership checks. It exists so + # tests can see AS-1 answer revoked; production revokes through + # AS-1's RFC 7009 route (stacklok/toolhive#6966). Tests and + # as1servertest are excluded below. + - pattern: '\.RevokeGrant\b' + msg: 'RevokeGrant is test-only: it bypasses AS-1''s handler and client authentication. Production revokes through AS-1''s RFC 7009 route (stacklok/toolhive#6966).' goconst: ignore-tests: true min-occurrences: 5 @@ -1450,14 +1457,22 @@ linters: # redirects the default to a file — so they MUST be allowed # slog.Default/SetDefault. The ban exists to keep the engine and the adapters # on the injected port.Diagnostics seam, not to police the mains. + # The text match keeps the RevokeGrant ban in force in cmd/. - linters: - forbidigo path: (^|.*/)cmd/ + text: slog # Test files may name the banned patterns in literals/messages (e.g. the guard # test asserting the rule bites, or doc-comments referencing slog.Warn). - linters: - forbidigo path: (.+)_test\.go + # as1servertest is the real-AS-1 test fixture; it may revoke in AS-1's + # storage for the tests that use it. + - linters: + - forbidigo + path: internal/identitybroker/adapter/as1server/as1servertest/ + text: RevokeGrant # SessionID and ToolSpec are deliberate, frozen domain names from the WP1 # ports that other packages depend on. revive flags them as "stutter" # (session.SessionID / tool.ToolSpec) but renaming would break the public diff --git a/cmd/mecak8s/identity_broker_harness_test.go b/cmd/mecak8s/identity_broker_harness_test.go index 6a53a38278..e0baeda44b 100644 --- a/cmd/mecak8s/identity_broker_harness_test.go +++ b/cmd/mecak8s/identity_broker_harness_test.go @@ -3,9 +3,6 @@ package main import ( "bufio" "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" "encoding/json" "errors" "fmt" @@ -38,58 +35,32 @@ import ( "github.com/stacklok/mecatl/internal/testutil/identityharness" ) -// TestIdentityBrokerAgainstOfflineHarness starts mecak8s with the identity -// broker on and AS-1 as its token issuer, all offline. Users sign in through -// the harness's AS-1 and upstream IdP; their AS-1 access tokens authenticate -// API requests and own the sessions they create, and tokens AS-1 would not +// TestIdentityBrokerOwnsSessionsAgainstRealAS1 starts mecak8s with the +// identity broker on and the real AS-1, built by the test with the harness +// IdP as its upstream, as its token issuer, all offline. Users sign in at +// AS-1, through two accepted clients; their access tokens authenticate API +// requests and own the sessions they create, and tokens AS-1 would not // issue are refused. Session open converts each user's access token at AS-1 -// into a refresh token the broker holds for the session. Later identity work -// extends this test as it adds steps. -// -// It stays on the harness's AS-1, not the real one, because it mints a second -// client's access token and moves AS-1's clock with the broker's. -// TestIdentityBrokerAgainstRealAS1 proves the session close and hard-expiry -// reopen against the real AS-1, and TestIdentityBrokerGatewayCallAgainstRealAS1 -// the gateway calls. -func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { - // The broker authenticates to AS-1 with its client key, which AS-1 holds - // registered for the broker's client. - clientKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - signer, err := identitybroker.NewClientAssertionSigner(clientKey, 0) - if err != nil { - t.Fatal(err) - } - // AS-1 and the broker share one clock, which the test moves past the - // sessions' hard expiry; AS-1 checks the broker's client assertions - // against it, so the broker's AS-1 client uses it too. - var clockOffset atomic.Int64 - now := func() time.Time { return time.Now().Add(time.Duration(clockOffset.Load())) } - const grantMaxLifetime = 5 * time.Minute - h := identityharness.New(t, identityharness.Options{ - BrokerKeys: []identityharness.BrokerKey{{KeyID: signer.JWKS().Keys[0].KeyID, Public: &clientKey.PublicKey}}, - Now: now, - GrantMaxLifetime: grantMaxLifetime, +// into a refresh token the broker holds for the session. +// TestIdentityBrokerAgainstRealAS1 proves the hard-expiry close and reopen, +// and TestIdentityBrokerGatewayCallAgainstRealAS1 the gateway calls. +func TestIdentityBrokerOwnsSessionsAgainstRealAS1(t *testing.T) { + h := identityharness.New(t, identityharness.Options{}) + studio := as1server.PublicClient{ID: "studio", RedirectURIs: []string{"http://127.0.0.1:18474/oauth/callback"}} + a := as1servertest.Start(t, h, func(c *as1server.Config, _ *as1server.DelegateClient) { + c.PublicClients = append(c.PublicClients, studio) }) api, built := serveIdentityBroker(t, identityBrokerAS1Tokens{ - issuer: h.AS1.Issuer(), audience: h.AS1.Audience(), caFile: h.WriteCACert(t, t.TempDir()), - clientIDs: identityharness.DefaultClientID + ",studio", + issuer: a.Issuer(), audience: as1servertest.Audience, caFile: h.WriteCACert(t, t.TempDir()), + clientIDs: as1servertest.PublicClientID + "," + studio.ID, }, &app.IdentityBrokerAS1{ - Issuer: h.AS1.Issuer(), TokenEndpoint: h.AS1.TokenEndpoint(), HTTPClient: h.HTTPClient(), ClientKey: clientKey, Now: now, AssertionNow: now, + Issuer: a.Issuer(), TokenEndpoint: a.Server.TokenEndpoint(), HTTPClient: a.HTTPClient(), ClientKey: a.Key, }, nil, nil) - alice, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: identityharness.Alice}) - if err != nil { - t.Fatalf("Alice signs in: %v", err) - } - bob, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: identityharness.Bob}) - if err != nil { - t.Fatalf("Bob signs in: %v", err) - } + alice := a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value() + bob := a.SignIn(t, as1servertest.SignIn{User: identityharness.Bob}).Value() - status, body := apiCall(t, http.MethodPost, api+"/v1/sessions", alice.AccessToken, "{}") + status, body := apiCall(t, http.MethodPost, api+"/v1/sessions", alice, "{}") if status != http.StatusCreated && status != http.StatusOK { t.Fatalf("Alice creates a session: status %d: %s", status, body) } @@ -103,15 +74,15 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { // issuer and pseudonymous subject. aliceCompany := identitybroker.Owner{Issuer: h.IdP.Issuer(), Subject: identityharness.Alice} bobCompany := identitybroker.Owner{Issuer: h.IdP.Issuer(), Subject: identityharness.Bob} - if owners := listSessionOwners(t, api, alice.AccessToken); owners[created.ID] != aliceCompany { + if owners := listSessionOwners(t, api, alice); owners[created.ID] != aliceCompany { t.Errorf("Alice's sessions %v: %s owner = %+v, want %+v", owners, created.ID, owners[created.ID], aliceCompany) } // The second accepted client carries the same identity. - studio := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: identityharness.Alice, ClientID: "studio"}) - if owners := listSessionOwners(t, api, studio); owners[created.ID] != aliceCompany { + throughStudio := a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice, Client: studio}).Value() + if owners := listSessionOwners(t, api, throughStudio); owners[created.ID] != aliceCompany { t.Errorf("Alice through studio: sessions %v, want %s owned by %+v", owners, created.ID, aliceCompany) } - if _, listed := listSessionOwners(t, api, bob.AccessToken)[created.ID]; listed { + if _, listed := listSessionOwners(t, api, bob)[created.ID]; listed { t.Errorf("Bob's sessions include Alice's %s", created.ID) } @@ -134,12 +105,12 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { t.Errorf("broker session owner = %+v, want Alice's company identity %+v", opened.Owner, aliceCompany) } // Creating the session converted Alice's sign-in at AS-1: the broker holds - // a refresh token for it, from AS-1's one grant. - if !opened.HoldsRefreshToken || h.AS1.GrantsIssued() != 1 { - t.Fatalf("Alice's broker session %+v after %d grants; want it holding the refresh token of AS-1's one grant", opened, h.AS1.GrantsIssued()) + // a refresh token for it, from AS-1's one conversion. + if !opened.HoldsRefreshToken || a.Faults.Conversions() != 1 { + t.Fatalf("Alice's broker session %+v after %d conversions; want it holding the refresh token of AS-1's one conversion", opened, a.Faults.Conversions()) } - status, body = apiCall(t, http.MethodPost, api+"/v1/sessions", bob.AccessToken, "{}") + status, body = apiCall(t, http.MethodPost, api+"/v1/sessions", bob, "{}") if status != http.StatusCreated && status != http.StatusOK { t.Fatalf("Bob creates a session: status %d: %s", status, body) } @@ -152,22 +123,22 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { if bobs, ok := findBrokerSession(bobCreated.ID); !ok || bobs.Owner != bobCompany || !bobs.HoldsRefreshToken { t.Errorf("Bob's broker session = %+v, %v; want one owned by %+v holding a refresh token", bobs, ok, bobCompany) } - grants := h.AS1.GrantsIssued() + conversions := a.Faults.Conversions() // The run passes run entry, which finds the open broker session and keeps it. const aliceTitle, alicePrompt = "alice-private-title", "alice-private-prompt" - if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/rename", alice.AccessToken, `{"title":"`+aliceTitle+`"}`); status != http.StatusOK { + if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/rename", alice, `{"title":"`+aliceTitle+`"}`); status != http.StatusOK { t.Fatalf("Alice renames her session: status %d: %s", status, body) } - if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/prompt", alice.AccessToken, `{"text":"`+alicePrompt+`"}`); status != http.StatusOK { + if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/prompt", alice, `{"text":"`+alicePrompt+`"}`); status != http.StatusOK { t.Fatalf("Alice prompts her session: status %d: %s", status, body) } if got, ok := findBrokerSession(created.ID); !ok || got != opened { t.Errorf("after a run, broker session = %+v, %v; want %+v", got, ok, opened) } // A session that holds a refresh token does not spend later requests' tokens. - if n := h.AS1.GrantsIssued(); n != grants { - t.Errorf("the run converted a token: %d grants, want %d", n, grants) + if n := a.Faults.Conversions(); n != conversions { + t.Errorf("the run converted a token: %d conversions, want %d", n, conversions) } // Another user's session is not found, never forbidden, so its existence, @@ -187,7 +158,7 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { if c.method == http.MethodPost { body = "{}" } - status, resp := apiCall(t, c.method, api+"/v1/sessions/"+created.ID+c.path, bob.AccessToken, body) + status, resp := apiCall(t, c.method, api+"/v1/sessions/"+created.ID+c.path, bob, body) if status != c.want || (c.want == http.StatusNotFound && !strings.Contains(resp, "session_not_found")) { t.Errorf("Bob %s %s on Alice's session: status %d: %s; want %d", c.method, c.path, status, resp, c.want) } @@ -195,26 +166,26 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { t.Errorf("Bob %s %s on Alice's session disclosed her title or prompt: %s", c.method, c.path, resp) } } - if status, resp := apiCall(t, http.MethodGet, api+"/v1/sessions/"+created.ID, alice.AccessToken, ""); status != http.StatusOK || !strings.Contains(resp, aliceTitle) { + if status, resp := apiCall(t, http.MethodGet, api+"/v1/sessions/"+created.ID, alice, ""); status != http.StatusOK || !strings.Contains(resp, aliceTitle) { t.Errorf("after Bob's delete, Alice gets her session: status %d: %s; want it intact", status, resp) } - if status, resp := apiCall(t, http.MethodGet, api+"/v1/sessions/"+created.ID+"/transcript", alice.AccessToken, ""); status != http.StatusOK || !strings.Contains(resp, alicePrompt) { + if status, resp := apiCall(t, http.MethodGet, api+"/v1/sessions/"+created.ID+"/transcript", alice, ""); status != http.StatusOK || !strings.Contains(resp, alicePrompt) { t.Errorf("Alice reads her transcript: status %d: %s; want her prompt", status, resp) } // Alice's sign-in token was converted for her first session, and a token // converts once: a fork with it is refused, retryably, before it creates // anything. - sessionsBefore := len(listSessionOwners(t, api, alice.AccessToken)) - status, body, challenge := apiRequest(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/fork", alice.AccessToken, "{}") + sessionsBefore := len(listSessionOwners(t, api, alice)) + status, body, challenge := apiRequest(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/fork", alice, "{}") if status != http.StatusUnauthorized || !strings.Contains(body, `"bearer_rejected"`) || challenge != `Bearer error="invalid_token"` { t.Fatalf("Alice forks with her spent token: status %d, challenge %q: %s; want 401 bearer_rejected with an invalid_token challenge", status, challenge, body) } - if n := len(listSessionOwners(t, api, alice.AccessToken)); n != sessionsBefore { + if n := len(listSessionOwners(t, api, alice)); n != sessionsBefore { t.Fatalf("the refused fork created a session: %d sessions, want %d", n, sessionsBefore) } - // Her client refreshes its token and retries. - refreshed := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: identityharness.Alice}) + // Her client gets a new token and retries. + refreshed := a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value() status, body = apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/fork", refreshed, "{}") if status != http.StatusCreated && status != http.StatusOK { t.Fatalf("Alice forks her session: status %d: %s", status, body) @@ -229,33 +200,60 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { t.Errorf("fork's broker session = %+v, %v; want its own, owned by Alice, holding a refresh token", fork, ok) } - if status, body := apiCall(t, http.MethodDelete, api+"/v1/sessions/"+created.ID, alice.AccessToken, ""); status >= 300 { + if status, body := apiCall(t, http.MethodDelete, api+"/v1/sessions/"+created.ID, alice, ""); status >= 300 { t.Fatalf("Alice releases her session: status %d: %s", status, body) } if got, ok := findBrokerSession(created.ID); !ok || got != opened { t.Errorf("after releasing the session, broker session = %+v, %v; want %+v", got, ok, opened) } - if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/delete", alice.AccessToken, ""); status >= 300 { + if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+created.ID+"/delete", alice, ""); status >= 300 { t.Fatalf("Alice deletes her session: status %d: %s", status, body) } if _, ok := findBrokerSession(created.ID); ok { t.Error("deleting Alice's session left its broker session open") } + // Tokens AS-1 would not issue are refused. Each forgery changes one thing + // in an access token AS-1 issued and, unless it changes the key, is + // signed again with AS-1's key, so it is refused for that change alone: + // the unchanged re-signed token is accepted. + issued := identitybroker.NewToken(refreshed) + forge := func(f as1servertest.Forgery) string { return a.Forge(t, issued, f).Value() } + claim := func(name string, value any) as1servertest.Forgery { + return as1servertest.Forgery{Claims: func(c jwt.MapClaims) { + if value == nil { + delete(c, name) + return + } + c[name] = value + }} + } + typ := func(value string) as1servertest.Forgery { + return as1servertest.Forgery{Header: func(h map[string]any) { + if value == "" { + delete(h, "typ") + return + } + h["typ"] = value + }} + } + if status, body := apiCall(t, http.MethodGet, api+"/v1/sessions", forge(as1servertest.Forgery{}), ""); status != http.StatusOK { + t.Fatalf("an AS-1 access token signed again unchanged: status %d: %s; want 200", status, body) + } for name, token := range map[string]string{ "no token": "", - "foreign key": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{ForeignKey: true}), - "other audience": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Audience: "https://other.test/api"}), - "other issuer": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Issuer: h.IdP.Issuer()}), - "expired": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Lifetime: -time.Hour}), - "typ JWT": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Type: "JWT"}), - "no typ": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{OmitType: true}), - "alg none": unsignedToken(t, h.AS1.Issuer(), h.AS1.Audience()), // toolhive-core's fixed algorithm allowlist rejects this - "other client": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{ClientID: "rogue"}), - "no sub_id": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{OmitSubID: true}), - "sub_id format": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{SubID: map[string]string{"format": "email", "iss": h.IdP.Issuer(), "sub": identityharness.Alice}}), - "sub_id string": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{SubID: identityharness.Alice}), - "sub_id no sub": h.AS1.MintAccessToken(identityharness.AccessTokenSpec{SubID: map[string]string{"format": "iss_sub", "iss": h.IdP.Issuer()}}), + "foreign key": forge(as1servertest.Forgery{ForeignKey: true}), + "other audience": forge(claim("aud", "https://other.test/api")), + "other issuer": forge(claim("iss", h.IdP.Issuer())), + "expired": a.ExpiredAccessToken(t, issued).Value(), + "typ JWT": forge(typ("JWT")), + "no typ": forge(typ("")), + "alg none": unsignedToken(t, a.Issuer(), as1servertest.Audience), // toolhive-core's fixed algorithm allowlist rejects this + "other client": forge(claim("client_id", "rogue")), + "no sub_id": forge(claim("sub_id", nil)), + "sub_id format": forge(claim("sub_id", map[string]string{"format": "email", "iss": h.IdP.Issuer(), "sub": identityharness.Alice})), + "sub_id string": forge(claim("sub_id", identityharness.Alice)), + "sub_id no sub": forge(claim("sub_id", map[string]string{"format": "iss_sub", "iss": h.IdP.Issuer()})), } { status, _, challenge := apiRequest(t, http.MethodGet, api+"/v1/sessions", token, "") if status != http.StatusUnauthorized { @@ -278,71 +276,12 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { if err != nil { t.Fatalf("create a session under the company IdP identity: %v", err) } - if status, body := apiCall(t, http.MethodGet, api+"/v1/sessions/"+string(legacy.ID), alice.AccessToken, ""); status != http.StatusOK { + if status, body := apiCall(t, http.MethodGet, api+"/v1/sessions/"+string(legacy.ID), alice, ""); status != http.StatusOK { t.Errorf("Alice through AS-1 gets her pre-AS-1 session: status %d: %s", status, body) } - if status, _ := apiCall(t, http.MethodGet, api+"/v1/sessions/"+string(legacy.ID), bob.AccessToken, ""); status != http.StatusNotFound { + if status, _ := apiCall(t, http.MethodGet, api+"/v1/sessions/"+string(legacy.ID), bob, ""); status != http.StatusNotFound { t.Errorf("Bob gets Alice's pre-AS-1 session: status %d, want 404", status) } - - // Hard expiry: a broker session holding a refresh token closes when the - // grant expires, and the user's next request opens a new one for the same - // agent. The fork and Bob's session each converted a token, so each has a - // hard expiry. - expiring, ok := findBrokerSession(forked.ID) - if !ok || !expiring.HoldsRefreshToken { - t.Fatalf("fork's broker session = %+v, %v; want one holding a refresh token", expiring, ok) - } - bobsExpiring, ok := findBrokerSession(bobCreated.ID) - if !ok || !bobsExpiring.HoldsRefreshToken { - t.Fatalf("Bob's broker session = %+v, %v; want one holding a refresh token", bobsExpiring, ok) - } - registerMain := func(brokerSession string) (identitybroker.Registration, error) { - return built.IdentityBroker.RegisterAgent(t.Context(), identitybroker.RegisterAgentRequest{ - SessionID: brokerSession, HostSessionID: forked.ID, Owner: aliceCompany, Incarnation: expiring.Incarnation, - Definition: identitybroker.DefinitionRef{Source: "system", Name: "main"}, - }) - } - before, err := registerMain(expiring.ID) - if err != nil { - t.Fatalf("register the fork's main agent: %v", err) - } - clockOffset.Store(int64(grantMaxLifetime + time.Second)) - closed := identitybroker.ReasonError(identitybroker.ReasonSessionClosed, "") - if _, err := registerMain(expiring.ID); !errors.Is(err, closed) { - t.Errorf("register in the expired broker session = %v, want %v", err, closed) - } - if _, err := built.IdentityBroker.AuthorizeCall(t.Context(), identitybroker.AuthorizeCallRequest{ - SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", RunID: "R42", RunOwner: aliceCompany, - Method: identitybroker.MethodToolsCall, Server: "gateway", Tool: "search", ArgumentsSHA256: strings.Repeat("ab", 32), - }); !errors.Is(err, closed) { - t.Errorf("authorize in the expired broker session = %v, want %v", err, closed) - } - // A fresh token is issued now by the API's clock, which the test did not - // move; it is still live on AS-1's, as the move is shorter than its - // lifetime. - fresh := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: identityharness.Alice, IssuedAt: time.Now()}) - if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+forked.ID+"/prompt", fresh, `{"text":"after expiry"}`); status != http.StatusOK { - t.Fatalf("Alice prompts her fork after its broker session expired: status %d: %s", status, body) - } - reopened, ok := findBrokerSession(forked.ID) - if !ok || reopened.ID == expiring.ID || !reopened.HoldsRefreshToken { - t.Fatalf("fork's broker session after expiry = %+v, %v; want a new one holding a refresh token", reopened, ok) - } - // The 200 means the prompt's run entry registered the main agent in the - // new broker session (TestIdentityBrokerRegistersAgainInAReopenedBrokerSession - // pins that at the server); registering again here returns its agent. - if after, err := registerMain(reopened.ID); err != nil || after.Agent != before.Agent { - t.Errorf("register in the new broker session = %+v, %v; want agent %+v", after.Agent, err, before.Agent) - } - // A tokenless open after the expiry pairs a new session that holds no - // refresh token. - bobsReopened, err := built.IdentityBroker.OpenSession(t.Context(), identitybroker.OpenSessionRequest{ - HostSessionID: bobCreated.ID, Incarnation: bobsExpiring.Incarnation, Owner: bobCompany, - }) - if err != nil || bobsReopened.ID == bobsExpiring.ID || bobsReopened.HoldsRefreshToken { - t.Errorf("Bob's tokenless open after expiry = %+v, %v; want a new broker session holding no refresh token", bobsReopened, err) - } } // gatewayCallbackURL is the MCP broker callback the gateway test configures; diff --git a/cmd/mecak8s/identity_broker_real_as1_test.go b/cmd/mecak8s/identity_broker_real_as1_test.go index 4c789f7031..29da744d52 100644 --- a/cmd/mecak8s/identity_broker_real_as1_test.go +++ b/cmd/mecak8s/identity_broker_real_as1_test.go @@ -19,7 +19,8 @@ import ( // and the real AS-1, built by the test with the harness IdP as its upstream, // as both the issuer of API access tokens and the authorization server // session open converts them at. Once a broker session's hard expiry passes, -// the session is closed, and a new sign-in opens a new one. AS-1 stamps a grant's expiry with wall time, so +// the session is closed, and a new sign-in opens a new one, for a session and +// for its fork alike. AS-1 stamps a grant's expiry with wall time, so // the test moves only the broker's clock past it, observes the close through // calls that do not reach AS-1, and moves the clock back before a new sign-in // reopens the session. @@ -72,19 +73,42 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { if !ok || bobsExpiring.Owner != bobCompany || !bobsExpiring.HoldsRefreshToken || a.Faults.Conversions() != 2 { t.Fatalf("Bob's broker session = %+v, %v after %d conversions; want his holding a refresh token", bobsExpiring, ok, a.Faults.Conversions()) } - registerMain := func(brokerSession string) (identitybroker.Registration, error) { + // Alice forks her session with a new sign-in; the fork gets its own + // broker session, which converts that sign-in. + status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+aliceID+"/fork", a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value(), "{}") + var forked struct { + ID string `json:"session_id"` + } + if status != http.StatusCreated && status != http.StatusOK || json.Unmarshal([]byte(body), &forked) != nil || forked.ID == "" { + t.Fatalf("Alice forks her session: status %d: %s", status, body) + } + forkExpiring, ok := findBrokerSession(forked.ID) + if !ok || forkExpiring.ID == expiring.ID || forkExpiring.Owner != aliceCompany || !forkExpiring.HoldsRefreshToken || a.Faults.Conversions() != 3 { + t.Fatalf("the fork's broker session = %+v, %v after %d conversions; want its own holding a refresh token", forkExpiring, ok, a.Faults.Conversions()) + } + register := func(host string, s identitybroker.Session, brokerSession string) (identitybroker.Registration, error) { return built.IdentityBroker.RegisterAgent(t.Context(), identitybroker.RegisterAgentRequest{ - SessionID: brokerSession, HostSessionID: aliceID, Owner: aliceCompany, Incarnation: expiring.Incarnation, + SessionID: brokerSession, HostSessionID: host, Owner: aliceCompany, Incarnation: s.Incarnation, Definition: identitybroker.DefinitionRef{Source: "system", Name: "main"}, }) } + registerMain := func(brokerSession string) (identitybroker.Registration, error) { + return register(aliceID, expiring, brokerSession) + } + registerForkMain := func(brokerSession string) (identitybroker.Registration, error) { + return register(forked.ID, forkExpiring, brokerSession) + } before, err := registerMain(expiring.ID) if err != nil { t.Fatalf("register Alice's main agent: %v", err) } + forkBefore, err := registerForkMain(forkExpiring.ID) + if err != nil { + t.Fatalf("register the fork's main agent: %v", err) + } // Hard expiry: AS-1 granted at most its configured maximum, so moving the - // broker past it closes both sessions. (The broker's SessionGrant is not + // broker past it closes every session. (The broker's SessionGrant is not // reachable outside its package.) requests := len(a.Faults.Requests()) clockOffset.Store(int64(as1servertest.IDJAGMaxLifetime + time.Minute)) @@ -104,6 +128,12 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { if s, ok := findBrokerSession(bobID); ok { t.Errorf("Bob's expired broker session is still found: %+v", s) } + if _, err := registerForkMain(forkExpiring.ID); !errors.Is(err, closed) { + t.Errorf("register in the fork's expired broker session = %v, want %v", err, closed) + } + if s, ok := findBrokerSession(forked.ID); ok { + t.Errorf("the fork's expired broker session is still found: %+v", s) + } if n := len(a.Faults.Requests()); n != requests { t.Fatalf("observing the close sent AS-1 %d requests, want none", n-requests) } @@ -115,7 +145,7 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { t.Fatalf("Alice prompts her session after its broker session expired: status %d: %s", status, body) } reopened, ok := findBrokerSession(aliceID) - if !ok || reopened.ID == expiring.ID || reopened.Owner != aliceCompany || !reopened.HoldsRefreshToken || a.Faults.Conversions() != 3 { + if !ok || reopened.ID == expiring.ID || reopened.Owner != aliceCompany || !reopened.HoldsRefreshToken || a.Faults.Conversions() != 4 { t.Fatalf("Alice's broker session after expiry = %+v, %v after %d conversions; want a new one holding the new sign-in's refresh token", reopened, ok, a.Faults.Conversions()) } // The 200 means the prompt's run entry registered the main agent in the @@ -123,6 +153,19 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { if after, err := registerMain(reopened.ID); err != nil || after.Agent != before.Agent { t.Errorf("register in the new broker session = %+v, %v; want agent %+v", after.Agent, err, before.Agent) } + // The fork reopens the same way, in a broker session of its own. + forkFresh := a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value() + if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+forked.ID+"/prompt", forkFresh, `{"text":"after expiry"}`); status != http.StatusOK { + t.Fatalf("Alice prompts her fork after its broker session expired: status %d: %s", status, body) + } + forkReopened, ok := findBrokerSession(forked.ID) + if !ok || forkReopened.ID == forkExpiring.ID || forkReopened.ID == reopened.ID || forkReopened.Owner != aliceCompany || + !forkReopened.HoldsRefreshToken || a.Faults.Conversions() != 5 { + t.Fatalf("the fork's broker session after expiry = %+v, %v after %d conversions; want a new one of its own holding the new sign-in's refresh token", forkReopened, ok, a.Faults.Conversions()) + } + if after, err := registerForkMain(forkReopened.ID); err != nil || after.Agent != forkBefore.Agent { + t.Errorf("register in the fork's new broker session = %+v, %v; want agent %+v", after.Agent, err, forkBefore.Agent) + } // A tokenless open after the expiry pairs a new session that holds no // refresh token. bobsReopened, err := built.IdentityBroker.OpenSession(t.Context(), identitybroker.OpenSessionRequest{ diff --git a/cmd/mecak8s/tui_sign_in_harness_test.go b/cmd/mecak8s/tui_sign_in_harness_test.go index c9cc8a4c3d..f06c8aab89 100644 --- a/cmd/mecak8s/tui_sign_in_harness_test.go +++ b/cmd/mecak8s/tui_sign_in_harness_test.go @@ -21,6 +21,8 @@ import ( "github.com/stacklok/mecatl/internal/adapter/clientauth" "github.com/stacklok/mecatl/internal/adapter/credentialstore" "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" "github.com/stacklok/mecatl/internal/testutil/identityharness" "github.com/stacklok/mecatl/mcp/oauthlogin" ) @@ -130,15 +132,18 @@ func (r *resourceRecorder) grantsWithResource(want string) map[string]int { } // TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken signs the TUI's real -// client code in at the offline AS-1 (authorization code + PKCE, RFC 8707 -// resource as mecak8s's protected-resource metadata asks), then drives mecak8s over gRPC through the TUI client with the -// clientauth refresh source: each session create carries a freshly refreshed -// token with its own jti, and mecak8s accepts each and opens a broker session -// owned by the signed-in company identity. +// client code in at the real AS-1, run outside mecak8s and named by +// --oidc-issuer (authorization code + PKCE, RFC 8707 resource as mecak8s's +// protected-resource metadata asks), then drives mecak8s over gRPC through +// the TUI client with the clientauth refresh source: each session create +// carries a freshly refreshed token with its own jti, and mecak8s accepts +// each and opens a broker session owned by the signed-in company identity. +// TestHostedAS1SignsTheTUIIn does the same with the AS-1 mecak8s hosts. func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) { - h := identityharness.New(t, identityharness.Options{Clients: []identityharness.Client{ - {ID: identityharness.DefaultClientID, RedirectURIs: []string{oauthlogin.ExactRedirectURL}}, - }}) + h := identityharness.New(t, identityharness.Options{}) + a := as1servertest.Start(t, h, func(c *as1server.Config, _ *as1server.DelegateClient) { + c.PublicClients = append(c.PublicClients, as1server.PublicClient{ID: identityharness.DefaultClientID, RedirectURIs: []string{oauthlogin.ExactRedirectURL}}) + }) cfg, err := parseFlags([]string{ "--mock", "--enable-identity-broker", "--no-shell", @@ -147,8 +152,8 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) { "--http-addr", freeLoopbackPort(t), "--drain-addr", freeLoopbackPort(t), "--session-lease-k8s-namespace", "", - "--oidc-issuer", h.AS1.Issuer(), - "--oidc-audience", h.AS1.Audience(), + "--oidc-issuer", a.Issuer(), + "--oidc-audience", as1servertest.Audience, "--oidc-allow-private-https-issuer", "--oidc-ca-cert-file", h.WriteCACert(t, t.TempDir()), "--oidc-owner-identity=sub_id", @@ -176,7 +181,7 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) { // The client learns its sign-in profile, including whether to send the // RFC 8707 resource, from mecak8s's protected-resource metadata. profile := fetchProtectedResourceProfile(t, http.DefaultClient, "http://"+cfg.httpAddr+"/.well-known/oauth-protected-resource") - if len(profile.AuthorizationServers) != 1 || profile.AuthorizationServers[0] != h.AS1.Issuer() || profile.Audience != h.AS1.Audience() || profile.ClientID != identityharness.DefaultClientID { + if len(profile.AuthorizationServers) != 1 || profile.AuthorizationServers[0] != a.Issuer() || profile.Audience != as1servertest.Audience || profile.ClientID != identityharness.DefaultClientID { t.Fatalf("protected-resource metadata = %+v, want the AS-1 issuer, audience, and client", profile) } if !profile.IdentityBrokerSignIn { @@ -184,7 +189,7 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) { } identity := clientauth.Identity{ Target: cfg.grpcAddr, Issuer: profile.AuthorizationServers[0], ClientID: profile.ClientID, - Audience: profile.Audience, RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid"}, + Audience: profile.Audience, RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid", "offline_access"}, } asClient := h.HTTPClient() tokenRequests := &resourceRecorder{next: asClient.Transport} @@ -193,10 +198,13 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) { if u, err := url.Parse(authorizationURL); err != nil || u.Query().Get("resource") != profile.Audience { return oauthlogin.Result{}, errors.New("authorization request did not name the audience as resource") } - back, err := h.Authorize(ctx, authorizationURL) + back, err := h.AuthorizeWithConsent(ctx, authorizationURL) if err != nil { return oauthlogin.Result{}, err } + if back.Get("error") != "" { + return oauthlogin.Result{}, errors.New("authorization refused: " + back.Get("error")) + } return oauthlogin.Result{Code: back.Get("code"), State: back.Get("state"), Iss: back.Get("iss")}, nil }) token, err := clientauth.Login(t.Context(), clientauth.LoginConfig{Identity: identity, Presenter: presenter, HTTPClient: asClient, IdentityBrokerSignIn: profile.IdentityBrokerSignIn}) diff --git a/internal/adapter/clientauth/as1_signin_test.go b/internal/adapter/clientauth/as1_signin_test.go index 8b9e8096d0..e3669df7ec 100644 --- a/internal/adapter/clientauth/as1_signin_test.go +++ b/internal/adapter/clientauth/as1_signin_test.go @@ -12,6 +12,8 @@ import ( "sync" "testing" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" "github.com/stacklok/mecatl/internal/testutil/identityharness" "github.com/stacklok/mecatl/mcp/oauthlogin" ) @@ -57,17 +59,21 @@ type as1Fixture struct { authorizeURLs []*url.URL } +// newAS1Fixture runs the real AS-1 with the TUI's client, mecatui, at the +// loopback redirect URI oauthlogin uses, and an identity for it that asks +// for offline access, without which AS-1 issues no refresh token. func newAS1Fixture(t *testing.T) *as1Fixture { t.Helper() - h := identityharness.New(t, identityharness.Options{Clients: []identityharness.Client{ - {ID: "mecatui", RedirectURIs: []string{oauthlogin.ExactRedirectURL}}, - }}) + h := identityharness.New(t, identityharness.Options{}) + a := as1servertest.Start(t, h, func(c *as1server.Config, _ *as1server.DelegateClient) { + c.PublicClients = append(c.PublicClients, as1server.PublicClient{ID: "mecatui", RedirectURIs: []string{oauthlogin.ExactRedirectURL}}) + }) client := h.HTTPClient() recorder := &tokenFormRecorder{next: client.Transport} client.Transport = recorder id, err := Identity{ - Target: "mecatl.test:443", Issuer: h.AS1.Issuer(), ClientID: "mecatui", - Audience: h.AS1.Audience(), RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid"}, + Target: "mecatl.test:443", Issuer: a.Issuer(), ClientID: "mecatui", + Audience: as1servertest.Audience, RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid", "offline_access"}, }.Canonical() if err != nil { t.Fatalf("identity: %v", err) @@ -75,8 +81,8 @@ func newAS1Fixture(t *testing.T) *as1Fixture { return &as1Fixture{harness: h, identity: id, client: client, recorder: recorder} } -// presenter completes the browser step at the harness for the real -// authorization URL Login built. +// presenter completes the browser step, approving AS-1's consent page, for +// the real authorization URL Login built. func (f *as1Fixture) presenter() Presenter { return PresenterFunc(func(ctx context.Context, raw string) (oauthlogin.Result, error) { u, err := url.Parse(raw) @@ -84,17 +90,23 @@ func (f *as1Fixture) presenter() Presenter { return oauthlogin.Result{}, err } f.authorizeURLs = append(f.authorizeURLs, u) - back, err := f.harness.Authorize(ctx, raw) + back, err := f.harness.AuthorizeWithConsent(ctx, raw) if err != nil { return oauthlogin.Result{}, err } if code := back.Get("error"); code != "" { - return oauthlogin.Result{}, errors.New("authorization refused: " + code) + return oauthlogin.Result{}, &authorizationRefused{code: code} } return oauthlogin.Result{Code: back.Get("code"), State: back.Get("state"), Iss: back.Get("iss")}, nil }) } +// authorizationRefused is the presenter's error for an authorization +// response that redirected back with an OAuth error code. +type authorizationRefused struct{ code string } + +func (e *authorizationRefused) Error() string { return "authorization refused: " + e.code } + func (f *as1Fixture) login(t *testing.T, identityBrokerSignIn bool) Token { t.Helper() tok, err := Login(t.Context(), LoginConfig{Identity: f.identity, Presenter: f.presenter(), HTTPClient: f.client, IdentityBrokerSignIn: identityBrokerSignIn}) @@ -104,7 +116,7 @@ func (f *as1Fixture) login(t *testing.T, identityBrokerSignIn bool) Token { return tok } -// TestLoginAtAS1SendsResourceAndRefreshRotates signs in at the AS-1 stand-in +// TestLoginAtAS1SendsResourceAndRefreshRotates signs in at the real AS-1 // with the real authorization code + PKCE flow and the resource indicator on, // then forces refreshes through a RefreshSource: every leg names the Mecatl API // as the RFC 8707 resource, each forced refresh yields a new access token and @@ -187,12 +199,14 @@ func TestLoginAtAS1SendsResourceAndRefreshRotates(t *testing.T) { // TestLoginAtAS1RefusesAForeignResource is the negative control for the // resource assertion: a client configured with another audience is refused at -// the authorization request. +// the authorization request with AS-1's invalid_target. func TestLoginAtAS1RefusesAForeignResource(t *testing.T) { f := newAS1Fixture(t) f.identity.Audience = "https://other.test/api" - if _, err := Login(t.Context(), LoginConfig{Identity: f.identity, Presenter: f.presenter(), HTTPClient: f.client, IdentityBrokerSignIn: true}); !errors.Is(err, ErrAuthorization) { - t.Fatalf("Login with a foreign audience: err=%v, want ErrAuthorization", err) + _, err := Login(t.Context(), LoginConfig{Identity: f.identity, Presenter: f.presenter(), HTTPClient: f.client, IdentityBrokerSignIn: true}) + var refused *authorizationRefused + if !errors.Is(err, ErrAuthorization) || !errors.As(err, &refused) || refused.code != "invalid_target" { + t.Fatalf("Login with a foreign audience: err=%v, want ErrAuthorization wrapping AS-1's invalid_target", err) } } diff --git a/internal/adapter/mcp/gatewaycall_test.go b/internal/adapter/mcp/gatewaycall_test.go index f1f12b1637..eda058da38 100644 --- a/internal/adapter/mcp/gatewaycall_test.go +++ b/internal/adapter/mcp/gatewaycall_test.go @@ -3,6 +3,7 @@ package mcp import ( "bytes" "context" + "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" @@ -73,20 +74,11 @@ func newGatewayFixture(t *testing.T) *gatewayFixture { h := identityharness.New(t, identityharness.Options{}) f := &gatewayFixture{h: h, g: h.StartGateway(t, identityharness.GatewayOptions{})} f.wire = &recordingTransport{base: h.HTTPClient().Transport} - f.token = h.AS1.MintAccessToken(identityharness.AccessTokenSpec{}) - // The stand-in records the token's jti. - parts := strings.Split(f.token, ".") - claims, err := base64.RawURLEncoding.DecodeString(parts[1]) - if err != nil { - t.Fatal(err) - } - var c struct { - JTI string `json:"jti"` - } - if err := json.Unmarshal(claims, &c); err != nil || c.JTI == "" { - t.Fatalf("token jti: %v", err) - } - f.jti = c.JTI + // The stand-in does not verify the token; it records its jti, read + // without verifying it, so an unsigned JWT with a jti serves. + f.jti = rand.Text() + f.token = base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + "." + + base64.RawURLEncoding.EncodeToString([]byte(`{"jti":"`+f.jti+`"}`)) + "." return f } diff --git a/internal/adapter/mcpbroker/as2_test.go b/internal/adapter/mcpbroker/as2_test.go index 98c5014f54..3ed40504a0 100644 --- a/internal/adapter/mcpbroker/as2_test.go +++ b/internal/adapter/mcpbroker/as2_test.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "io" + "maps" "net/http" "net/http/httptest" "net/url" @@ -32,6 +33,7 @@ import ( "github.com/stacklok/mecatl/engine/tool" "github.com/stacklok/mecatl/internal/adapter/mcpbroker/internal/as2trust" "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" "github.com/stacklok/mecatl/internal/identitybroker/adapter/inprocesshttp" "github.com/stacklok/mecatl/internal/testutil/identityharness" "github.com/stacklok/mecatl/internal/testutil/oauthbrowser" @@ -112,21 +114,62 @@ func postAS2Token(t *testing.T, as2 *AS2, form url.Values) (int, map[string]any) return resp.StatusCode, body } -// as2TestAct is the act claim of the ID-JAGs the tests mint, in the design's -// shape (credentials-and-lifecycle.md, step (7)): the instance's ag_ -// identifier, and AS-1, which minted act, as its issuer. -func as2TestAct(h *identityharness.Harness) map[string]any { - return map[string]any{"iss": h.AS1.Issuer(), "sub": "ag_7hq2x9"} +// trustedAS1 is the real AS-1, with the harness IdP as its upstream, and +// Alice's and Bob's access tokens from it. The tests forge their assertions +// from Alice's token and sign them with AS-1's key. +type trustedAS1 struct { + a *as1servertest.AS1 + alice, bob identitybroker.Token } -// mintAS2IDJAG is an ID-JAG for Alice from the harness's AS-1, for the broker -// client at as2. -func mintAS2IDJAG(h *identityharness.Harness, as2 *AS2) string { - return h.AS1.MintAccessToken(identityharness.AccessTokenSpec{ - User: identityharness.Alice, ClientID: identitybroker.BrokerClientID, Audience: as2.Issuer, - Type: idJAGType, Lifetime: 5 * time.Minute, - Claims: map[string]any{"resource": as2.Resource, "act": as2TestAct(h)}, - }) +// startTrustedAS1 starts the real AS-1 and signs Alice and Bob in. +func startTrustedAS1(t *testing.T) trustedAS1 { + t.Helper() + a := as1servertest.Start(t, identityharness.New(t, identityharness.Options{}), nil) + return trustedAS1{ + a: a, + alice: a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}), + bob: a.SignIn(t, as1servertest.SignIn{User: identityharness.Bob}), + } +} + +// act is the act claim of the ID-JAGs the tests mint, in the design's shape +// (credentials-and-lifecycle.md, step (7)): the instance's ag_ identifier, +// and AS-1, which minted act, as its issuer. +func (s trustedAS1) act() map[string]any { + return map[string]any{"iss": s.a.Issuer(), "sub": "ag_7hq2x9"} +} + +// jwt is Alice's access token turned into a JWT AS-1 signs for the broker +// client: aud audience, typ typ (none when empty), a fresh jti, five +// minutes to live, and an ID-JAG's resource and act claims for as2 unless +// claims replaces them. +func (s trustedAS1) jwt(t *testing.T, as2 *AS2, audience, typ string, claims map[string]any) string { + t.Helper() + if claims == nil { + claims = map[string]any{"resource": as2.Resource, "act": s.act()} + } + now := time.Now() + return s.a.Forge(t, s.alice, as1servertest.Forgery{ + Claims: func(c jwt.MapClaims) { + c["aud"], c["client_id"], c["jti"] = audience, identitybroker.BrokerClientID, rand.Text() + c["iat"], c["exp"] = now.Unix(), now.Add(5*time.Minute).Unix() + maps.Copy(c, claims) + }, + Header: func(h map[string]any) { + if typ == "" { + delete(h, "typ") + return + } + h["typ"] = typ + }, + }).Value() +} + +// idJAG is an ID-JAG for Alice from AS-1, for the broker client at as2. +func (s trustedAS1) idJAG(t *testing.T, as2 *AS2) string { + t.Helper() + return s.jwt(t, as2, as2.Issuer, idJAGType, nil) } // unverifiedClaims decodes a JWT's claims without verifying it. @@ -632,21 +675,21 @@ func TestAS2GatewayLoginUsesTheVMCPResource(t *testing.T) { } } -// newTrustingAS2 is AS-2 configured to trust the harness's AS-1, for Alice -// and Bob, through the test-only seam, ToolHiveConfig.AS2Trust. It is this +// newTrustingAS2 is AS-2 configured to trust the real AS-1, for Alice and +// Bob, through the test-only seam, ToolHiveConfig.AS2Trust. It is this // package's counterpart of mcpbrokertest.StartAS2, which these tests cannot // call: mcpbrokertest imports this package, and the tests here use its // unexported helpers. Both build the trust with as2trust.Trust.WithDefaults. -func newTrustingAS2(t *testing.T) (*identityharness.Harness, as2BrokerClient, *Process) { +func newTrustingAS2(t *testing.T) (trustedAS1, as2BrokerClient, *Process) { t.Helper() t.Setenv("MECATL_TEST_CLIENT_SECRET", "construction-only-secret") - h := identityharness.New(t, identityharness.Options{}) + as1 := startTrustedAS1(t) broker := newAS2BrokerClient(t) process, err := NewToolHiveProcess(t.Context(), ToolHiveConfig{ CallbackURL: as2TestCallbackURL, Profiles: []ToolHiveProfile{staticProtectedProfile("private")}, BrokerClient: broker.config, AS2Trust: NewAS2Trust(as2trust.Trust{ - Issuer: h.AS1.Issuer(), JWKSURL: h.AS1.JWKSURL(), CAFile: h.WriteCACert(t, t.TempDir()), - Subjects: []string{h.AS1.Subject(identityharness.Alice), h.AS1.Subject(identityharness.Bob)}, + Issuer: as1.a.Issuer(), JWKSURL: as1.a.JWKSURL(), CAFile: as1.a.Harness.WriteCACert(t, t.TempDir()), + Subjects: []string{as1servertest.Subject(t, as1.alice), as1servertest.Subject(t, as1.bob)}, }.WithDefaults()), }) if err != nil { @@ -656,16 +699,16 @@ func newTrustingAS2(t *testing.T) (*identityharness.Harness, as2BrokerClient, *P if process.AS2 == nil { t.Fatal("AS-2 is not set up") } - return h, broker, process + return as1, broker, process } -// TestAS2RedeemsAHarnessIDJAG configures AS-2 to trust the harness's AS-1 -// through the test-only seam and redeems ID-JAGs it signs, then checks the -// broker client's assertions. -func TestAS2RedeemsAHarnessIDJAG(t *testing.T) { - h, broker, process := newTrustingAS2(t) +// TestAS2RedeemsAnAS1IDJAG configures AS-2 to trust the real AS-1 through +// the test-only seam and redeems ID-JAGs signed with AS-1's key, then checks +// the broker client's assertions. +func TestAS2RedeemsAnAS1IDJAG(t *testing.T) { + as1, broker, process := newTrustingAS2(t) as2 := process.AS2 - idJAG := func() string { return mintAS2IDJAG(h, as2) } + idJAG := func() string { return as1.idJAG(t, as2) } redeem := func(assertion, clientAssertion string) (int, map[string]any) { return postAS2Token(t, as2, url.Values{ "grant_type": {oauthproto.GrantTypeJWTBearer}, @@ -689,10 +732,10 @@ func TestAS2RedeemsAHarnessIDJAG(t *testing.T) { if claims["client_id"] != identitybroker.BrokerClientID { t.Errorf("gateway token client_id = %v, want %s", claims["client_id"], identitybroker.BrokerClientID) } - if want := as2TestAct(h); !reflect.DeepEqual(claims["act"], want) { + if want := as1.act(); !reflect.DeepEqual(claims["act"], want) { t.Errorf("gateway token act = %v, want %v", claims["act"], want) } - if sub, _ := claims.GetSubject(); sub != h.AS1.Issuer()+"#"+h.AS1.Subject(identityharness.Alice) { + if sub, _ := claims.GetSubject(); sub != as1.a.Issuer()+"#"+as1servertest.Subject(t, as1.alice) { t.Errorf("gateway token sub = %q, want issuer#sub", sub) } if aud, _ := claims.GetAudience(); !slices.Equal([]string(aud), []string{as2.Resource}) { @@ -782,16 +825,6 @@ func as2Redemption(t *testing.T, as2 *AS2, broker as2BrokerClient, assertion str return postAS2Token(t, as2, form) } -// as1JWT signs a JWT for Alice from the harness's AS-1 per spec, with an -// ID-JAG's resource and act claims unless spec sets its own. -func as1JWT(h *identityharness.Harness, as2 *AS2, spec identityharness.AccessTokenSpec) string { - spec.User, spec.ClientID, spec.Lifetime = identityharness.Alice, identitybroker.BrokerClientID, 5*time.Minute - if spec.Claims == nil { - spec.Claims = map[string]any{"resource": as2.Resource, "act": as2TestAct(h)} - } - return h.AS1.MintAccessToken(spec) -} - // TestAS2RefusesRedemptionsOutsideItsConfiguration shows that AS-2 refuses // what its configuration leaves out, not only that it redeems what it allows: // a resource, requested or taken from the ID-JAG's claim, other than the @@ -800,19 +833,16 @@ func as1JWT(h *identityharness.Harness, as2 *AS2, spec identityharness.AccessTok // checks that keep an AS-1 access token from being redeemed once #2533 trusts // AS-1 in production, and that a ToolHive bump must not loosen. func TestAS2RefusesRedemptionsOutsideItsConfiguration(t *testing.T) { - h, broker, process := newTrustingAS2(t) + as1, broker, process := newTrustingAS2(t) as2 := process.AS2 - idJAG := func(audience string) string { - return as1JWT(h, as2, identityharness.AccessTokenSpec{Audience: audience, Type: idJAGType}) - } + idJAG := func(audience string) string { return as1.jwt(t, as2, audience, idJAGType, nil) } resource := func(value string) *string { return &value } if status, body := as2Redemption(t, as2, broker, idJAG(as2.Issuer), resource(as2.Resource), true); status != http.StatusOK { t.Fatalf("valid ID-JAG: status %d, body %v", status, body) } - accessToken := as1JWT(h, as2, identityharness.AccessTokenSpec{Audience: as2.Issuer}) - otherClaim := as1JWT(h, as2, identityharness.AccessTokenSpec{Audience: as2.Issuer, Type: idJAGType, - Claims: map[string]any{"resource": "https://other.example/mcp", "act": as2TestAct(h)}}) + accessToken := as1.jwt(t, as2, as2.Issuer, "at+jwt", nil) + otherClaim := as1.jwt(t, as2, as2.Issuer, idJAGType, map[string]any{"resource": "https://other.example/mcp", "act": as1.act()}) for _, test := range []struct { name string assertion string @@ -842,7 +872,7 @@ func TestAS2RefusesRedemptionsOutsideItsConfiguration(t *testing.T) { // tickets that close them flip these cases to refusals rather than finding the // behaviour by accident. func TestAS2RedeemsWhatTrackedShortcutsAllow(t *testing.T) { - h, broker, process := newTrustingAS2(t) + as1, broker, process := newTrustingAS2(t) as2 := process.AS2 vmcp := as2.Resource @@ -850,8 +880,7 @@ func TestAS2RedeemsWhatTrackedShortcutsAllow(t *testing.T) { // (stacklok/toolhive#6892, stacklok/toolhive#6983; #2533). The broker // client's audiences allow only the vMCP resource, so the request's // resource still limits the token. - otherClaim := as1JWT(h, as2, identityharness.AccessTokenSpec{Audience: as2.Issuer, Type: idJAGType, - Claims: map[string]any{"resource": "https://other.example/mcp", "act": as2TestAct(h)}}) + otherClaim := as1.jwt(t, as2, as2.Issuer, idJAGType, map[string]any{"resource": "https://other.example/mcp", "act": as1.act()}) if status, body := as2Redemption(t, as2, broker, otherClaim, &vmcp, true); status != http.StatusOK { t.Errorf("ID-JAG whose resource claim names another server: status %d, body %v; if ToolHive now refuses it, make this a refusal and update #2533", status, body) } @@ -860,11 +889,11 @@ func TestAS2RedeemsWhatTrackedShortcutsAllow(t *testing.T) { // assertions from it, without client authentication. #2533 trusts AS-1 for // ID-JAGs only (acceptedAssertionTypes [id_jag], PR // stacklok/toolhive#6678), which refuses these. - for name, spec := range map[string]identityharness.AccessTokenSpec{ - "typ JWT": {Audience: as2.Issuer, Type: "JWT"}, - "typ absent": {Audience: as2.Issuer, OmitType: true}, + for name, typ := range map[string]string{ + "typ JWT": "JWT", + "typ absent": "", } { - if status, body := as2Redemption(t, as2, broker, as1JWT(h, as2, spec), &vmcp, false); status != http.StatusOK { + if status, body := as2Redemption(t, as2, broker, as1.jwt(t, as2, as2.Issuer, typ, nil), &vmcp, false); status != http.StatusOK { t.Errorf("plain AS-1 assertion (%s) without client authentication: status %d, body %v; if ToolHive now refuses it, make this a refusal and update #2533", name, status, body) } } @@ -872,7 +901,7 @@ func TestAS2RedeemsWhatTrackedShortcutsAllow(t *testing.T) { func TestAS2TrustsNoIssuerWithoutTheTestSeam(t *testing.T) { t.Setenv("MECATL_TEST_CLIENT_SECRET", "construction-only-secret") - h := identityharness.New(t, identityharness.Options{}) + as1 := startTrustedAS1(t) broker := newAS2BrokerClient(t) process, err := NewToolHiveProcess(t.Context(), ToolHiveConfig{ CallbackURL: as2TestCallbackURL, Profiles: []ToolHiveProfile{staticProtectedProfile("private")}, BrokerClient: broker.config, @@ -883,7 +912,7 @@ func TestAS2TrustsNoIssuerWithoutTheTestSeam(t *testing.T) { t.Cleanup(func() { _ = process.Close() }) status, body := postAS2Token(t, process.AS2, url.Values{ "grant_type": {oauthproto.GrantTypeJWTBearer}, - "assertion": {mintAS2IDJAG(h, process.AS2)}, + "assertion": {as1.idJAG(t, process.AS2)}, "resource": {process.AS2.Resource}, "client_assertion_type": {clientAssertionTyp}, "client_assertion": {broker.assertion(t, process.AS2.Issuer)}, diff --git a/internal/app/build.go b/internal/app/build.go index 8c5dde2c5c..de26467fbf 100644 --- a/internal/app/build.go +++ b/internal/app/build.go @@ -1001,8 +1001,8 @@ type Config struct { IdentityBrokerAS2Trust as2Trust // IdentityBrokerAS1 connects the real identity broker's session open to an // AS-1, where it converts users' access tokens. No flag sets it; with a - // hosted AS-1, Build fills it for that AS-1. Only an offline harness test - // sets it directly, pointing the broker at an external AS-1. + // hosted AS-1, Build fills it for that AS-1. Only tests set it directly, + // pointing the broker at an AS-1 they run outside mecak8s. IdentityBrokerAS1 *IdentityBrokerAS1 // IdentityBrokerHostedAS1 hosts AS-1 beside the identity broker; nil hosts // none. Only mecak8s sets it. Build points session open at the hosted AS-1, diff --git a/internal/identitybroker/adapter/as1server/as1server.go b/internal/identitybroker/adapter/as1server/as1server.go index e1adac5a67..ba946dfc0b 100644 --- a/internal/identitybroker/adapter/as1server/as1server.go +++ b/internal/identitybroker/adapter/as1server/as1server.go @@ -31,6 +31,7 @@ import ( "strconv" "strings" "sync" + "time" "github.com/stacklok/toolhive/pkg/authserver" "github.com/stacklok/toolhive/pkg/authserver/runner" @@ -114,6 +115,9 @@ type Server struct { // actors checks ID-JAG requests' actor tokens; nil when the delegate // client issues no ID-JAGs. actors *actorValidator + // store is the storage the authorization server uses, which the + // test-only RevokeGrant revokes grants in. + store *cappedStorage // release releases the authorization server, then its storage, once. release func() error } @@ -205,7 +209,7 @@ func newServer(ctx context.Context, cfg Config, opts options) (*Server, error) { _ = store.Close() return nil, fmt.Errorf("as1server: create authorization server: %w", err) } - s := &Server{issuerID: cfg.Issuer, issuer: issuer, actors: actors, release: sync.OnceValue(func() error { + s := &Server{issuerID: cfg.Issuer, issuer: issuer, actors: actors, store: store, release: sync.OnceValue(func() error { return errors.Join(auth.Close(), store.Close()) })} s.routes, s.handler = signInRoutes(issuer, auth.Handler()) @@ -409,3 +413,33 @@ func (s *Server) Handler() http.Handler { return s.handler } // Close releases the authorization server and its storage. It is idempotent. func (s *Server) Close() error { return s.release() } + +// ErrUnknownGrant reports a refresh token RevokeGrant cannot revoke: it is +// malformed, or it names no live grant of AS-1. +var ErrUnknownGrant = errors.New("as1server: unknown grant") + +// RevokeGrant is test-only. It revokes the grant behind refreshToken, a +// refresh token AS-1 issued the delegate client at session open, directly in +// AS-1's storage, so tests can see AS-1 answer revoked for it. It bypasses +// AS-1's handler, client authentication, and ownership checks, so nothing +// outside tests may call it (a forbidigo rule enforces this); production +// revocation goes through AS-1's RFC 7009 route (stacklok/toolhive#6966). +// Revoking a revoked grant succeeds. A malformed token, a public client's +// refresh token, or an unknown grant is ErrUnknownGrant. Errors never carry +// the token. +func (s *Server) RevokeGrant(ctx context.Context, refreshToken string) error { + // AS-1 keys a grant by the HMAC signature of its refresh token, the part + // after the '.' (fosite's HMAC strategy, which ToolHive uses). + _, signature, ok := strings.Cut(refreshToken, ".") + if !ok || signature == "" { + return ErrUnknownGrant + } + err := s.store.RevokeExchangeGrant(ctx, signature, time.Now()) + switch { + case errors.Is(err, storage.ErrNotFound): + return ErrUnknownGrant + case err != nil: + return fmt.Errorf("as1server: revoke grant: %w", err) + } + return nil +} diff --git a/internal/identitybroker/adapter/as1server/as1servertest/actorvalidator.go b/internal/identitybroker/adapter/as1server/as1servertest/actorvalidator.go deleted file mode 100644 index 122f56da54..0000000000 --- a/internal/identitybroker/adapter/as1server/as1servertest/actorvalidator.go +++ /dev/null @@ -1,34 +0,0 @@ -package as1servertest - -import ( - "context" - "errors" - "time" - - "github.com/stacklok/mecatl/internal/identitybroker" - "github.com/stacklok/mecatl/internal/testutil/identityharness" -) - -// HarnessActorValidator is the identity harness's AS-1 checking actor tokens -// with v, as the real AS-1 does: an expired credential is -// identityharness.ErrActorExpired, any other refusal -// identityharness.ErrActorDenied, and anything else an outage. It lives here, -// not in the harness, because the harness never imports the broker. -// Shortcut: only tests of revocation reasons run the harness's AS-1, as the real AS-1 sends none yet; removed by #2568 (AS-1 revocation reasons). -func HarnessActorValidator(v identitybroker.CredentialVerifier) identityharness.ActorValidator { - return func(ctx context.Context, owner identityharness.Owner, actor string) (string, time.Time, error) { - got, err := v.VerifyCredentialForOwner(ctx, identitybroker.VerifyCredentialForOwnerRequest{ - Owner: identitybroker.Owner{Issuer: owner.Issuer, Subject: owner.Subject}, Credential: identitybroker.NewToken(actor), - }) - var e *identitybroker.Error - switch { - case err == nil: - return got.AgentID, got.ExpiresAt, nil - case errors.As(err, &e) && e.Code == identitybroker.CodeUnauthenticated && e.Reason == identitybroker.ReasonSVIDExpired: - return "", time.Time{}, identityharness.ErrActorExpired - case errors.As(err, &e) && e.Code == identitybroker.CodePermissionDenied: - return "", time.Time{}, identityharness.ErrActorDenied - } - return "", time.Time{}, err - } -} diff --git a/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go b/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go index a6ed7d187f..21e3e31c9e 100644 --- a/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go +++ b/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go @@ -19,6 +19,7 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" + "maps" "net" "net/http" "net/http/httptest" @@ -341,15 +342,10 @@ func accessTokenClaims(t testing.TB, accessToken identitybroker.Token) jwt.MapCl // ExpiredAccessToken returns accessToken, an access token AS-1 issued, with // its iat and exp moved an hour into the past and signed again with AS-1's -// signing key, so AS-1 verifies it and refuses it only for its expiry. It -// needs Config.SigningKeyFile to hold a key identityharness's WriteSigningKey -// wrote, as Start's does. +// signing key, so AS-1 verifies it and refuses it only for its expiry. func (a *AS1) ExpiredAccessToken(t testing.TB, accessToken identitybroker.Token) identitybroker.Token { t.Helper() - if a.signingKeyFile == "" { - t.Fatal("as1servertest: AS-1 has no signing key file") - } - return identitybroker.NewToken(identityharness.ResignAccessToken(t, a.signingKeyFile, accessToken.Value(), func(claims jwt.MapClaims) { + return a.Forge(t, accessToken, Forgery{Claims: func(claims jwt.MapClaims) { iat, errIat := claims.GetIssuedAt() exp, errExp := claims.GetExpirationTime() if errIat != nil || errExp != nil || iat == nil || exp == nil { @@ -357,5 +353,57 @@ func (a *AS1) ExpiredAccessToken(t testing.TB, accessToken identitybroker.Token) } end := time.Now().Add(-time.Hour) claims["iat"], claims["exp"] = end.Add(-exp.Sub(iat.Time)).Unix(), end.Unix() - })) + }}) +} + +// Forgery is how Forge alters a token. The zero value changes nothing. +type Forgery struct { + // Claims, when set, edits the claims. + Claims func(jwt.MapClaims) + // Header, when set, edits the JOSE header, such as its typ. A forgery + // keeps alg ES256 and, unless Header changes it, AS-1's kid. + Header func(map[string]any) + // ForeignKey signs with a fresh key AS-1 never published, under the same + // kid, instead of AS-1's signing key. + ForeignKey bool +} + +// Forge returns token, a JWT AS-1 issued such as a user's access token, with +// f's changes, signed again with AS-1's own signing key unless f.ForeignKey +// is set. A forgery signed with AS-1's key verifies against AS-1's key set, +// so its verifier judges it by the changes alone. It needs +// Config.SigningKeyFile to hold a key identityharness's WriteSigningKey +// wrote, as Start's does. +func (a *AS1) Forge(t testing.TB, token identitybroker.Token, f Forgery) identitybroker.Token { + t.Helper() + claims := jwt.MapClaims{} + parsed, _, err := jwt.NewParser().ParseUnverified(token.Value(), claims) + if err != nil { + t.Fatalf("as1servertest: parse token to forge: %v", err) + } + if f.Claims != nil { + f.Claims(claims) + } + forged := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + forged.Header = maps.Clone(parsed.Header) + forged.Header["alg"] = jwt.SigningMethodES256.Alg() + if f.Header != nil { + f.Header(forged.Header) + } + var key *ecdsa.PrivateKey + if f.ForeignKey { + if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil { + t.Fatalf("as1servertest: foreign key: %v", err) + } + } else { + if a.signingKeyFile == "" { + t.Fatal("as1servertest: AS-1 has no signing key file") + } + key = identityharness.ReadSigningKey(t, a.signingKeyFile) + } + signed, err := forged.SignedString(key) + if err != nil { + t.Fatalf("as1servertest: sign forged token: %v", err) + } + return identitybroker.NewToken(signed) } diff --git a/internal/identitybroker/adapter/as1server/revoke_test.go b/internal/identitybroker/adapter/as1server/revoke_test.go new file mode 100644 index 0000000000..d3711b8c0e --- /dev/null +++ b/internal/identitybroker/adapter/as1server/revoke_test.go @@ -0,0 +1,49 @@ +package as1server + +import ( + "errors" + "strings" + "testing" + "time" +) + +// TestRevokeGrant revokes a session-open grant in AS-1's storage: its next +// ID-JAG exchange is refused as revoked, a second revocation succeeds, and a +// token naming no grant is ErrUnknownGrant without the token or its +// signature in the error. +func TestRevokeGrant(t *testing.T) { + x := startIDJAG(t) + if err := x.f.server.UseCredentialVerifier(allowing(time.Now().Add(time.Hour))); err != nil { + t.Fatalf("UseCredentialVerifier: %v", err) + } + if err := x.f.server.RevokeGrant(t.Context(), x.grant.Value()); err != nil { + t.Fatalf("RevokeGrant: %v", err) + } + _, err := x.issue(t, actorToken(t)) + wantIDJAGRefusal(t, err, 400, "invalid_request", "revoked") + if err := x.f.server.RevokeGrant(t.Context(), x.grant.Value()); err != nil { + t.Fatalf("RevokeGrant of a revoked grant: %v", err) + } + + for name, token := range map[string]string{ + "empty": "", + "no dot": "not-a-refresh-token", + "two dots": "a.b.c", + "no key": ".signature", + "unknown": "ory_rt_unknown.signature", + "a public sign-in's": x.f.signIn(t, testAudience).RefreshToken, + "trailing .": x.grant.Value() + ".", + } { + err := x.f.server.RevokeGrant(t.Context(), token) + if !errors.Is(err, ErrUnknownGrant) { + t.Errorf("%s: RevokeGrant = %v, want ErrUnknownGrant", name, err) + continue + } + _, signature, _ := strings.Cut(token, ".") + for _, secret := range []string{token, signature} { + if secret != "" && strings.Contains(err.Error(), secret) { + t.Errorf("%s: the error discloses the refresh token or its signature", name) + } + } + } +} diff --git a/internal/identitybroker/adapter/authserverclient/client_test.go b/internal/identitybroker/adapter/authserverclient/client_test.go index c00767b860..2f41b9c9cd 100644 --- a/internal/identitybroker/adapter/authserverclient/client_test.go +++ b/internal/identitybroker/adapter/authserverclient/client_test.go @@ -101,31 +101,28 @@ func aliceSignsIn(t *testing.T, a *as1servertest.AS1) string { return a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value() } -// fixture is the harness's AS-1, kept for revocation, which the real AS-1 -// does not serve yet: retired by stacklok/toolhive#6966 and -// stacklok/toolhive#6972 (mecatl #2568). -type fixture struct { - h *identityharness.Harness - signer *identitybroker.ClientAssertionSigner -} - -func newFixture(t *testing.T) *fixture { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - signer, err := identitybroker.NewClientAssertionSigner(key, 0) - if err != nil { - t.Fatal(err) - } - // Register the key as a server would: from the published JWKS. - h := identityharness.New(t, identityharness.Options{BrokerKeys: []identityharness.BrokerKey{jwksKey(t, signer.JWKS())}}) - return &fixture{h: h, signer: signer} -} - -func jwksKey(t *testing.T, set identitybroker.JWKSet) identityharness.BrokerKey { +// revocationStub stands in for an RFC 7009 revocation endpoint, which the +// real AS-1 does not serve until stacklok/toolhive#6966. It authenticates +// the broker client by private_key_jwt only: a jwt-bearer client assertion +// signed with ES256 by the registered key under its kid. The assertion's +// claims are not checked here; TestSessionOpenAuthenticatesWithTheBrokerKey +// checks them at the real AS-1. It records each token it revokes. +type revocationStub struct { + issuer string + endpoint string + client *http.Client + key *ecdsa.PublicKey + kid string + + mu sync.Mutex + revoked []url.Values +} + +// startRevocationStub serves a revocation endpoint that registers signer's +// one key, the way a server would from the broker's published JWKS. +func startRevocationStub(t *testing.T, signer *identitybroker.ClientAssertionSigner) *revocationStub { t.Helper() + set := signer.JWKS() if len(set.Keys) != 1 { t.Fatalf("JWKS has %d keys, want 1", len(set.Keys)) } @@ -139,31 +136,85 @@ func jwksKey(t *testing.T, set identitybroker.JWKSet) identityharness.BrokerKey if err != nil { t.Fatalf("JWK key: %v", err) } - return identityharness.BrokerKey{KeyID: k.KeyID, Public: pub} + stub := &revocationStub{key: pub, kid: k.KeyID} + server := httptest.NewTLSServer(http.HandlerFunc(stub.serve)) + t.Cleanup(server.Close) + stub.issuer, stub.endpoint, stub.client = server.URL+"/as1", server.URL+"/as1/oauth/revoke", server.Client() + return stub +} + +func (s *revocationStub) serve(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/as1/oauth/revoke" || r.ParseForm() != nil || r.PostForm.Get("token") == "" { + w.WriteHeader(http.StatusBadRequest) + return + } + if !s.authenticated(r) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"invalid_client"}`) + return + } + s.mu.Lock() + s.revoked = append(s.revoked, url.Values{"token": r.PostForm["token"], "token_type_hint": r.PostForm["token_type_hint"]}) + s.mu.Unlock() + w.WriteHeader(http.StatusOK) +} + +// authenticated reports whether r authenticates the broker client. +func (s *revocationStub) authenticated(r *http.Request) bool { + form := r.PostForm + if form.Has("client_secret") || r.Header.Get("Authorization") != "" || + form.Get("client_assertion_type") != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" || + (form.Has("client_id") && form.Get("client_id") != identitybroker.BrokerClientID) { + return false + } + _, err := jwt.Parse(form.Get("client_assertion"), func(token *jwt.Token) (any, error) { + if token.Header["kid"] != s.kid { + return nil, jwt.ErrTokenUnverifiable + } + return s.key, nil + }, jwt.WithValidMethods([]string{"ES256"}), jwt.WithoutClaimsValidation()) + return err == nil } -// client returns a client for AS-1 whose assertions r records, after edit -// changes its configuration. -func (f *fixture) client(t *testing.T, r *recorder, edit func(*authserverclient.Config)) *authserverclient.Client { +func (s *revocationStub) revocations() []url.Values { + s.mu.Lock() + defer s.mu.Unlock() + return append([]url.Values(nil), s.revoked...) +} + +// newClient returns a client for the stub's issuer that signs assertions +// with signer, recorded by r. +func (s *revocationStub) newClient(t *testing.T, r *recorder, signer authserverclient.Assertions) *authserverclient.Client { t.Helper() - r.signer = f.signer - cfg := authserverclient.Config{ - Issuer: f.h.AS1.Issuer(), - TokenEndpoint: f.h.AS1.TokenEndpoint(), - RevocationEndpoint: f.h.AS1.RevocationEndpoint(), + r.signer = signer + c, err := authserverclient.New(authserverclient.Config{ + Issuer: s.issuer, + TokenEndpoint: s.issuer + "/oauth/token", + RevocationEndpoint: s.endpoint, Assertions: r, - HTTPClient: f.h.HTTPClient(), - } - if edit != nil { - edit(&cfg) - } - c, err := authserverclient.New(cfg) + HTTPClient: s.client, + }) if err != nil { t.Fatalf("New: %v", err) } return c } +// newBrokerSigner is a broker client assertion signer with a fresh key. +func newBrokerSigner(t *testing.T) *identitybroker.ClientAssertionSigner { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + signer, err := identitybroker.NewClientAssertionSigner(key, 0) + if err != nil { + t.Fatal(err) + } + return signer +} + // sessionOpenForm is a session-open exchange (design step (3)): one // exchange-grant entry listing only id-jag, without client authentication. func sessionOpenForm(t *testing.T, accessToken string) url.Values { @@ -183,10 +234,6 @@ func sessionOpenForm(t *testing.T, accessToken string) url.Values { } } -func (f *fixture) aliceToken() string { - return f.h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: identityharness.Alice}) -} - type sessionOpenResult struct { RefreshToken string `json:"access_token"` IssuedTokenType string `json:"issued_token_type"` @@ -258,21 +305,34 @@ func TestSessionOpenAuthenticatesWithTheBrokerKey(t *testing.T) { } } -// TestRevocationAuthenticates stays on the harness's AS-1, as the real AS-1 -// serves no revocation yet: retired by stacklok/toolhive#6966 and -// stacklok/toolhive#6972 (mecatl #2568). +// TestRevocationAuthenticates revokes at a stub RFC 7009 endpoint, as the real +// AS-1 serves none until stacklok/toolhive#6966: the request authenticates +// the broker client with private_key_jwt, and one signed with a key the +// endpoint does not know is refused as a configuration fault. func TestRevocationAuthenticates(t *testing.T) { - f := newFixture(t) - c := f.client(t, &recorder{}, nil) - var res sessionOpenResult - if err := c.Token(t.Context(), sessionOpenForm(t, f.aliceToken()), &res); err != nil { - t.Fatalf("Token: %v", err) - } - if err := c.Revoke(t.Context(), url.Values{"token": {res.RefreshToken}, "token_type_hint": {"refresh_token"}}); err != nil { + signer := newBrokerSigner(t) + stub := startRevocationStub(t, signer) + const refreshToken = "ory_rt_grant.signature" // #nosec G101 -- test value, not a credential. + r := &recorder{} + if err := stub.newClient(t, r, signer).Revoke(t.Context(), url.Values{"token": {refreshToken}, "token_type_hint": {"refresh_token"}}); err != nil { t.Fatalf("Revoke: %v", err) } - if grant, _ := f.h.AS1.Grant(res.RefreshToken); grant.Active || grant.Reason != "revoked" { - t.Fatalf("grant = %+v after revocation, want revoked", grant) + if got := stub.revocations(); len(got) != 1 || got[0].Get("token") != refreshToken || got[0].Get("token_type_hint") != "refresh_token" { + t.Fatalf("the endpoint revoked %d tokens, want the one refresh token with its hint", len(got)) + } + if len(r.all()) != 1 { + t.Fatalf("minted %d assertions, want 1", len(r.all())) + } + + unregistered := &recorder{} + err := stub.newClient(t, unregistered, newBrokerSigner(t)).Revoke(t.Context(), url.Values{"token": {refreshToken}}) + var oe *identitybroker.ServerRefusal + if !errors.As(err, &oe) || oe.Status != http.StatusUnauthorized || oe.Code != "invalid_client" || !identitybroker.IsConfigurationFault(err) { + t.Fatalf("Revoke with an unregistered key = %v, want a 401 invalid_client configuration fault", err) + } + assertNoSecrets(t, err, append(values(unregistered.all()), refreshToken)...) + if n := len(stub.revocations()); n != 1 { + t.Fatalf("the endpoint revoked %d tokens after the refusal, want 1", n) } } @@ -295,14 +355,7 @@ func (o overLongAssertions) ClientAssertion(audience string, now time.Time) (ide } func TestClientAuthenticationRefusals(t *testing.T) { - unregistered, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - unregisteredSigner, err := identitybroker.NewClientAssertionSigner(unregistered, 0) - if err != nil { - t.Fatal(err) - } + unregisteredSigner := newBrokerSigner(t) tests := []struct { name string // signer replaces the registered broker key's signer. @@ -605,34 +658,28 @@ func TestOversizedRefusalKeepsItsStatus(t *testing.T) { // newStubClient returns a client for a stand-in server at base. func newStubClient(t *testing.T, base string, hc *http.Client) *authserverclient.Client { t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - signer, err := identitybroker.NewClientAssertionSigner(key, 0) - if err != nil { - t.Fatal(err) - } - c, err := authserverclient.New(authserverclient.Config{Issuer: base, TokenEndpoint: base + "/token", Assertions: signer, HTTPClient: hc}) + c, err := authserverclient.New(authserverclient.Config{Issuer: base, TokenEndpoint: base + "/token", Assertions: newBrokerSigner(t), HTTPClient: hc}) if err != nil { t.Fatal(err) } return c } -// TestFormMustNotCarryClientCredentials revokes, so it stays on the harness's -// AS-1: retired by stacklok/toolhive#6966 and stacklok/toolhive#6972. +// TestFormMustNotCarryClientCredentials revokes at the stub RFC 7009 +// endpoint: a form carrying its own client credentials is refused before an +// assertion is minted or anything is sent. func TestFormMustNotCarryClientCredentials(t *testing.T) { - f := newFixture(t) + signer := newBrokerSigner(t) + stub := startRevocationStub(t, signer) r := &recorder{} - c := f.client(t, r, nil) + c := stub.newClient(t, r, signer) for _, name := range []string{"client_secret", "client_id", "client_assertion", "client_assertion_type"} { if err := c.Revoke(t.Context(), url.Values{"token": {"x"}, name: {"v"}}); err == nil { t.Errorf("a form carrying %s was sent", name) } } - if len(r.all()) != 0 { - t.Fatal("assertions were minted for refused forms") + if len(r.all()) != 0 || len(stub.revocations()) != 0 { + t.Fatal("assertions were minted or revocations sent for refused forms") } } @@ -676,15 +723,7 @@ func (blockingTransport) RoundTrip(req *http.Request) (*http.Response, error) { } func TestTransportErrorTextIsNeverReturned(t *testing.T) { - r := &recorder{} - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - r.signer, err = identitybroker.NewClientAssertionSigner(key, 0) - if err != nil { - t.Fatal(err) - } + r := &recorder{signer: newBrokerSigner(t)} c, err := authserverclient.New(authserverclient.Config{ Issuer: "https://as.example.com", TokenEndpoint: "https://as.example.com/token", Assertions: r, HTTPClient: &http.Client{Transport: echoingTransport{}}, diff --git a/internal/identitybroker/authorize_integration_test.go b/internal/identitybroker/authorize_integration_test.go index 4e816ae77a..4fe87daa82 100644 --- a/internal/identitybroker/authorize_integration_test.go +++ b/internal/identitybroker/authorize_integration_test.go @@ -25,6 +25,7 @@ import ( "github.com/stacklok/mecatl/internal/adapter/mcpbroker" "github.com/stacklok/mecatl/internal/adapter/mcpbroker/mcpbrokertest" "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" "github.com/stacklok/mecatl/internal/identitybroker/adapter/authserverclient" "github.com/stacklok/mecatl/internal/identitybroker/adapter/inprocesshttp" @@ -45,9 +46,11 @@ const testTrustDomain = "agents.example.com" // real AS-2, with Alice's session open on openHost and its main agent // registered. type harnessFixture struct { - h *identityharness.Harness - b *identitybroker.Broker - rec *identitybroker.MemoryRecorder + h *identityharness.Harness + // as1Server is AS-1, for revoking grants in it. + as1Server *as1server.Server + b *identitybroker.Broker + rec *identitybroker.MemoryRecorder // as1 and as2 are the fault transports in front of each server's token // endpoint. as1, as2 *identityharness.FaultTransport @@ -78,70 +81,6 @@ type harnessOptions struct { // unknownAS2Key has the broker sign its AS-2 client assertions with a key // AS-2 does not know. unknownAS2Key bool - // harnessAS1 runs the identity harness's AS-1 instead of the real one, - // for tests of revocation reasons only it gives. - // Shortcut: revocation-reason tests run the harness's AS-1, which revokes a user's grants and answers revoked, as the real AS-1 sends no revocation reasons yet; removed by #2568 (AS-1 revocation reasons). - harnessAS1 bool -} - -// fixtureAS1 is the AS-1 a harnessFixture exchanges at. -type fixtureAS1 struct { - issuer, tokenEndpoint, jwksURL string - signer *identitybroker.ClientAssertionSigner - http *http.Client - subjects map[string]string - accessToken func(user string) string - // bind binds the built broker as AS-1's actor-token check. - bind func(*identitybroker.Broker) -} - -// realFixtureAS1 starts the real AS-1 issuing ID-JAGs for AS-2 and signs -// Alice and Bob in, so AS-2's test trust can name their AS-1 subjects. -func realFixtureAS1(t *testing.T, h *identityharness.Harness, as2Issuer, as2Resource string) fixtureAS1 { - t.Helper() - a := as1servertest.Start(t, h, as1servertest.IssueIDJAGs(testTrustDomain, as2Issuer, as2Resource)) - accessToken := func(user string) string { return a.SignIn(t, as1servertest.SignIn{User: user}).Value() } - subjects := map[string]string{} - for _, user := range []string{identityharness.Alice, identityharness.Bob} { - subjects[user] = as1servertest.Subject(t, identitybroker.NewToken(accessToken(user))) - } - return fixtureAS1{ - issuer: a.Issuer(), tokenEndpoint: a.Server.TokenEndpoint(), jwksURL: a.JWKSURL(), signer: a.Signer, - http: a.HTTPClient(), subjects: subjects, accessToken: accessToken, - bind: func(b *identitybroker.Broker) { - if err := a.Server.UseCredentialVerifier(b); err != nil { - t.Fatal(err) - } - }, - } -} - -// harnessFixtureAS1 is the identity harness's AS-1, checking actor tokens -// with the broker's verifier. -func harnessFixtureAS1(t *testing.T, as2Issuer, as2Resource string) (*identityharness.Harness, fixtureAS1) { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - signer, err := identitybroker.NewClientAssertionSigner(key, 0) - if err != nil { - t.Fatal(err) - } - h := identityharness.New(t, identityharness.Options{ - BrokerKeys: []identityharness.BrokerKey{{KeyID: signer.JWKS().Keys[0].KeyID, Public: &key.PublicKey}}, - }) - h.AS1.AddIDJAGTarget(as2Issuer, as2Resource) - return h, fixtureAS1{ - issuer: h.AS1.Issuer(), tokenEndpoint: h.AS1.TokenEndpoint(), jwksURL: h.AS1.JWKSURL(), signer: signer, http: h.HTTPClient(), - subjects: map[string]string{ - identityharness.Alice: h.AS1.Subject(identityharness.Alice), identityharness.Bob: h.AS1.Subject(identityharness.Bob), - }, - accessToken: func(user string) string { - return h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: user}) - }, - bind: func(b *identitybroker.Broker) { h.AS1.SetActorValidator(as1servertest.HarnessActorValidator(b)) }, - } } func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { @@ -151,15 +90,16 @@ func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { if err != nil { t.Fatal(err) } - var h *identityharness.Harness - var fa fixtureAS1 - if opts.harnessAS1 { - h, fa = harnessFixtureAS1(t, as2Issuer, as2Resource) - } else { - h = identityharness.New(t, identityharness.Options{}) - fa = realFixtureAS1(t, h, as2Issuer, as2Resource) + h := identityharness.New(t, identityharness.Options{}) + a := as1servertest.Start(t, h, as1servertest.IssueIDJAGs(testTrustDomain, as2Issuer, as2Resource)) + // Alice and Bob sign in first, so AS-2's test trust can name their AS-1 + // subjects. + accessToken := func(user string) string { return a.SignIn(t, as1servertest.SignIn{User: user}).Value() } + subjectOf := map[string]string{} + for _, user := range []string{identityharness.Alice, identityharness.Bob} { + subjectOf[user] = as1servertest.Subject(t, identitybroker.NewToken(accessToken(user))) } - signer := fa.signer + signer := a.Signer as2Signer := signer if opts.unknownAS2Key { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) @@ -174,21 +114,21 @@ func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { if err != nil { t.Fatal(err) } - subjects := []string{fa.subjects[identityharness.Alice], fa.subjects[identityharness.Bob]} + subjects := []string{subjectOf[identityharness.Alice], subjectOf[identityharness.Bob]} if opts.distrustAlice { subjects = subjects[1:] } process := mcpbrokertest.StartAS2(t, identitybroker.BrokerClientID, keySet, mcpbrokertest.AS1Trust{ - Issuer: fa.issuer, JWKSURL: fa.jwksURL, CAFile: h.WriteCACert(t, t.TempDir()), + Issuer: a.Issuer(), JWKSURL: a.JWKSURL(), CAFile: h.WriteCACert(t, t.TempDir()), Subjects: subjects, }) as2 := process.AS2 - as1HTTP := fa.http - as1Faults := identityharness.NewFaultTransport(as1HTTP.Transport, fa.tokenEndpoint) + as1HTTP := a.HTTPClient() + as1Faults := identityharness.NewFaultTransport(as1HTTP.Transport, a.Server.TokenEndpoint()) as1HTTP.Transport = as1Faults as1, err := authserverclient.New(authserverclient.Config{ - Issuer: fa.issuer, TokenEndpoint: fa.tokenEndpoint, Assertions: signer, HTTPClient: as1HTTP, + Issuer: a.Issuer(), TokenEndpoint: a.Server.TokenEndpoint(), Assertions: signer, HTTPClient: as1HTTP, }) if err != nil { t.Fatal(err) @@ -212,11 +152,13 @@ func newHarnessFixtureWith(t *testing.T, opts harnessOptions) *harnessFixture { Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: as2.Resource, AuthServer: as2Client}, })) - fa.bind(b) + if err := a.Server.UseCredentialVerifier(b); err != nil { + t.Fatal(err) + } f := &harnessFixture{ - h: h, b: b, rec: rec, as1: as1Faults, as2: as2Faults, as2Client: as2Client, - as2Issuer: as2.Issuer, as2Resource: as2.Resource, as1Iss: fa.issuer, vmcp: process.Handlers.VMCP, - subjects: fa.subjects, accessToken: fa.accessToken, + h: h, as1Server: a.Server, b: b, rec: rec, as1: as1Faults, as2: as2Faults, as2Client: as2Client, + as2Issuer: as2.Issuer, as2Resource: as2.Resource, as1Iss: a.Issuer(), vmcp: process.Handlers.VMCP, + subjects: subjectOf, accessToken: accessToken, } f.s, f.cred = f.open(t, openHost, identityharness.Alice) return f @@ -417,8 +359,8 @@ func TestAuthorizeCallIDJAGShapeAtAS2(t *testing.T) { if len(redeemed) != 1 { t.Fatalf("%d redemptions, want 1", len(redeemed)) } - if typ := jwtPart(t, redeemed[0].Assertion, 0)["typ"]; typ != identityharness.IDJAGHeaderType { - t.Fatalf("the redeemed assertion's typ = %v, want %s", typ, identityharness.IDJAGHeaderType) + if typ := jwtPart(t, redeemed[0].Assertion, 0)["typ"]; typ != "oauth-id-jag+jwt" { + t.Fatalf("the redeemed assertion's typ = %v, want oauth-id-jag+jwt", typ) } jag := jwtPart(t, redeemed[0].Assertion, 1) issued := f.issued(t) @@ -535,9 +477,8 @@ func TestAuthorizeCallRejectedTokenRetryAtGateway(t *testing.T) { f.wantCounts(t, 3, 3) } -// TestAuthorizeCallRevokedRulesAtAS1 runs the revocation rules against AS-1 -// (#2535 done-when 4): the real one, and the harness's for the subtests whose -// revoked reason only it gives (harnessOptions.harnessAS1). +// TestAuthorizeCallRevokedRulesAtAS1 runs the revocation rules against the +// real AS-1 (#2535 done-when 4), revoking grants in it in process. func TestAuthorizeCallRevokedRulesAtAS1(t *testing.T) { closesSession := func(t *testing.T, f *harnessFixture, err error) { t.Helper() @@ -547,10 +488,14 @@ func TestAuthorizeCallRevokedRulesAtAS1(t *testing.T) { } } - t.Run("AS-1 revoking the user's grants closes the session", func(t *testing.T) { - f := newHarnessFixtureWith(t, harnessOptions{harnessAS1: true}) - if n := f.h.AS1.RevokeGrants(identityharness.Alice); n != 1 { - t.Fatalf("AS-1 revoked %d grants, want 1", n) + t.Run("AS-1 revoking the session's grant closes the session", func(t *testing.T) { + f := newHarnessFixture(t) + grant, ok := identitybroker.SessionGrant(f.b, f.s.ID) + if !ok { + t.Fatal("the session holds no grant") + } + if err := f.as1Server.RevokeGrant(t.Context(), grant.RefreshToken.Value()); err != nil { + t.Fatalf("AS-1 RevokeGrant: %v", err) } _, err := f.authorize(callRequest(f.s.ID, f.cred)) closesSession(t, f, err) @@ -565,6 +510,10 @@ func TestAuthorizeCallRevokedRulesAtAS1(t *testing.T) { t.Run("parent_revoked closes the session", func(t *testing.T) { f := newHarnessFixture(t) + // The answer is injected because the real AS-1 cannot give it for + // the broker's grants: AS-1 answers parent_revoked only for a child + // grant, it derives child grants only from grants that issue refresh + // tokens, and the broker's session-open grants issue only ID-JAGs. f.as1.FailNext(identityharness.KindIDJAG, identityharness.Fault{Error: "invalid_request", Reason: "parent_revoked"}) _, err := f.authorize(callRequest(f.s.ID, f.cred)) closesSession(t, f, err) @@ -572,14 +521,14 @@ func TestAuthorizeCallRevokedRulesAtAS1(t *testing.T) { }) t.Run("a newer grant is retried", func(t *testing.T) { - f := newHarnessFixtureWith(t, harnessOptions{harnessAS1: true}) + f := newHarnessFixture(t) old, _ := identitybroker.SessionGrant(f.b, f.s.ID) var reopenErr, revokeErr error // The session is reopened with a fresh token and AS-1 revokes the old // grant while the call's exchange is on its way. f.as1.OnNext(identityharness.KindIDJAG, func() { _, reopenErr = f.openToken(openHost, identityharness.Alice) - revokeErr = f.h.ScriptedBroker().Revoke(context.Background(), old.RefreshToken.Value()) + revokeErr = f.as1Server.RevokeGrant(context.Background(), old.RefreshToken.Value()) }) got, err := f.authorize(callRequest(f.s.ID, f.cred)) if reopenErr != nil || revokeErr != nil { diff --git a/internal/identitybroker/sessionopen_test.go b/internal/identitybroker/sessionopen_test.go index e3484eb6fc..3d49db37f7 100644 --- a/internal/identitybroker/sessionopen_test.go +++ b/internal/identitybroker/sessionopen_test.go @@ -18,6 +18,8 @@ import ( "testing" "time" + "github.com/golang-jwt/jwt/v5" + "github.com/stacklok/mecatl/internal/identitybroker" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" @@ -84,10 +86,23 @@ func (f *openFixture) token(t *testing.T, user string) identitybroker.Token { return f.as1.SignIn(t, as1servertest.SignIn{User: user}) } -// crafted mints an access token at the harness's AS-1 as spec describes, for -// checks that refuse it before AS-1 is called. -func (f *openFixture) crafted(spec identityharness.AccessTokenSpec) identitybroker.Token { - return identitybroker.NewToken(f.as1.Harness.AS1.MintAccessToken(spec)) +// crafted is Alice's access token from AS-1 with f's changes, signed again +// with AS-1's key unless f.ForeignKey is set. +func (f *openFixture) crafted(t *testing.T, forgery as1servertest.Forgery) identitybroker.Token { + t.Helper() + return f.as1.Forge(t, f.token(t, identityharness.Alice), forgery) +} + +// withSubID is a forgery replacing sub_id with subID, or removing it when +// subID is nil. +func withSubID(subID any) as1servertest.Forgery { + return as1servertest.Forgery{Claims: func(c jwt.MapClaims) { + if subID == nil { + delete(c, "sub_id") + return + } + c["sub_id"] = subID + }} } func (f *openFixture) open(host string, owner identitybroker.Owner, token identitybroker.Token) (identitybroker.Session, error) { @@ -334,17 +349,17 @@ func TestSessionOpenIgnoresTokensWithoutAnAuthServer(t *testing.T) { } } -// TestSessionOpenBrokerCheck1RefusesWithoutCallingAS1 crafts the malformed -// tokens at the harness's AS-1: the broker refuses them before AS-1 is called. +// TestSessionOpenBrokerCheck1RefusesWithoutCallingAS1 forges the malformed +// tokens from AS-1's own: the broker refuses them before AS-1 is called. func TestSessionOpenBrokerCheck1RefusesWithoutCallingAS1(t *testing.T) { subID := func(members map[string]string) func(*testing.T, *openFixture) identitybroker.Token { - return func(_ *testing.T, f *openFixture) identitybroker.Token { + return func(t *testing.T, f *openFixture) identitybroker.Token { for k, v := range members { if v == "IDP" { members[k] = f.as1.Harness.IdP.Issuer() } } - return f.crafted(identityharness.AccessTokenSpec{SubID: members}) + return f.crafted(t, withSubID(members)) } } tests := []struct { @@ -355,11 +370,11 @@ func TestSessionOpenBrokerCheck1RefusesWithoutCallingAS1(t *testing.T) { }{ {"another user's token", func(t *testing.T, f *openFixture) identitybroker.Token { return f.token(t, identityharness.Bob) }, identitybroker.CodePermissionDenied, identitybroker.ReasonOwnerMismatch}, - {"no sub_id", func(_ *testing.T, f *openFixture) identitybroker.Token { - return f.crafted(identityharness.AccessTokenSpec{OmitSubID: true}) + {"no sub_id", func(t *testing.T, f *openFixture) identitybroker.Token { + return f.crafted(t, withSubID(nil)) }, identitybroker.CodeUnauthenticated, identitybroker.ReasonSubjectInvalid}, - {"sub_id as a string", func(_ *testing.T, f *openFixture) identitybroker.Token { - return f.crafted(identityharness.AccessTokenSpec{SubID: identityharness.Alice}) + {"sub_id as a string", func(t *testing.T, f *openFixture) identitybroker.Token { + return f.crafted(t, withSubID(identityharness.Alice)) }, identitybroker.CodeUnauthenticated, identitybroker.ReasonSubjectInvalid}, {"sub_id of another format", subID(map[string]string{"format": "email", "iss": "IDP", "sub": identityharness.Alice}), identitybroker.CodeUnauthenticated, identitybroker.ReasonSubjectInvalid}, @@ -856,8 +871,8 @@ func TestSessionOpenReportsAS1sOwnRefusals(t *testing.T) { }{ { name: "a token AS-1 did not sign: subject_token_invalid is subject_invalid", - token: func(_ *testing.T, f *openFixture) identitybroker.Token { - return f.crafted(identityharness.AccessTokenSpec{ForeignKey: true, Issuer: f.as1.Issuer()}) + token: func(t *testing.T, f *openFixture) identitybroker.Token { + return f.crafted(t, as1servertest.Forgery{ForeignKey: true}) }, as1Code: "invalid_request", as1Reason: "subject_token_invalid", code: identitybroker.CodeUnauthenticated, reason: identitybroker.ReasonSubjectInvalid, diff --git a/internal/testutil/identityharness/as1.go b/internal/testutil/identityharness/as1.go deleted file mode 100644 index fab9d7b962..0000000000 --- a/internal/testutil/identityharness/as1.go +++ /dev/null @@ -1,616 +0,0 @@ -package identityharness - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "maps" - "math/big" - "net/http" - "net/http/httptest" - "net/url" - "slices" - "strings" - "sync" - "testing" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -const ( - as1KeyID = "as1-key-1" - as1UpstreamClient = "as1" - as1CodeLifetime = time.Minute - as1IssuerPath = "/as" -) - -// AS1 stands in for AS-1, Mecatl's sign-in authorization server. It signs -// users in with the authorization code flow and PKCE (S256, required), sends -// them to the upstream IdP as an ordinary OIDC client asking for offline -// access, and issues the AS-1 access token design step (1) describes: -// -// header: typ at+jwt, alg ES256, kid -// claims: iss, sub, sub_id {format iss_sub, iss, sub}, aud, client_id, iat, exp, jti -// -// sub is AS-1's own subject for the company identity: stable across sign-ins, -// and never shared by two company identities. Clients also receive a refresh -// token they can use at the refresh_token grant. -// -// The issuer has a path (/as), as AS-1's final issuer URL does, so discovery -// is served both at {issuer}/.well-known/openid-configuration and at the -// RFC 8414 location. -type AS1 struct { - server *httptest.Server - key *ecdsa.PrivateKey - foreign *ecdsa.PrivateKey - now func() time.Time - audience string - lifetime time.Duration - idp *IdP - secret string - http *http.Client - - brokerKey *ecdsa.PrivateKey - assertionMax time.Duration - grantMax time.Duration - idjagLifetime time.Duration - - mu sync.Mutex - clients map[string]Client - pending map[string]as1Pending // by upstream state - codes map[string]as1Code - refresh map[string]as1Refresh - subjects map[string]string // AS-1 subject by company identity - upstream map[string]string // upstream refresh token by company subject - - brokerKeys map[string]*ecdsa.PublicKey // by kid - assertionJTIs map[string]time.Time // used client assertion jti, kept until - grants map[string]*as1Grant // by refresh token - conversions map[string]time.Time // converted access token jti, kept until - - validator ActorValidator - idjagTargets map[idjagTarget]bool - idjags []IDJAGIssuance -} - -type as1Pending struct { - clientID, redirectURI, state, challenge string - nonce, verifier string -} - -type as1Code struct { - clientID, redirectURI, challenge, user string - expires time.Time -} - -type as1Refresh struct{ clientID, user string } - -func newAS1(t testing.TB, opts Options, idp *IdP) *AS1 { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("identityharness: AS-1 key: %v", err) - } - foreign, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("identityharness: foreign key: %v", err) - } - brokerKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("identityharness: broker key: %v", err) - } - as := &AS1{ - key: key, foreign: foreign, now: opts.Now, audience: opts.Audience, - lifetime: opts.AccessTokenLifetime, idp: idp, secret: randomToken("as1-secret-"), - brokerKey: brokerKey, assertionMax: opts.ClientAssertionMaxLifetime, - grantMax: opts.GrantMaxLifetime, - idjagLifetime: opts.IDJAGLifetime, - clients: make(map[string]Client), - pending: make(map[string]as1Pending), - codes: make(map[string]as1Code), - refresh: make(map[string]as1Refresh), - subjects: make(map[string]string), - upstream: make(map[string]string), - brokerKeys: make(map[string]*ecdsa.PublicKey), - assertionJTIs: make(map[string]time.Time), - grants: make(map[string]*as1Grant), - conversions: make(map[string]time.Time), - idjagTargets: make(map[idjagTarget]bool), - } - for _, c := range opts.Clients { - as.clients[c.ID] = Client{ID: c.ID, RedirectURIs: slices.Clone(c.RedirectURIs)} - } - as.registerBrokerKeys(t, opts.BrokerKeys) - mux := http.NewServeMux() - mux.HandleFunc("GET "+as1IssuerPath+"/.well-known/openid-configuration", as.discovery) - mux.HandleFunc("GET /.well-known/oauth-authorization-server"+as1IssuerPath, as.discovery) - mux.HandleFunc("GET "+as1IssuerPath+"/authorize", as.authorize) - mux.HandleFunc("GET "+as1IssuerPath+"/callback", as.callback) - mux.HandleFunc("POST "+as1IssuerPath+"/token", as.token) - mux.HandleFunc("POST "+as1IssuerPath+"/revoke", as.revoke) - mux.HandleFunc("GET "+as1IssuerPath+"/jwks", as.jwks) - as.server = httptest.NewTLSServer(mux) - t.Cleanup(as.server.Close) - idp.RegisterClient(as1UpstreamClient, as.secret, as.Issuer()+"/callback") - return as -} - -// Issuer is AS-1's issuer URL, which mecak8s accepts (--oidc-issuer). -func (a *AS1) Issuer() string { return a.server.URL + as1IssuerPath } - -// AuthorizationEndpoint is where clients start sign-in. -func (a *AS1) AuthorizationEndpoint() string { return a.Issuer() + "/authorize" } - -// JWKSURL is where AS-1 publishes the keys it signs tokens with. -func (a *AS1) JWKSURL() string { return a.Issuer() + "/jwks" } - -// TokenEndpoint is AS-1's token endpoint. -func (a *AS1) TokenEndpoint() string { return a.Issuer() + "/token" } - -// Audience is the Mecatl API identifier AS-1 access tokens carry. -func (a *AS1) Audience() string { return a.audience } - -// Subject returns AS-1's subject for the company identity user, assigning one -// on first use. Two company identities never share a subject. -func (a *AS1) Subject(user string) string { - a.mu.Lock() - defer a.mu.Unlock() - return a.subjectLocked(user) -} - -func (a *AS1) subjectLocked(user string) string { - if sub, ok := a.subjects[user]; ok { - return sub - } - sum := sha256.Sum256([]byte(a.idp.Issuer() + "\x00" + user)) - sub := "u-" + hex.EncodeToString(sum[:8]) - a.subjects[user] = sub - return sub -} - -// HasUpstreamRefreshToken reports whether AS-1 holds an upstream refresh -// token for user, which its later upstream re-check needs. -func (a *AS1) HasUpstreamRefreshToken(user string) bool { - a.mu.Lock() - defer a.mu.Unlock() - return a.upstream[user] != "" -} - -// AccessTokenSpec describes an AS-1 access token for MintAccessToken. Fields -// left empty take the values a real sign-in produces, so a test changes only -// the defect it checks. -type AccessTokenSpec struct { - // User is the company identity (IdP subject). Empty selects the IdP's - // default user. - User string - // ClientID is the client_id claim. Empty selects the first registered - // client. - ClientID string - // Audience replaces the Mecatl API identifier in aud. - Audience string - // Issuer replaces AS-1's issuer in iss. - Issuer string - // IssuedAt replaces the current time in iat; exp follows from it. - IssuedAt time.Time - // Lifetime replaces the configured lifetime. Negative issues an expired - // token. - Lifetime time.Duration - // Type replaces at+jwt in the typ header. - Type string - // OmitType leaves typ out of the header. - OmitType bool - // OmitSubID leaves the sub_id claim out. - OmitSubID bool - // SubID, when non-nil, replaces the sub_id claim, for a malformed one. - SubID any - // ForeignKey signs with a key that is not in AS-1's JWKS, under AS-1's - // kid. - ForeignKey bool - // Claims are added to the claims, replacing any of the same name, for a - // token such as an ID-JAG with resource and act. - Claims map[string]any -} - -// MintAccessToken issues an AS-1 access token without a sign-in, for tests -// that need a specific token or a specific defect. -func (a *AS1) MintAccessToken(spec AccessTokenSpec) string { - if spec.User == "" { - spec.User, _ = a.idp.user("") - } - if spec.ClientID == "" { - spec.ClientID = a.firstClient() - } - token, err := a.signAccessToken(spec) - if err != nil { - panic("identityharness: mint access token: " + err.Error()) - } - return token -} - -func (a *AS1) firstClient() string { - a.mu.Lock() - defer a.mu.Unlock() - ids := make([]string, 0, len(a.clients)) - for id := range a.clients { - ids = append(ids, id) - } - slices.Sort(ids) - if len(ids) == 0 { - return "" - } - return ids[0] -} - -func (a *AS1) signAccessToken(spec AccessTokenSpec) (string, error) { - iat := spec.IssuedAt - if iat.IsZero() { - iat = a.now() - } - lifetime := spec.Lifetime - if lifetime == 0 { - lifetime = a.lifetime - } - claims := jwt.MapClaims{ - "iss": firstNonEmpty(spec.Issuer, a.Issuer()), - "sub": a.Subject(spec.User), - "aud": firstNonEmpty(spec.Audience, a.audience), - "client_id": spec.ClientID, - "iat": iat.Unix(), - "exp": iat.Add(lifetime).Unix(), - "jti": randomToken("at-"), - } - switch { - case spec.OmitSubID: - case spec.SubID != nil: - claims["sub_id"] = spec.SubID - default: - claims["sub_id"] = map[string]string{"format": "iss_sub", "iss": a.idp.Issuer(), "sub": spec.User} - } - maps.Copy(claims, spec.Claims) - token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) - token.Header["kid"] = as1KeyID - switch { - case spec.OmitType: - delete(token.Header, "typ") - default: - token.Header["typ"] = firstNonEmpty(spec.Type, "at+jwt") - } - key := a.key - if spec.ForeignKey { - key = a.foreign - } - return token.SignedString(key) -} - -func firstNonEmpty(values ...string) string { - for _, v := range values { - if v != "" { - return v - } - } - return "" -} - -func (a *AS1) discovery(w http.ResponseWriter, _ *http.Request) { - iss := a.Issuer() - writeJSON(w, http.StatusOK, map[string]any{ - "issuer": iss, - "authorization_endpoint": iss + "/authorize", - "token_endpoint": iss + "/token", - "revocation_endpoint": iss + "/revoke", - "jwks_uri": iss + "/jwks", - "response_types_supported": []string{responseTypeCode}, - "grant_types_supported": []string{grantAuthorizationCode, grantRefreshToken, grantTokenExchange}, - "code_challenge_methods_supported": []string{pkceS256}, - // none for the public clients, private_key_jwt for the broker. - "token_endpoint_auth_methods_supported": []string{"none", authPrivateKeyJWT}, - "token_endpoint_auth_signing_alg_values_supported": []string{"ES256"}, - "revocation_endpoint_auth_methods_supported": []string{authPrivateKeyJWT}, - "authorization_details_types_supported": []string{ExchangeGrantType}, - }) -} - -func (a *AS1) jwks(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"keys": []map[string]string{ecJWK(as1KeyID, &a.key.PublicKey)}}) -} - -func (a *AS1) authorize(w http.ResponseWriter, r *http.Request) { - q := r.URL.Query() - clientID, redirectURI, state := q.Get(paramClientID), q.Get("redirect_uri"), q.Get("state") - a.mu.Lock() - client, ok := a.clients[clientID] - a.mu.Unlock() - // An unknown client or redirect URI is never redirected to (RFC 6749 - // §4.1.2.1). - registered := -1 - if ok { - registered = slices.Index(client.RedirectURIs, redirectURI) - } - if registered < 0 { - http.Error(w, "unknown client or redirect_uri", http.StatusBadRequest) - return - } - // Redirect to the registered value, not the request's copy of it. - redirectURI = client.RedirectURIs[registered] - if q.Get("response_type") != responseTypeCode { - redirectWithError(w, r, redirectURI, state, "unsupported_response_type") - return - } - // Public clients must use PKCE with S256 (RFC 9700 §2.1.1). - if q.Get("code_challenge") == "" || q.Get("code_challenge_method") != pkceS256 { - redirectWithError(w, r, redirectURI, state, "invalid_request") - return - } - if !a.validResource(q) { - redirectWithError(w, r, redirectURI, state, errInvalidTarget) - return - } - upstreamState := randomToken("as1-state-") - pending := as1Pending{ - clientID: clientID, redirectURI: redirectURI, state: state, challenge: q.Get("code_challenge"), - nonce: randomToken("as1-nonce-"), verifier: randomToken("as1-verifier-"), - } - a.mu.Lock() - a.pending[upstreamState] = pending - a.mu.Unlock() - up := url.Values{ - "response_type": {responseTypeCode}, - paramClientID: {as1UpstreamClient}, - "redirect_uri": {a.Issuer() + "/callback"}, - "scope": {"openid email offline_access"}, - "prompt": {"consent"}, - "state": {upstreamState}, - "nonce": {pending.nonce}, - "code_challenge": {s256(pending.verifier)}, - "code_challenge_method": {pkceS256}, - } - if hint := q.Get("login_hint"); hint != "" { - up.Set("login_hint", hint) - } - http.Redirect(w, r, withQuery(a.idp.Issuer()+"/authorize", up), http.StatusFound) -} - -func (a *AS1) callback(w http.ResponseWriter, r *http.Request) { - q := r.URL.Query() - a.mu.Lock() - pending, ok := a.pending[q.Get("state")] - delete(a.pending, q.Get("state")) // single use - a.mu.Unlock() - if !ok { - http.Error(w, "unknown sign-in state", http.StatusBadRequest) - return - } - if upstreamErr := q.Get("error"); upstreamErr != "" { - code := "server_error" - if upstreamErr == "access_denied" { - code = "access_denied" - } - redirectWithError(w, r, pending.redirectURI, pending.state, code) - return - } - user, upstreamRefresh, err := a.redeemUpstream(r, q.Get("code"), pending) - if err != nil { - redirectWithError(w, r, pending.redirectURI, pending.state, "server_error") - return - } - code := randomToken("as1-code-") - a.mu.Lock() - a.subjectLocked(user) - if upstreamRefresh != "" { - a.upstream[user] = upstreamRefresh - } - a.codes[code] = as1Code{ - clientID: pending.clientID, redirectURI: pending.redirectURI, challenge: pending.challenge, - user: user, expires: a.now().Add(as1CodeLifetime), - } - a.mu.Unlock() - back := url.Values{"code": {code}} - if pending.state != "" { - back.Set("state", pending.state) - } - redirect(w, r, pending.redirectURI, back) -} - -// redeemUpstream exchanges the IdP's code and verifies its ID token as an OIDC -// client would, fetching the IdP's keys over HTTP. It returns the company -// subject and any upstream refresh token. -func (a *AS1) redeemUpstream(r *http.Request, code string, pending as1Pending) (string, string, error) { - form := url.Values{ - "grant_type": {grantAuthorizationCode}, - "code": {code}, - "redirect_uri": {a.Issuer() + "/callback"}, - "code_verifier": {pending.verifier}, - } - req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, a.idp.Issuer()+"/token", strings.NewReader(form.Encode())) - if err != nil { - return "", "", err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetBasicAuth(as1UpstreamClient, a.secret) - var tokens struct { - IDToken string `json:"id_token"` - RefreshToken string `json:"refresh_token"` - } - if err := a.doJSON(req, &tokens); err != nil { - return "", "", err - } - key, err := a.idpKey(r) - if err != nil { - return "", "", err - } - var claims struct { - jwt.RegisteredClaims - Nonce string `json:"nonce"` - } - _, err = jwt.ParseWithClaims(tokens.IDToken, &claims, func(*jwt.Token) (any, error) { return key, nil }, - jwt.WithValidMethods([]string{"RS256"}), jwt.WithIssuer(a.idp.Issuer()), - jwt.WithAudience(as1UpstreamClient), jwt.WithExpirationRequired(), jwt.WithTimeFunc(a.now)) - if err != nil { - return "", "", fmt.Errorf("upstream ID token: %w", err) - } - if claims.Nonce != pending.nonce || claims.Subject == "" { - return "", "", errors.New("upstream ID token: nonce or subject mismatch") - } - return claims.Subject, tokens.RefreshToken, nil -} - -func (a *AS1) idpKey(r *http.Request) (*rsa.PublicKey, error) { - req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, a.idp.Issuer()+"/jwks", nil) - if err != nil { - return nil, err - } - var set struct { - Keys []struct{ Kid, N, E string } `json:"keys"` - } - if err := a.doJSON(req, &set); err != nil { - return nil, err - } - for _, k := range set.Keys { - if k.Kid != idpKeyID { - continue - } - n, nErr := base64.RawURLEncoding.DecodeString(k.N) - e, eErr := base64.RawURLEncoding.DecodeString(k.E) - if nErr != nil || eErr != nil { - return nil, errors.New("upstream JWKS: malformed key") - } - return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}, nil - } - return nil, errors.New("upstream JWKS: key not found") -} - -func (a *AS1) doJSON(req *http.Request, out any) error { - resp, err := a.http.Do(req) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("%s %s: status %d", req.Method, req.URL.Path, resp.StatusCode) - } - return json.NewDecoder(resp.Body).Decode(out) -} - -func (a *AS1) token(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", "") - return - } - clientID, confidential, ok := a.authenticateClient(r) - if !ok { - writeOAuthError(w, http.StatusUnauthorized, "invalid_client", "") - return - } - if confidential { - a.brokerToken(w, r) - return - } - if !a.validResource(r.PostForm) { - writeOAuthError(w, http.StatusBadRequest, errInvalidTarget, "") - return - } - var user, refresh string - switch r.PostForm.Get("grant_type") { - case grantAuthorizationCode: - var ok bool - user, ok = a.redeemCode(clientID, r.PostForm) - if !ok { - writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "") - return - } - refresh = randomToken("as1-rt-") - a.mu.Lock() - a.refresh[refresh] = as1Refresh{clientID: clientID, user: user} - a.mu.Unlock() - case grantRefreshToken: - // Refresh tokens rotate on every use, as they do at ToolHive's fosite - // AS: the presented one stops working. - presented := r.PostForm.Get("refresh_token") - refresh = randomToken("as1-rt-") - a.mu.Lock() - record, ok := a.refresh[presented] - if ok && record.clientID == clientID { - delete(a.refresh, presented) - a.refresh[refresh] = record - } - a.mu.Unlock() - if !ok || record.clientID != clientID { - writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "") - return - } - user = record.user - case grantTokenExchange: - writeOAuthError(w, http.StatusBadRequest, "unauthorized_client", "") - return - default: - writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "") - return - } - access, err := a.signAccessToken(AccessTokenSpec{User: user, ClientID: clientID}) - if err != nil { - writeOAuthError(w, http.StatusInternalServerError, "server_error", "") - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "access_token": access, "token_type": "Bearer", - "expires_in": int(a.lifetime.Seconds()), "refresh_token": refresh, - }) -} - -// brokerToken serves the authenticated broker, which may use only the -// token-exchange grant: for an ID-JAG when it asks for one, and otherwise for -// session open. Grant refresh tokens are stored apart from client refresh -// tokens and the broker holds none of the latter, so the refresh-token grant -// always fails with invalid_grant. -func (a *AS1) brokerToken(w http.ResponseWriter, r *http.Request) { - switch r.PostForm.Get("grant_type") { - case grantTokenExchange: - if r.PostForm.Get("requested_token_type") == TokenTypeIDJAG { - a.issueIDJAG(w, r) - return - } - a.exchange(w, r) - case grantRefreshToken: - writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "") - case grantAuthorizationCode: - writeOAuthError(w, http.StatusBadRequest, "unauthorized_client", "") - default: - writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "") - } -} - -const ( - paramResource = "resource" - // errInvalidTarget is RFC 8707's error for an unacceptable resource. - errInvalidTarget = "invalid_target" -) - -// validResource reports whether an optional RFC 8707 resource names the Mecatl -// API, the only resource AS-1 issues tokens for (so aud stays the audience). -func (a *AS1) validResource(values url.Values) bool { - resources, ok := values[paramResource] - return !ok || len(resources) == 1 && resources[0] == a.audience -} - -// redeemCode checks an authorization code grant (RFC 6749 §4.1.3, RFC 7636 -// §4.6) and returns the signed-in company identity. Codes are single use. -func (a *AS1) redeemCode(clientID string, form url.Values) (string, bool) { - a.mu.Lock() - code, ok := a.codes[form.Get("code")] - delete(a.codes, form.Get("code")) - a.mu.Unlock() - verifier := form.Get("code_verifier") - if !ok || code.clientID != clientID || code.redirectURI != form.Get("redirect_uri") || - !a.now().Before(code.expires) || !validVerifier(verifier) || s256(verifier) != code.challenge { - return "", false - } - return code.user, true -} diff --git a/internal/testutil/identityharness/broker.go b/internal/testutil/identityharness/broker.go deleted file mode 100644 index 9f0a05f8cb..0000000000 --- a/internal/testutil/identityharness/broker.go +++ /dev/null @@ -1,82 +0,0 @@ -package identityharness - -import ( - "context" - "encoding/json" - "net/url" -) - -// ScriptedBroker is a hand-driven caller holding the identity broker's -// credentials (client BrokerClientID and the harness's broker key), for -// exercising AS-1 directly: each request carries a fresh client assertion. It -// is not the identity broker and not its token-endpoint client; production -// code under test must use its own client, registering its key through -// Options.BrokerKeys. -type ScriptedBroker struct{ h *Harness } - -// ScriptedBroker returns a hand-driven caller holding the broker's -// credentials. -func (h *Harness) ScriptedBroker() *ScriptedBroker { return &ScriptedBroker{h: h} } - -// Assertion mints a private_key_jwt client assertion, with any defect spec -// selects. -func (b *ScriptedBroker) Assertion(spec ClientAssertionSpec) string { - return b.h.AS1.signAssertion(spec) -} - -// SessionOpenExchange is one session-open exchange: the user's AS-1 access -// token and the grant expiry to ask for. -type SessionOpenExchange struct { - SubjectToken string - // ExpiresAt is the requested expires_at in Unix seconds; zero leaves it - // out, as a session's first open does. - ExpiresAt int64 - // Assertion replaces the fresh, valid client assertion. - Assertion string -} - -// SessionOpenResult is AS-1's RFC 8693 response to a session open. The -// grant's refresh token arrives in access_token (RFC 8693 §2.2.1). -type SessionOpenResult struct { - RefreshToken string `json:"access_token"` - IssuedTokenType string `json:"issued_token_type"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - AuthorizationDetails []ExchangeGrant `json:"authorization_details"` -} - -// OpenSession runs the session-open token exchange of design step (3), with -// one exchange-grant entry listing only id-jag. A refusal returns an -// *OAuthError; a lost response returns a transport error. -func (b *ScriptedBroker) OpenSession(ctx context.Context, ex SessionOpenExchange) (SessionOpenResult, error) { - details, err := json.Marshal([]ExchangeGrant{{Type: ExchangeGrantType, IssuableTokenTypes: []string{TokenTypeIDJAG}, ExpiresAt: ex.ExpiresAt}}) - if err != nil { - return SessionOpenResult{}, err - } - form := url.Values{ - "grant_type": {grantTokenExchange}, - "subject_token": {ex.SubjectToken}, - "subject_token_type": {tokenTypeAccess}, - "requested_token_type": {tokenTypeRefresh}, - paramAuthDetails: {string(details)}, - } - b.authenticate(form, ex.Assertion) - var result SessionOpenResult - err = b.h.postForm(ctx, b.h.AS1.TokenEndpoint(), form, &result) - return result, err -} - -// Revoke revokes a grant refresh token at AS-1's RFC 7009 endpoint. -func (b *ScriptedBroker) Revoke(ctx context.Context, token string) error { - form := url.Values{"token": {token}, "token_type_hint": {"refresh_token"}} - b.authenticate(form, "") - return b.h.postForm(ctx, b.h.AS1.RevocationEndpoint(), form, nil) -} - -func (b *ScriptedBroker) authenticate(form url.Values, assertion string) { - if assertion == "" { - assertion = b.Assertion(ClientAssertionSpec{}) - } - form.Set("client_assertion_type", clientAssertionTypeJWT) - form.Set("client_assertion", assertion) -} diff --git a/internal/testutil/identityharness/browser.go b/internal/testutil/identityharness/browser.go index db87178775..3dfc4a36ca 100644 --- a/internal/testutil/identityharness/browser.go +++ b/internal/testutil/identityharness/browser.go @@ -19,9 +19,9 @@ var ( // AuthorizeWithConsent plays the browser for a real client's authorization // request at a real AS-1 that shows a consent page, as ToolHive's embedded -// authorization server does for public clients. Unlike Authorize, it keeps -// cookies for the one sign-in (ToolHive binds the sign-in to the browser with -// a cookie), follows 302 and 303 redirects, and approves each consent page by +// authorization server does for public clients. It keeps cookies for the one +// sign-in (ToolHive binds the sign-in to the browser with a cookie), follows +// 302 and 303 redirects, and approves each consent page by // posting its form with the page's Origin, as a browser would. It returns the // query of the redirect to the request's redirect_uri (code, state, or error) // without contacting the client's redirect URI. diff --git a/internal/testutil/identityharness/clientauth.go b/internal/testutil/identityharness/clientauth.go deleted file mode 100644 index 1277fc372f..0000000000 --- a/internal/testutil/identityharness/clientauth.go +++ /dev/null @@ -1,202 +0,0 @@ -package identityharness - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "maps" - "net/http" - "testing" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -const ( - // BrokerClientID is the identity broker's confidential client at AS-1 - // (design step (5)). It authenticates only with private_key_jwt. - BrokerClientID = "mecatl" - // DefaultClientAssertionMaxLifetime is the largest exp - iat AS-1 accepts - // in a client assertion. - DefaultClientAssertionMaxLifetime = 60 * time.Second - // DefaultBrokerKeyID is the kid of the broker key the harness generates - // and registers for BrokerClientID. - DefaultBrokerKeyID = "broker-1" - - authPrivateKeyJWT = "private_key_jwt" - clientAssertionTypeJWT = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" - clientAssertionTyp = "client-authentication+jwt" - // as1ClockSkew is the clock skew AS-1 allows a client assertion's exp and - // iat, and so how long past exp it keeps a used jti. - as1ClockSkew = time.Minute - // ClientAssertionClockSkew is as1ClockSkew, for tests at the boundary. - ClientAssertionClockSkew = as1ClockSkew -) - -// BrokerKey is a public key registered for BrokerClientID, as from its -// jwks_uri or static configuration. Only ES256 (P-256) keys are accepted. -type BrokerKey struct { - KeyID string - Public *ecdsa.PublicKey -} - -// ClientAssertionSpec describes a private_key_jwt client assertion for -// ScriptedBroker.Assertion. Fields left empty produce an assertion AS-1 accepts, so a -// test changes only the defect it checks. -type ClientAssertionSpec struct { - // Issuer and Subject replace BrokerClientID in iss and sub. - Issuer, Subject string - // Audience replaces aud. Nil selects AS-1's issuer; one value is encoded - // as a string, more as an array. - Audience []string - // IssuedAt replaces the current time in iat, which may be in the - // future; exp follows from it. - IssuedAt time.Time - // Lifetime is exp - iat. Zero selects the configured maximum. - Lifetime time.Duration - // JTI replaces the fresh jti, for a replayed assertion. - JTI string - // OmitJTI, OmitIssuedAt, and OmitExpiry leave jti, iat, and exp out. - OmitJTI, OmitIssuedAt, OmitExpiry bool - // KeyID replaces DefaultBrokerKeyID in the kid header; OmitKeyID leaves - // kid out. - KeyID string - OmitKeyID bool - // ForeignKey signs with a key that is not registered for the broker. - ForeignKey bool - // Type replaces client-authentication+jwt in typ; OmitType leaves typ out. - Type string - OmitType bool -} - -func (a *AS1) signAssertion(spec ClientAssertionSpec) string { - iat := spec.IssuedAt - if iat.IsZero() { - iat = a.now() - } - lifetime := spec.Lifetime - if lifetime == 0 { - lifetime = a.assertionMax - } - claims := jwt.MapClaims{ - "iss": firstNonEmpty(spec.Issuer, BrokerClientID), - "sub": firstNonEmpty(spec.Subject, BrokerClientID), - "iat": iat.Unix(), - "exp": iat.Add(lifetime).Unix(), - "jti": firstNonEmpty(spec.JTI, randomToken("ca-")), - } - for name, omit := range map[string]bool{"jti": spec.OmitJTI, "iat": spec.OmitIssuedAt, "exp": spec.OmitExpiry} { - if omit { - delete(claims, name) - } - } - switch len(spec.Audience) { - case 0: - claims["aud"] = a.Issuer() - case 1: - claims["aud"] = spec.Audience[0] - default: - claims["aud"] = spec.Audience - } - token := jwt.NewWithClaims(jwt.SigningMethodES256, claims) - if !spec.OmitKeyID { - token.Header["kid"] = firstNonEmpty(spec.KeyID, DefaultBrokerKeyID) - } - if spec.OmitType { - delete(token.Header, "typ") - } else { - token.Header["typ"] = firstNonEmpty(spec.Type, clientAssertionTyp) - } - key := a.brokerKey - if spec.ForeignKey { - key = a.foreign - } - signed, err := token.SignedString(key) - if err != nil { - panic("identityharness: sign client assertion: " + err.Error()) - } - return signed -} - -// authenticateClient identifies the token or revocation endpoint caller. The -// broker authenticates with private_key_jwt; public clients name themselves -// with client_id and no credential. A client secret, in the form or in Basic -// authentication, is refused for every client, as is mixing methods -// (RFC 6749 §2.3). -func (a *AS1) authenticateClient(r *http.Request) (clientID string, confidential, ok bool) { - form := r.PostForm - if form.Has("client_secret") || r.Header.Get("Authorization") != "" { - return "", false, false - } - if form.Has("client_assertion") || form.Has("client_assertion_type") { - if form.Get("client_assertion_type") != clientAssertionTypeJWT || - (form.Has(paramClientID) && form.Get(paramClientID) != BrokerClientID) || - !a.verifyAssertion(form.Get("client_assertion")) { - return "", false, false - } - return BrokerClientID, true, true - } - clientID = form.Get(paramClientID) - a.mu.Lock() - _, known := a.clients[clientID] - a.mu.Unlock() - return clientID, false, known -} - -// verifyAssertion runs design step (5)'s checks on a client assertion. -func (a *AS1) verifyAssertion(assertion string) bool { - var claims jwt.RegisteredClaims - token, err := jwt.ParseWithClaims(assertion, &claims, func(t *jwt.Token) (any, error) { - kid, isString := t.Header["kid"].(string) - if !isString || kid == "" { - return nil, jwt.ErrTokenUnverifiable - } - a.mu.Lock() - key, ok := a.brokerKeys[kid] - a.mu.Unlock() - if !ok { - return nil, jwt.ErrTokenUnverifiable - } - return key, nil - }, jwt.WithValidMethods([]string{"ES256"}), jwt.WithIssuer(BrokerClientID), jwt.WithSubject(BrokerClientID), - jwt.WithExpirationRequired(), jwt.WithIssuedAt(), jwt.WithLeeway(as1ClockSkew), jwt.WithTimeFunc(a.now)) - if err != nil { - return false - } - // Guess: an explicit typ other than the rfc7523bis type or the generic - // JWT (golang-jwt's default) is refused; an untyped assertion is - // accepted, as the design says. - if typ, present := token.Header["typ"]; present && typ != clientAssertionTyp && typ != "JWT" { - return false - } - if len(claims.Audience) != 1 || claims.Audience[0] != a.Issuer() { - return false - } - if claims.IssuedAt == nil || claims.ExpiresAt.Sub(claims.IssuedAt.Time) > a.assertionMax || claims.ID == "" { - return false - } - now := a.now() - a.mu.Lock() - defer a.mu.Unlock() - maps.DeleteFunc(a.assertionJTIs, func(_ string, keep time.Time) bool { return now.After(keep) }) - if _, seen := a.assertionJTIs[claims.ID]; seen { - return false - } - a.assertionJTIs[claims.ID] = claims.ExpiresAt.Add(as1ClockSkew) - return true -} - -// registerBrokerKeys registers the harness's own broker key and keys, -// failing t on a key AS-1 could never use or that shadows another. -func (a *AS1) registerBrokerKeys(t testing.TB, keys []BrokerKey) { - t.Helper() - a.brokerKeys[DefaultBrokerKeyID] = &a.brokerKey.PublicKey - for _, k := range keys { - if _, dup := a.brokerKeys[k.KeyID]; k.KeyID == "" || dup { - t.Fatalf("identityharness: broker key ID %q is empty, %s, or repeated", k.KeyID, DefaultBrokerKeyID) - } - if k.Public == nil || k.Public.Curve != elliptic.P256() { - t.Fatalf("identityharness: broker key %q is not a P-256 key", k.KeyID) - } - a.brokerKeys[k.KeyID] = k.Public - } -} diff --git a/internal/testutil/identityharness/clientauth_test.go b/internal/testutil/identityharness/clientauth_test.go deleted file mode 100644 index db464fc2fe..0000000000 --- a/internal/testutil/identityharness/clientauth_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package identityharness_test - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "net/http" - "net/url" - "testing" - "time" - - "github.com/golang-jwt/jwt/v5" - - "github.com/stacklok/mecatl/internal/testutil/identityharness" -) - -// TestClientAssertionDefects: every failed design step (5) check returns 401 -// invalid_client, before any session-open check runs. -func TestClientAssertionDefects(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now}) - b := h.ScriptedBroker() - - // Using a jti once, even for an open AS-1 then refuses, consumes it. - _, err := b.OpenSession(t.Context(), identityharness.SessionOpenExchange{ - SubjectToken: "not-a-jwt", - Assertion: b.Assertion(identityharness.ClientAssertionSpec{JTI: "ca-reused"}), - }) - assertReason(t, err, http.StatusBadRequest, "invalid_request", "subject_token_invalid") - - maxLife := identityharness.DefaultClientAssertionMaxLifetime - skew := identityharness.ClientAssertionClockSkew - defects := map[string]string{ - "alg none": handBuilt(t, h, clock, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType), - "HS256": handBuilt(t, h, clock, jwt.SigningMethodHS256, []byte("shared-secret-0123456789abcdef")), - } - for name, spec := range map[string]identityharness.ClientAssertionSpec{ - "token endpoint aud": {Audience: []string{h.AS1.TokenEndpoint()}}, - "two audiences": {Audience: []string{h.AS1.Issuer(), h.AS1.TokenEndpoint()}}, - "expired": {IssuedAt: clock.Now().Add(-2*maxLife - skew)}, - "exp plus skew now": {IssuedAt: clock.Now().Add(-maxLife - skew), Lifetime: maxLife}, - "over-long": {Lifetime: maxLife + time.Second}, - "iat in the future": {IssuedAt: clock.Now().Add(skew + 30*time.Second), Lifetime: 10 * time.Second}, - "no iat": {OmitIssuedAt: true}, - "no exp": {OmitExpiry: true}, - "no jti": {OmitJTI: true}, - "reused jti": {JTI: "ca-reused"}, - "unregistered key": {ForeignKey: true}, - "unknown kid": {KeyID: "other-key"}, - "no kid": {OmitKeyID: true}, - "other iss": {Issuer: "rogue"}, - "other sub": {Subject: "rogue"}, - "other typ": {Type: "at+jwt"}, - } { - defects[name] = b.Assertion(spec) - } - for name, assertion := range defects { - t.Run(name, func(t *testing.T) { - _, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("control open: %v", err) - } - req := openReq(aliceToken(h)) - req.Assertion = assertion - _, err = b.OpenSession(t.Context(), req) - assertReason(t, err, http.StatusUnauthorized, "invalid_client", "") - }) - } - - valid := func() string { return b.Assertion(identityharness.ClientAssertionSpec{}) } - for name, form := range map[string]url.Values{ - "client_secret alone": {"client_id": {"mecatl"}, "client_secret": {"s3cret"}}, - "client_secret with jwt": {"client_secret": {"s3cret"}, "client_assertion_type": {jwtBearer}, "client_assertion": {valid()}}, - "no assertion": {"client_id": {"mecatl"}}, - "wrong assertion type": {"client_assertion_type": {"urn:example:other"}, "client_assertion": {valid()}}, - "assertion for other id": {"client_id": {identityharness.DefaultClientID}, "client_assertion_type": {jwtBearer}, "client_assertion": {valid()}}, - "assertion type, no assert": {"client_assertion_type": {jwtBearer}}, - } { - t.Run(name, func(t *testing.T) { - form.Set("grant_type", grantTokenExchange) - _, err := postToken(t, h, form) - assertOAuthError(t, err, "invalid_client") - }) - } - - t.Run("basic authentication", func(t *testing.T) { - req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, h.AS1.TokenEndpoint(), nil) - if err != nil { - t.Fatal(err) - } - req.SetBasicAuth("mecatl", "s3cret") - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := h.HTTPClient().Do(req) - if err != nil { - t.Fatal(err) - } - _ = resp.Body.Close() - if resp.StatusCode != http.StatusUnauthorized { - t.Errorf("Basic authentication: status %d, want 401", resp.StatusCode) - } - }) -} - -func TestClientAssertionAccepted(t *testing.T) { - brokerKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{ - Now: clock.Now, - BrokerKeys: []identityharness.BrokerKey{{KeyID: "external", Public: &brokerKey.PublicKey}}, - ClientAssertionMaxLifetime: 5 * time.Minute, - }) - b := h.ScriptedBroker() - skew := identityharness.ClientAssertionClockSkew - - external := jwt.NewWithClaims(jwt.SigningMethodES256, assertionClaims(h, clock)) - external.Header["kid"] = "external" - externalAssertion, err := external.SignedString(brokerKey) - if err != nil { - t.Fatal(err) - } - for name, assertion := range map[string]string{ - "registered key from Options, aud array": externalAssertion, - "untyped": b.Assertion(identityharness.ClientAssertionSpec{OmitType: true}), - "typ JWT": b.Assertion(identityharness.ClientAssertionSpec{Type: "JWT"}), - "lifetime exactly at the maximum": b.Assertion(identityharness.ClientAssertionSpec{Lifetime: 5 * time.Minute}), - // The clock skew AS-1 allows, on each side. - "exp passed, within the skew": b.Assertion(identityharness.ClientAssertionSpec{ - IssuedAt: clock.Now().Add(-time.Minute - skew + time.Second), Lifetime: time.Minute, - }), - "iat ahead, within the skew": b.Assertion(identityharness.ClientAssertionSpec{ - IssuedAt: clock.Now().Add(skew - time.Second), Lifetime: time.Minute, - }), - } { - t.Run(name, func(t *testing.T) { - req := openReq(aliceToken(h)) - req.Assertion = assertion - if _, err := b.OpenSession(t.Context(), req); err != nil { - t.Fatalf("OpenSession: %v", err) - } - }) - } -} - -// TestBrokerKeyOptionsRefused: New fails on a broker key AS-1 could never -// use or that shadows the harness's own. -func TestBrokerKeyOptionsRefused(t *testing.T) { - p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - p384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - if err != nil { - t.Fatal(err) - } - for name, key := range map[string]identityharness.BrokerKey{ - "empty key ID": {Public: &p256.PublicKey}, - "default key ID": {KeyID: identityharness.DefaultBrokerKeyID, Public: &p256.PublicKey}, - "P-384": {KeyID: "p384", Public: &p384.PublicKey}, - "nil key": {KeyID: "nil"}, - } { - t.Run(name, func(t *testing.T) { - ft := &fatalRecorder{TB: t} - func() { - defer func() { _ = recover() }() - identityharness.New(ft, identityharness.Options{BrokerKeys: []identityharness.BrokerKey{key}}) - }() - if !ft.failed { - t.Error("New accepted the key") - } - }) - } -} - -// fatalRecorder records Fatalf instead of ending the test, so a test can -// check that New refuses its options. -type fatalRecorder struct { - testing.TB - failed bool -} - -func (f *fatalRecorder) Fatalf(string, ...any) { - f.failed = true - panic("fatal") -} - -// assertionClaims are claims of an assertion AS-1 accepts, at clock's time. -func assertionClaims(h *identityharness.Harness, clock *testClock) jwt.MapClaims { - now := clock.Now() - return jwt.MapClaims{ - "iss": "mecatl", "sub": "mecatl", "aud": []string{h.AS1.Issuer()}, - "iat": now.Unix(), "exp": now.Add(time.Minute).Unix(), "jti": randomJTI(), - } -} - -// handBuilt signs valid claims with method and key under the harness's broker -// kid, for an algorithm AS-1 must refuse. -func handBuilt(t *testing.T, h *identityharness.Harness, clock *testClock, method jwt.SigningMethod, key any) string { - t.Helper() - token := jwt.NewWithClaims(method, assertionClaims(h, clock)) - token.Header["kid"] = identityharness.DefaultBrokerKeyID - token.Header["typ"] = "client-authentication+jwt" - signed, err := token.SignedString(key) - if err != nil { - t.Fatal(err) - } - return signed -} - -func randomJTI() string { return rand.Text() } diff --git a/internal/testutil/identityharness/faulttransport.go b/internal/testutil/identityharness/faulttransport.go index 95c49bd8af..f25c118c85 100644 --- a/internal/testutil/identityharness/faulttransport.go +++ b/internal/testutil/identityharness/faulttransport.go @@ -14,7 +14,11 @@ import ( "sync" ) -const grantJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" // #nosec G101 -- RFC 7523 grant type URN, not a credential. +const ( + grantJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" // #nosec G101 -- RFC 7523 grant type URN, not a credential. + grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" // #nosec G101 -- RFC 8693 grant type URN, not a credential. + tokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" // #nosec G101 -- token type URN, not a credential. +) // GrantKind is the kind of a token endpoint request FaultTransport tells // apart. @@ -44,9 +48,20 @@ const ( // as a connection closed without a response. var errConnectionClosed = fmt.Errorf("identityharness: connection closed without a response: %w", io.ErrUnexpectedEOF) +// Fault is an answer FailNext has a FaultTransport return once instead of +// forwarding the request. +type Fault struct { + // Status is the HTTP status. Zero selects 400. + Status int + // Error is the OAuth error code, such as invalid_request or invalid_grant. + Error string + // Reason starts error_description, as the design's error reasons do. + Reason string +} + // FaultTransport is an http.RoundTripper in front of an authorization -// server's transport, such as HTTPClient's for AS-1 or an in-process client -// for AS-2. It forwards every request, records each one for the token +// server's transport, such as as1servertest's HTTPClient for AS-1 or an +// in-process client for AS-2. It forwards every request, records each one for the token // endpoint, and applies the faults a test queued, one per request of the // fault's kind in the order queued. It is a transport rather than a handler // wrapper because a lost connection can only be modelled on the caller's @@ -166,7 +181,7 @@ func (f *FaultTransport) record(r GrantRequest) { func grantKind(form url.Values) GrantKind { switch form.Get("grant_type") { case grantTokenExchange: - if form.Get("requested_token_type") == TokenTypeIDJAG { + if form.Get("requested_token_type") == tokenTypeIDJAG { return KindIDJAG } return "" diff --git a/internal/testutil/identityharness/faulttransport_test.go b/internal/testutil/identityharness/faulttransport_test.go index 869f2c4275..5f4f5d5ddb 100644 --- a/internal/testutil/identityharness/faulttransport_test.go +++ b/internal/testutil/identityharness/faulttransport_test.go @@ -1,25 +1,99 @@ package identityharness_test import ( + "crypto/rand" + "encoding/json" "errors" "io" "net/http" + "net/http/httptest" "net/url" + "strconv" + "sync" "testing" "github.com/stacklok/mecatl/internal/testutil/identityharness" ) -// faultClient is a client for the harness's AS-1 through a FaultTransport. -func faultClient(f *idjagFixture) (*http.Client, *identityharness.FaultTransport) { - client := f.h.HTTPClient() - ft := identityharness.NewFaultTransport(client.Transport, f.h.AS1.TokenEndpoint()) - client.Transport = ft - return client, ft +const ( + grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" + grantJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + tokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" +) + +// tokenServer is a stub token endpoint: it issues an ID-JAG for an ID-JAG +// exchange unless revoked is set, then answering invalid_request revoked, a +// refresh token for any other token exchange, and refuses a redemption with +// invalid_grant. A client assertion it has seen before is refused with 401 +// invalid_client. +type tokenServer struct { + base, endpoint string + client *http.Client + + mu sync.Mutex + revoked bool + seen map[string]bool + issued int +} + +func startTokenServer(t *testing.T) *tokenServer { + t.Helper() + s := &tokenServer{seen: map[string]bool{}} + server := httptest.NewServer(http.HandlerFunc(s.serve)) + t.Cleanup(server.Close) + s.base, s.endpoint, s.client = server.URL, server.URL+"/token", server.Client() + return s +} + +func (s *tokenServer) serve(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + answer := func(status int, body map[string]string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) + } + s.mu.Lock() + defer s.mu.Unlock() + if assertion := r.PostForm.Get("client_assertion"); assertion != "" { + if s.seen[assertion] { + answer(http.StatusUnauthorized, map[string]string{"error": "invalid_client"}) + return + } + s.seen[assertion] = true + } + switch { + case r.URL.Path != "/token": + w.WriteHeader(http.StatusOK) + case r.PostForm.Get("grant_type") == grantJWTBearer: + answer(http.StatusBadRequest, map[string]string{"error": "invalid_grant"}) + case r.PostForm.Get("requested_token_type") == tokenTypeIDJAG && s.revoked: + answer(http.StatusBadRequest, map[string]string{"error": "invalid_request", "error_description": "revoked"}) + default: + s.issued++ + answer(http.StatusOK, map[string]string{"access_token": "issued-" + strconv.Itoa(s.issued)}) + } } -// post sends form to AS-1's token endpoint through client and returns the -// status, or the transport error. +func (s *tokenServer) revoke() { + s.mu.Lock() + defer s.mu.Unlock() + s.revoked = true +} + +func (s *tokenServer) issuedCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.issued +} + +// faultClient is a client for s through a FaultTransport. +func faultClient(s *tokenServer) (*http.Client, *identityharness.FaultTransport) { + ft := identityharness.NewFaultTransport(s.client.Transport, s.endpoint) + return &http.Client{Transport: ft}, ft +} + +// post sends form to endpoint through client and returns the status, or the +// transport error. func post(t *testing.T, client *http.Client, endpoint string, form url.Values) (int, error) { t.Helper() resp, err := client.PostForm(endpoint, form) @@ -31,34 +105,43 @@ func post(t *testing.T, client *http.Client, endpoint string, form url.Values) ( return resp.StatusCode, nil } +// idjagForm is an ID-JAG exchange with a fresh client assertion. +func idjagForm() url.Values { + return url.Values{ + "grant_type": {grantTokenExchange}, "requested_token_type": {tokenTypeIDJAG}, + "subject_token": {"grant"}, "actor_token": {"svid"}, "mecatl_operation": {"op-1"}, + "client_assertion": {rand.Text()}, + } +} + func TestFaultTransportTellsKindsApart(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - client, ft := faultClient(f) - endpoint := f.h.AS1.TokenEndpoint() - if status, err := post(t, client, endpoint, idjagForm(f.h, f.grant, svidAlice)); err != nil || status != http.StatusOK { + s := startTokenServer(t) + client, ft := faultClient(s) + if status, err := post(t, client, s.endpoint, idjagForm()); err != nil || status != http.StatusOK { t.Fatalf("ID-JAG exchange = %d, %v", status, err) } - open := exchangeForm(f.h, aliceToken(f.h), `[{"type":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeIDJAG+`"]}]`) - if status, err := post(t, client, endpoint, open); err != nil || status != http.StatusOK { + open := url.Values{"grant_type": {grantTokenExchange}, "requested_token_type": {"urn:ietf:params:oauth:token-type:refresh_token"}} + if status, err := post(t, client, s.endpoint, open); err != nil || status != http.StatusOK { t.Fatalf("session open = %d, %v", status, err) } - // AS-1 refuses a redemption, but the transport still records it. - if status, err := post(t, client, endpoint, url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, "assertion": {"jag"}}); err != nil || status < 400 { + // The server refuses a redemption, but the transport still records it. + if status, err := post(t, client, s.endpoint, url.Values{"grant_type": {grantJWTBearer}, "assertion": {"jag"}}); err != nil || status < 400 { t.Fatalf("redemption = %d, %v", status, err) } // Requests elsewhere pass through unrecorded. - if _, err := post(t, client, f.h.AS1.RevocationEndpoint(), url.Values{"token": {"x"}}); err != nil { + if _, err := post(t, client, s.base+"/revoke", url.Values{"token": {"x"}}); err != nil { t.Fatal(err) } got := ft.Requests() if len(got) != 3 || got[0].Kind != identityharness.KindIDJAG || got[1].Kind != "" || got[2].Kind != identityharness.KindRedemption { t.Fatalf("requests = %+v, want an ID-JAG exchange, a session open of no kind, and a redemption", got) } - if got[0].IssuedToken == "" || got[0].ClientAssertion == "" || !got[0].Reached || got[0].Status != http.StatusOK { - t.Fatalf("ID-JAG request = %+v, want the issued token and client assertion recorded", got[0]) + if got[0].IssuedToken == "" || got[0].ClientAssertion == "" || got[0].ActorToken != "svid" || got[0].Operation != "op-1" || + !got[0].Reached || got[0].Status != http.StatusOK { + t.Fatalf("ID-JAG request = %+v, want the issued token, client assertion, actor token, and operation recorded", got[0]) } if got[2].Assertion != "jag" || got[2].IssuedToken != "" || got[2].Code == "" { - t.Fatalf("redemption = %+v, want its assertion and AS-1's refusal recorded", got[2]) + t.Fatalf("redemption = %+v, want its assertion and the server's refusal recorded", got[2]) } for kind, want := range map[identityharness.GrantKind]int{identityharness.KindIDJAG: 1, identityharness.KindRedemption: 1} { if n := ft.Count(kind); n != want { @@ -68,10 +151,9 @@ func TestFaultTransportTellsKindsApart(t *testing.T) { } func TestFaultTransportFaults(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - client, ft := faultClient(f) - endpoint := f.h.AS1.TokenEndpoint() - idjag := func() (int, error) { return post(t, client, endpoint, idjagForm(f.h, f.grant, svidAlice)) } + s := startTokenServer(t) + client, ft := faultClient(s) + idjag := func() (int, error) { return post(t, client, s.endpoint, idjagForm()) } // Faults apply to their kind only, in the order queued. ft.FailNext(identityharness.KindIDJAG, identityharness.Fault{Error: "invalid_request", Reason: "revoked: grant revoked"}) @@ -90,35 +172,36 @@ func TestFaultTransportFaults(t *testing.T) { want := []struct { fault string reached bool - code string - reason string }{ - {identityharness.FaultAnswered, false, "", ""}, - {identityharness.FaultLost, true, "", ""}, - {identityharness.FaultForwarded, true, "", ""}, + {identityharness.FaultAnswered, false}, + {identityharness.FaultLost, true}, + {identityharness.FaultForwarded, true}, } if len(got) != len(want) { t.Fatalf("requests = %+v", got) } for i, w := range want { - if got[i].Fault != w.fault || got[i].Reached != w.reached || got[i].Code != w.code || got[i].Reason != w.reason { + if got[i].Fault != w.fault || got[i].Reached != w.reached || got[i].Code != "" || got[i].Reason != "" { t.Errorf("request %d = %+v, want %+v", i, got[i], w) } } // A lost response's ID-JAG was issued: the server processed it. - if got[1].IssuedToken == "" || len(f.h.AS1.IDJAGsIssued()) != 2 { - t.Fatalf("lost request = %+v with %d ID-JAGs issued, want it issued", got[1], len(f.h.AS1.IDJAGsIssued())) + if got[1].IssuedToken == "" || s.issuedCount() != 2 { + t.Fatalf("lost request = %+v with %d ID-JAGs issued, want it issued", got[1], s.issuedCount()) + } + // The redemption fault is still queued for its own kind. + if status, err := post(t, client, s.endpoint, url.Values{"grant_type": {grantJWTBearer}, "assertion": {"jag"}}); err != nil || status != http.StatusServiceUnavailable { + t.Fatalf("faulted redemption = %d, %v; want 503", status, err) } } func TestFaultTransportOnNextAndDuplicate(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - client, ft := faultClient(f) - endpoint := f.h.AS1.TokenEndpoint() + s := startTokenServer(t) + client, ft := faultClient(s) // OnNext runs before forwarding, so revoking there refuses this request. - ft.OnNext(identityharness.KindIDJAG, func() { f.h.AS1.RevokeGrants(identityharness.Alice) }) - if status, err := post(t, client, endpoint, idjagForm(f.h, f.grant, svidAlice)); err != nil || status != http.StatusBadRequest { + ft.OnNext(identityharness.KindIDJAG, s.revoke) + if status, err := post(t, client, s.endpoint, idjagForm()); err != nil || status != http.StatusBadRequest { t.Fatalf("exchange after OnNext revoked = %d, %v; want 400", status, err) } if r := ft.Requests()[0]; r.Fault != identityharness.FaultOnNext || r.Code != "invalid_request" || r.Reason != "revoked" { @@ -127,9 +210,11 @@ func TestFaultTransportOnNextAndDuplicate(t *testing.T) { // DuplicateNext returns the first answer and records the resubmission's: // the replayed client assertion is refused. - grant := f.openGrant(t, identityharness.Alice) + s.mu.Lock() + s.revoked = false // a newer grant + s.mu.Unlock() ft.DuplicateNext(identityharness.KindIDJAG) - if status, err := post(t, client, endpoint, idjagForm(f.h, grant, svidAlice)); err != nil || status != http.StatusOK { + if status, err := post(t, client, s.endpoint, idjagForm()); err != nil || status != http.StatusOK { t.Fatalf("duplicated exchange = %d, %v; want the first answer, 200", status, err) } got := ft.Requests() diff --git a/internal/testutil/identityharness/gateway_test.go b/internal/testutil/identityharness/gateway_test.go index f1a8ac9638..a94ed16b42 100644 --- a/internal/testutil/identityharness/gateway_test.go +++ b/internal/testutil/identityharness/gateway_test.go @@ -2,6 +2,7 @@ package identityharness_test import ( "bufio" + "crypto/rand" "encoding/json" "errors" "net/http" @@ -9,6 +10,8 @@ import ( "strings" "testing" + "github.com/golang-jwt/jwt/v5" + "github.com/stacklok/mecatl/internal/testutil/identityharness" ) @@ -34,6 +37,26 @@ func rpc(t *testing.T, h *identityharness.Harness, g *identityharness.Gateway, t return resp.StatusCode, resp.Header.Get("WWW-Authenticate"), out } +// unsignedJWT is a JWT with claims and alg none, for the gateway stand-in, +// which reads a bearer token's jti without verifying it. +func unsignedJWT(t *testing.T, claims jwt.MapClaims) string { + t.Helper() + token, err := jwt.NewWithClaims(jwt.SigningMethodNone, claims).SignedString(jwt.UnsafeAllowNoneSignatureType) + if err != nil { + t.Fatal(err) + } + return token +} + +func mustJSON(t *testing.T, v any) string { + t.Helper() + raw, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return string(raw) +} + const ( initializeBody = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}` listBody = `{"jsonrpc":"2.0","id":2,"method":"tools/list"}` @@ -46,7 +69,8 @@ func TestGatewayServesWithABearerToken(t *testing.T) { if !strings.HasPrefix(g.URL(), "https://") || !strings.HasSuffix(g.URL(), "/mcp") { t.Fatalf("URL = %q", g.URL()) } - token := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{}) + jti := rand.Text() + token := unsignedJWT(t, jwt.MapClaims{"jti": jti}) if status, _, body := rpc(t, h, g, token, initializeBody); status != http.StatusOK || body["result"] == nil { t.Fatalf("initialize = %d, %v", status, body) } @@ -62,8 +86,6 @@ func TestGatewayServesWithABearerToken(t *testing.T) { if status != http.StatusUnauthorized || challenge != "Bearer" { t.Fatalf("no token = %d, %q; want 401 Bearer", status, challenge) } - _, claims := verify(t, h, token) - jti := claims["jti"].(string) want := []identityharness.GatewayCall{ {Method: "initialize", Status: 200, TokenJTI: jti}, {Method: "tools/list", Status: 200, TokenJTI: jti}, diff --git a/internal/testutil/identityharness/harness.go b/internal/testutil/identityharness/harness.go index 1484b81ec5..e3540f08e9 100644 --- a/internal/testutil/identityharness/harness.go +++ b/internal/testutil/identityharness/harness.go @@ -1,72 +1,22 @@ -// Package identityharness stands in, offline, for the external parties of the -// agent identity credential flow: the upstream company IdP and AS-1, Mecatl's -// sign-in authorization server. It follows +// Package identityharness is what tests of the agent identity credential +// flow need offline around the real authorization servers: AS-1 and AS-2 are +// ToolHive's embedded authorization servers, run by the tests themselves +// (AS-1 through as1servertest), and the harness supplies the rest, following // docs/drafts/agent-identity/credentials-and-lifecycle.md for every step it -// covers, so identity broker tests and Mecatl composition tests share one -// stand-in instead of each inventing its own. +// covers: // -// The harness covers: -// -// - user sign-in: authorization code with PKCE at AS-1, which signs the -// user in at the upstream IdP as an ordinary OIDC client, and AS-1 access -// tokens as design step (1) describes them (as1.go, signin.go); -// - broker client authentication, design step (5): the confidential client -// BrokerClientID with private_key_jwt, checking the registered key, iss -// and sub, aud equal to AS-1's issuer, exp and iat with -// ClientAssertionClockSkew allowed, exp - iat, and a jti used once and -// kept until exp plus the skew; a client secret is refused (clientauth.go); -// - AS-1's conversion of a sign-in at session open, design step (3), kept -// only as the grant fixture for tests of revocation and its reasons, -// which the real AS-1 does not serve yet (#2568), and for mecak8s's -// TestIdentityBrokerAgainstOfflineHarness, which mints a second client's -// access token and moves AS-1's clock. Session-open -// behaviour itself, including refusals and faults, is tested against the -// real AS-1 (as1servertest). The RFC 8693 exchange turns an AS-1 access -// token into a non-rotating refresh token of a generic grant -// (stacklok/toolhive#6897) that names the client and the user, never a -// Mecatl session or owner, and issues only ID-JAGs. The request carries -// one exchange-grant entry whose optional expires_at AS-1 caps at its -// maximum and echoes. Each access-token jti converts once; a refused -// access token gets subject_token_invalid, not the real AS-1's reasons. -// The grant's refresh token is refused at the refresh-token grant -// (sessionopen.go); -// - AS-1's per-call ID-JAG exchange, design step (7), kept only for tests -// of revocation reasons until the real AS-1 sends them (#2568): a -// grant's refresh token with the agent's SVID as -// the actor token, for a configured AS-2 audience and vMCP resource. The -// actor checks are a test-supplied ActorValidator; the upstream re-check -// is not modelled, so tests inject its reasons as faults (idjag.go); -// - RFC 7009 revocation of grant refresh tokens, until -// stacklok/toolhive#6966 and stacklok/toolhive#6972 (revoke.go); -// - ScriptedBroker, a hand-driven caller holding the broker's credentials -// for exercising AS-1 directly (broker.go). Production code under test -// uses its own client, not ScriptedBroker; -// - one-shot IdP faults for sign-in (idp.go), and FaultTransport, which -// fails, drops, loses, duplicates, or intercepts session-open, ID-JAG, -// and redemption requests on the caller's side of any authorization -// server (faulttransport.go); +// - the upstream company IdP, which AS-1 signs users in at as an ordinary +// OIDC client (idp.go); +// - a browser that keeps cookies and approves ToolHive's consent page +// (browser.go); +// - FaultTransport, which fails, drops, loses, duplicates, or intercepts +// ID-JAG and redemption requests on the caller's side of any +// authorization server (faulttransport.go); // - a gateway stand-in, a minimal MCP server that needs a bearer token and -// can reject it or ask the user to connect a server (gateway.go); -// - a browser for tests hosting the real AS-1, which keeps cookies and -// approves ToolHive's consent page (browser.go). -// -// Keeping one live refresh token per session, checking the owner, and -// refusing to reopen a closed session are the broker's job, so AS-1 does -// none of them. Later work adds child grants (with parent_revoked and -// not_issuable) and client refresh-token revocation, each in its own files. -// AS-2 is deliberately absent: tests use the real embedded ToolHive -// authorization server for it. -// -// Where the design is silent the harness guesses, marked "Guess:" in the code: -// -// - Revocation is RFC 7009 at {issuer}/revoke, callable only by the -// authenticated broker. Revoking a grant's refresh token revokes the -// grant; any other value changes nothing and answers 200. -// - A client assertion with an explicit typ other than -// client-authentication+jwt or JWT (golang-jwt's default) is refused; an -// untyped one is accepted; only ES256 is accepted. Because the harness -// accepts JWT, the production broker's own tests must check the typ it -// emits. +// can reject it or ask the user to connect a server, until #2537 and +// #2812 (gateway.go); +// - the loopback TLS certificate, CA, signing-key, and upstream-client +// helpers a real AS-1 needs to run against the IdP (harness.go). // // Everything runs on loopback TLS servers that close when the test ends. The // harness is test code; production packages never import it. @@ -83,116 +33,55 @@ import ( "net/http" "os" "path/filepath" - "sync" "testing" "time" "github.com/golang-jwt/jwt/v5" ) -// Defaults used when Options leaves a field empty. +// Values shared by the tests that use the harness. const ( // DefaultAudience is the Mecatl API identifier AS-1 access tokens carry in // aud. mecak8s must accept the same value (--oidc-audience). DefaultAudience = "https://mecatl.test/api" - // DefaultClientID is the public client registered when Options.Clients is - // empty. + // DefaultClientID is the TUI's public client ID at AS-1. DefaultClientID = "mecatui" - // DefaultRedirectURI is DefaultClientID's only redirect URI. + // DefaultRedirectURI is a redirect URI for DefaultClientID. DefaultRedirectURI = "http://127.0.0.1:8765/callback" - // DefaultAccessTokenLifetime is the AS-1 access token lifetime. - DefaultAccessTokenLifetime = 15 * time.Minute // Alice and Bob are the company identities the upstream IdP knows by // default. Alice is the default user. Alice = "alice-204" Bob = "bob-317" ) -// Client is a public OAuth client registered at AS-1, such as the TUI or -// Studio. Redirect URIs match exactly. -type Client struct { - ID string - RedirectURIs []string -} - -// Options configures a Harness. The zero value is usable. -type Options struct { - // Audience is the Mecatl API identifier. Empty selects DefaultAudience. - Audience string - // Clients are AS-1's public clients. Empty registers DefaultClientID with - // DefaultRedirectURI. - Clients []Client - // Users are the company identities (IdP subjects) the upstream IdP can - // sign in. The first is the default user. Empty selects Alice and Bob. - Users []string - // AccessTokenLifetime is the AS-1 access token lifetime. Zero selects - // DefaultAccessTokenLifetime. - AccessTokenLifetime time.Duration - // Now is the clock for every issued token and code. Nil selects time.Now. - Now func() time.Time - // BrokerKeys are public keys registered for BrokerClientID in addition - // to the harness's own broker key, DefaultBrokerKeyID. Each needs a - // unique, nonempty KeyID other than DefaultBrokerKeyID and a P-256 key. - BrokerKeys []BrokerKey - // ClientAssertionMaxLifetime is the largest exp - iat AS-1 accepts in a - // client assertion. Zero selects DefaultClientAssertionMaxLifetime. - ClientAssertionMaxLifetime time.Duration - // GrantMaxLifetime is AS-1's maximum lifetime for a grant that issues - // ID-JAGs: the expiry when an exchange asks for none, and the cap on one - // it asks for. Zero selects DefaultGrantMaxLifetime. - GrantMaxLifetime time.Duration - // IDJAGLifetime is the lifetime of the ID-JAGs AS-1 issues, before the cap - // at the actor token's expiry. Zero selects DefaultIDJAGLifetime. - IDJAGLifetime time.Duration -} +// Options configures a Harness. It has no settings yet; the IdP knows Alice, +// its default user, and Bob. +type Options struct{} // Harness is a running set of stand-ins. Create it with New. type Harness struct { IdP *IdP - AS1 *AS1 certPEM []byte } +// Owner is a company identity: the upstream IdP's issuer and subject, as in +// an AS-1 access token's sub_id. +type Owner struct { + Issuer string `json:"iss"` + Subject string `json:"sub"` +} + // New starts the stand-ins and stops them when t ends. -func New(t testing.TB, opts Options) *Harness { +func New(t testing.TB, _ Options) *Harness { t.Helper() - if opts.Audience == "" { - opts.Audience = DefaultAudience - } - if len(opts.Clients) == 0 { - opts.Clients = []Client{{ID: DefaultClientID, RedirectURIs: []string{DefaultRedirectURI}}} - } - if len(opts.Users) == 0 { - opts.Users = []string{Alice, Bob} - } - if opts.AccessTokenLifetime <= 0 { - opts.AccessTokenLifetime = DefaultAccessTokenLifetime - } - if opts.Now == nil { - opts.Now = time.Now - } - if opts.ClientAssertionMaxLifetime <= 0 { - opts.ClientAssertionMaxLifetime = DefaultClientAssertionMaxLifetime - } - if opts.GrantMaxLifetime <= 0 { - opts.GrantMaxLifetime = DefaultGrantMaxLifetime - } - if opts.IDJAGLifetime <= 0 { - opts.IDJAGLifetime = DefaultIDJAGLifetime - } - - idp := newIdP(t, opts) - as1 := newAS1(t, opts, idp) + idp := newIdP(t) // httptest serves every TLS server with the same loopback certificate, so - // one client and one CA file cover both stand-ins. - h := &Harness{ + // one client and one CA file cover every stand-in. + return &Harness{ IdP: idp, - AS1: as1, certPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: idp.server.Certificate().Raw}), } - as1.http = h.HTTPClient() - return h } // HTTPClient returns a client that trusts the stand-ins' TLS certificate and @@ -211,11 +100,8 @@ func (h *Harness) HTTPClient() *http.Client { // access token's sub_id carries it. func (h *Harness) Owner(user string) Owner { return Owner{Issuer: h.IdP.Issuer(), Subject: user} } -// CACertPEM returns the PEM certificate that verifies every stand-in. -func (h *Harness) CACertPEM() []byte { return append([]byte(nil), h.certPEM...) } - -// WriteCACert writes CACertPEM to a file in dir and returns its path, for a -// server's --oidc-ca-cert-file flag. +// WriteCACert writes the PEM certificate that verifies every stand-in to a +// file in dir and returns its path, for a server's --oidc-ca-cert-file flag. func (h *Harness) WriteCACert(t testing.TB, dir string) string { t.Helper() path := filepath.Join(dir, "identityharness-ca.pem") @@ -244,19 +130,10 @@ func (*Harness) WriteSigningKey(t testing.TB, dir string) string { return path } -// ResignAccessToken returns token, a JWT signed with the key WriteSigningKey -// wrote to keyFile, with its claims changed by edit and signed again with that -// key under the same header, so its issuer verifies it and judges it by the -// changed claims. -func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapClaims)) string { +// ReadSigningKey reads the private key WriteSigningKey wrote to file. +func ReadSigningKey(t testing.TB, file string) *ecdsa.PrivateKey { t.Helper() - claims := jwt.MapClaims{} - parsed, _, err := jwt.NewParser().ParseUnverified(token, claims) - if err != nil { - t.Fatalf("identityharness: parse access token: %v", err) - } - edit(claims) - raw, err := os.ReadFile(keyFile) + raw, err := os.ReadFile(file) if err != nil { t.Fatalf("identityharness: read signing key: %v", err) } @@ -268,9 +145,24 @@ func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapCla if err != nil { t.Fatalf("identityharness: parse signing key: %v", err) } + return key +} + +// ResignAccessToken returns token, a JWT signed with the key WriteSigningKey +// wrote to keyFile, with its claims changed by edit and signed again with that +// key under the same header, so its issuer verifies it and judges it by the +// changed claims. +func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapClaims)) string { + t.Helper() + claims := jwt.MapClaims{} + parsed, _, err := jwt.NewParser().ParseUnverified(token, claims) + if err != nil { + t.Fatalf("identityharness: parse access token: %v", err) + } + edit(claims) resigned := jwt.NewWithClaims(jwt.SigningMethodES256, claims) resigned.Header = maps.Clone(parsed.Header) - signed, err := resigned.SignedString(key) + signed, err := resigned.SignedString(ReadSigningKey(t, keyFile)) if err != nil { t.Fatalf("identityharness: sign access token: %v", err) } @@ -311,40 +203,3 @@ func (h *Harness) WriteServerKeyPair(t testing.TB, dir string) (certFile, keyFil } return certFile, keyFile } - -// faults holds one-shot failures a test forces on an IdP endpoint. -type faults struct { - mu sync.Mutex - pending map[string][]Fault -} - -// Fault is a failure the IdP or a FaultTransport returns once instead of the -// normal response. -type Fault struct { - // Status is the HTTP status for a token endpoint fault. Zero selects 400. - Status int - // Error is the OAuth error code, such as access_denied or invalid_grant. - Error string - // Reason starts error_description, as the design's error reasons do. - Reason string -} - -func (f *faults) push(endpoint string, fault Fault) { - f.mu.Lock() - defer f.mu.Unlock() - if f.pending == nil { - f.pending = make(map[string][]Fault) - } - f.pending[endpoint] = append(f.pending[endpoint], fault) -} - -func (f *faults) pop(endpoint string) (Fault, bool) { - f.mu.Lock() - defer f.mu.Unlock() - queue := f.pending[endpoint] - if len(queue) == 0 { - return Fault{}, false - } - f.pending[endpoint] = queue[1:] - return queue[0], true -} diff --git a/internal/testutil/identityharness/harness_test.go b/internal/testutil/identityharness/harness_test.go deleted file mode 100644 index d734f693bc..0000000000 --- a/internal/testutil/identityharness/harness_test.go +++ /dev/null @@ -1,499 +0,0 @@ -package identityharness_test - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "net/http" - "net/url" - "strings" - "testing" - "time" - - "github.com/golang-jwt/jwt/v5" - - "github.com/stacklok/mecatl/internal/testutil/identityharness" -) - -// TestSignInIssuesDesignAccessToken checks the AS-1 access token against -// design step (1), verifying it with the keys AS-1 publishes through both -// discovery locations. -func TestSignInIssuesDesignAccessToken(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: identityharness.Alice}) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - if tokens.TokenType != "Bearer" || tokens.RefreshToken == "" || tokens.ExpiresIn != int(identityharness.DefaultAccessTokenLifetime.Seconds()) { - t.Fatalf("tokens = %+v, want Bearer with a refresh token and the default lifetime", tokens) - } - - header, claims := verify(t, h, tokens.AccessToken) - if header["typ"] != "at+jwt" || header["alg"] != "ES256" || header["kid"] == "" { - t.Errorf("header = %v, want typ at+jwt, alg ES256, and a kid", header) - } - want := map[string]any{ - "iss": h.AS1.Issuer(), - "sub": h.AS1.Subject(identityharness.Alice), - "aud": identityharness.DefaultAudience, - "client_id": identityharness.DefaultClientID, - "sub_id": map[string]any{"format": "iss_sub", "iss": h.IdP.Issuer(), "sub": identityharness.Alice}, - } - for name, value := range want { - if got, _ := json.Marshal(claims[name]); string(got) != mustJSON(t, value) { - t.Errorf("claim %s = %s, want %s", name, got, mustJSON(t, value)) - } - } - if claims["jti"] == "" || claims["jti"] == nil { - t.Error("access token has no jti") - } - if life := claims["exp"].(float64) - claims["iat"].(float64); life != identityharness.DefaultAccessTokenLifetime.Seconds() { - t.Errorf("exp - iat = %v, want %v", life, identityharness.DefaultAccessTokenLifetime.Seconds()) - } - if !strings.HasSuffix(h.AS1.Issuer(), "/as") { - t.Errorf("issuer %q has no path; AS-1's final issuer URL has one", h.AS1.Issuer()) - } -} - -// TestSubjectsAreStableAndDistinct also pins the AS-1 property mecak8s's -// ownership relies on (the real AS-1 must hold it too): two AS-1 subjects never -// carry the same company identity in sub_id. -func TestSubjectsAreStableAndDistinct(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - subjects := map[string]string{} - companyBySubject := map[string]string{} - for _, user := range []string{identityharness.Alice, identityharness.Bob, identityharness.Alice} { - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: user}) - if err != nil { - t.Fatalf("SignIn(%s): %v", user, err) - } - _, claims := verify(t, h, tokens.AccessToken) - sub := claims["sub"].(string) - if prev, ok := subjects[user]; ok && prev != sub { - t.Errorf("%s signed in as %q, then %q", user, prev, sub) - } - subjects[user] = sub - company := mustJSON(t, claims["sub_id"]) - for otherSub, otherCompany := range companyBySubject { - if otherSub != sub && otherCompany == company { - t.Errorf("AS-1 subjects %q and %q both carry company identity %s", otherSub, sub, company) - } - } - companyBySubject[sub] = company - } - if subjects[identityharness.Alice] == subjects[identityharness.Bob] { - t.Errorf("Alice and Bob share AS-1 subject %q", subjects[identityharness.Alice]) - } -} - -// TestSignInAsksUpstreamForOfflineAccess: AS-1 needs an upstream refresh -// token for its later re-check, and the IdP issues one only for -// offline_access with prompt=consent. -func TestSignInAsksUpstreamForOfflineAccess(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - if _, err := h.SignIn(t.Context(), identityharness.SignInRequest{}); err != nil { - t.Fatalf("SignIn: %v", err) - } - if got := h.IdP.RefreshTokensIssued(identityharness.Alice); got != 1 { - t.Errorf("IdP refresh tokens for Alice = %d, want 1", got) - } - if !h.AS1.HasUpstreamRefreshToken(identityharness.Alice) { - t.Error("AS-1 holds no upstream refresh token for Alice") - } -} - -// TestSignInNextAsSelectsTheNextSignInOnly: the IdP signs in the selected -// user once, over login_hint, and then falls back to login_hint or the -// default user; an unknown selection is refused. -func TestSignInNextAsSelectsTheNextSignInOnly(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - signedIn := func(t *testing.T, req identityharness.SignInRequest) string { - t.Helper() - tokens, err := h.SignIn(t.Context(), req) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - _, claims := verify(t, h, tokens.AccessToken) - subID, _ := claims["sub_id"].(map[string]any) - user, _ := subID["sub"].(string) - return user - } - - h.IdP.SignInNextAs(identityharness.Bob) - if got := signedIn(t, identityharness.SignInRequest{}); got != identityharness.Bob { - t.Fatalf("selected sign-in signed in %q, want %q", got, identityharness.Bob) - } - if got := signedIn(t, identityharness.SignInRequest{}); got != identityharness.Alice { - t.Fatalf("the next sign-in signed in %q, want the default user %q", got, identityharness.Alice) - } - h.IdP.SignInNextAs(identityharness.Bob) - if got := signedIn(t, identityharness.SignInRequest{User: identityharness.Alice}); got != identityharness.Bob { - t.Fatalf("selected sign-in with login_hint signed in %q, want %q", got, identityharness.Bob) - } - if got := signedIn(t, identityharness.SignInRequest{User: identityharness.Bob}); got != identityharness.Bob { - t.Fatalf("login_hint sign-in signed in %q, want %q", got, identityharness.Bob) - } - - h.IdP.SignInNextAs("mallory-404") - _, err := h.SignIn(t.Context(), identityharness.SignInRequest{}) - var oauthErr *identityharness.OAuthError - if !errors.As(err, &oauthErr) || oauthErr.Code != "access_denied" { - t.Fatalf("SignIn as an unknown selected user = %v, want access_denied", err) - } -} - -func TestRefreshRenewsForTheSameUserAndClient(t *testing.T) { - h := identityharness.New(t, identityharness.Options{Clients: []identityharness.Client{ - {ID: "mecatui", RedirectURIs: []string{identityharness.DefaultRedirectURI}}, - {ID: "studio", RedirectURIs: []string{"https://studio.test/callback"}}, - }}) - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: identityharness.Bob}) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - renewed, err := h.Refresh(t.Context(), "mecatui", tokens.RefreshToken) - if err != nil { - t.Fatalf("Refresh: %v", err) - } - _, claims := verify(t, h, renewed.AccessToken) - if claims["sub"] != h.AS1.Subject(identityharness.Bob) || claims["client_id"] != "mecatui" { - t.Errorf("renewed claims = %v, want Bob for mecatui", claims) - } - _, err = h.Refresh(t.Context(), "studio", renewed.RefreshToken) - assertOAuthError(t, err, "invalid_grant") - _, err = h.Refresh(t.Context(), "mecatui", "not-a-refresh-token") - assertOAuthError(t, err, "invalid_grant") -} - -// TestRefreshRotatesTheRefreshToken: each refresh grant issues a new refresh -// token and retires the presented one, as ToolHive's AS does. -func TestRefreshRotatesTheRefreshToken(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{}) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - renewed, err := h.Refresh(t.Context(), "", tokens.RefreshToken) - if err != nil { - t.Fatalf("Refresh: %v", err) - } - if renewed.RefreshToken == "" || renewed.RefreshToken == tokens.RefreshToken { - t.Fatal("refresh did not rotate the refresh token") - } - _, err = h.Refresh(t.Context(), "", tokens.RefreshToken) - assertOAuthError(t, err, "invalid_grant") - if _, err := h.Refresh(t.Context(), "", renewed.RefreshToken); err != nil { - t.Fatalf("Refresh with the rotated token: %v", err) - } -} - -// TestResourceMustNameTheMecatlAPI: an RFC 8707 resource is optional, but when -// sent it must be the audience, at the authorization and token endpoints. -func TestResourceMustNameTheMecatlAPI(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - authorize := func(resource string) url.Values { - t.Helper() - q := url.Values{ - "response_type": {"code"}, "client_id": {identityharness.DefaultClientID}, - "redirect_uri": {identityharness.DefaultRedirectURI}, "state": {"s"}, - "code_challenge": {"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"}, "code_challenge_method": {"S256"}, - "resource": {resource}, - } - back, err := h.Authorize(t.Context(), h.AS1.AuthorizationEndpoint()+"?"+q.Encode()) - if err != nil { - t.Fatalf("Authorize: %v", err) - } - return back - } - if back := authorize("https://other.test/api"); back.Get("error") != "invalid_target" { - t.Fatalf("foreign resource: error = %q, want invalid_target", back.Get("error")) - } - if back := authorize(h.AS1.Audience()); back.Get("code") == "" { - t.Fatalf("audience resource: no code (error %q)", back.Get("error")) - } - - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{}) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - refresh := func(resource string) (*http.Response, error) { - form := url.Values{"grant_type": {"refresh_token"}, "client_id": {identityharness.DefaultClientID}, "refresh_token": {tokens.RefreshToken}, "resource": {resource}} - return h.HTTPClient().PostForm(h.AS1.TokenEndpoint(), form) - } - resp, err := refresh("https://other.test/api") - if err != nil { - t.Fatalf("refresh: %v", err) - } - var oauthErr identityharness.OAuthError - decodeErr := json.NewDecoder(resp.Body).Decode(&oauthErr) - _ = resp.Body.Close() - if resp.StatusCode != http.StatusBadRequest || decodeErr != nil || oauthErr.Code != "invalid_target" { - t.Fatalf("foreign resource refresh: status %d error %q, want 400 invalid_target", resp.StatusCode, oauthErr.Code) - } - resp, err = refresh(h.AS1.Audience()) - if err != nil { - t.Fatalf("refresh: %v", err) - } - var renewed identityharness.Tokens - decodeErr = json.NewDecoder(resp.Body).Decode(&renewed) - _ = resp.Body.Close() - if resp.StatusCode != http.StatusOK || decodeErr != nil { - t.Fatalf("audience resource refresh: status %d", resp.StatusCode) - } - if _, claims := verify(t, h, renewed.AccessToken); claims["aud"] != h.AS1.Audience() { - t.Errorf("aud = %v, want the audience", claims["aud"]) - } -} - -func TestSignInFailures(t *testing.T) { - for _, c := range []struct { - name string - force func(*identityharness.Harness) - user string - want string - }{ - {"IdP denies", func(h *identityharness.Harness) { - h.IdP.FailNextAuthorization(identityharness.Fault{Error: "access_denied"}) - }, "", "access_denied"}, - {"IdP fails otherwise", func(h *identityharness.Harness) { - h.IdP.FailNextAuthorization(identityharness.Fault{Error: "temporarily_unavailable"}) - }, "", "server_error"}, - {"IdP token endpoint fails", func(h *identityharness.Harness) { - h.IdP.FailNextToken(identityharness.Fault{Status: http.StatusServiceUnavailable, Error: "temporarily_unavailable"}) - }, "", "server_error"}, - {"unknown company user", func(*identityharness.Harness) {}, "mallory", "access_denied"}, - } { - t.Run(c.name, func(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - c.force(h) - _, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: c.user}) - assertOAuthError(t, err, c.want) - // Each fault fires once. - if _, err := h.SignIn(t.Context(), identityharness.SignInRequest{}); err != nil { - t.Fatalf("SignIn after the fault: %v", err) - } - }) - } -} - -func TestAuthorizationRefusesUnknownClientWithoutRedirect(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - for _, req := range []identityharness.SignInRequest{ - {ClientID: "unknown"}, - {RedirectURI: "http://127.0.0.1:9999/elsewhere"}, - } { - _, err := h.SignIn(t.Context(), req) - var oauthErr *identityharness.OAuthError - if err == nil || errors.As(err, &oauthErr) { - t.Errorf("SignIn(%+v) = %v, want a refusal that does not redirect", req, err) - } - } -} - -// TestCodeGrantChecks drives the authorization request by hand to present -// defective code grants. -func TestCodeGrantChecks(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - const verifier = "verifier-0123456789-0123456789-0123456789-0123456789" - - back := authorize(t, h, url.Values{"code_challenge": {challenge(verifier)}, "code_challenge_method": {"S256"}}) - code := back.Get("code") - if code == "" || back.Get("state") != "s1" { - t.Fatalf("authorization redirect = %v, want a code and state s1", back) - } - exchange := func(code, verifier, redirect string) error { - _, err := postToken(t, h, url.Values{ - "grant_type": {"authorization_code"}, "client_id": {identityharness.DefaultClientID}, - "code": {code}, "code_verifier": {verifier}, "redirect_uri": {redirect}, - }) - return err - } - assertOAuthError(t, exchange(code, "wrong-verifier-0123456789-0123456789-0123456789", identityharness.DefaultRedirectURI), "invalid_grant") - // A failed redemption consumes the code. - assertOAuthError(t, exchange(code, verifier, identityharness.DefaultRedirectURI), "invalid_grant") - - code = authorize(t, h, url.Values{"code_challenge": {challenge(verifier)}, "code_challenge_method": {"S256"}}).Get("code") - assertOAuthError(t, exchange(code, verifier, "http://127.0.0.1:8765/other"), "invalid_grant") - - code = authorize(t, h, url.Values{"code_challenge": {challenge(verifier)}, "code_challenge_method": {"S256"}}).Get("code") - if err := exchange(code, verifier, identityharness.DefaultRedirectURI); err != nil { - t.Fatalf("valid exchange: %v", err) - } - assertOAuthError(t, exchange(code, verifier, identityharness.DefaultRedirectURI), "invalid_grant") - - for _, pkce := range []url.Values{{}, {"code_challenge": {challenge(verifier)}, "code_challenge_method": {"plain"}}} { - if got := authorize(t, h, pkce).Get("error"); got != "invalid_request" { - t.Errorf("authorization with PKCE %v: error %q, want invalid_request", pkce, got) - } - } - - _, err := postToken(t, h, url.Values{"grant_type": {"refresh_token"}, "client_id": {"unknown"}}) - assertOAuthError(t, err, "invalid_client") - _, err = postToken(t, h, url.Values{"grant_type": {"password"}, "client_id": {identityharness.DefaultClientID}}) - assertOAuthError(t, err, "unsupported_grant_type") -} - -func TestMintAccessTokenDefects(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - _, claims := verify(t, h, h.AS1.MintAccessToken(identityharness.AccessTokenSpec{OmitSubID: true})) - if _, ok := claims["sub_id"]; ok { - t.Error("OmitSubID token carries sub_id") - } - header, claims := verify(t, h, h.AS1.MintAccessToken(identityharness.AccessTokenSpec{ - User: identityharness.Bob, Audience: "https://other.test", Type: "application/at+jwt", - })) - if claims["aud"] != "https://other.test" || header["typ"] != "application/at+jwt" || claims["sub"] != h.AS1.Subject(identityharness.Bob) { - t.Errorf("minted token = %v %v, want Bob, other audience, application/at+jwt", header, claims) - } - header, _ = verify(t, h, h.AS1.MintAccessToken(identityharness.AccessTokenSpec{OmitType: true})) - if _, ok := header["typ"]; ok { - t.Error("OmitType token carries typ") - } - expired := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Lifetime: -time.Minute}) - if _, err := parse(t, h, expired); !errors.Is(err, jwt.ErrTokenExpired) { - t.Errorf("expired token parse = %v, want ErrTokenExpired", err) - } - foreign := h.AS1.MintAccessToken(identityharness.AccessTokenSpec{ForeignKey: true}) - if _, err := parse(t, h, foreign); !errors.Is(err, jwt.ErrTokenSignatureInvalid) { - t.Errorf("foreign-key token parse = %v, want ErrTokenSignatureInvalid", err) - } -} - -// authorize sends an authorization request to AS-1 with extra parameters and -// follows redirects back to the default redirect URI. -func authorize(t *testing.T, h *identityharness.Harness, extra url.Values) url.Values { - t.Helper() - q := url.Values{ - "response_type": {"code"}, "client_id": {identityharness.DefaultClientID}, - "redirect_uri": {identityharness.DefaultRedirectURI}, "state": {"s1"}, - } - for k, v := range extra { - q[k] = v - } - next := h.AS1.AuthorizationEndpoint() + "?" + q.Encode() - for range 10 { - resp, err := h.HTTPClient().Get(next) - if err != nil { - t.Fatal(err) - } - _ = resp.Body.Close() - loc, err := resp.Location() - if err != nil { - t.Fatalf("GET %s: status %d, no redirect", next, resp.StatusCode) - } - if next = loc.String(); strings.HasPrefix(next, identityharness.DefaultRedirectURI+"?") { - return loc.Query() - } - } - t.Fatal("too many redirects") - return nil -} - -func postToken(t *testing.T, h *identityharness.Harness, form url.Values) (map[string]any, error) { - t.Helper() - resp, err := h.HTTPClient().PostForm(h.AS1.TokenEndpoint(), form) - if err != nil { - t.Fatal(err) - } - defer func() { _ = resp.Body.Close() }() - if resp.Header.Get("Cache-Control") != "no-store" { - t.Errorf("token response Cache-Control = %q, want no-store", resp.Header.Get("Cache-Control")) - } - if resp.StatusCode != http.StatusOK { - oauthErr := &identityharness.OAuthError{Status: resp.StatusCode} - if err := json.NewDecoder(resp.Body).Decode(oauthErr); err != nil { - t.Fatal(err) - } - return nil, oauthErr - } - var body map[string]any - return body, json.NewDecoder(resp.Body).Decode(&body) -} - -// challenge is the PKCE S256 challenge, computed independently of the -// harness's own PKCE code. -func challenge(verifier string) string { - sum := sha256.Sum256([]byte(verifier)) - return base64.RawURLEncoding.EncodeToString(sum[:]) -} - -func verify(t *testing.T, h *identityharness.Harness, token string) (map[string]any, jwt.MapClaims) { - t.Helper() - parsed, err := parse(t, h, token) - if err != nil { - t.Fatalf("verify access token: %v", err) - } - return parsed.Header, parsed.Claims.(jwt.MapClaims) -} - -// parse verifies token against the JWKS AS-1 publishes, found through both -// discovery locations. -func parse(t *testing.T, h *identityharness.Harness, token string) (*jwt.Token, error) { - t.Helper() - issuer, _ := url.Parse(h.AS1.Issuer()) - var jwksURI string - for _, path := range []string{ - h.AS1.Issuer() + "/.well-known/openid-configuration", - issuer.Scheme + "://" + issuer.Host + "/.well-known/oauth-authorization-server" + issuer.Path, - } { - var doc struct { - Issuer string `json:"issuer"` - JWKSURI string `json:"jwks_uri"` - } - getJSON(t, h, path, &doc) - if doc.Issuer != h.AS1.Issuer() || doc.JWKSURI == "" { - t.Fatalf("discovery %s = %+v, want issuer %s and a jwks_uri", path, doc, h.AS1.Issuer()) - } - jwksURI = doc.JWKSURI - } - var set struct { - Keys []struct{ Kty, Crv, Kid, X, Y string } `json:"keys"` - } - getJSON(t, h, jwksURI, &set) - return jwt.Parse(token, func(tok *jwt.Token) (any, error) { - for _, k := range set.Keys { - if k.Kid != tok.Header["kid"] || k.Kty != "EC" || k.Crv != "P-256" { - continue - } - x, _ := base64.RawURLEncoding.DecodeString(k.X) - y, _ := base64.RawURLEncoding.DecodeString(k.Y) - return ecdsa.ParseUncompressedPublicKey(elliptic.P256(), append(append([]byte{4}, x...), y...)) - } - return nil, errors.New("no matching key") - }, jwt.WithValidMethods([]string{"ES256"}), jwt.WithIssuer(h.AS1.Issuer()), jwt.WithExpirationRequired()) -} - -func getJSON(t *testing.T, h *identityharness.Harness, target string, out any) { - t.Helper() - resp, err := h.HTTPClient().Get(target) - if err != nil { - t.Fatal(err) - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - t.Fatalf("GET %s: status %d", target, resp.StatusCode) - } - if err := json.NewDecoder(resp.Body).Decode(out); err != nil { - t.Fatal(err) - } -} - -func assertOAuthError(t *testing.T, err error, code string) { - t.Helper() - var oauthErr *identityharness.OAuthError - if !errors.As(err, &oauthErr) || oauthErr.Code != code { - t.Fatalf("error = %v, want OAuth error %s", err, code) - } -} - -func mustJSON(t *testing.T, v any) string { - t.Helper() - b, err := json.Marshal(v) - if err != nil { - t.Fatal(err) - } - return string(b) -} diff --git a/internal/testutil/identityharness/idjag.go b/internal/testutil/identityharness/idjag.go deleted file mode 100644 index d8181aa136..0000000000 --- a/internal/testutil/identityharness/idjag.go +++ /dev/null @@ -1,222 +0,0 @@ -package identityharness - -import ( - "context" - "errors" - "net/http" - "net/url" - "slices" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -const ( - // DefaultIDJAGLifetime is the lifetime of the ID-JAGs AS-1 issues, before - // the cap at the actor token's expiry. - DefaultIDJAGLifetime = 2 * time.Minute - // IDJAGHeaderType is the typ header of an ID-JAG. - IDJAGHeaderType = "oauth-id-jag+jwt" - - tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" // #nosec G101 -- RFC 8693 token type URN, not a credential. - - // Reasons AS-1 returns for an ID-JAG exchange (design step (7)). - reasonGrantInvalid = "grant_invalid" - reasonActorExpired = "actor_token_expired" - reasonDenied = "denied" -) - -// ActorValidator is AS-1's pluggable actor-token validator (design step (7), -// check 6), called with the grant's company identity and the actor token. It -// returns the agent's identifier, which becomes act.sub, and the actor -// token's expiry, which caps the ID-JAG's exp. An error matching -// ErrActorExpired answers actor_token_expired, one matching ErrActorDenied -// answers denied, and any other answers 500 server_error, as the real AS-1 -// does. It is the harness's own type, so the harness never imports the broker; -// tests adapt the broker's validator to it. -type ActorValidator func(ctx context.Context, owner Owner, actorToken string) (agentID string, expiresAt time.Time, err error) - -var ( - // ErrActorExpired is an ActorValidator's refusal of an expired actor token. - ErrActorExpired = errors.New("identityharness: actor token expired") - // ErrActorDenied is an ActorValidator's refusal of any other actor token. - ErrActorDenied = errors.New("identityharness: actor token denied") -) - -// IDJAGIssuance is AS-1's record of an ID-JAG it issued. -type IDJAGIssuance struct { - // JTI is the ID-JAG's jti and Subject its sub, the grant's AS-1 subject. - JTI, Subject string - // Owner is the grant's company identity. - Owner Owner - // AgentID is the validator's agent identifier, the ID-JAG's act.sub. - AgentID string - // Audience and Resource are the ID-JAG's aud and resource. - Audience, Resource string - // Operation is the request's mecatl_operation. - Operation string - ExpiresAt time.Time -} - -type idjagTarget struct{ audience, resource string } - -// idjagClaims are an ID-JAG's claims (design step (7)). Audience replaces -// the registered claims' array with one string, as the design shows it. -type idjagClaims struct { - jwt.RegisteredClaims - Audience string `json:"aud"` - Resource string `json:"resource"` - ClientID string `json:"client_id"` - Actor idjagActor `json:"act"` -} - -// idjagActor is act: AS-1, which minted it, and the agent. -type idjagActor struct { - Issuer string `json:"iss"` - Subject string `json:"sub"` -} - -// SetActorValidator sets the validator the ID-JAG exchange calls. Without -// one, every actor token is denied. -func (a *AS1) SetActorValidator(v ActorValidator) { - a.mu.Lock() - defer a.mu.Unlock() - a.validator = v -} - -// AddIDJAGTarget configures an AS-2 issuer, audience, and a vMCP resource for -// it that the ID-JAG exchange issues for. Any other pair is invalid_target. -func (a *AS1) AddIDJAGTarget(audience, resource string) { - a.mu.Lock() - defer a.mu.Unlock() - a.idjagTargets[idjagTarget{audience, resource}] = true -} - -// RevokeGrants revokes every grant of the company identity user, as AS-1 -// does when it ends a user's grants, and returns how many it revoked. A later -// ID-JAG exchange for one gets revoked. -func (a *AS1) RevokeGrants(user string) int { - a.mu.Lock() - defer a.mu.Unlock() - n := 0 - for _, g := range a.grants { - if g.subID.Subject == user && g.subID.Issuer == a.idp.Issuer() && !g.revoked { - g.revoked = true - n++ - } - } - return n -} - -// IDJAGsIssued returns the ID-JAGs AS-1 has issued, oldest first. -func (a *AS1) IDJAGsIssued() []IDJAGIssuance { - a.mu.Lock() - defer a.mu.Unlock() - return slices.Clone(a.idjags) -} - -// issueIDJAG is AS-1's side of a call, design step (7): the RFC 8693 -// exchange of a grant's refresh token, with the agent's SVID as the actor -// token, for an ID-JAG addressed to AS-2. Check 1 (client authentication) has -// passed. Check 5, the upstream re-check, is not modelled: tests inject its -// reasons as faults. Check 6 is the validator's. -func (a *AS1) issueIDJAG(w http.ResponseWriter, r *http.Request) { - form := r.PostForm - if !validIDJAGForm(form) { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", "") - return - } - target := idjagTarget{form.Get("audience"), form.Get(paramResource)} - now := a.now() - a.mu.Lock() - configured := a.idjagTargets[target] - g, known := a.grants[form.Get("subject_token")] - var grant as1Grant - if known { - grant = *g - } - validator := a.validator - a.mu.Unlock() - if !configured { - writeOAuthError(w, http.StatusBadRequest, errInvalidTarget, "") - return - } - switch { - case !known || grant.clientID != BrokerClientID || grant.output != TokenTypeIDJAG || !now.Before(grant.expiresAt): - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonGrantInvalid) - return - case grant.revoked: - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonRevoked) - return - } - if validator == nil { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonDenied) - return - } - agentID, actorExpires, err := validator(r.Context(), grant.subID, form.Get("actor_token")) - switch { - case errors.Is(err, ErrActorExpired): - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonActorExpired) - return - case errors.Is(err, ErrActorDenied): - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonDenied) - return - case err != nil: - writeOAuthError(w, http.StatusInternalServerError, "server_error", "") - return - } - expires := now.Add(a.idjagLifetime) - if !actorExpires.IsZero() && actorExpires.Before(expires) { - expires = actorExpires - } - if expires.Unix() <= now.Unix() { - // Guess: an actor token at its expiry is expired, whatever the - // validator said. - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonActorExpired) - return - } - jti := randomToken("jag-") - token := jwt.NewWithClaims(jwt.SigningMethodES256, idjagClaims{ - RegisteredClaims: jwt.RegisteredClaims{ - Issuer: a.Issuer(), Subject: grant.subject, ID: jti, - IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(expires), - }, - Audience: target.audience, Resource: target.resource, ClientID: BrokerClientID, - Actor: idjagActor{Issuer: a.Issuer(), Subject: agentID}, - }) - token.Header["typ"], token.Header["kid"] = IDJAGHeaderType, as1KeyID - signed, err := token.SignedString(a.key) - if err != nil { - writeOAuthError(w, http.StatusInternalServerError, "server_error", "") - return - } - a.mu.Lock() - a.idjags = append(a.idjags, IDJAGIssuance{ - JTI: jti, Subject: grant.subject, Owner: grant.subID, AgentID: agentID, - Audience: target.audience, Resource: target.resource, Operation: form.Get("mecatl_operation"), - ExpiresAt: time.Unix(expires.Unix(), 0), - }) - a.mu.Unlock() - writeJSON(w, http.StatusOK, map[string]any{ - "access_token": signed, - "issued_token_type": TokenTypeIDJAG, - "token_type": "N_A", - "expires_in": expires.Unix() - now.Unix(), - }) -} - -// validIDJAGForm runs check 2: one value per field, the three token types, -// the subject and actor tokens, an audience and a resource, and no scope or -// authorization_details. -func validIDJAGForm(form url.Values) bool { - for _, values := range form { - if len(values) > 1 { // RFC 6749 §3.2 - return false - } - } - return form.Get("subject_token") != "" && form.Get("subject_token_type") == tokenTypeRefresh && - form.Get("actor_token") != "" && form.Get("actor_token_type") == tokenTypeJWT && - form.Get("requested_token_type") == TokenTypeIDJAG && - form.Get("audience") != "" && form.Get(paramResource) != "" && - !form.Has("scope") && !form.Has(paramAuthDetails) -} diff --git a/internal/testutil/identityharness/idjag_test.go b/internal/testutil/identityharness/idjag_test.go deleted file mode 100644 index 8a0d56d90b..0000000000 --- a/internal/testutil/identityharness/idjag_test.go +++ /dev/null @@ -1,256 +0,0 @@ -package identityharness_test - -import ( - "context" - "errors" - "net/http" - "net/url" - "reflect" - "strings" - "testing" - "time" - - "github.com/stacklok/mecatl/internal/testutil/identityharness" -) - -const ( - tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" - testAS2Issuer = "https://gateway.example/v1/mcp/broker" - testAS2VMCP = testAS2Issuer + "/mcp" - testAgentID = "ag_7hq2x9" - svidAlice = "svid-alice" - svidExpired = "svid-expired" - svidForeign = "svid-foreign" - svidValidatorX = "svid-validator-fails" -) - -// idjagFixture is a harness whose AS-1 issues ID-JAGs for one AS-2 target, -// with a grant for Alice and a validator that accepts svidAlice for her. -type idjagFixture struct { - h *identityharness.Harness - clock *testClock - grant string - // actorExpiry is the expiry the validator reports, relative to the clock. - actorExpiry time.Duration -} - -func newIDJAGFixture(t *testing.T, opts identityharness.Options) *idjagFixture { - t.Helper() - f := &idjagFixture{clock: newTestClock(), actorExpiry: time.Hour} - opts.Now = f.clock.Now - f.h = identityharness.New(t, opts) - f.h.AS1.AddIDJAGTarget(testAS2Issuer, testAS2VMCP) - f.h.AS1.SetActorValidator(f.validate) - f.grant = f.openGrant(t, identityharness.Alice) - return f -} - -func (f *idjagFixture) validate(_ context.Context, owner identityharness.Owner, actor string) (string, time.Time, error) { - switch { - case actor == svidExpired: - return "", time.Time{}, identityharness.ErrActorExpired - case actor == svidForeign || owner != f.h.Owner(identityharness.Alice): - return "", time.Time{}, identityharness.ErrActorDenied - case actor == svidValidatorX: - return "", time.Time{}, errors.New("registry unavailable") - } - return testAgentID, f.clock.Now().Add(f.actorExpiry), nil -} - -// openGrant opens a session for user and returns the grant's refresh token. -func (f *idjagFixture) openGrant(t *testing.T, user string) string { - t.Helper() - resp, err := f.h.ScriptedBroker().OpenSession(t.Context(), openReq(f.h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: user}))) - if err != nil { - t.Fatalf("OpenSession: %v", err) - } - return resp.RefreshToken -} - -// idjagForm is a valid ID-JAG exchange form, authenticated as the broker. -func idjagForm(h *identityharness.Harness, grant, actor string) url.Values { - return url.Values{ - "grant_type": {grantTokenExchange}, - "subject_token": {grant}, - "subject_token_type": {tokenTypeRefresh}, - "actor_token": {actor}, - "actor_token_type": {tokenTypeJWT}, - "requested_token_type": {tokenTypeIDJAG}, - "audience": {testAS2Issuer}, - "resource": {testAS2VMCP}, - "mecatl_operation": {"op-1"}, - "client_assertion_type": {jwtBearer}, - "client_assertion": {h.ScriptedBroker().Assertion(identityharness.ClientAssertionSpec{})}, - } -} - -func TestIDJAGExchangeChecks(t *testing.T) { - set := func(name, value string) func(*testing.T, *idjagFixture, url.Values) { - return func(_ *testing.T, _ *idjagFixture, form url.Values) { form.Set(name, value) } - } - del := func(name string) func(*testing.T, *idjagFixture, url.Values) { - return func(_ *testing.T, _ *idjagFixture, form url.Values) { form.Del(name) } - } - for _, tt := range []struct { - name string - edit func(*testing.T, *idjagFixture, url.Values) - status int - code string - reason string - }{ - // Check 2: the form. - {"subject token type", set("subject_token_type", tokenTypeAccess), 400, "invalid_request", ""}, - {"actor token type", set("actor_token_type", tokenTypeAccess), 400, "invalid_request", ""}, - {"no actor token", del("actor_token"), 400, "invalid_request", ""}, - {"no subject token", del("subject_token"), 400, "invalid_request", ""}, - {"no audience", del("audience"), 400, "invalid_request", ""}, - {"no resource", del("resource"), 400, "invalid_request", ""}, - {"scope", set("scope", "openid"), 400, "invalid_request", ""}, - {"authorization_details", set("authorization_details", "[]"), 400, "invalid_request", ""}, - {"two audiences", func(_ *testing.T, _ *idjagFixture, form url.Values) { form.Add("audience", testAS2Issuer) }, 400, "invalid_request", ""}, - // Check 3: the target. - {"unknown audience", set("audience", "https://other.example"), 400, "invalid_target", ""}, - {"unknown resource", set("resource", testAS2Issuer), 400, "invalid_target", ""}, - // Check 4: the grant. - {"unknown grant", set("subject_token", "as1-grant-rt-unknown"), 400, "invalid_request", "grant_invalid"}, - {"expired grant", func(_ *testing.T, f *idjagFixture, form url.Values) { - f.clock.Advance(identityharness.DefaultGrantMaxLifetime) - form.Set("client_assertion", f.h.ScriptedBroker().Assertion(identityharness.ClientAssertionSpec{})) - }, 400, "invalid_request", "grant_invalid"}, - {"revoked grant", func(t *testing.T, f *idjagFixture, _ url.Values) { - if err := f.h.ScriptedBroker().Revoke(t.Context(), f.grant); err != nil { - t.Fatal(err) - } - }, 400, "invalid_request", "revoked"}, - // Check 6: the actor, through the validator. - {"expired actor", set("actor_token", svidExpired), 400, "invalid_request", "actor_token_expired"}, - {"foreign actor", set("actor_token", svidForeign), 400, "invalid_request", "denied"}, - {"validator failure", set("actor_token", svidValidatorX), 500, "server_error", ""}, - {"no validator", func(_ *testing.T, f *idjagFixture, _ url.Values) { f.h.AS1.SetActorValidator(nil) }, 400, "invalid_request", "denied"}, - {"actor at its expiry", func(_ *testing.T, f *idjagFixture, _ url.Values) { f.actorExpiry = 0 }, 400, "invalid_request", "actor_token_expired"}, - {"another user's grant", func(t *testing.T, f *idjagFixture, form url.Values) { - form.Set("subject_token", f.openGrant(t, identityharness.Bob)) - }, 400, "invalid_request", "denied"}, - } { - t.Run(tt.name, func(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - form := idjagForm(f.h, f.grant, svidAlice) - tt.edit(t, f, form) - _, err := postToken(t, f.h, form) - assertReason(t, err, tt.status, tt.code, tt.reason) - if got := f.h.AS1.IDJAGsIssued(); len(got) != 0 { - t.Fatalf("AS-1 issued %d ID-JAGs on a refusal", len(got)) - } - }) - } -} - -func TestIDJAGShape(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - now := f.clock.Now() - body, err := postToken(t, f.h, idjagForm(f.h, f.grant, svidAlice)) - if err != nil { - t.Fatalf("ID-JAG exchange: %v", err) - } - if body["issued_token_type"] != tokenTypeIDJAG || body["token_type"] != "N_A" || body["expires_in"] != float64(120) { - t.Fatalf("response = %v, want an id-jag, N_A, and expires_in 120", body) - } - if _, ok := body["refresh_token"]; ok { - t.Fatal("the ID-JAG came with a refresh token") - } - token, _ := body["access_token"].(string) - header, claims := verify(t, f.h, token) - if want := map[string]any{"typ": identityharness.IDJAGHeaderType, "alg": "ES256", "kid": "as1-key-1"}; !reflect.DeepEqual(header, want) { - t.Fatalf("header = %v, want %v", header, want) - } - jti, _ := claims["jti"].(string) - want := map[string]any{ - "iss": f.h.AS1.Issuer(), "sub": f.h.AS1.Subject(identityharness.Alice), "aud": testAS2Issuer, - "resource": testAS2VMCP, "client_id": identityharness.BrokerClientID, - "act": map[string]any{"iss": f.h.AS1.Issuer(), "sub": testAgentID}, - "jti": jti, "iat": float64(now.Unix()), "exp": float64(now.Add(identityharness.DefaultIDJAGLifetime).Unix()), - } - if !reflect.DeepEqual(map[string]any(claims), want) || !strings.HasPrefix(jti, "jag-") { - t.Fatalf("claims = %v, want %v with a jag- jti", claims, want) - } - issued := f.h.AS1.IDJAGsIssued() - wantIssued := identityharness.IDJAGIssuance{ - JTI: jti, Subject: f.h.AS1.Subject(identityharness.Alice), Owner: f.h.Owner(identityharness.Alice), - AgentID: testAgentID, Audience: testAS2Issuer, Resource: testAS2VMCP, Operation: "op-1", - ExpiresAt: now.Add(identityharness.DefaultIDJAGLifetime), - } - if len(issued) != 1 || issued[0] != wantIssued { - t.Fatalf("issued = %+v, want [%+v]", issued, wantIssued) - } - // Every exchange issues a new ID-JAG; the grant is not used up. - again, err := postToken(t, f.h, idjagForm(f.h, f.grant, svidAlice)) - if err != nil || again["access_token"] == token { - t.Fatalf("second exchange = %v, %v; want a new ID-JAG", again["access_token"] != nil, err) - } - if issued := f.h.AS1.IDJAGsIssued(); len(issued) != 2 || issued[1].JTI == jti { - t.Fatalf("issued = %+v, want two ID-JAGs with distinct jtis", issued) - } -} - -func TestIDJAGExpCappedAtActor(t *testing.T) { - for _, tt := range []struct { - name string - lifetime time.Duration - actor time.Duration - want time.Duration - }{ - {"actor expires first", 0, 30 * time.Second, 30 * time.Second}, - {"configured lifetime first", 10 * time.Second, time.Hour, 10 * time.Second}, - {"default lifetime first", 0, time.Hour, identityharness.DefaultIDJAGLifetime}, - } { - t.Run(tt.name, func(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{IDJAGLifetime: tt.lifetime}) - f.actorExpiry = tt.actor - body, err := postToken(t, f.h, idjagForm(f.h, f.grant, svidAlice)) - if err != nil { - t.Fatalf("ID-JAG exchange: %v", err) - } - _, claims := verify(t, f.h, body["access_token"].(string)) - exp := f.clock.Now().Add(tt.want) - if claims["exp"] != float64(exp.Unix()) || body["expires_in"] != tt.want.Seconds() { - t.Fatalf("exp %v, expires_in %v; want %d and %v", claims["exp"], body["expires_in"], exp.Unix(), tt.want.Seconds()) - } - if issued := f.h.AS1.IDJAGsIssued(); len(issued) != 1 || !issued[0].ExpiresAt.Equal(exp) { - t.Fatalf("issued = %+v, want one expiring at %v", issued, exp) - } - }) - } -} - -func TestRevokeGrants(t *testing.T) { - f := newIDJAGFixture(t, identityharness.Options{}) - second := f.openGrant(t, identityharness.Alice) - bob := f.openGrant(t, identityharness.Bob) - if n := f.h.AS1.RevokeGrants(identityharness.Alice); n != 2 { - t.Fatalf("RevokeGrants = %d, want Alice's 2", n) - } - if n := f.h.AS1.RevokeGrants(identityharness.Alice); n != 0 { - t.Fatalf("RevokeGrants again = %d, want 0", n) - } - for _, grant := range []string{f.grant, second} { - if g, _ := f.h.AS1.Grant(grant); g.Active || g.Reason != "revoked" { - t.Fatalf("Alice's grant = %+v, want revoked", g) - } - _, err := postToken(t, f.h, idjagForm(f.h, grant, svidAlice)) - assertReason(t, err, http.StatusBadRequest, "invalid_request", "revoked") - } - if g, _ := f.h.AS1.Grant(bob); !g.Active { - t.Fatalf("Bob's grant = %+v, want active", g) - } -} - -func TestSessionOpenIgnoresIDJAGParameters(t *testing.T) { - // A session-open exchange still refuses an actor token: only an ID-JAG - // request reaches the ID-JAG exchange. - f := newIDJAGFixture(t, identityharness.Options{}) - form := exchangeForm(f.h, aliceToken(f.h), `[{"type":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeIDJAG+`"]}]`) - form.Set("actor_token", svidAlice) - form.Set("actor_token_type", tokenTypeJWT) - _, err := postToken(t, f.h, form) - assertReason(t, err, http.StatusBadRequest, "invalid_request", "") -} diff --git a/internal/testutil/identityharness/idp.go b/internal/testutil/identityharness/idp.go index 0e9584903b..e01f937373 100644 --- a/internal/testutil/identityharness/idp.go +++ b/internal/testutil/identityharness/idp.go @@ -34,8 +34,6 @@ const ( type IdP struct { server *httptest.Server key *rsa.PrivateKey - now func() time.Time - faults faults mu sync.Mutex users []string @@ -56,15 +54,16 @@ type idpCode struct { expires time.Time } -func newIdP(t testing.TB, opts Options) *IdP { +// newIdP starts an IdP that knows Alice, its default user, and Bob. +func newIdP(t testing.TB) *IdP { t.Helper() key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { t.Fatalf("identityharness: IdP key: %v", err) } idp := &IdP{ - key: key, now: opts.Now, - users: slices.Clone(opts.Users), + key: key, + users: []string{Alice, Bob}, clients: make(map[string]idpClient), codes: make(map[string]idpCode), offline: make(map[string]int), @@ -96,8 +95,8 @@ func (p *IdP) AddUser(subject string) { } // RegisterClient registers a confidential OIDC client that authenticates to -// the token endpoint with client_secret_basic or client_secret_post. AS-1 -// registers itself this way; a test hosting a real AS-1 registers that one. +// the token endpoint with client_secret_basic or client_secret_post. A test +// running a real AS-1 registers it this way (Harness.RegisterAS1Upstream). func (p *IdP) RegisterClient(id, secret, redirectURI string) { p.mu.Lock() defer p.mu.Unlock() @@ -125,13 +124,6 @@ func (p *IdP) ClearSignInNextAs() { p.next = nil } -// FailNextAuthorization makes the next authorization request redirect back -// with fault.Error, such as access_denied, instead of signing the user in. -func (p *IdP) FailNextAuthorization(fault Fault) { p.faults.push("authorize", fault) } - -// FailNextToken makes the next token request fail with fault. -func (p *IdP) FailNextToken(fault Fault) { p.faults.push("token", fault) } - // RefreshTokensIssued reports how many upstream refresh tokens the IdP issued // for subject, which shows whether AS-1 asked for offline access. func (p *IdP) RefreshTokensIssued(subject string) int { @@ -175,10 +167,6 @@ func (p *IdP) authorize(w http.ResponseWriter, r *http.Request) { } // Redirect to the registered value, not the request's copy of it. redirectURI = client.redirectURI - if fault, ok := p.faults.pop("authorize"); ok { - redirectWithError(w, r, redirectURI, state, fault.Error) - return - } scopes := strings.Fields(q.Get("scope")) method := q.Get("code_challenge_method") switch { @@ -203,7 +191,7 @@ func (p *IdP) authorize(w http.ResponseWriter, r *http.Request) { clientID: clientID, redirectURI: redirectURI, challenge: q.Get("code_challenge"), nonce: q.Get("nonce"), subject: subject, offline: slices.Contains(scopes, "offline_access") && slices.Contains(strings.Fields(q.Get("prompt")), "consent"), - expires: p.now().Add(idpCodeLifetime), + expires: time.Now().Add(idpCodeLifetime), } p.mu.Unlock() back := url.Values{"code": {code}} @@ -239,20 +227,16 @@ func (p *IdP) user(hint string) (string, bool) { func (p *IdP) token(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", "") + writeOAuthError(w, http.StatusBadRequest, "invalid_request") return } clientID, ok := p.authenticateClient(r) if !ok { - writeOAuthError(w, http.StatusUnauthorized, "invalid_client", "") - return - } - if fault, ok := p.faults.pop("token"); ok { - writeOAuthError(w, fault.Status, fault.Error, fault.Reason) + writeOAuthError(w, http.StatusUnauthorized, "invalid_client") return } if r.PostForm.Get("grant_type") != grantAuthorizationCode { - writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "") + writeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type") return } p.mu.Lock() @@ -260,11 +244,11 @@ func (p *IdP) token(w http.ResponseWriter, r *http.Request) { delete(p.codes, r.PostForm.Get("code")) // single use p.mu.Unlock() if !found || code.clientID != clientID || code.redirectURI != r.PostForm.Get("redirect_uri") || - !p.now().Before(code.expires) || code.challenge != "" && s256(r.PostForm.Get("code_verifier")) != code.challenge { - writeOAuthError(w, http.StatusBadRequest, "invalid_grant", "") + !time.Now().Before(code.expires) || code.challenge != "" && s256(r.PostForm.Get("code_verifier")) != code.challenge { + writeOAuthError(w, http.StatusBadRequest, "invalid_grant") return } - now := p.now() + now := time.Now() claims := jwt.MapClaims{ "iss": p.server.URL, "sub": code.subject, "aud": clientID, "iat": now.Unix(), "exp": now.Add(idpIDTokenLife).Unix(), @@ -278,7 +262,7 @@ func (p *IdP) token(w http.ResponseWriter, r *http.Request) { idToken.Header["kid"] = idpKeyID signed, err := idToken.SignedString(p.key) if err != nil { - writeOAuthError(w, http.StatusInternalServerError, "server_error", "") + writeOAuthError(w, http.StatusInternalServerError, "server_error") return } body := map[string]any{ diff --git a/internal/testutil/identityharness/idp_test.go b/internal/testutil/identityharness/idp_test.go new file mode 100644 index 0000000000..7c221865d5 --- /dev/null +++ b/internal/testutil/identityharness/idp_test.go @@ -0,0 +1,171 @@ +package identityharness_test + +import ( + "encoding/json" + "net/http" + "net/url" + "strings" + "testing" + + "github.com/golang-jwt/jwt/v5" + + "github.com/stacklok/mecatl/internal/testutil/identityharness" +) + +// The IdP's test client, registered as a real AS-1 registers itself. +const ( + idpClientID = "as1-test" + idpClientSecret = "as1-test-secret" // #nosec G101 -- test value, not a credential. + idpRedirectURI = "https://as1.test/oauth/callback" +) + +// newIdPHarness starts a harness whose IdP knows the test client. +func newIdPHarness(t *testing.T) *identityharness.Harness { + t.Helper() + h := identityharness.New(t, identityharness.Options{}) + h.IdP.RegisterClient(idpClientID, idpClientSecret, idpRedirectURI) + return h +} + +// idpAuthorize sends an authorization request for the openid scope, with +// extra parameters, and returns the query the IdP redirected back with. +func idpAuthorize(t *testing.T, h *identityharness.Harness, extra url.Values) url.Values { + t.Helper() + q := url.Values{"response_type": {"code"}, "client_id": {idpClientID}, "redirect_uri": {idpRedirectURI}, "scope": {"openid"}, "state": {"st"}} + for k, v := range extra { + q[k] = v + } + resp, err := h.HTTPClient().Get(h.IdP.Issuer() + "/authorize?" + q.Encode()) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + location, err := resp.Location() + if resp.StatusCode != http.StatusFound || err != nil || !strings.HasPrefix(location.String(), idpRedirectURI+"?") { + t.Fatalf("authorize: status %d, location %v; want a redirect to the client", resp.StatusCode, location) + } + return location.Query() +} + +// idpToken redeems code and returns the status and decoded body. +func idpToken(t *testing.T, h *identityharness.Harness, code string) (int, map[string]any) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, h.IdP.Issuer()+"/token", strings.NewReader(url.Values{ + "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {idpRedirectURI}, + }.Encode())) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.SetBasicAuth(idpClientID, idpClientSecret) + resp, err := h.HTTPClient().Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + var body map[string]any + _ = json.NewDecoder(resp.Body).Decode(&body) + return resp.StatusCode, body +} + +// idpSignIn signs a user in with extra authorization parameters and returns +// the token response, failing t unless the IdP issues tokens. +func idpSignIn(t *testing.T, h *identityharness.Harness, extra url.Values) map[string]any { + t.Helper() + back := idpAuthorize(t, h, extra) + if back.Get("code") == "" { + t.Fatalf("authorize redirected with error %q, want a code", back.Get("error")) + } + status, body := idpToken(t, h, back.Get("code")) + if status != http.StatusOK { + t.Fatalf("token: status %d, body %v", status, body) + } + return body +} + +// signedInUser is the sub of a token response's ID token, read without +// verifying it. +func signedInUser(t *testing.T, body map[string]any) string { + t.Helper() + idToken, _ := body["id_token"].(string) + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(idToken, claims); err != nil { + t.Fatalf("parse ID token: %v", err) + } + sub, _ := claims.GetSubject() + return sub +} + +// TestSignInNextAsSelectsTheNextSignInOnly: the IdP signs in the selected +// user once, over login_hint, and then falls back to login_hint or the +// default user; an unknown selection or login_hint is refused. +func TestSignInNextAsSelectsTheNextSignInOnly(t *testing.T) { + h := newIdPHarness(t) + hint := func(user string) url.Values { return url.Values{"login_hint": {user}} } + + h.IdP.SignInNextAs(identityharness.Bob) + if got := signedInUser(t, idpSignIn(t, h, nil)); got != identityharness.Bob { + t.Fatalf("selected sign-in signed in %q, want %q", got, identityharness.Bob) + } + if got := signedInUser(t, idpSignIn(t, h, nil)); got != identityharness.Alice { + t.Fatalf("the next sign-in signed in %q, want the default user %q", got, identityharness.Alice) + } + h.IdP.SignInNextAs(identityharness.Bob) + if got := signedInUser(t, idpSignIn(t, h, hint(identityharness.Alice))); got != identityharness.Bob { + t.Fatalf("selected sign-in with login_hint signed in %q, want %q", got, identityharness.Bob) + } + if got := signedInUser(t, idpSignIn(t, h, hint(identityharness.Bob))); got != identityharness.Bob { + t.Fatalf("login_hint sign-in signed in %q, want %q", got, identityharness.Bob) + } + + h.IdP.SignInNextAs("mallory-404") + if back := idpAuthorize(t, h, nil); back.Get("error") != "access_denied" { + t.Fatalf("sign-in as an unknown selected user = %v, want access_denied", back) + } + if back := idpAuthorize(t, h, hint("mallory-404")); back.Get("error") != "access_denied" { + t.Fatalf("sign-in as an unknown hinted user = %v, want access_denied", back) + } +} + +// TestIdPIssuesARefreshTokenForOfflineConsentOnly: OIDC Core §11 offline +// access needs the offline_access scope and prompt=consent together. +func TestIdPIssuesARefreshTokenForOfflineConsentOnly(t *testing.T) { + h := newIdPHarness(t) + for name, extra := range map[string]url.Values{ + "openid only": nil, + "offline_access, no prompt": {"scope": {"openid offline_access"}}, + "prompt=consent, no scope": {"prompt": {"consent"}}, + } { + if _, issued := idpSignIn(t, h, extra)["refresh_token"]; issued { + t.Errorf("%s: the IdP issued a refresh token", name) + } + } + if got := h.IdP.RefreshTokensIssued(identityharness.Alice); got != 0 { + t.Fatalf("refresh tokens issued = %d before offline consent, want 0", got) + } + body := idpSignIn(t, h, url.Values{"scope": {"openid offline_access"}, "prompt": {"consent"}}) + if body["refresh_token"] == nil || h.IdP.RefreshTokensIssued(identityharness.Alice) != 1 { + t.Fatalf("offline consent: refresh token %v, %d counted; want one", body["refresh_token"] != nil, h.IdP.RefreshTokensIssued(identityharness.Alice)) + } +} + +// TestIdPRefusesAnUnknownClientWithoutRedirect never redirects to a client +// or redirect URI it does not know (RFC 6749 §4.1.2.1). +func TestIdPRefusesAnUnknownClientWithoutRedirect(t *testing.T) { + h := newIdPHarness(t) + for name, q := range map[string]url.Values{ + "unknown client": {"client_id": {"unknown"}, "redirect_uri": {idpRedirectURI}}, + "unknown redirect URI": {"client_id": {idpClientID}, "redirect_uri": {"https://as1.test/elsewhere"}}, + } { + q.Set("response_type", "code") + q.Set("scope", "openid") + resp, err := h.HTTPClient().Get(h.IdP.Issuer() + "/authorize?" + q.Encode()) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest || resp.Header.Get("Location") != "" { + t.Errorf("%s: status %d, location %q; want 400 without a redirect", name, resp.StatusCode, resp.Header.Get("Location")) + } + } +} diff --git a/internal/testutil/identityharness/oauth.go b/internal/testutil/identityharness/oauth.go index 19a4886a92..4cdc5ac257 100644 --- a/internal/testutil/identityharness/oauth.go +++ b/internal/testutil/identityharness/oauth.go @@ -1,7 +1,6 @@ package identityharness import ( - "crypto/ecdsa" "crypto/rand" "crypto/rsa" "crypto/sha256" @@ -13,12 +12,11 @@ import ( "strings" ) -// OAuth protocol values shared by the stand-ins. +// OAuth protocol values the IdP uses. const ( paramClientID = "client_id" responseTypeCode = "code" grantAuthorizationCode = "authorization_code" - grantRefreshToken = "refresh_token" pkceS256 = "S256" ) @@ -30,21 +28,12 @@ func writeJSON(w http.ResponseWriter, status int, body any) { _ = json.NewEncoder(w).Encode(body) } -// writeOAuthError writes an RFC 6749 §5.2 error. A nonempty reason starts -// error_description, as the design's error reasons require; it is never a -// token or claim value. -func writeOAuthError(w http.ResponseWriter, status int, code, reason string) { - if status == 0 { - status = http.StatusBadRequest - } +// writeOAuthError writes an RFC 6749 §5.2 error with no description. +func writeOAuthError(w http.ResponseWriter, status int, code string) { if status == http.StatusUnauthorized { w.Header().Set("WWW-Authenticate", `Basic realm="token"`) } - body := map[string]string{"error": code} - if reason != "" { - body["error_description"] = reason - } - writeJSON(w, status, body) + writeJSON(w, status, map[string]string{"error": code}) } // redirectWithError sends an authorization error back to a validated redirect @@ -93,20 +82,6 @@ func s256(verifier string) string { return base64.RawURLEncoding.EncodeToString(sum[:]) } -// validVerifier reports whether v is an RFC 7636 §4.1 code verifier. -func validVerifier(v string) bool { - if len(v) < 43 || len(v) > 128 { - return false - } - for _, c := range v { - unreserved := c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("-._~", c) - if !unreserved { - return false - } - } - return true -} - func rsaJWK(kid string, key *rsa.PublicKey) map[string]string { return map[string]string{ "kty": "RSA", "use": "sig", "alg": "RS256", "kid": kid, @@ -114,17 +89,3 @@ func rsaJWK(kid string, key *rsa.PublicKey) map[string]string { "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.E)).Bytes()), } } - -func ecJWK(kid string, key *ecdsa.PublicKey) map[string]string { - // The uncompressed P-256 point is 0x04 || X || Y, each coordinate 32 - // bytes (RFC 7518 §6.2.1.2). - point, err := key.Bytes() - if err != nil { - panic("identityharness: encode EC key: " + err.Error()) - } - return map[string]string{ - "kty": "EC", "use": "sig", "alg": "ES256", "kid": kid, "crv": "P-256", - "x": base64.RawURLEncoding.EncodeToString(point[1:33]), - "y": base64.RawURLEncoding.EncodeToString(point[33:65]), - } -} diff --git a/internal/testutil/identityharness/revoke.go b/internal/testutil/identityharness/revoke.go deleted file mode 100644 index f7cc42f615..0000000000 --- a/internal/testutil/identityharness/revoke.go +++ /dev/null @@ -1,37 +0,0 @@ -package identityharness - -import "net/http" - -// RevocationEndpoint is AS-1's RFC 7009 revocation endpoint. -func (a *AS1) RevocationEndpoint() string { return a.Issuer() + "/revoke" } - -// revoke is an RFC 7009 revocation endpoint for grant refresh tokens. It is -// kept until stacklok/toolhive#6966 and stacklok/toolhive#6972 retire it -// (mecatl #2568). -// -// Guess: only the authenticated broker may call it. Revoking a grant's -// refresh token revokes the grant, so a later use gets revoked; any other -// value changes nothing and, as RFC 7009 §2.2 requires for an invalid token, -// still answers 200. -func (a *AS1) revoke(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", "") - return - } - if _, confidential, ok := a.authenticateClient(r); !ok || !confidential { - writeOAuthError(w, http.StatusUnauthorized, "invalid_client", "") - return - } - token := r.PostForm.Get("token") - if token == "" { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", "") - return - } - a.mu.Lock() - if g, ok := a.grants[token]; ok && g.clientID == BrokerClientID { - g.revoked = true - } - a.mu.Unlock() - w.Header().Set("Cache-Control", "no-store") - w.WriteHeader(http.StatusOK) -} diff --git a/internal/testutil/identityharness/sessionopen.go b/internal/testutil/identityharness/sessionopen.go deleted file mode 100644 index 0d3f13533c..0000000000 --- a/internal/testutil/identityharness/sessionopen.go +++ /dev/null @@ -1,333 +0,0 @@ -package identityharness - -import ( - "bytes" - "encoding/json" - "maps" - "net/http" - "net/url" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -const ( - // ExchangeGrantType is the RFC 9396 authorization_details type of - // ToolHive's generic grant (stacklok/toolhive#6897): a refresh token - // whose use is fixed when it is issued. - ExchangeGrantType = "https://toolhive.dev/exchange_grant" - // TokenTypeIDJAG is the ID-JAG token type, the only output AS-1 issues - // the broker's grants for. - TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" // #nosec G101 -- token type URN, not a credential. - // DefaultGrantMaxLifetime is AS-1's configured maximum lifetime for a - // grant that issues ID-JAGs. - DefaultGrantMaxLifetime = 12 * time.Hour - - grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" // #nosec G101 -- RFC 8693 grant type URN, not a credential. - tokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token" // #nosec G101 -- RFC 8693 token type URN, not a credential. - tokenTypeRefresh = "urn:ietf:params:oauth:token-type:refresh_token" // #nosec G101 -- RFC 8693 token type URN, not a credential. - paramAuthDetails = "authorization_details" - errInvalidAuthDetail = "invalid_authorization_details" - - // Reason codes AS-1 returns for grants (design "Error reasons"). - reasonTokenUsed = "token_used" - reasonRevoked = "revoked" - reasonSubjectTokenInvalid = "subject_token_invalid" - - // Reasons for an invalid_authorization_details refusal - // (stacklok/toolhive#6897). - reasonSingleEntryRequired = "single_entry_required" - reasonMalformedEntry = "malformed_entry" - reasonInvalidIssuableTypes = "invalid_issuable_token_types" - reasonTokenTypeNotPermitted = "token_type_not_permitted" - reasonInvalidExpiresAt = "invalid_expires_at" -) - -// Owner is a company identity: the upstream IdP's issuer and subject, as in -// an access token's sub_id. -type Owner struct { - Issuer string `json:"iss"` - Subject string `json:"sub"` -} - -// ExchangeGrant is the exchange-grant authorization_details entry a session -// open sends and AS-1 echoes with the expiry it granted. ExpiresAt is Unix -// seconds; zero leaves it out. -type ExchangeGrant struct { - Type string `json:"type"` - IssuableTokenTypes []string `json:"issuable_token_types"` - ExpiresAt int64 `json:"expires_at,omitempty"` -} - -// Grant is AS-1's record of a grant and its refresh token. It names the -// client and the user, never a Mecatl session or owner. -type Grant struct { - ClientID string - // Subject is the user's AS-1 subject, and SubID their company identity. - Subject string - SubID Owner - // SourceJTI is the jti of the access token the exchange converted. - SourceJTI string - // Output is the one token type the grant issues. - Output string - ExpiresAt time.Time - // Active reports whether the refresh token is still usable. Otherwise - // Reason is revoked for a revoked grant, which the ID-JAG exchange also - // answers, and empty for an expired one, which the exchange answers with - // grant_invalid. - Active bool - Reason string -} - -type as1Grant struct { - clientID, subject, sourceJTI, output string - subID Owner - expiresAt time.Time - revoked bool -} - -// GrantsIssued returns how many grants AS-1 has issued. -func (a *AS1) GrantsIssued() int { - a.mu.Lock() - defer a.mu.Unlock() - return len(a.grants) -} - -// Grant returns AS-1's record of the grant of refresh token. -func (a *AS1) Grant(token string) (Grant, bool) { - a.mu.Lock() - defer a.mu.Unlock() - g, ok := a.grants[token] - if !ok { - return Grant{}, false - } - grant := Grant{ - ClientID: g.clientID, Subject: g.subject, SubID: g.subID, SourceJTI: g.sourceJTI, - Output: g.output, ExpiresAt: g.expiresAt, Active: true, - } - switch { - case g.revoked: - grant.Active, grant.Reason = false, reasonRevoked - case !a.now().Before(g.expiresAt): - grant.Active = false - } - return grant, true -} - -// exchange is AS-1's side of session open, design step (3): the RFC 8693 -// exchange of an access token for a grant that issues only ID-JAGs, for an -// authenticated broker. Check 1 (client authentication) and check 2 (the -// broker may use this grant) have passed. -// -// It is kept as the grant fixture for tests of revocation and its reasons, -// which the real AS-1 does not serve yet (#2568), and for mecak8s's -// TestIdentityBrokerAgainstOfflineHarness: the harness can revoke and redeem -// only refresh tokens it issued. Session-open behaviour itself is tested -// against the real AS-1 (as1servertest). -func (a *AS1) exchange(w http.ResponseWriter, r *http.Request) { - now := a.now() - entry, code, reason := checkExchangeForm(r.PostForm, now) - if code != "" { - writeOAuthError(w, http.StatusBadRequest, code, reason) - return - } - // Check 4: the subject token is a live AS-1 access token for the Mecatl - // API, issued to a public client. Unlike the real AS-1, a refused token - // gets subject_token_invalid whatever the failure. - subject, ok := a.verifySubjectToken(r.PostForm.Get("subject_token")) - if !ok { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonSubjectTokenInvalid) - return - } - refresh, granted, ok := a.convert(subject, entry, now) - if !ok { - writeOAuthError(w, http.StatusBadRequest, "invalid_request", reasonTokenUsed) - return - } - echo := ExchangeGrant{Type: ExchangeGrantType, IssuableTokenTypes: entry.IssuableTokenTypes, ExpiresAt: granted.Unix()} - writeJSON(w, http.StatusOK, map[string]any{ - "access_token": refresh, - "issued_token_type": tokenTypeRefresh, - "token_type": "N_A", - "expires_in": int(granted.Sub(now).Seconds()), - paramAuthDetails: []ExchangeGrant{echo}, - }) -} - -// checkExchangeForm runs check 3: the request is well formed. It returns the -// entry, or the OAuth error code and any reason. -func checkExchangeForm(form url.Values, now time.Time) (ExchangeGrant, string, string) { - for _, values := range form { - if len(values) > 1 { // RFC 6749 §3.2 - return ExchangeGrant{}, "invalid_request", "" - } - } - switch { - case form.Has("scope"): - return ExchangeGrant{}, "invalid_scope", "" - case form.Has("resource") || form.Has("audience"): - return ExchangeGrant{}, errInvalidTarget, "" - case form.Get("subject_token") == "" || form.Get("subject_token_type") != tokenTypeAccess || - form.Get("requested_token_type") != tokenTypeRefresh || form.Has("actor_token") || - form.Has("actor_token_type") || !form.Has(paramAuthDetails): - return ExchangeGrant{}, "invalid_request", "" - } - entry, reason := parseExchangeGrant(form.Get(paramAuthDetails), now) - if reason != "" { - return ExchangeGrant{}, errInvalidAuthDetail, reason - } - return entry, "", "" -} - -// parseExchangeGrant accepts exactly one exchange-grant entry listing only -// id-jag, with an optional expires_at in the future, and returns it, or the -// invalid_authorization_details reason. Member names match exactly, appear -// once, and no other member is allowed; encoding/json alone would match them -// case-insensitively, let a duplicate win, and ignore unknown ones. -func parseExchangeGrant(value string, now time.Time) (ExchangeGrant, string) { - var entries []json.RawMessage - if json.Unmarshal([]byte(value), &entries) != nil { - return ExchangeGrant{}, reasonMalformedEntry - } - if len(entries) != 1 { - return ExchangeGrant{}, reasonSingleEntryRequired - } - members, ok := strictObject(entries[0]) - if !ok || strictString(members["type"]) != ExchangeGrantType { - return ExchangeGrant{}, reasonMalformedEntry - } - for name := range members { - if name != "type" && name != "issuable_token_types" && name != "expires_at" { - return ExchangeGrant{}, reasonMalformedEntry - } - } - var types []string - if json.Unmarshal(members["issuable_token_types"], &types) != nil || len(types) != 1 { - return ExchangeGrant{}, reasonInvalidIssuableTypes - } - switch types[0] { - case TokenTypeIDJAG: - case tokenTypeRefresh: - // The broker's client is configured for ID-JAG grants only. - return ExchangeGrant{}, reasonTokenTypeNotPermitted - default: - return ExchangeGrant{}, reasonInvalidIssuableTypes - } - entry := ExchangeGrant{Type: ExchangeGrantType, IssuableTokenTypes: types} - if raw, ok := members["expires_at"]; ok { - dec := json.NewDecoder(bytes.NewReader(raw)) - dec.UseNumber() - var n json.Number - if dec.Decode(&n) != nil { - return ExchangeGrant{}, reasonInvalidExpiresAt - } - exp, err := n.Int64() - if err != nil || exp <= now.Unix() { - return ExchangeGrant{}, reasonInvalidExpiresAt - } - entry.ExpiresAt = exp - } - return entry, "" -} - -// convert runs check 5 and, if it passes, in one transaction records the -// converted jti and writes the grant, expiring at the requested expires_at -// capped at AS-1's maximum. It returns false when the jti was converted -// before; a retry is not an exception. -func (a *AS1) convert(subject as1Subject, entry ExchangeGrant, now time.Time) (string, time.Time, bool) { - a.mu.Lock() - defer a.mu.Unlock() - // Check 4 already holds the token within exp, so a converted jti is kept - // until exp plus the clock skew. - maps.DeleteFunc(a.conversions, func(_ string, until time.Time) bool { - return now.After(until.Add(as1ClockSkew)) - }) - if _, used := a.conversions[subject.jti]; used { - return "", time.Time{}, false - } - a.conversions[subject.jti] = subject.expires - expires := now.Add(a.grantMax) - if requested := time.Unix(entry.ExpiresAt, 0); entry.ExpiresAt != 0 && requested.Before(expires) { - expires = requested - } - refresh := randomToken("as1-grant-rt-") - // Only BrokerClientID reaches this exchange. - a.grants[refresh] = &as1Grant{ - clientID: BrokerClientID, subject: subject.sub, subID: subject.owner, - sourceJTI: subject.jti, output: TokenTypeIDJAG, expiresAt: expires, - } - return refresh, expires, true -} - -// strictObject decodes a JSON object into its members by exact name, -// refusing anything else and any repeated name. -func strictObject(raw json.RawMessage) (map[string]json.RawMessage, bool) { - dec := json.NewDecoder(bytes.NewReader(raw)) - if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { - return nil, false - } - members := make(map[string]json.RawMessage) - for dec.More() { - tok, err := dec.Token() - name, isName := tok.(string) - if err != nil || !isName { - return nil, false - } - if _, dup := members[name]; dup { - return nil, false - } - var value json.RawMessage - if dec.Decode(&value) != nil { - return nil, false - } - members[name] = value - } - if tok, err := dec.Token(); err != nil || tok != json.Delim('}') { - return nil, false - } - return members, true -} - -// strictString returns raw as a string, or "" when it is absent or not one. -func strictString(raw json.RawMessage) string { - var s string - if raw == nil || json.Unmarshal(raw, &s) != nil { - return "" - } - return s -} - -type as1Subject struct { - sub, jti string - owner Owner - expires time.Time -} - -// verifySubjectToken runs check 4 on an exchange's subject token. -func (a *AS1) verifySubjectToken(token string) (as1Subject, bool) { - var claims struct { - jwt.RegisteredClaims - ClientID string `json:"client_id"` - SubID struct { - Format string `json:"format"` - Owner - } `json:"sub_id"` - } - parsed, err := jwt.ParseWithClaims(token, &claims, func(*jwt.Token) (any, error) { return &a.key.PublicKey, nil }, - jwt.WithValidMethods([]string{"ES256"}), jwt.WithIssuer(a.Issuer()), jwt.WithAudience(a.audience), - jwt.WithExpirationRequired(), jwt.WithTimeFunc(a.now)) - if err != nil { - return as1Subject{}, false - } - if typ := parsed.Header["typ"]; typ != "at+jwt" && typ != "application/at+jwt" { - return as1Subject{}, false - } - a.mu.Lock() - _, publicClient := a.clients[claims.ClientID] - a.mu.Unlock() - if !publicClient || claims.ID == "" || claims.Subject == "" || claims.SubID.Format != "iss_sub" || - claims.SubID.Issuer == "" || claims.SubID.Subject == "" { - return as1Subject{}, false - } - return as1Subject{sub: claims.Subject, jti: claims.ID, owner: claims.SubID.Owner, expires: claims.ExpiresAt.Time}, true -} diff --git a/internal/testutil/identityharness/sessionopen_test.go b/internal/testutil/identityharness/sessionopen_test.go deleted file mode 100644 index 70b3e69a11..0000000000 --- a/internal/testutil/identityharness/sessionopen_test.go +++ /dev/null @@ -1,383 +0,0 @@ -package identityharness_test - -import ( - "encoding/json" - "errors" - "net/http" - "net/url" - "reflect" - "slices" - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/stacklok/mecatl/internal/testutil/identityharness" -) - -const ( - grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" - jwtBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" - tokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token" - tokenTypeRefresh = "urn:ietf:params:oauth:token-type:refresh_token" - tokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" - exchangeGrantType = "https://toolhive.dev/exchange_grant" -) - -// testClock is a settable clock safe to read from server goroutines. -type testClock struct { - mu sync.Mutex - now time.Time -} - -func newTestClock() *testClock { return &testClock{now: time.Unix(1_800_000_000, 0)} } - -func (c *testClock) Now() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - return c.now -} - -func (c *testClock) Advance(d time.Duration) { - c.mu.Lock() - defer c.mu.Unlock() - c.now = c.now.Add(d) -} - -func openReq(token string) identityharness.SessionOpenExchange { - return identityharness.SessionOpenExchange{SubjectToken: token} -} - -func aliceToken(h *identityharness.Harness) string { - return h.AS1.MintAccessToken(identityharness.AccessTokenSpec{User: identityharness.Alice}) -} - -// grantEntry is the exchange-grant entry listing only id-jag, with -// expiresAt when nonzero. -func grantEntry(expiresAt int64) identityharness.ExchangeGrant { - return identityharness.ExchangeGrant{Type: exchangeGrantType, IssuableTokenTypes: []string{tokenTypeIDJAG}, ExpiresAt: expiresAt} -} - -func TestSessionOpenIssuesAGenericGrant(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now}) - tokens, err := h.SignIn(t.Context(), identityharness.SignInRequest{User: identityharness.Alice}) - if err != nil { - t.Fatalf("SignIn: %v", err) - } - resp, err := h.ScriptedBroker().OpenSession(t.Context(), openReq(tokens.AccessToken)) - if err != nil { - t.Fatalf("OpenSession: %v", err) - } - expires := clock.Now().Add(identityharness.DefaultGrantMaxLifetime) - want := []identityharness.ExchangeGrant{grantEntry(expires.Unix())} - if resp.RefreshToken == "" || resp.IssuedTokenType != tokenTypeRefresh || resp.TokenType != "N_A" || - resp.ExpiresIn != int(identityharness.DefaultGrantMaxLifetime.Seconds()) || - !reflect.DeepEqual(resp.AuthorizationDetails, want) { - t.Fatalf("response = %+v, want a refresh token in access_token, N_A, AS-1's maximum, and the entry echoed with it", resp) - } - _, claims := verify(t, h, tokens.AccessToken) - grant, ok := h.AS1.Grant(resp.RefreshToken) - wantGrant := identityharness.Grant{ - ClientID: identityharness.BrokerClientID, Subject: h.AS1.Subject(identityharness.Alice), - SubID: h.Owner(identityharness.Alice), SourceJTI: claims["jti"].(string), - Output: tokenTypeIDJAG, ExpiresAt: expires, Active: true, - } - if !ok || grant != wantGrant { - t.Fatalf("grant = %+v, %v; want %+v", grant, ok, wantGrant) - } -} - -// TestSessionOpenDoesNotRotate checks the raw response: the grant's refresh -// token arrives in access_token, with no second refresh token, and the echo -// is exactly the entry with the granted expiry, naming no session or owner. -func TestSessionOpenDoesNotRotate(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now}) - requested := clock.Now().Add(time.Hour).Unix() - entry := `{"type":"` + exchangeGrantType + `","issuable_token_types":["` + tokenTypeIDJAG + `"],"expires_at":` + strconv.FormatInt(requested, 10) + `}` - body, err := postToken(t, h, exchangeForm(h, aliceToken(h), "["+entry+"]")) - if err != nil { - t.Fatalf("exchange: %v", err) - } - if _, ok := body["refresh_token"]; ok { - t.Errorf("response carries refresh_token: %v", body) - } - var sent any - if err := json.Unmarshal([]byte("["+entry+"]"), &sent); err != nil { - t.Fatal(err) - } - if got := mustJSON(t, body["authorization_details"]); got != mustJSON(t, sent) { - t.Errorf("echo = %s, want the entry sent, %s", got, mustJSON(t, sent)) - } -} - -func TestSessionOpenCapsExpiresAt(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now, GrantMaxLifetime: time.Hour}) - b := h.ScriptedBroker() - maxExpiry := clock.Now().Add(time.Hour).Unix() - for _, tt := range []struct { - name string - requested, granted int64 - }{ - {"absent: AS-1's maximum", 0, maxExpiry}, - {"below the maximum: kept", maxExpiry - 600, maxExpiry - 600}, - {"at the maximum", maxExpiry, maxExpiry}, - {"above the maximum: capped", maxExpiry + 3600, maxExpiry}, - } { - t.Run(tt.name, func(t *testing.T) { - resp, err := b.OpenSession(t.Context(), identityharness.SessionOpenExchange{SubjectToken: aliceToken(h), ExpiresAt: tt.requested}) - if err != nil { - t.Fatalf("OpenSession: %v", err) - } - grant, _ := h.AS1.Grant(resp.RefreshToken) - if !reflect.DeepEqual(resp.AuthorizationDetails, []identityharness.ExchangeGrant{grantEntry(tt.granted)}) || - resp.ExpiresIn != int(tt.granted-clock.Now().Unix()) || grant.ExpiresAt.Unix() != tt.granted { - t.Fatalf("echo %+v, expires_in %d, grant expiry %v; want %d", resp.AuthorizationDetails, resp.ExpiresIn, grant.ExpiresAt, tt.granted) - } - }) - } -} - -func TestSessionOpenRefusals(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now}) - b := h.ScriptedBroker() - details := func(entries ...string) string { return "[" + strings.Join(entries, ",") + "]" } - member := func(name, value string) string { return `,"` + name + `":` + value } - entry := func(extra string) string { - return `{"type":"` + exchangeGrantType + `","issuable_token_types":["` + tokenTypeIDJAG + `"]` + extra + `}` - } - good := entry("") - - // Positive control: the unmodified form converts, so each check 3 case - // below fails only for its own defect. - if _, err := postToken(t, h, exchangeForm(h, aliceToken(h), details(good))); err != nil { - t.Fatalf("unmodified form: %v", err) - } - - t.Run("check 2: public client", func(t *testing.T) { - form := exchangeForm(h, aliceToken(h), details(good)) - form.Del("client_assertion") - form.Del("client_assertion_type") - form.Set("client_id", identityharness.DefaultClientID) - _, err := postToken(t, h, form) - assertOAuthError(t, err, "unauthorized_client") - }) - - past := strconv.FormatInt(clock.Now().Unix(), 10) - for _, c := range []struct { - name string - edit func(url.Values) - code, reason string - }{ - {"subject token type", func(f url.Values) { f.Set("subject_token_type", "urn:ietf:params:oauth:token-type:id_token") }, "invalid_request", ""}, - {"requested token type", func(f url.Values) { f.Set("requested_token_type", tokenTypeAccess) }, "invalid_request", ""}, - {"no subject token", func(f url.Values) { f.Del("subject_token") }, "invalid_request", ""}, - {"actor token", func(f url.Values) { f.Set("actor_token", "svid") }, "invalid_request", ""}, - {"scope", func(f url.Values) { f.Set("scope", "openid") }, "invalid_scope", ""}, - {"resource", func(f url.Values) { f.Set("resource", h.AS1.Audience()) }, "invalid_target", ""}, - {"audience", func(f url.Values) { f.Set("audience", h.AS1.Audience()) }, "invalid_target", ""}, - {"no authorization_details", func(f url.Values) { f.Del("authorization_details") }, "invalid_request", ""}, - {"repeated parameter", func(f url.Values) { f.Add("authorization_details", details(good)) }, "invalid_request", ""}, - {"not JSON", func(f url.Values) { f.Set("authorization_details", "{") }, "invalid_authorization_details", "malformed_entry"}, - {"no entry", func(f url.Values) { f.Set("authorization_details", "[]") }, "invalid_authorization_details", "single_entry_required"}, - {"two entries", func(f url.Values) { f.Set("authorization_details", details(good, good)) }, "invalid_authorization_details", "single_entry_required"}, - {"other type", func(f url.Values) { - f.Set("authorization_details", details(`{"type":"mecatl_session","issuable_token_types":["`+tokenTypeIDJAG+`"]}`)) - }, "invalid_authorization_details", "malformed_entry"}, - {"session member", func(f url.Values) { f.Set("authorization_details", details(entry(member("session", `"A42"`)))) }, "invalid_authorization_details", "malformed_entry"}, - {"type in another case", func(f url.Values) { - f.Set("authorization_details", details(`{"TYPE":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeIDJAG+`"]}`)) - }, "invalid_authorization_details", "malformed_entry"}, - {"duplicated member", func(f url.Values) { - f.Set("authorization_details", details(entry(member("issuable_token_types", `["`+tokenTypeIDJAG+`"]`)))) - }, "invalid_authorization_details", "malformed_entry"}, - {"no issuable token types", func(f url.Values) { f.Set("authorization_details", details(`{"type":"`+exchangeGrantType+`"}`)) }, "invalid_authorization_details", "invalid_issuable_token_types"}, - {"two issuable token types", func(f url.Values) { - f.Set("authorization_details", details(`{"type":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeIDJAG+`","`+tokenTypeIDJAG+`"]}`)) - }, "invalid_authorization_details", "invalid_issuable_token_types"}, - {"unknown output", func(f url.Values) { - f.Set("authorization_details", details(`{"type":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeAccess+`"]}`)) - }, "invalid_authorization_details", "invalid_issuable_token_types"}, - {"refresh token output", func(f url.Values) { - f.Set("authorization_details", details(`{"type":"`+exchangeGrantType+`","issuable_token_types":["`+tokenTypeRefresh+`"]}`)) - }, "invalid_authorization_details", "token_type_not_permitted"}, - {"expires_at now", func(f url.Values) { f.Set("authorization_details", details(entry(member("expires_at", past)))) }, "invalid_authorization_details", "invalid_expires_at"}, - {"expires_at string", func(f url.Values) { f.Set("authorization_details", details(entry(member("expires_at", `"`+past+`"`)))) }, "invalid_authorization_details", "invalid_expires_at"}, - {"expires_at fraction", func(f url.Values) { - f.Set("authorization_details", details(entry(member("expires_at", "1900000000.5")))) - }, "invalid_authorization_details", "invalid_expires_at"}, - } { - t.Run("check 3: "+c.name, func(t *testing.T) { - form := exchangeForm(h, aliceToken(h), details(good)) - c.edit(form) - _, err := postToken(t, h, form) - assertReason(t, err, http.StatusBadRequest, c.code, c.reason) - }) - } - // RFC 9068's media-type form of typ is accepted. - if _, err := b.OpenSession(t.Context(), openReq(h.AS1.MintAccessToken(identityharness.AccessTokenSpec{Type: "application/at+jwt"}))); err != nil { - t.Errorf("application/at+jwt subject token: %v", err) - } - - t.Run("check 5: token used", func(t *testing.T) { - token := aliceToken(h) - if _, err := b.OpenSession(t.Context(), openReq(token)); err != nil { - t.Fatalf("first exchange: %v", err) - } - issued := h.AS1.GrantsIssued() - // A later expires_at makes the request differ; the jti still decides. - _, err := b.OpenSession(t.Context(), identityharness.SessionOpenExchange{SubjectToken: token, ExpiresAt: clock.Now().Add(time.Hour).Unix()}) - assertReason(t, err, http.StatusBadRequest, "invalid_request", "token_used") - if h.AS1.GrantsIssued() != issued { - t.Error("a used token was converted again") - } - }) -} - -// TestLaterExchangeDoesNotTouchEarlierGrants: AS-1 keeps no per-session -// state, so a second exchange for the same user is a second grant, and the -// first stays active until the broker revokes it. -func TestLaterExchangeDoesNotTouchEarlierGrants(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - b := h.ScriptedBroker() - first, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("first exchange: %v", err) - } - second, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("second exchange: %v", err) - } - old, _ := h.AS1.Grant(first.RefreshToken) - current, _ := h.AS1.Grant(second.RefreshToken) - if !old.Active || !current.Active || first.RefreshToken == second.RefreshToken { - t.Errorf("old %+v, current %+v; want two distinct active grants", old, current) - } -} - -func TestGrantRefreshTokenRefusedAtRefreshGrant(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - resp, err := h.ScriptedBroker().OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("OpenSession: %v", err) - } - _, err = postToken(t, h, url.Values{ - "grant_type": {"refresh_token"}, "refresh_token": {resp.RefreshToken}, - "client_assertion_type": {jwtBearer}, - "client_assertion": {h.ScriptedBroker().Assertion(identityharness.ClientAssertionSpec{})}, - }) - assertOAuthError(t, err, "invalid_grant") - _, err = h.Refresh(t.Context(), identityharness.DefaultClientID, resp.RefreshToken) - assertOAuthError(t, err, "invalid_grant") - if grant, _ := h.AS1.Grant(resp.RefreshToken); !grant.Active { - t.Error("presenting the token at the refresh grant revoked it") - } -} - -func TestRevocationRevokesTheGrant(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - b := h.ScriptedBroker() - first, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("first exchange: %v", err) - } - second, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("second exchange: %v", err) - } - // An unknown value is answered 200 and changes nothing. - if err := b.Revoke(t.Context(), "not-a-token"); err != nil { - t.Fatalf("Revoke(unknown): %v", err) - } - - resp, err := h.HTTPClient().PostForm(h.AS1.RevocationEndpoint(), url.Values{"token": {first.RefreshToken}, "client_id": {identityharness.DefaultClientID}}) - if err != nil { - t.Fatal(err) - } - _ = resp.Body.Close() - if resp.StatusCode != http.StatusUnauthorized { - t.Errorf("revocation by a public client: status %d, want 401", resp.StatusCode) - } - if grant, _ := h.AS1.Grant(first.RefreshToken); !grant.Active { - t.Fatalf("grant %+v after refused revocations, want active", grant) - } - - if err := b.Revoke(t.Context(), first.RefreshToken); err != nil { - t.Fatalf("Revoke: %v", err) - } - if grant, _ := h.AS1.Grant(first.RefreshToken); grant.Active || grant.Reason != "revoked" { - t.Fatalf("after revocation: grant %+v, want revoked", grant) - } - if grant, _ := h.AS1.Grant(second.RefreshToken); !grant.Active { - t.Fatalf("revoking one grant changed another: %+v", grant) - } - // AS-1 knows no sessions, so it has nothing to refuse a later open for. - if _, err := b.OpenSession(t.Context(), openReq(aliceToken(h))); err != nil { - t.Fatalf("exchange after a revocation: %v", err) - } -} - -func TestGrantExpiry(t *testing.T) { - clock := newTestClock() - h := identityharness.New(t, identityharness.Options{Now: clock.Now, GrantMaxLifetime: time.Hour}) - b := h.ScriptedBroker() - byClock, err := b.OpenSession(t.Context(), openReq(aliceToken(h))) - if err != nil { - t.Fatalf("exchange: %v", err) - } - if byClock.ExpiresIn != 3600 { - t.Errorf("expires_in = %d, want the configured maximum 3600", byClock.ExpiresIn) - } - - if grant, _ := h.AS1.Grant(byClock.RefreshToken); !grant.Active { - t.Fatalf("grant %+v before its expiry, want active", grant) - } - clock.Advance(time.Hour) - if grant, _ := h.AS1.Grant(byClock.RefreshToken); grant.Active || grant.Reason != "" { - t.Errorf("at its expiry: grant %+v, want inactive with no reason", grant) - } -} - -func TestDiscoveryAdvertisesBrokerSupport(t *testing.T) { - h := identityharness.New(t, identityharness.Options{}) - var doc struct { - RevocationEndpoint string `json:"revocation_endpoint"` - GrantTypes []string `json:"grant_types_supported"` - AuthMethods []string `json:"token_endpoint_auth_methods_supported"` - DetailsTypes []string `json:"authorization_details_types_supported"` - } - getJSON(t, h, h.AS1.Issuer()+"/.well-known/openid-configuration", &doc) - if doc.RevocationEndpoint != h.AS1.RevocationEndpoint() || - !slices.Contains(doc.GrantTypes, grantTokenExchange) || !slices.Contains(doc.GrantTypes, "authorization_code") || - !slices.Contains(doc.AuthMethods, "none") || !slices.Contains(doc.AuthMethods, "private_key_jwt") || - !slices.Equal(doc.DetailsTypes, []string{exchangeGrantType}) { - t.Errorf("discovery = %+v, want revocation, token exchange, none and private_key_jwt, the exchange-grant type", doc) - } -} - -// exchangeForm is a valid session-open form, authenticated as the broker. -func exchangeForm(h *identityharness.Harness, token, details string) url.Values { - return url.Values{ - "grant_type": {grantTokenExchange}, - "subject_token": {token}, - "subject_token_type": {tokenTypeAccess}, - "requested_token_type": {tokenTypeRefresh}, - "authorization_details": {details}, - "client_assertion_type": {jwtBearer}, - "client_assertion": {h.ScriptedBroker().Assertion(identityharness.ClientAssertionSpec{})}, - } -} - -// assertReason checks an OAuth error's status, code, and the reason that -// starts its description. -func assertReason(t *testing.T, err error, status int, code, reason string) { - t.Helper() - var oauthErr *identityharness.OAuthError - if !errors.As(err, &oauthErr) || oauthErr.Status != status || oauthErr.Code != code || oauthErr.Description != reason { - t.Fatalf("error = %v (%+v), want %d %s with reason %q", err, oauthErr, status, code, reason) - } -} diff --git a/internal/testutil/identityharness/signin.go b/internal/testutil/identityharness/signin.go deleted file mode 100644 index 328ac601ce..0000000000 --- a/internal/testutil/identityharness/signin.go +++ /dev/null @@ -1,168 +0,0 @@ -package identityharness - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" -) - -// SignInRequest selects who signs in, with which client. -type SignInRequest struct { - // User is the company identity to sign in. Empty selects the IdP's - // default user. - User string - // ClientID is the AS-1 client. Empty selects DefaultClientID. - ClientID string - // RedirectURI is the client's redirect URI. Empty selects - // DefaultRedirectURI. - RedirectURI string -} - -// Tokens are what a client holds after signing in at AS-1. -type Tokens struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` -} - -// OAuthError is an OAuth error a sign-in ended with, from the authorization -// redirect or the token endpoint. -type OAuthError struct { - Code string `json:"error"` - Description string `json:"error_description"` - // Status is the HTTP status of a token or revocation endpoint error. - Status int `json:"-"` -} - -func (e *OAuthError) Error() string { - if e.Description == "" { - return "oauth error " + e.Code - } - return "oauth error " + e.Code + ": " + e.Description -} - -// SignIn drives the browser side of a sign-in, as the TUI or Studio would: -// authorization code with PKCE at AS-1, through the upstream IdP, then the -// code exchange at AS-1's token endpoint. A refused sign-in returns an -// *OAuthError. -func (h *Harness) SignIn(ctx context.Context, req SignInRequest) (Tokens, error) { - clientID := firstNonEmpty(req.ClientID, DefaultClientID) - redirectURI := firstNonEmpty(req.RedirectURI, DefaultRedirectURI) - verifier := randomToken("verifier-") + randomToken("") - state := randomToken("state-") - q := url.Values{ - "response_type": {responseTypeCode}, - paramClientID: {clientID}, - "redirect_uri": {redirectURI}, - "state": {state}, - "code_challenge": {s256(verifier)}, - "code_challenge_method": {pkceS256}, - } - if req.User != "" { - q.Set("login_hint", req.User) - } - back, err := h.followToRedirect(ctx, withQuery(h.AS1.AuthorizationEndpoint(), q), redirectURI) - if err != nil { - return Tokens{}, err - } - if code := back.Get("error"); code != "" { - return Tokens{}, &OAuthError{Code: code, Description: back.Get("error_description")} - } - if back.Get("state") != state { - return Tokens{}, fmt.Errorf("identityharness: sign-in state mismatch") - } - return h.exchange(ctx, url.Values{ - "grant_type": {grantAuthorizationCode}, - paramClientID: {clientID}, - "code": {back.Get("code")}, - "redirect_uri": {redirectURI}, - "code_verifier": {verifier}, - }) -} - -// Refresh renews an access token with a client refresh token. -func (h *Harness) Refresh(ctx context.Context, clientID, refreshToken string) (Tokens, error) { - return h.exchange(ctx, url.Values{ - "grant_type": {grantRefreshToken}, - paramClientID: {firstNonEmpty(clientID, DefaultClientID)}, - "refresh_token": {refreshToken}, - }) -} - -// Authorize plays the browser for a real client's authorization request: -// it follows authorizationURL through AS-1 and the upstream IdP to the -// redirect_uri the request names, and returns that redirect's query (code, -// state, or error) without contacting the client's redirect URI. -func (h *Harness) Authorize(ctx context.Context, authorizationURL string) (url.Values, error) { - u, err := url.Parse(authorizationURL) - if err != nil { - return nil, err - } - return h.followToRedirect(ctx, authorizationURL, u.Query().Get("redirect_uri")) -} - -// followToRedirect follows redirects from start until one targets -// redirectURI, and returns that redirect's query. -func (h *Harness) followToRedirect(ctx context.Context, start, redirectURI string) (url.Values, error) { - client := h.HTTPClient() - next := start - for range 10 { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, next, nil) - if err != nil { - return nil, err - } - resp, err := client.Do(req) - if err != nil { - return nil, err - } - _ = resp.Body.Close() - if resp.StatusCode != http.StatusFound { - return nil, fmt.Errorf("identityharness: GET %s: status %d", req.URL.Path, resp.StatusCode) - } - location, err := resp.Location() - if err != nil { - return nil, err - } - next = location.String() - if strings.HasPrefix(next, redirectURI+"?") { - return location.Query(), nil - } - } - return nil, fmt.Errorf("identityharness: too many redirects") -} - -func (h *Harness) exchange(ctx context.Context, form url.Values) (Tokens, error) { - var tokens Tokens - err := h.postForm(ctx, h.AS1.TokenEndpoint(), form, &tokens) - return tokens, err -} - -// postForm posts form to an AS-1 endpoint and decodes a 200 response into -// out, when out is non-nil. An OAuth error response returns an *OAuthError. -func (h *Harness) postForm(ctx context.Context, endpoint string, form url.Values, out any) error { - req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := h.HTTPClient().Do(req) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { - oauthErr := &OAuthError{Status: resp.StatusCode} - if err := json.NewDecoder(resp.Body).Decode(oauthErr); err != nil || oauthErr.Code == "" { - return fmt.Errorf("identityharness: %s: status %d", req.URL.Path, resp.StatusCode) - } - return oauthErr - } - if out == nil { - return nil - } - return json.NewDecoder(resp.Body).Decode(out) -} From d707a5e54c2ad443e37b57d737147262d25c4fd7 Mon Sep 17 00:00:00 2001 From: Chris Burns <29541485+ChrisJBurns@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:23:51 +0000 Subject: [PATCH 2/2] test(identityharness): address review of the real-AS-1 move - The alg none forgery copies the issued token's claims, so it is refused for its algorithm alone. - clientauth's no-resource sign-in checks AS-1 grants its sole audience on the issued and refreshed token. - The RFC 7009 stub checks the assertion's iss, sub, aud, exp, and jti again. - forbidigo no longer exempts as1servertest from the RevokeGrant ban. - IdP.AddUser, unused, is gone, and re-signing has one implementation, identityharness.ResignToken. - New real-AS-1 tests: an ID-JAG for a resource the target doesn't list is refused with invalid_target, and a session-open expiry above the maximum is capped. Co-authored-by: Mecatl --- .golangci.yml | 10 ++---- cmd/mecak8s/identity_broker_harness_test.go | 18 +++++----- .../adapter/clientauth/as1_signin_test.go | 23 +++++++++++-- .../as1server/as1servertest/as1servertest.go | 22 ++----------- .../adapter/authserverclient/client_test.go | 20 +++++++---- .../adapter/authserverclient/exchange_test.go | 12 ++++--- .../adapter/authserverclient/idjag_test.go | 27 +++++++++++++++ internal/testutil/identityharness/harness.go | 33 ++++++++++++++----- internal/testutil/identityharness/idp.go | 9 ----- 9 files changed, 107 insertions(+), 67 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 4542101a61..cc59b1421e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1290,8 +1290,8 @@ linters: # as1server.Server.RevokeGrant revokes in AS-1's storage, past AS-1's # handler, client authentication, and ownership checks. It exists so # tests can see AS-1 answer revoked; production revokes through - # AS-1's RFC 7009 route (stacklok/toolhive#6966). Tests and - # as1servertest are excluded below. + # AS-1's RFC 7009 route (stacklok/toolhive#6966). Tests are + # excluded below. - pattern: '\.RevokeGrant\b' msg: 'RevokeGrant is test-only: it bypasses AS-1''s handler and client authentication. Production revokes through AS-1''s RFC 7009 route (stacklok/toolhive#6966).' goconst: @@ -1467,12 +1467,6 @@ linters: - linters: - forbidigo path: (.+)_test\.go - # as1servertest is the real-AS-1 test fixture; it may revoke in AS-1's - # storage for the tests that use it. - - linters: - - forbidigo - path: internal/identitybroker/adapter/as1server/as1servertest/ - text: RevokeGrant # SessionID and ToolSpec are deliberate, frozen domain names from the WP1 # ports that other packages depend on. revive flags them as "stutter" # (session.SessionID / tool.ToolSpec) but renaming would break the public diff --git a/cmd/mecak8s/identity_broker_harness_test.go b/cmd/mecak8s/identity_broker_harness_test.go index e0baeda44b..014f3adc91 100644 --- a/cmd/mecak8s/identity_broker_harness_test.go +++ b/cmd/mecak8s/identity_broker_harness_test.go @@ -248,7 +248,7 @@ func TestIdentityBrokerOwnsSessionsAgainstRealAS1(t *testing.T) { "expired": a.ExpiredAccessToken(t, issued).Value(), "typ JWT": forge(typ("JWT")), "no typ": forge(typ("")), - "alg none": unsignedToken(t, a.Issuer(), as1servertest.Audience), // toolhive-core's fixed algorithm allowlist rejects this + "alg none": unsignedToken(t, issued.Value()), // toolhive-core's fixed algorithm allowlist rejects this "other client": forge(claim("client_id", "rogue")), "no sub_id": forge(claim("sub_id", nil)), "sub_id format": forge(claim("sub_id", map[string]string{"format": "email", "iss": h.IdP.Issuer(), "sub": identityharness.Alice})), @@ -1089,15 +1089,15 @@ func apiRequest(t *testing.T, method, url, token, body string) (int, string, str return resp.StatusCode, string(raw), resp.Header.Get("WWW-Authenticate") } -// unsignedToken is an otherwise well-formed AS-1 access token with alg none. -func unsignedToken(t *testing.T, issuer, audience string) string { +// unsignedToken is issued, an AS-1 access token, with its claims and typ +// unchanged but unsigned with alg none. +func unsignedToken(t *testing.T, issued string) string { t.Helper() - now := time.Now() - token := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{ - "iss": issuer, "sub": "u-alice", "aud": audience, "client_id": identityharness.DefaultClientID, - "sub_id": map[string]string{"format": "iss_sub", "iss": "https://login.example.com", "sub": identityharness.Alice}, - "iat": now.Unix(), "exp": now.Add(time.Minute).Unix(), - }) + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(issued, claims); err != nil { + t.Fatalf("parse the issued access token: %v", err) + } + token := jwt.NewWithClaims(jwt.SigningMethodNone, claims) token.Header["typ"] = "at+jwt" signed, err := token.SignedString(jwt.UnsafeAllowNoneSignatureType) if err != nil { diff --git a/internal/adapter/clientauth/as1_signin_test.go b/internal/adapter/clientauth/as1_signin_test.go index e3669df7ec..c5155706b2 100644 --- a/internal/adapter/clientauth/as1_signin_test.go +++ b/internal/adapter/clientauth/as1_signin_test.go @@ -12,6 +12,8 @@ import ( "sync" "testing" + "github.com/golang-jwt/jwt/v5" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server" "github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest" "github.com/stacklok/mecatl/internal/testutil/identityharness" @@ -233,10 +235,13 @@ func (f *as1Fixture) assertNoResource(t *testing.T, wantRefreshes int) { // TestLoginWithoutIdentityBrokerSignInOmitsResource is the default: without the // server's request, no leg (authorization, code exchange, refresh) sends -// resource, and AS-1 still issues tokens for the audience. +// resource, and AS-1 still issues tokens for the audience: it grants its sole +// allowed audience on a code exchange without resource and carries it forward +// on refresh. func TestLoginWithoutIdentityBrokerSignInOmitsResource(t *testing.T) { f := newAS1Fixture(t) initial := f.login(t, false) + assertAudience(t, "issued access token", initial.AccessToken, as1servertest.Audience) c := credentials(t) if _, err := c.Save(t.Context(), f.identity, initial, nil); err != nil { t.Fatal(err) @@ -250,15 +255,29 @@ func TestLoginWithoutIdentityBrokerSignInOmitsResource(t *testing.T) { t.Fatalf("NewRefreshSource: %v", err) } defer func() { _ = s.Close() }() - if _, err := s.Refresh(t.Context()); err != nil { + refreshed, err := s.Refresh(t.Context()) + if err != nil { t.Fatalf("Refresh: %v", err) } + assertAudience(t, "refreshed access token", refreshed, as1servertest.Audience) if len(f.authorizeURLs) != 1 { t.Fatalf("authorization requests = %d, want 1", len(f.authorizeURLs)) } f.assertNoResource(t, 1) } +// assertAudience fails unless the access token's aud is exactly want. +func assertAudience(t *testing.T, what, token, want string) { + t.Helper() + claims := jwt.MapClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil { + t.Fatalf("%s: parse: %v", what, err) + } + if aud, err := claims.GetAudience(); err != nil || len(aud) != 1 || aud[0] != want { + t.Errorf("%s aud = %v (err %v), want [%s]", what, aud, err, want) + } +} + // TestRefreshAfterReloadUsesTheSavedIdentityBrokerSignIn drives the restart path // the TUI uses: the flag comes back from the saved registry row, not from // fresh discovery. A row written without the field (as older registries are) diff --git a/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go b/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go index 21e3e31c9e..7e3be27926 100644 --- a/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go +++ b/internal/identitybroker/adapter/as1server/as1servertest/as1servertest.go @@ -19,7 +19,6 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" - "maps" "net" "net/http" "net/http/httptest" @@ -376,22 +375,9 @@ type Forgery struct { // wrote, as Start's does. func (a *AS1) Forge(t testing.TB, token identitybroker.Token, f Forgery) identitybroker.Token { t.Helper() - claims := jwt.MapClaims{} - parsed, _, err := jwt.NewParser().ParseUnverified(token.Value(), claims) - if err != nil { - t.Fatalf("as1servertest: parse token to forge: %v", err) - } - if f.Claims != nil { - f.Claims(claims) - } - forged := jwt.NewWithClaims(jwt.SigningMethodES256, claims) - forged.Header = maps.Clone(parsed.Header) - forged.Header["alg"] = jwt.SigningMethodES256.Alg() - if f.Header != nil { - f.Header(forged.Header) - } var key *ecdsa.PrivateKey if f.ForeignKey { + var err error if key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil { t.Fatalf("as1servertest: foreign key: %v", err) } @@ -401,9 +387,5 @@ func (a *AS1) Forge(t testing.TB, token identitybroker.Token, f Forgery) identit } key = identityharness.ReadSigningKey(t, a.signingKeyFile) } - signed, err := forged.SignedString(key) - if err != nil { - t.Fatalf("as1servertest: sign forged token: %v", err) - } - return identitybroker.NewToken(signed) + return identitybroker.NewToken(identityharness.ResignToken(t, key, token.Value(), f.Claims, f.Header)) } diff --git a/internal/identitybroker/adapter/authserverclient/client_test.go b/internal/identitybroker/adapter/authserverclient/client_test.go index 2f41b9c9cd..75cd4c4d50 100644 --- a/internal/identitybroker/adapter/authserverclient/client_test.go +++ b/internal/identitybroker/adapter/authserverclient/client_test.go @@ -104,9 +104,10 @@ func aliceSignsIn(t *testing.T, a *as1servertest.AS1) string { // revocationStub stands in for an RFC 7009 revocation endpoint, which the // real AS-1 does not serve until stacklok/toolhive#6966. It authenticates // the broker client by private_key_jwt only: a jwt-bearer client assertion -// signed with ES256 by the registered key under its kid. The assertion's -// claims are not checked here; TestSessionOpenAuthenticatesWithTheBrokerKey -// checks them at the real AS-1. It records each token it revokes. +// signed with ES256 by the registered key under its kid, whose iss and sub +// are the broker client ID, whose one aud is the stub's issuer, and which +// carries an unexpired exp and a jti. It does not track jti replay. It +// records each token it revokes. type revocationStub struct { issuer string endpoint string @@ -168,13 +169,20 @@ func (s *revocationStub) authenticated(r *http.Request) bool { (form.Has("client_id") && form.Get("client_id") != identitybroker.BrokerClientID) { return false } - _, err := jwt.Parse(form.Get("client_assertion"), func(token *jwt.Token) (any, error) { + claims := jwt.MapClaims{} + _, err := jwt.ParseWithClaims(form.Get("client_assertion"), claims, func(token *jwt.Token) (any, error) { if token.Header["kid"] != s.kid { return nil, jwt.ErrTokenUnverifiable } return s.key, nil - }, jwt.WithValidMethods([]string{"ES256"}), jwt.WithoutClaimsValidation()) - return err == nil + }, jwt.WithValidMethods([]string{"ES256"}), jwt.WithExpirationRequired(), + jwt.WithIssuer(identitybroker.BrokerClientID), jwt.WithSubject(identitybroker.BrokerClientID)) + if err != nil { + return false + } + aud, err := claims.GetAudience() + jti, _ := claims["jti"].(string) + return err == nil && len(aud) == 1 && aud[0] == s.issuer && jti != "" } func (s *revocationStub) revocations() []url.Values { diff --git a/internal/identitybroker/adapter/authserverclient/exchange_test.go b/internal/identitybroker/adapter/authserverclient/exchange_test.go index f72134b708..c252166733 100644 --- a/internal/identitybroker/adapter/authserverclient/exchange_test.go +++ b/internal/identitybroker/adapter/authserverclient/exchange_test.go @@ -21,7 +21,11 @@ func sessionGrant(expiresAt time.Time) identitybroker.ExchangeGrant { } func TestExchangeConvertsAtAS1(t *testing.T) { - for name, expiresAt := range map[string]time.Duration{"no expires_at": 0, "expires_at": as1servertest.IDJAGMaxLifetime / 2} { + for name, expiresAt := range map[string]time.Duration{ + "no expires_at": 0, + "expires_at": as1servertest.IDJAGMaxLifetime / 2, + "expires_at above the maximum": as1servertest.IDJAGMaxLifetime + time.Hour, + } { t.Run(name, func(t *testing.T) { a := startAS1(t) c := as1Client(t, a, &recorder{}, nil) @@ -42,14 +46,14 @@ func TestExchangeConvertsAtAS1(t *testing.T) { if g.Type != identitybroker.ExchangeGrantType || !slices.Equal(g.IssuableTokenTypes, []string{identitybroker.TokenTypeIDJAG}) { t.Fatalf("echo = %+v, want the exchange grant for id-jag", g) } - if expiresAt != 0 { + if expiresAt != 0 && expiresAt <= as1servertest.IDJAGMaxLifetime { if !g.ExpiresAt.Equal(req.Grant.ExpiresAt) { t.Fatalf("echoed expiry %v, want the requested %v", g.ExpiresAt, req.Grant.ExpiresAt) } return } - // No expires_at: AS-1 applies its maximum to its wall clock, in - // whole seconds. + // No expires_at, or one past the maximum: AS-1 applies its maximum + // to its wall clock, in whole seconds. earliest, latest := before.Add(as1servertest.IDJAGMaxLifetime).Truncate(time.Second), after.Add(as1servertest.IDJAGMaxLifetime+time.Second) if g.ExpiresAt.Before(earliest) || g.ExpiresAt.After(latest) { t.Fatalf("echoed expiry %v, want AS-1's maximum, between %v and %v", g.ExpiresAt, earliest, latest) diff --git a/internal/identitybroker/adapter/authserverclient/idjag_test.go b/internal/identitybroker/adapter/authserverclient/idjag_test.go index 0faf3d3244..ec681be79b 100644 --- a/internal/identitybroker/adapter/authserverclient/idjag_test.go +++ b/internal/identitybroker/adapter/authserverclient/idjag_test.go @@ -179,6 +179,33 @@ func TestIssueIDJAGAgainstRealAS1(t *testing.T) { } } +// TestIssueIDJAGAgainstRealAS1RefusesAnUnconfiguredResource checks design +// step (7)'s check 3 at the real AS-1: the audience is the configured AS-2, +// but the resource is not one of its vMCPs, so AS-1 refuses with +// invalid_target and issues no ID-JAG. +func TestIssueIDJAGAgainstRealAS1RefusesAnUnconfiguredResource(t *testing.T) { + x := startIDJAGAS1(t, testAS2Issuer, testVMCP) + _, err := x.client.IssueIDJAG(t.Context(), x.request(testAS2Issuer, testAS2Issuer+"/other-mcp")) + var refusal *identitybroker.ServerRefusal + if !errors.As(err, &refusal) || refusal.Status != http.StatusBadRequest || refusal.Code != "invalid_target" || + !identitybroker.IsConfigurationFault(err) { + t.Fatalf("IssueIDJAG for an unconfigured resource = %v, want a 400 invalid_target configuration fault", err) + } + var exchanges int + for _, r := range x.faults.Requests() { + if r.Kind != identityharness.KindIDJAG { + continue + } + exchanges++ + if r.Status != http.StatusBadRequest || r.IssuedToken != "" { + t.Fatalf("AS-1 answered the ID-JAG exchange with status %d, issuing a token: %v; want 400 and none", r.Status, r.IssuedToken != "") + } + } + if exchanges != 1 { + t.Fatalf("AS-1 answered %d ID-JAG exchanges, want 1", exchanges) + } +} + func TestIssueIDJAGSendsTheForm(t *testing.T) { var form url.Values server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/testutil/identityharness/harness.go b/internal/testutil/identityharness/harness.go index e3540f08e9..2b1788da7b 100644 --- a/internal/testutil/identityharness/harness.go +++ b/internal/testutil/identityharness/harness.go @@ -150,21 +150,36 @@ func ReadSigningKey(t testing.TB, file string) *ecdsa.PrivateKey { // ResignAccessToken returns token, a JWT signed with the key WriteSigningKey // wrote to keyFile, with its claims changed by edit and signed again with that -// key under the same header, so its issuer verifies it and judges it by the -// changed claims. +// key under the same header with alg ES256, so its issuer verifies it and +// judges it by the changed claims. func ResignAccessToken(t testing.TB, keyFile, token string, edit func(jwt.MapClaims)) string { t.Helper() - claims := jwt.MapClaims{} - parsed, _, err := jwt.NewParser().ParseUnverified(token, claims) + return ResignToken(t, ReadSigningKey(t, keyFile), token, edit, nil) +} + +// ResignToken returns token, a JWT, with its claims changed by claims and its +// JOSE header by header, either of which may be nil, signed again with key. +// The header keeps token's other parameters, such as kid and typ, but its alg +// is ES256, the key's, unless header changes it. +func ResignToken(t testing.TB, key *ecdsa.PrivateKey, token string, claims func(jwt.MapClaims), header func(map[string]any)) string { + t.Helper() + edited := jwt.MapClaims{} + parsed, _, err := jwt.NewParser().ParseUnverified(token, edited) if err != nil { - t.Fatalf("identityharness: parse access token: %v", err) + t.Fatalf("identityharness: parse token: %v", err) } - edit(claims) - resigned := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + if claims != nil { + claims(edited) + } + resigned := jwt.NewWithClaims(jwt.SigningMethodES256, edited) resigned.Header = maps.Clone(parsed.Header) - signed, err := resigned.SignedString(ReadSigningKey(t, keyFile)) + resigned.Header["alg"] = jwt.SigningMethodES256.Alg() + if header != nil { + header(resigned.Header) + } + signed, err := resigned.SignedString(key) if err != nil { - t.Fatalf("identityharness: sign access token: %v", err) + t.Fatalf("identityharness: sign token: %v", err) } return signed } diff --git a/internal/testutil/identityharness/idp.go b/internal/testutil/identityharness/idp.go index e01f937373..109fefb7c0 100644 --- a/internal/testutil/identityharness/idp.go +++ b/internal/testutil/identityharness/idp.go @@ -85,15 +85,6 @@ func (p *IdP) Issuer() string { return p.server.URL } // oid claim, as Entra ID does. It differs from subject. func OID(subject string) string { return "oid-" + subject } -// AddUser lets the IdP sign in subject. -func (p *IdP) AddUser(subject string) { - p.mu.Lock() - defer p.mu.Unlock() - if !slices.Contains(p.users, subject) { - p.users = append(p.users, subject) - } -} - // RegisterClient registers a confidential OIDC client that authenticates to // the token endpoint with client_secret_basic or client_secret_post. A test // running a real AS-1 registers it this way (Harness.RegisterAS1Upstream).