diff --git a/cmd/mecak8s/identity_broker_harness_test.go b/cmd/mecak8s/identity_broker_harness_test.go index dcb27cb5fa..dbf78886fe 100644 --- a/cmd/mecak8s/identity_broker_harness_test.go +++ b/cmd/mecak8s/identity_broker_harness_test.go @@ -298,7 +298,8 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) { 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", Target: "gateway", Tool: "search", + 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) } diff --git a/cmd/mecak8s/identity_broker_real_as1_test.go b/cmd/mecak8s/identity_broker_real_as1_test.go index 7b38c2f6e8..1c9d4715b1 100644 --- a/cmd/mecak8s/identity_broker_real_as1_test.go +++ b/cmd/mecak8s/identity_broker_real_as1_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "net/http" + "strings" "sync/atomic" "testing" "time" @@ -92,7 +93,8 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { 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", Target: "gateway", Tool: "search", + 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) } diff --git a/internal/identitybroker/attempts.go b/internal/identitybroker/attempts.go new file mode 100644 index 0000000000..027b89e5f2 --- /dev/null +++ b/internal/identitybroker/attempts.go @@ -0,0 +1,86 @@ +package identitybroker + +import "slices" + +// maxAttemptsPerSession bounds how many issued attempts a session's ledger +// keeps; the oldest is forgotten first, so a rejection report for it is +// refused. +const maxAttemptsPerSession = 1024 + +// callKey is what an attempt was issued for. A rejection report must repeat +// it exactly. +type callKey struct { + operationID, agent, method, server, tool, argumentsSHA256 string +} + +// attemptLedger remembers the attempts AuthorizeCall issued, so a caller can +// report one rejected token and get one retry: per session, the issued +// attempts in issue order, at most maxAttemptsPerSession of them. An attempt +// issued by a retry is never added, so a second rejection fails the call. Its +// methods are guarded by sessionTable.mu. +// +// Shortcut: retry state held in memory, forgetting a session's oldest attempt beyond 1024; removed by #2563 (durable state). +type attemptLedger struct { + bySession map[string]*sessionAttempts +} + +type sessionAttempts struct { + order []string // attempt IDs, oldest first + calls map[string]callKey +} + +func newAttemptLedger() *attemptLedger { + return &attemptLedger{bySession: map[string]*sessionAttempts{}} +} + +// issueLocked records attemptID as issued in sessionID for call. +func (m *attemptLedger) issueLocked(sessionID, attemptID string, call callKey) { + s, ok := m.bySession[sessionID] + if !ok { + s = &sessionAttempts{calls: map[string]callKey{}} + m.bySession[sessionID] = s + } + if _, ok := s.calls[attemptID]; ok { + return + } + if len(s.order) == maxAttemptsPerSession { + delete(s.calls, s.order[0]) + s.order = slices.Delete(s.order, 0, 1) + } + s.order = append(s.order, attemptID) + s.calls[attemptID] = call +} + +// knownLocked reports whether attemptID was issued in sessionID and not yet +// consumed. It does not compare the call: it runs before the credential +// identifies the agent, so consumeLocked checks the call. +func (m *attemptLedger) knownLocked(sessionID, attemptID string) bool { + s, ok := m.bySession[sessionID] + if !ok { + return false + } + _, ok = s.calls[attemptID] + return ok +} + +// consumeLocked deletes attemptID and reports whether it was issued in +// sessionID for call. A mismatched call deletes it too, so an attempt is +// reported at most once whatever the report says. +func (m *attemptLedger) consumeLocked(sessionID, attemptID string, call callKey) bool { + s, ok := m.bySession[sessionID] + if !ok { + return false + } + issued, ok := s.calls[attemptID] + if !ok { + return false + } + delete(s.calls, attemptID) + s.order = slices.DeleteFunc(s.order, func(id string) bool { return id == attemptID }) + return issued == call +} + +// dropLocked forgets every attempt of sessionID. +func (m *attemptLedger) dropLocked(sessionID string) { + delete(m.bySession, sessionID) +} diff --git a/internal/identitybroker/attempts_test.go b/internal/identitybroker/attempts_test.go new file mode 100644 index 0000000000..f0d91b9810 --- /dev/null +++ b/internal/identitybroker/attempts_test.go @@ -0,0 +1,90 @@ +package identitybroker + +import ( + "context" + "fmt" + "testing" +) + +var testCall = callKey{ + operationID: "op-1", agent: "spiffe://agents.example.com/mecatl/agent/shared/inst/" + incMain, + method: MethodToolsCall, server: "github", tool: "github.pull_request_read", + argumentsSHA256: "abababababababababababababababababababababababababababababababab", +} + +func TestMemoryAttemptsForgetTheOldestPastTheBound(t *testing.T) { + m := newAttemptLedger() + for i := range maxAttemptsPerSession + 1 { + m.issueLocked("bs_a", fmt.Sprintf("att_%d", i), testCall) + } + if m.knownLocked("bs_a", "att_0") { + t.Fatal("the oldest attempt is still known past the bound") + } + for _, id := range []string{"att_1", fmt.Sprintf("att_%d", maxAttemptsPerSession)} { + if !m.knownLocked("bs_a", id) { + t.Fatalf("attempt %s is not known", id) + } + } + if got := len(m.bySession["bs_a"].order); got != maxAttemptsPerSession { + t.Fatalf("the ledger keeps %d attempts, want %d", got, maxAttemptsPerSession) + } +} + +func TestMemoryAttemptsAreConsumedOnce(t *testing.T) { + m := newAttemptLedger() + m.issueLocked("bs_a", "att_1", testCall) + if !m.knownLocked("bs_a", "att_1") || !m.consumeLocked("bs_a", "att_1", testCall) { + t.Fatal("an issued attempt is not consumed") + } + if m.knownLocked("bs_a", "att_1") || m.consumeLocked("bs_a", "att_1", testCall) { + t.Fatal("a consumed attempt is consumed again") + } + if m.knownLocked("bs_a", "att_never") || m.consumeLocked("bs_a", "att_never", testCall) { + t.Fatal("an attempt never issued is consumed") + } +} + +func TestMemoryAttemptsMatchTheCall(t *testing.T) { + m := newAttemptLedger() + m.issueLocked("bs_a", "att_1", testCall) + if m.knownLocked("bs_b", "att_1") || m.consumeLocked("bs_b", "att_1", testCall) { + t.Fatal("another session consumed the attempt") + } + other := testCall + other.tool = "github.create_pull_request" + if m.consumeLocked("bs_a", "att_1", other) { + t.Fatal("a report for another call consumed the attempt") + } + // The mismatched report used the attempt up. + if m.consumeLocked("bs_a", "att_1", testCall) { + t.Fatal("the attempt is consumed after a mismatched report used it up") + } +} + +func TestAttemptsAreDroppedWhenTheSessionCloses(t *testing.T) { + b, err := New(testConfig(), nil, testKey(t, "attempts")) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + workload := Workload{Name: "system:serviceaccount:mecatl:mecak8s"} + owner := Owner{Issuer: "https://login.example.com", Subject: "alice-204"} + s, err := b.OpenSession(ctx, workload, OpenSessionRequest{HostSessionID: "hostS42", Incarnation: incMain, Owner: owner}) + if err != nil { + t.Fatal(err) + } + b.sessions.mu.Lock() + b.sessions.attempts.issueLocked(s.ID, "att_1", testCall) + b.sessions.mu.Unlock() + if err := b.CloseSession(ctx, workload, CloseSessionRequest{SessionID: s.ID, Reason: ReasonSessionClosed}); err != nil { + t.Fatal(err) + } + b.sessions.mu.Lock() + defer b.sessions.mu.Unlock() + if b.sessions.attempts.knownLocked(s.ID, "att_1") { + t.Fatal("a closed session's attempt is still known") + } + if _, ok := b.sessions.attempts.bySession[s.ID]; ok { + t.Fatal("a closed session's ledger is kept") + } +} diff --git a/internal/identitybroker/authorize.go b/internal/identitybroker/authorize.go new file mode 100644 index 0000000000..8b0152126c --- /dev/null +++ b/internal/identitybroker/authorize.go @@ -0,0 +1,97 @@ +package identitybroker + +import ( + "context" + "errors" + "time" +) + +// AuthorizeCall implements Core, in the order Service.AuthorizeCall +// documents. Every refusal after the session lookup is recorded. +func (b *Broker) AuthorizeCall(ctx context.Context, workload Workload, req AuthorizeCallRequest) (Authorization, error) { + if err := checkCall(workload, req); err != nil { + return Authorization{}, err + } + t := b.sessions + t.mu.Lock() + s, err := t.callSessionLocked(workload, req.SessionID) + if s == nil { + t.mu.Unlock() + return Authorization{}, err + } + rec := decisionRecord(t.now(), workload, s, req) + // The rejection report is checked before the grant, so a session without + // one still refuses a report it never issued. + if err == nil && req.RejectedAttemptID != "" && !t.attempts.knownLocked(s.ID, req.RejectedAttemptID) { + err = ReasonError(ReasonDenied, "the rejected attempt is unknown or already retried") + } + if err == nil { + _, err = grantForCallLocked(s) + } + t.mu.Unlock() + if err != nil { + return Authorization{}, b.refuse(ctx, rec, err) + } + + // Check 3: the credential identifies an agent registered to this open + // session. + agent, err := b.VerifyCredential(ctx, VerifyCredentialRequest{SessionID: s.ID, Credential: req.Credential}) + if err != nil { + return Authorization{}, b.refuse(ctx, rec, err) + } + rec.Agent, rec.AgentID = agent.Agent, agent.AgentID + + // Shortcut: step (6) checks 4 and 5 (run and owner) and 7 (ceiling) accept their inputs; removed by #2557 (checks 4 and 5) and the authority work (docs/drafts/agent-identity/README.md, "Order of work") for check 7. + + // Check 6: the gateway routes the server. + // Shortcut: check 6 matches the call's server, not the tool's route; removed by #2538 (gateway entries carry their routed tools, or the design moves the tool check to the vMCP). + if !b.gateway.routes(req.Server) { + return Authorization{}, b.refuse(ctx, rec, ReasonError(ReasonDenied, "no gateway routes the server")) + } + + // A call that passes every check is still refused: the next change adds + // design steps (7) and (8), the per-call ID-JAG exchange at AS-1 and its + // redemption at AS-2 for the gateway token. + return Authorization{}, b.refuse(ctx, rec, ReasonError(ReasonDenied, "call authorization is not available yet")) +} + +// grantForCallLocked returns the grant a call in s uses: the refresh token s +// holds. It fails with ReasonNoGrant when s holds none. It is the one place +// that decides which grant a call uses; scheduled runs (#2569) and the +// chained exchange change only this function. The caller holds t.mu. +func grantForCallLocked(s *brokerSession) (*heldGrant, error) { + if s.grant == nil { + return nil, ReasonError(ReasonNoGrant, "the broker session holds no refresh token") + } + return s.grant, nil +} + +// decisionRecord returns the record of a decision on req in s, before any +// outcome. Its owner is the session's verified owner, or the reported one +// when the session has none. The caller holds t.mu. +func decisionRecord(now time.Time, workload Workload, s *brokerSession, req AuthorizeCallRequest) DecisionRecord { + owner := s.Owner + if s.verifiedOwner != nil { + owner = *s.verifiedOwner + } + return DecisionRecord{ + At: now, SessionID: s.ID, Workload: workload, Owner: owner, + RunID: req.RunID, DelegationID: req.DelegationID, RunOwner: req.RunOwner, + OperationID: req.OperationID, RejectedAttemptID: req.RejectedAttemptID, + Method: req.Method, Server: req.Server, Tool: req.Tool, ArgumentsSHA256: req.ArgumentsSHA256, + } +} + +// refuse records err as the refusal of rec's call and returns err. The +// refusal is recorded even when ctx is cancelled, as a cancelled call is +// still a decision. +func (b *Broker) refuse(ctx context.Context, rec DecisionRecord, err error) error { + rec.Code = CodeInternal + var e *Error + if errors.As(err, &e) { + rec.Code, rec.Reason = e.Code, e.Reason + } + rec.Outcome = outcomeFor(rec.Code) + b.recordDecision(context.WithoutCancel(ctx), rec) + return err +} diff --git a/internal/identitybroker/authorize_checks_test.go b/internal/identitybroker/authorize_checks_test.go new file mode 100644 index 0000000000..9af3b6c9b7 --- /dev/null +++ b/internal/identitybroker/authorize_checks_test.go @@ -0,0 +1,281 @@ +package identitybroker_test + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/stacklok/mecatl/internal/identitybroker" +) + +// grantedFixture is a broker on a settable clock whose session holds a +// grant, with its main agent registered. +type grantedFixture struct { + b *identitybroker.Broker + s identitybroker.Session + cred identitybroker.Token + clock *time.Time +} + +// openGranted opens openHost with a token on a broker converting at a fake +// AS-1, and registers the session's main agent. +func openGranted(t *testing.T, opts ...identitybroker.Option) grantedFixture { + t.Helper() + as1 := &fakeAS1{answer: func(context.Context, int) (identitybroker.TokenExchangeResult, error) { + return grantResult("rt-fake-" + rand.Text()), nil + }} + clock := new(time.Time) + *clock = fixedNow() + opts = append([]identitybroker.Option{ + identitybroker.WithAuthServer(as1), + identitybroker.WithClock(func() time.Time { return *clock }), + }, opts...) + b := newBroker(t, opts...) + s, err := b.OpenSession(context.Background(), testWorkload, identitybroker.OpenSessionRequest{ + HostSessionID: openHost, Incarnation: openIncarnation, Owner: testOwner, AccessToken: unsignedToken(t, testOwner), + }) + if err != nil || !s.HoldsRefreshToken { + t.Fatalf("OpenSession = %+v, %v; want a session holding a grant", s, err) + } + reg, err := b.RegisterAgent(context.Background(), testWorkload, mainAgent(s)) + if err != nil { + t.Fatalf("RegisterAgent: %v", err) + } + return grantedFixture{b: b, s: s, cred: reg.Credential, clock: clock} +} + +func (f grantedFixture) authorize(req identitybroker.AuthorizeCallRequest) (identitybroker.Authorization, error) { + return f.b.AuthorizeCall(context.Background(), testWorkload, req) +} + +// wantDetail fails t unless err's detail contains want. +func wantDetail(t *testing.T, err error, want string) { + t.Helper() + var e *identitybroker.Error + if !errors.As(err, &e) || !strings.Contains(e.Detail, want) { + t.Fatalf("error = %v, want detail containing %q", err, want) + } +} + +func TestNewRefusesAnInvalidGateway(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + config := identitybroker.Config{TrustDomain: "agents.example.com", Audience: "https://broker.example.com", CredentialLifetime: 5 * time.Minute} + collaborators := []identitybroker.Option{identitybroker.WithRecorder(identitybroker.NewMemoryRecorder())} + for name, g := range map[string]identitybroker.Gateway{ + "no servers": {}, + "an empty server": {Servers: []string{""}}, + "a spaced server": {Servers: []string{"git hub"}}, + "a repeat": {Servers: []string{"github", "calendar", "github"}}, + } { + _, err := identitybroker.New(config, nil, key, append(collaborators, identitybroker.WithGateway(g))...) + if !errors.Is(err, identitybroker.ErrInvalidConfig) { + t.Errorf("New with %s = %v, want ErrInvalidConfig", name, err) + } + } + gateway := identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"github"}}) + for name, opts := range map[string][]identitybroker.Option{ + "no recorder": {gateway}, + "a nil recorder": {identitybroker.WithRecorder(nil), gateway}, + } { + _, err := identitybroker.New(config, nil, key, opts...) + if !errors.Is(err, identitybroker.ErrInvalidConfig) { + t.Errorf("New with a gateway and %s = %v, want ErrInvalidConfig", name, err) + } + } + _, err = identitybroker.New(config, nil, key, + identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), + gateway, identitybroker.WithGateway(identitybroker.Gateway{Servers: []string{"calendar"}})) + if !errors.Is(err, identitybroker.ErrInvalidConfig) { + t.Errorf("New with two gateways = %v, want ErrInvalidConfig", err) + } +} + +func TestNewCopiesTheGatewayServers(t *testing.T) { + servers := []string{"github"} + f := openGranted(t, withGateway(identitybroker.Gateway{Servers: servers})) + servers[0] = "calendar" + _, err := f.authorize(callRequest(f.s.ID, f.cred)) + if err == nil { + t.Fatal("AuthorizeCall allowed a call before call authorization exists") + } + var e *identitybroker.Error + if errors.As(err, &e) && strings.Contains(e.Detail, "no gateway routes") { + t.Fatalf("changing the caller's server list changed the broker's: %v", err) + } +} + +// withGateway configures g with a recorder, which a gateway requires; later +// options may replace it. +func withGateway(g identitybroker.Gateway) identitybroker.Option { + opts := []identitybroker.Option{ + identitybroker.WithRecorder(identitybroker.NewMemoryRecorder()), + identitybroker.WithGateway(g), + } + return func(b *identitybroker.Broker) { + for _, opt := range opts { + opt(b) + } + } +} + +func TestAuthorizeCallPassingEveryCheckIsDeniedForNow(t *testing.T) { + rec := identitybroker.NewMemoryRecorder() + f := openGranted(t, withGateway(identitybroker.Gateway{Servers: []string{"github"}}), identitybroker.WithRecorder(rec)) + got, err := f.authorize(callRequest(f.s.ID, f.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred) + wantDetail(t, err, "not available yet") + if !got.GatewayToken.IsZero() { + t.Fatal("a refused call returned a gateway token") + } + if d := rec.Decisions(); len(d) != 1 || d[0].Outcome != identitybroker.OutcomeDenied || d[0].AgentID == "" { + t.Fatalf("recorded %+v, want one denial with the verified agent", d) + } +} + +func TestAuthorizeCallRefusesAnInvalidCredential(t *testing.T) { + gateway := withGateway(identitybroker.Gateway{Servers: []string{"github"}}) + + t.Run("an expired credential", func(t *testing.T) { + f := openGranted(t, gateway) + *f.clock = f.clock.Add(6 * time.Minute) // past the 5-minute lifetime and the skew + got, err := f.authorize(callRequest(f.s.ID, f.cred)) + wantError(t, err, identitybroker.CodeUnauthenticated, identitybroker.ReasonSVIDExpired, f.cred) + if !got.GatewayToken.IsZero() { + t.Fatal("a refused call returned a gateway token") + } + }) + + t.Run("another broker's credential", func(t *testing.T) { + f := openGranted(t, gateway) + other := openGranted(t, gateway) + _, err := f.authorize(callRequest(f.s.ID, other.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, other.cred) + }) +} + +func TestAuthorizeCallWithoutAGatewayIsDenied(t *testing.T) { + f := openGranted(t) + got, err := f.authorize(callRequest(f.s.ID, f.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred) + wantDetail(t, err, "no gateway routes") + if !got.GatewayToken.IsZero() { + t.Fatal("a refused call returned a gateway token") + } +} + +func TestAuthorizeCallUnroutedServerIsDenied(t *testing.T) { + f := openGranted(t, withGateway(identitybroker.Gateway{Servers: []string{"calendar"}})) + _, err := f.authorize(callRequest(f.s.ID, f.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred) + wantDetail(t, err, "no gateway routes") + + // A routed server passes check 6. + req := callRequest(f.s.ID, f.cred) + req.Server = "calendar" + _, err = f.authorize(req) + var e *identitybroker.Error + if !errors.As(err, &e) || strings.Contains(e.Detail, "no gateway routes") { + t.Fatalf("a call to a routed server = %v, want past the server check", err) + } +} + +// failingRecorder refuses every record. +type failingRecorder struct{} + +func (failingRecorder) RecordIDJAG(context.Context, identitybroker.IDJAGRecord) error { + return errors.New("recorder unavailable") +} + +func (failingRecorder) RecordDecision(context.Context, identitybroker.DecisionRecord) error { + return errors.New("recorder unavailable") +} + +func TestAuthorizeCallRecordsRefusals(t *testing.T) { + rec := identitybroker.NewMemoryRecorder() + f := openGranted(t, withGateway(identitybroker.Gateway{Servers: []string{"calendar"}}), identitybroker.WithRecorder(rec)) + ctx := context.Background() + + // Neither an invalid request nor an unknown session is recorded. + invalid := callRequest(f.s.ID, f.cred) + invalid.Method = "" + _, err := f.authorize(invalid) + wantError(t, err, identitybroker.CodeInvalidArgument, "", f.cred) + _, err = f.authorize(callRequest("bs_unknown", f.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, "", f.cred) + if got := rec.Decisions(); len(got) != 0 { + t.Fatalf("recorded %d decisions for refusals before the session lookup, want none", len(got)) + } + + tokenless, err := f.b.OpenSession(ctx, testWorkload, identitybroker.OpenSessionRequest{ + HostSessionID: "hostS43", Incarnation: "inc_bbcdefghijklmnopqrstuvwxya", Owner: testOwner, + }) + if err != nil { + t.Fatalf("OpenSession: %v", err) + } + report := callRequest(f.s.ID, f.cred) + report.RejectedAttemptID = "att_unknown" + type step struct { + name string + session identitybroker.Session + req identitybroker.AuthorizeCallRequest + code identitybroker.Code + reason identitybroker.Reason + agent bool // whether check 3 passed + } + steps := []step{ + {"an unknown attempt", f.s, report, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, false}, + {"no grant", tokenless, callRequest(tokenless.ID, f.cred), identitybroker.CodeFailedPrecondition, identitybroker.ReasonNoGrant, false}, + {"an unrouted server", f.s, callRequest(f.s.ID, f.cred), identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, true}, + {"a closed session", f.s, callRequest(f.s.ID, f.cred), identitybroker.CodeFailedPrecondition, identitybroker.ReasonSessionClosed, false}, + } + for _, step := range steps { + if step.reason == identitybroker.ReasonSessionClosed { + if err := f.b.CloseSession(ctx, testWorkload, identitybroker.CloseSessionRequest{SessionID: step.session.ID, Reason: step.reason}); err != nil { + t.Fatalf("CloseSession: %v", err) + } + } + _, err := f.authorize(step.req) + wantError(t, err, step.code, step.reason, f.cred) + } + + got := rec.Decisions() + if len(got) != len(steps) { + t.Fatalf("recorded %d decisions, want %d", len(got), len(steps)) + } + for i, step := range steps { + d := got[i] + session := step.session + if d.Outcome != identitybroker.OutcomeDenied || d.Code != step.code || d.Reason != step.reason { + t.Errorf("%s: recorded %s %s %q, want denied %s %q", step.name, d.Outcome, d.Code, d.Reason, step.code, step.reason) + } + r := step.req + if !d.At.Equal(fixedNow()) || d.SessionID != session.ID || d.Workload != testWorkload || d.Owner != session.Owner || + d.RunID != r.RunID || d.RunOwner != r.RunOwner || d.DelegationID != r.DelegationID || d.OperationID != r.OperationID || + d.RejectedAttemptID != r.RejectedAttemptID || d.Method != r.Method || d.Server != r.Server || + d.Tool != r.Tool || d.ArgumentsSHA256 != r.ArgumentsSHA256 || d.AttemptID != "" { + t.Errorf("%s: recorded %+v, want the request's call fields", step.name, d) + } + if gotAgent := !d.Agent.IsZero() && strings.HasPrefix(d.AgentID, "ag_"); gotAgent != step.agent { + t.Errorf("%s: recorded agent %+v %q, want it set: %v", step.name, d.Agent, d.AgentID, step.agent) + } + if strings.Contains(fmt.Sprintf("%+v", d), f.cred.Value()) { + t.Errorf("%s: the record carries the credential", step.name) + } + } +} + +func TestAuthorizeCallReturnsRefusalWhenItsRecordFails(t *testing.T) { + f := openGranted(t, withGateway(identitybroker.Gateway{Servers: []string{"calendar"}}), identitybroker.WithRecorder(failingRecorder{})) + _, err := f.authorize(callRequest(f.s.ID, f.cred)) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred) + wantDetail(t, err, "no gateway routes") +} diff --git a/internal/identitybroker/boundary.go b/internal/identitybroker/boundary.go index 41c31bd06e..84dd82f56f 100644 --- a/internal/identitybroker/boundary.go +++ b/internal/identitybroker/boundary.go @@ -43,6 +43,13 @@ func (w Workload) Validate() error { // as for an unknown session ID (CodePermissionDenied, before any closing // reason), and FindSession reports none open. Opening its host session is // refused with CodePermissionDenied. +// - AuthorizeCall checks the workload, then the request, neither recorded; +// then the session, where an unknown session is not recorded and a +// closed one is; then a rejection report, the session's grant, the +// credential, and the server, in the order documented on Service; then it +// refuses the call, as no call is authorized yet. Every refusal after the +// session lookup is recorded with the configured Recorder, and is +// returned whether or not the record is accepted. type Core interface { OpenSession(ctx context.Context, workload Workload, req OpenSessionRequest) (Session, error) FindSession(ctx context.Context, workload Workload, req FindSessionRequest) (Session, bool, error) diff --git a/internal/identitybroker/broker.go b/internal/identitybroker/broker.go index d0541b27d1..1a378c36cc 100644 --- a/internal/identitybroker/broker.go +++ b/internal/identitybroker/broker.go @@ -21,7 +21,9 @@ // with at AS-1 and AS-2, with the broker client key, separate from the agent // issuer key; the token-endpoint client is an adapter. With WithAuthServer, // session open converts the user's access token at AS-1 through that adapter -// into a refresh token the session holds. The package performs no +// into a refresh token the session holds. With WithGateway, AuthorizeCall +// runs the checks before a grant on each MCP gateway call and records its +// decisions (Recorder); it authorizes no call yet. The package performs no // file, environment, or network access; source loading and transport belong // in adapters that call it. package identitybroker @@ -57,6 +59,15 @@ type Broker struct { // as1 converts access tokens at session open; nil when the broker only // pairs sessions. as1 AuthServer + // gateway is the gateway calls are authorized through; nil when none is + // configured, and every call is denied at the server check. There is at + // most one until #2538 (see WithGateway). + gateway *Gateway + // gateways counts WithGateway options, so New refuses a second. + gateways int + // recorder records AuthorizeCall's ID-JAGs and decisions; nil records + // nothing, and is set whenever gateway is. + recorder Recorder sessions *sessionTable } @@ -73,7 +84,8 @@ type Broker struct { // JWT-SVID permits. A raw *ecdsa.PrivateKey is copied; any other signer, such // as a KMS handle, is retained as supplied. // -// Options add optional collaborators, such as WithAuthServer. +// Options add optional collaborators, such as WithAuthServer, and are +// validated after they are applied. func New(config Config, definitions []DefinitionRecord, signer crypto.Signer, opts ...Option) (*Broker, error) { if err := config.validate(); err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidConfig, err) @@ -100,6 +112,9 @@ func New(config Config, definitions []DefinitionRecord, signer crypto.Signer, op for _, opt := range opts { opt(b) } + if err := b.configureGateway(); err != nil { + return nil, fmt.Errorf("%w: %v", ErrInvalidConfig, err) + } return b, nil } diff --git a/internal/identitybroker/conformance/conformance.go b/internal/identitybroker/conformance/conformance.go index abecec3c24..9d647ca75d 100644 --- a/internal/identitybroker/conformance/conformance.go +++ b/internal/identitybroker/conformance/conformance.go @@ -99,11 +99,15 @@ func registerRequest(s identitybroker.Session) identitybroker.RegisterAgentReque func authorizeRequest(sessionID string) identitybroker.AuthorizeCallRequest { return identitybroker.AuthorizeCallRequest{ - SessionID: sessionID, - Credential: identitybroker.NewToken("credential"), - OperationID: "op-1", - Target: "gateway", - Tool: "pull_request_read", + SessionID: sessionID, + Credential: identitybroker.NewToken("credential"), + OperationID: "op-1", + RunID: "R42", + RunOwner: alice, + Method: identitybroker.MethodToolsCall, + Server: "github", + Tool: "github.pull_request_read", + ArgumentsSHA256: strings.Repeat("ab", 32), } } diff --git a/internal/identitybroker/conformance/sessions.go b/internal/identitybroker/conformance/sessions.go index 2f388c20e2..d018adcec7 100644 --- a/internal/identitybroker/conformance/sessions.go +++ b/internal/identitybroker/conformance/sessions.go @@ -118,6 +118,33 @@ func runSessions(t *testing.T, factory serviceFactory) { wantError(t, "CloseSession of an unknown session", err, identitybroker.CodePermissionDenied, "") }) + t.Run("a session opened without a token has no grant", func(t *testing.T) { + svc := factory(t) + s := mustOpen(t, svc, openRequest("hostS42", alice)) + got, err := svc.AuthorizeCall(ctx, authorizeRequest(s.ID)) + wantError(t, "AuthorizeCall in a session without a grant", err, identitybroker.CodeFailedPrecondition, identitybroker.ReasonNoGrant) + if !got.GatewayToken.IsZero() { + t.Fatal("a refused AuthorizeCall returned a gateway token") + } + // A tools/list carries no tool and no arguments hash. + list := authorizeRequest(s.ID) + list.Method, list.Tool, list.ArgumentsSHA256 = identitybroker.MethodToolsList, "", "" + _, err = svc.AuthorizeCall(ctx, list) + wantError(t, "AuthorizeCall listing tools in a session without a grant", err, identitybroker.CodeFailedPrecondition, identitybroker.ReasonNoGrant) + }) + + t.Run("a rejection report for an attempt never issued is refused", func(t *testing.T) { + svc := factory(t) + s := mustOpen(t, svc, openRequest("hostS42", alice)) + req := authorizeRequest(s.ID) + req.RejectedAttemptID = "att_unknown" + _, err := svc.AuthorizeCall(ctx, req) + wantError(t, "AuthorizeCall reporting an attempt never issued", err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied) + mustClose(t, svc, s.ID) + _, err = svc.AuthorizeCall(ctx, req) + wantError(t, "AuthorizeCall reporting an attempt in a closed session", err, identitybroker.CodeFailedPrecondition, identitybroker.ReasonSessionClosed) + }) + t.Run("registration under another owner is refused", func(t *testing.T) { svc := factory(t) s := mustOpen(t, svc, openRequest("hostS42", alice)) @@ -259,8 +286,32 @@ func runInvalidRequests(t *testing.T, factory serviceFactory) { "no session": func(r *identitybroker.AuthorizeCallRequest) { r.SessionID = "" }, "no credential": func(r *identitybroker.AuthorizeCallRequest) { r.Credential = identitybroker.Token{} }, "no operation": func(r *identitybroker.AuthorizeCallRequest) { r.OperationID = "" }, - "no target": func(r *identitybroker.AuthorizeCallRequest) { r.Target = "" }, + "no server": func(r *identitybroker.AuthorizeCallRequest) { r.Server = "" }, "no tool": func(r *identitybroker.AuthorizeCallRequest) { r.Tool = "" }, + "no arguments hash": func(r *identitybroker.AuthorizeCallRequest) { + r.ArgumentsSHA256 = "" + }, + "a 63-character arguments hash": func(r *identitybroker.AuthorizeCallRequest) { + r.ArgumentsSHA256 = r.ArgumentsSHA256[:63] + }, + "an uppercase arguments hash": func(r *identitybroker.AuthorizeCallRequest) { + r.ArgumentsSHA256 = strings.ToUpper(r.ArgumentsSHA256) + }, + "a list naming a tool": func(r *identitybroker.AuthorizeCallRequest) { + r.Method, r.ArgumentsSHA256 = identitybroker.MethodToolsList, "" + }, + "a list carrying an arguments hash": func(r *identitybroker.AuthorizeCallRequest) { + r.Method, r.Tool = identitybroker.MethodToolsList, "" + }, + "no method": func(r *identitybroker.AuthorizeCallRequest) { r.Method = "" }, + "an unknown method": func(r *identitybroker.AuthorizeCallRequest) { r.Method = "resources/read" }, + "no run": func(r *identitybroker.AuthorizeCallRequest) { r.RunID = "" }, + "no run owner": func(r *identitybroker.AuthorizeCallRequest) { r.RunOwner = identitybroker.Owner{} }, + "a bad run owner": func(r *identitybroker.AuthorizeCallRequest) { r.RunOwner.Subject = "alice 204" }, + "a bad delegation": func(r *identitybroker.AuthorizeCallRequest) { r.DelegationID = "D 1" }, + "a bad rejected attempt": func(r *identitybroker.AuthorizeCallRequest) { + r.RejectedAttemptID = "att\x00" + }, } for name, mutate := range authorizes { req := authorizeRequest(s.ID) diff --git a/internal/identitybroker/errors.go b/internal/identitybroker/errors.go index 010d819a1d..1d437d7c03 100644 --- a/internal/identitybroker/errors.go +++ b/internal/identitybroker/errors.go @@ -59,12 +59,18 @@ const ( ReasonUpstreamRevoked Reason = "upstream_revoked" // ReasonOwnerActionRequired: the user must sign in again. ReasonOwnerActionRequired Reason = "owner_action_required" + // ReasonNoGrant: the broker session holds no refresh token, so no call + // can be authorized in it; open the session with an access token. + ReasonNoGrant Reason = "no_grant" + // ReasonConsentRequired: the gateway's authorization server needs the + // user's consent before it issues a token for the call. + ReasonConsentRequired Reason = "consent_required" ) // Code returns the code the design assigns to r. func (r Reason) Code() Code { switch r { - case ReasonSessionClosed, ReasonSignedOut, ReasonOwnerActionRequired: + case ReasonSessionClosed, ReasonSignedOut, ReasonOwnerActionRequired, ReasonNoGrant, ReasonConsentRequired: return CodeFailedPrecondition case ReasonSessionOwned, ReasonDenied, ReasonOwnerMismatch, ReasonUpstreamRevoked: return CodePermissionDenied diff --git a/internal/identitybroker/gateway.go b/internal/identitybroker/gateway.go new file mode 100644 index 0000000000..c8cee34884 --- /dev/null +++ b/internal/identitybroker/gateway.go @@ -0,0 +1,73 @@ +package identitybroker + +import ( + "errors" + "fmt" + "slices" +) + +// Gateway is the MCP gateway the broker authorizes calls through. +type Gateway struct { + // Servers are the backend names the gateway routes. A call naming any + // other server is denied. + Servers []string +} + +// WithGateway has AuthorizeCall authorize calls through g. Without it every +// call that reaches the server check is denied. New refuses a second +// WithGateway, a gateway with no servers, or with a server name that is not +// printable text without spaces or that appears twice, and a gateway without +// WithRecorder. +// +// Shortcut: one gateway, the embedded one; removed by #2538 (operator-declared gateway entries, each with its own AS-2). +func WithGateway(g Gateway) Option { + return func(b *Broker) { + // Each broker gets its own copy, so the caller's server list cannot + // change the broker's. + gc := g + gc.Servers = slices.Clone(g.Servers) + b.gateways++ + b.gateway = &gc + } +} + +// configureGateway validates the broker's gateway and the collaborators it +// requires. +func (b *Broker) configureGateway() error { + g := b.gateway + if g == nil { + return nil + } + if b.gateways > 1 { + return errors.New("only one gateway can be configured") + } + if err := g.validate(); err != nil { + return err + } + if b.recorder == nil { + return errors.New("a gateway requires a recorder") + } + return nil +} + +func (g *Gateway) validate() error { + if len(g.Servers) == 0 { + return errors.New("the gateway routes no servers") + } + seen := make(map[string]bool, len(g.Servers)) + for _, s := range g.Servers { + if !isToken(s) { + return fmt.Errorf("gateway server %q must be non-empty printable text without spaces", s) + } + if seen[s] { + return fmt.Errorf("gateway server %q is listed twice", s) + } + seen[s] = true + } + return nil +} + +// routes reports whether g routes server. A nil g routes nothing. +func (g *Gateway) routes(server string) bool { + return g != nil && slices.Contains(g.Servers, server) +} diff --git a/internal/identitybroker/recorder.go b/internal/identitybroker/recorder.go new file mode 100644 index 0000000000..b2afffa4b8 --- /dev/null +++ b/internal/identitybroker/recorder.go @@ -0,0 +1,161 @@ +package identitybroker + +import ( + "context" + "slices" + "sync" + "time" +) + +// Recorder keeps the broker's records of AuthorizeCall: each ID-JAG it +// obtains and each decision it makes. Records name credentials by reference, +// never by value. An implementation is safe for concurrent use. +type Recorder interface { + RecordIDJAG(ctx context.Context, rec IDJAGRecord) error + RecordDecision(ctx context.Context, rec DecisionRecord) error +} + +// CredentialRef names a credential by its issuer and ID (iss, jti), never by +// its value. +type CredentialRef struct { + Issuer string + ID string +} + +// DecisionOutcome is how an AuthorizeCall ended. +type DecisionOutcome string + +// Decision outcomes: success when the call is allowed, error for a +// CodeInternal or CodeUnavailable failure, and denied for any other refusal. +const ( + OutcomeSuccess DecisionOutcome = "success" + OutcomeDenied DecisionOutcome = "denied" + OutcomeError DecisionOutcome = "error" +) + +// outcomeFor returns the outcome of a refusal with code. +func outcomeFor(code Code) DecisionOutcome { + if code == CodeInternal || code == CodeUnavailable { + return OutcomeError + } + return OutcomeDenied +} + +// IDJAGRecord records an ID-JAG the broker obtained for a call. +type IDJAGRecord struct { + At time.Time + SessionID string + Agent AgentRef + AgentID string + RunID string + OperationID string + AttemptID string + IDJAG CredentialRef + ExpiresAt time.Time +} + +// DecisionRecord records one AuthorizeCall decision. +type DecisionRecord struct { + At time.Time + SessionID string + Workload Workload + // Owner is the broker session's verified owner, or the owner mecak8s + // reported when the session has none. + Owner Owner + // Agent and AgentID are zero when the credential did not verify. + Agent AgentRef + AgentID string + RunID string + DelegationID string + RunOwner Owner + OperationID string + AttemptID string + RejectedAttemptID string + Method string + Server string + Tool string + ArgumentsSHA256 string + Outcome DecisionOutcome + // Code and Reason are the refusal's; empty on success. + Code Code + Reason Reason + IDJAG CredentialRef + // GatewayToken names the gateway token. GatewayTokenUnreferenced reports + // an issued token that is not a JWT, so it has no (iss, jti) reference; + // it does not mean no token was issued. + GatewayToken CredentialRef + GatewayTokenUnreferenced bool +} + +// WithRecorder has AuthorizeCall record its decisions with r. Without it, or +// with nil, nothing is recorded. +func WithRecorder(r Recorder) Option { + return func(b *Broker) { b.recorder = r } +} + +// recordDecision records rec, if a recorder is configured. A refusal is +// returned whether or not its record is accepted, so the error is dropped. +func (b *Broker) recordDecision(ctx context.Context, rec DecisionRecord) { + if b.recorder == nil { + return + } + // Shortcut: a refusal whose record is not accepted is not reported anywhere else; removed by #2541 (the record sink reports delivery failures on a separate channel). + _ = b.recorder.RecordDecision(ctx, rec) +} + +// maxMemoryRecords bounds each of MemoryRecorder's record lists. +const maxMemoryRecords = 10000 + +// MemoryRecorder is a Recorder holding the most recent records in memory, up +// to maxMemoryRecords of each kind, dropping the oldest. Its methods are safe +// for concurrent use. +// +// Shortcut: records held in memory, dropping the oldest beyond 10,000 of each kind; removed by #2541 (record sink) and #2563 (durable state). +type MemoryRecorder struct { + mu sync.Mutex + idjags []IDJAGRecord + decisions []DecisionRecord +} + +// NewMemoryRecorder returns an empty MemoryRecorder. +func NewMemoryRecorder() *MemoryRecorder { return &MemoryRecorder{} } + +// RecordIDJAG implements Recorder. +func (r *MemoryRecorder) RecordIDJAG(_ context.Context, rec IDJAGRecord) error { + r.mu.Lock() + defer r.mu.Unlock() + r.idjags = appendBounded(r.idjags, rec) + return nil +} + +// RecordDecision implements Recorder. +func (r *MemoryRecorder) RecordDecision(_ context.Context, rec DecisionRecord) error { + r.mu.Lock() + defer r.mu.Unlock() + r.decisions = appendBounded(r.decisions, rec) + return nil +} + +// IDJAGs returns a copy of the ID-JAG records, oldest first. +func (r *MemoryRecorder) IDJAGs() []IDJAGRecord { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.idjags) +} + +// Decisions returns a copy of the decision records, oldest first. +func (r *MemoryRecorder) Decisions() []DecisionRecord { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.decisions) +} + +// appendBounded appends rec to list, dropping the oldest records past +// maxMemoryRecords. +func appendBounded[T any](list []T, rec T) []T { + list = append(list, rec) + if len(list) > maxMemoryRecords { + list = list[len(list)-maxMemoryRecords:] + } + return list +} diff --git a/internal/identitybroker/recorder_test.go b/internal/identitybroker/recorder_test.go new file mode 100644 index 0000000000..91d6d13dff --- /dev/null +++ b/internal/identitybroker/recorder_test.go @@ -0,0 +1,46 @@ +package identitybroker + +import ( + "context" + "fmt" + "testing" +) + +func TestMemoryRecorderBoundsAndCopies(t *testing.T) { + ctx := context.Background() + r := NewMemoryRecorder() + for i := range maxMemoryRecords + 1 { + id := fmt.Sprintf("op-%d", i) + if err := r.RecordDecision(ctx, DecisionRecord{OperationID: id}); err != nil { + t.Fatal(err) + } + if err := r.RecordIDJAG(ctx, IDJAGRecord{OperationID: id}); err != nil { + t.Fatal(err) + } + } + decisions, idjags := r.Decisions(), r.IDJAGs() + if len(decisions) != maxMemoryRecords || len(idjags) != maxMemoryRecords { + t.Fatalf("recorder holds %d decisions and %d ID-JAGs, want %d of each", len(decisions), len(idjags), maxMemoryRecords) + } + last := fmt.Sprintf("op-%d", maxMemoryRecords) + if decisions[0].OperationID != "op-1" || decisions[len(decisions)-1].OperationID != last || + idjags[0].OperationID != "op-1" || idjags[len(idjags)-1].OperationID != last { + t.Fatal("the recorder did not drop the oldest record first") + } + decisions[0].OperationID, idjags[0].OperationID = "changed", "changed" + if r.Decisions()[0].OperationID != "op-1" || r.IDJAGs()[0].OperationID != "op-1" { + t.Fatal("changing a returned record changed the recorder's") + } +} + +func TestDecisionOutcomes(t *testing.T) { + want := map[Code]DecisionOutcome{ + CodeInternal: OutcomeError, CodeUnavailable: OutcomeError, + CodePermissionDenied: OutcomeDenied, CodeFailedPrecondition: OutcomeDenied, CodeUnauthenticated: OutcomeDenied, + } + for code, outcome := range want { + if got := outcomeFor(code); got != outcome { + t.Errorf("outcomeFor(%s) = %s, want %s", code, got, outcome) + } + } +} diff --git a/internal/identitybroker/serverrefusal.go b/internal/identitybroker/serverrefusal.go index dba83f66e9..7ad7a612c9 100644 --- a/internal/identitybroker/serverrefusal.go +++ b/internal/identitybroker/serverrefusal.go @@ -30,11 +30,11 @@ var knownErrorCodes = map[string]bool{ // subject_token_invalid, subject_token_audience, subject_token_source_client, // subject_token_offline_access, and grant_invalid for the tokens a request // presents; subject_invalid, -// owner_mismatch, session_owned, session_closed, and schedule_ended are the -// broker's own, kept so a server sending one is not taken for a +// owner_mismatch, session_owned, session_closed, schedule_ended, and no_grant +// are the broker's own, kept so a server sending one is not taken for a // configuration fault. var knownReasons = map[string]bool{ - "subject_invalid": true, "token_used": true, "owner_mismatch": true, + "subject_invalid": true, "token_used": true, "owner_mismatch": true, "no_grant": true, "session_owned": true, "session_closed": true, "signed_out": true, "upstream_revoked": true, "schedule_ended": true, "owner_action_required": true, "revoked": true, "parent_revoked": true, "not_issuable": true, diff --git a/internal/identitybroker/service.go b/internal/identitybroker/service.go index dedb335c5a..6df0976d7d 100644 --- a/internal/identitybroker/service.go +++ b/internal/identitybroker/service.go @@ -99,6 +99,21 @@ type Service interface { // AuthorizeCall decides whether the agent presenting the credential may // make an MCP call, and returns the gateway token when it may. A denial is // an error, so a caller that ignores the result cannot dispatch. + // + // The checks run in order, each failing as shown: + // - an invalid request: CodeInvalidArgument; + // - an unknown session: as for any call; + // - a closed session: its closing reason; + // - a rejection report for an attempt never issued, or already + // reported: CodePermissionDenied, ReasonDenied; + // - a session that holds no refresh token: CodeFailedPrecondition, + // ReasonNoGrant; + // - a credential that does not verify for the session: as + // VerifyCredential refuses it; + // - a server no gateway routes: CodePermissionDenied, ReasonDenied. + // + // A call that passes every check is refused with CodePermissionDenied, + // ReasonDenied, until the broker obtains a gateway token for each call. AuthorizeCall(ctx context.Context, req AuthorizeCallRequest) (Authorization, error) } @@ -316,6 +331,12 @@ type VerifiedAgent struct { ExpiresAt time.Time } +// The MCP methods AuthorizeCallRequest.Method names. +const ( + MethodToolsCall = "tools/call" + MethodToolsList = "tools/list" +) + // AuthorizeCallRequest asks whether an agent may make one MCP call. type AuthorizeCallRequest struct { SessionID string @@ -324,31 +345,89 @@ type AuthorizeCallRequest struct { Credential Token // OperationID identifies this call. OperationID string - // Target is the gateway or backend the call is routed to. - Target string - Tool string - // GatewayRejectedToken reports that the gateway rejected the token - // returned for this operation, so the broker obtains a fresh one. A caller - // sets it on at most one retry. - GatewayRejectedToken bool + // RunID is the run the call belongs to. + RunID string + // DelegationID is the delegation the run acts under; empty for a root + // run. + DelegationID string + // RunOwner is the owner the run acts for. + RunOwner Owner + // Method is MethodToolsCall or MethodToolsList. + Method string + // Server is the gateway backend the call is routed to, such as "github". + Server string + // Tool is the exact tool name the call sends as params.name, such as + // "github.pull_request_read". Set for tools/call only. + Tool string + // ArgumentsSHA256 is the SHA-256 of the call's arguments, 64 lowercase + // hex characters. Set for tools/call only. + ArgumentsSHA256 string + // RejectedAttemptID, when set, reports that the gateway rejected the token + // of that attempt, so the broker obtains a fresh one. A caller reports an + // attempt at most once, with the attempt's own call fields. + RejectedAttemptID string } // Validate reports whether r is well formed. The error is an *Error with // CodeInvalidArgument. func (r AuthorizeCallRequest) Validate() error { - if err := requireIDs("broker session", r.SessionID, "operation", r.OperationID, "target", r.Target, "tool", r.Tool); err != nil { + if err := requireIDs("broker session", r.SessionID, "operation", r.OperationID, "run", r.RunID, "server", r.Server); err != nil { return err } if r.Credential.IsZero() { return invalid("credential is required") } + if err := r.RunOwner.validate(); err != nil { + return err + } + if r.DelegationID != "" && !isToken(r.DelegationID) { + return invalid("delegation ID must be printable text without spaces") + } + if r.RejectedAttemptID != "" && !isToken(r.RejectedAttemptID) { + return invalid("rejected attempt ID must be printable text without spaces") + } + switch r.Method { + case MethodToolsCall: + if !isToken(r.Tool) { + return invalid("a tools/call must name its tool in printable text without spaces") + } + if !isSHA256Hex(r.ArgumentsSHA256) { + return invalid("a tools/call must carry its arguments' SHA-256 as 64 lowercase hex characters") + } + case MethodToolsList: + if r.Tool != "" || r.ArgumentsSHA256 != "" { + return invalid("a tools/list carries no tool and no arguments hash") + } + default: + return invalid(fmt.Sprintf("method %q is not supported", r.Method)) + } return nil } +// isSHA256Hex reports whether s is 64 lowercase hex characters. +func isSHA256Hex(s string) bool { + if len(s) != 64 { + return false + } + for _, c := range []byte(s) { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + // Authorization is an allowed MCP call. type Authorization struct { - // GatewayToken is the token the call is dispatched with. + // GatewayToken is the token the call is dispatched with, obtained for + // this call alone. GatewayToken Token + // ExpiresAt is when GatewayToken expires; never later than the ID-JAG it + // was redeemed from. + ExpiresAt time.Time + // AttemptID identifies this authorization, so a caller whose token the + // gateway rejects reports it in AuthorizeCallRequest.RejectedAttemptID. + AttemptID string } // requireIDs checks name/value pairs of identifiers. diff --git a/internal/identitybroker/service_test.go b/internal/identitybroker/service_test.go index 0b64a82d6a..617179fd59 100644 --- a/internal/identitybroker/service_test.go +++ b/internal/identitybroker/service_test.go @@ -17,7 +17,7 @@ func TestTokenNeverFormatsItsValue(t *testing.T) { } req := AuthorizeCallRequest{SessionID: "A42", Credential: tok} for _, verb := range []string{"%v", "%+v", "%#v", "%s", "%q", "%x", "%d"} { - for _, operand := range []any{tok, req, &req} { + for _, operand := range []any{tok, req, &req, Authorization{GatewayToken: tok}} { if got := fmt.Sprintf(verb, operand); strings.Contains(got, secret) || strings.Contains(got, fmt.Sprintf("%x", secret)) { t.Errorf("Sprintf(%s, %T) = %q leaks the credential", verb, operand, got) } @@ -61,6 +61,8 @@ func TestReasonsCarryTheDesignCodes(t *testing.T) { ReasonSignedOut: CodeFailedPrecondition, ReasonUpstreamRevoked: CodePermissionDenied, ReasonOwnerActionRequired: CodeFailedPrecondition, + ReasonNoGrant: CodeFailedPrecondition, + ReasonConsentRequired: CodeFailedPrecondition, Reason("unknown"): CodeInternal, } for reason, code := range want { diff --git a/internal/identitybroker/sessionopen_test.go b/internal/identitybroker/sessionopen_test.go index 1c8956efd1..a4a318e7ff 100644 --- a/internal/identitybroker/sessionopen_test.go +++ b/internal/identitybroker/sessionopen_test.go @@ -559,9 +559,7 @@ func TestSessionHardExpiryClosesTheSession(t *testing.T) { wantError(t, err, identitybroker.CodeFailedPrecondition, identitybroker.ReasonSessionClosed) }}, {"AuthorizeCall", false, func(t *testing.T, f *openFixture, old identitybroker.Session, cred identitybroker.Token) { - _, err := f.b.AuthorizeCall(ctx, testWorkload, identitybroker.AuthorizeCallRequest{ - SessionID: old.ID, Credential: cred, OperationID: "op-1", Target: "gateway", Tool: "search", - }) + _, err := f.b.AuthorizeCall(ctx, testWorkload, callRequest(old.ID, cred)) wantError(t, err, identitybroker.CodeFailedPrecondition, identitybroker.ReasonSessionClosed, cred) }}, {"VerifyCredential", false, func(t *testing.T, f *openFixture, old identitybroker.Session, cred identitybroker.Token) { diff --git a/internal/identitybroker/sessions.go b/internal/identitybroker/sessions.go index 5351d57aa8..7d67ec2c46 100644 --- a/internal/identitybroker/sessions.go +++ b/internal/identitybroker/sessions.go @@ -32,7 +32,10 @@ type sessionTable struct { // for any session, with the token's exp; entries are dropped once exp // plus convertedClockSkew has passed. converted map[string]time.Time - now func() time.Time + // attempts holds the attempts AuthorizeCall issued, per session, until + // the session closes. + attempts *attemptLedger + now func() time.Time hostMu sync.Mutex hostLocks map[string]*hostLock // root host session ID -> its open lock @@ -64,7 +67,7 @@ type brokerSession struct { func newSessionTable() *sessionTable { return &sessionTable{ open: map[string]string{}, byID: map[string]*brokerSession{}, agents: map[string]*agentRecord{}, - converted: map[string]time.Time{}, hostLocks: map[string]*hostLock{}, now: time.Now, + converted: map[string]time.Time{}, attempts: newAttemptLedger(), hostLocks: map[string]*hostLock{}, now: time.Now, } } @@ -146,7 +149,7 @@ func (t *sessionTable) viewLocked(s *brokerSession) Session { } // closeLocked closes s with reason, unless it is already closed, and -// discards its refresh token. The caller holds t.mu. +// discards its refresh token and issued attempts. The caller holds t.mu. func (t *sessionTable) closeLocked(s *brokerSession, reason Reason) { if s.closed != "" { return @@ -154,6 +157,7 @@ func (t *sessionTable) closeLocked(s *brokerSession, reason Reason) { s.closed = reason s.closedAt = t.now() s.grant = nil + t.attempts.dropLocked(s.ID) delete(t.open, s.HostSessionID) } @@ -219,38 +223,38 @@ func (b *Broker) CloseSession(_ context.Context, workload Workload, req CloseSes return nil } -// AuthorizeCall implements Core. It applies the session checks, then denies -// every call: no call is authorized until per-call grants exist. -func (b *Broker) AuthorizeCall(_ context.Context, workload Workload, req AuthorizeCallRequest) (Authorization, error) { - if err := checkCall(workload, req); err != nil { - return Authorization{}, err - } - if _, err := b.usableSession(workload, req.SessionID); err != nil { - return Authorization{}, err +// usableLocked returns the open session for id, or the error for a session +// that does not exist or belongs to another workload (the same error, so the +// two cannot be told apart), or is closed. The caller holds t.mu. +func (t *sessionTable) usableLocked(workload Workload, id string) (Session, error) { + s, err := t.callSessionLocked(workload, id) + if err != nil { + return Session{}, err } - return Authorization{}, ReasonError(ReasonDenied, "call authorization is not available yet") + return s.Session, nil } -// usableSession returns the open session for id, or the error for a session -// that does not exist or belongs to another workload (the same error, so the -// two cannot be told apart), or is closed. -func (b *Broker) usableSession(workload Workload, id string) (Session, error) { - t := b.sessions - t.mu.Lock() - defer t.mu.Unlock() - return t.usableLocked(workload, id) +// callSessionLocked returns workload's session id and nil while it is open. +// It returns the session record with its closing reason as the error when +// the session is closed, so the refusal can be recorded against it, and nil +// with the unknown-session error when no session id exists for workload. The +// caller holds t.mu. +func (t *sessionTable) callSessionLocked(workload Workload, id string) (*brokerSession, error) { + s, ok := t.byID[id] + if !ok || s.workload != workload { + return nil, unknownSession() + } + return s, t.closedLocked(s) } -// usableLocked is usableSession for a caller holding t.mu. -func (t *sessionTable) usableLocked(workload Workload, id string) (Session, error) { - s, ok := t.byID[id] - switch { - case !ok || s.workload != workload: - return Session{}, unknownSession() - case t.expireLocked(s): - return Session{}, ReasonError(s.closed, "the broker session is closed") +// closedLocked returns s's closing reason as an error if s is closed, first +// closing s if it has reached its hard expiry (see expireLocked). The caller +// holds t.mu. +func (t *sessionTable) closedLocked(s *brokerSession) error { + if t.expireLocked(s) { + return ReasonError(s.closed, "the broker session is closed") } - return s.Session, nil + return nil } // newSessionID returns a random broker session ID in the same lowercase diff --git a/internal/identitybroker/sessions_test.go b/internal/identitybroker/sessions_test.go index 06dfd53c6f..3bb0644c1c 100644 --- a/internal/identitybroker/sessions_test.go +++ b/internal/identitybroker/sessions_test.go @@ -6,6 +6,7 @@ import ( "crypto/elliptic" "crypto/rand" "errors" + "strings" "testing" "time" @@ -94,20 +95,24 @@ func TestBrokerAgentIDIsRandomPerProcess(t *testing.T) { } } -func TestBrokerAuthorizeCallDeniesEveryCall(t *testing.T) { +func TestBrokerAuthorizeCallWithoutAGrantIsNoGrant(t *testing.T) { b := newBroker(t) s := openSession(t, b) - got, err := b.AuthorizeCall(context.Background(), testWorkload, identitybroker.AuthorizeCallRequest{ - SessionID: s.ID, - Credential: identitybroker.NewToken("credential"), - OperationID: "op-1", - Target: "gateway", - Tool: "pull_request_read", - }) - if !errors.Is(err, identitybroker.ReasonError(identitybroker.ReasonDenied, "")) { - t.Fatalf("AuthorizeCall error = %v, want PERMISSION_DENIED denied", err) + got, err := b.AuthorizeCall(context.Background(), testWorkload, callRequest(s.ID, identitybroker.NewToken("credential"))) + if !errors.Is(err, identitybroker.ReasonError(identitybroker.ReasonNoGrant, "")) { + t.Fatalf("AuthorizeCall error = %v, want FAILED_PRECONDITION no_grant", err) } if !got.GatewayToken.IsZero() { - t.Fatal("a denied AuthorizeCall returned a gateway token") + t.Fatal("a refused AuthorizeCall returned a gateway token") + } +} + +// callRequest is a well-formed tools/call request in session id with +// credential. +func callRequest(id string, credential identitybroker.Token) identitybroker.AuthorizeCallRequest { + return identitybroker.AuthorizeCallRequest{ + SessionID: id, Credential: credential, OperationID: "op-1", RunID: "R42", RunOwner: testOwner, + Method: identitybroker.MethodToolsCall, Server: "github", Tool: "github.pull_request_read", + ArgumentsSHA256: strings.Repeat("ab", 32), } }