From 2e76a010079cd6d9a5e1a24c39efa5bf552e0c26 Mon Sep 17 00:00:00 2001 From: Juan Antonio Osorio Date: Mon, 27 Jul 2026 21:40:59 +0300 Subject: [PATCH 1/2] Capture RFC 8693 act claim in audit logs (#6035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add first-class support for the RFC 8693 actor claim in ToolHive's audit pipeline so delegated requests record the full chain of acting parties, not just the terminal subject. - Introduce auth.DelegationChain and auth.ParseDelegationChain to parse nested act claims with a bounded depth (default 10, aligned with the token-exchange issuance cap) and explicit truncation reporting (dropped_count). - Promote the parsed chain into auth.Identity / auth.PrincipalInfo during claimsToIdentity so downstream consumers see it as a structured field rather than an opaque JWT claim. - Extend audit.AuditEvent with a delegationChain member and teach both the HTTP Auditor and WorkflowAuditor to populate it from the request identity, respecting the configured maxDelegationDepth. - Cover issuance → validation → audit extraction with unit tests, middleware-level tests (including SSE stream opens), and an end-to-end integration test that mints a delegated token via the real token-exchange handler and asserts the audit event. - Document the new audit field and maxDelegationDepth config knob; regenerate operator CRD/swagger docs. Closes #6035 --- docs/arch/02-core-concepts.md | 2 + docs/middleware.md | 18 +++ docs/server/docs.go | 4 + docs/server/swagger.json | 4 + docs/server/swagger.yaml | 8 ++ pkg/audit/auditor.go | 94 ++++++++++-- pkg/audit/auditor_test.go | 188 ++++++++++++++++++++++++ pkg/audit/config.go | 18 +++ pkg/audit/event.go | 17 +++ pkg/audit/workflow_auditor.go | 20 +++ pkg/audit/workflow_auditor_test.go | 121 ++++++++++++++++ pkg/audit/zz_generated.deepcopy.go | 5 + pkg/auth/context.go | 10 ++ pkg/auth/context_test.go | 50 +++++++ pkg/auth/delegation.go | 103 +++++++++++++ pkg/auth/delegation_test.go | 223 +++++++++++++++++++++++++++++ pkg/auth/identity.go | 7 + pkg/auth/identity_test.go | 56 ++++++++ pkg/authserver/integration_test.go | 188 ++++++++++++++++++++++++ 19 files changed, 1125 insertions(+), 11 deletions(-) create mode 100644 pkg/auth/delegation.go create mode 100644 pkg/auth/delegation_test.go diff --git a/docs/arch/02-core-concepts.md b/docs/arch/02-core-concepts.md index bfc7eb45bb..8ec9677ddc 100644 --- a/docs/arch/02-core-concepts.md +++ b/docs/arch/02-core-concepts.md @@ -659,6 +659,8 @@ See `pkg/audit/mcp_events.go` for complete list of event types. **Event data:** - Timestamp, source, outcome - Subjects (user, session) +- Delegation chain (`delegationChain`) — RFC 8693 `act` claim actors, outermost + first, when the caller used a delegated token - Target (endpoint, method, resource) - Request/response data (configurable) - Duration and metadata diff --git a/docs/middleware.md b/docs/middleware.md index 619b816ef8..573bc7808b 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -481,6 +481,13 @@ Audit events are logged as structured JSON objects: "client_name": "my-mcp-client", "client_version": "1.0.0" }, + "delegation_chain": { + "actors": [ + {"sub": "agent-client-1", "act_claims": {"iss": "https://auth.example.com"}}, + {"sub": "agent-client-2"} + ], + "truncated": false + }, "target": { "endpoint": "/messages", "method": "POST", @@ -517,6 +524,17 @@ Audit events are logged as structured JSON objects: - `user`: User display name (from `name` claim, `preferred_username`, or `email`) - `client_name`: MCP client name (from JWT claims) - `client_version`: MCP client version (from JWT claims) +- `delegation_chain`: RFC 8693 delegation chain, present only when the caller + authenticated with a delegated token (i.e. the JWT carries an `act` claim) + - `actors`: Acting parties, outermost (most recent) first — `actors[0]` is + the direct delegate that presented the token + - `sub`: Acting party identifier (from the `act` claim's `sub` member) + - `act_claims`: Additional `act` claim members (e.g. `iss`), when present + - `truncated`: `true` when the chain exceeded the configured maximum depth + (`maxDelegationDepth` in the audit config, default 10) and trailing + actors were dropped + - `dropped_count`: Number of actors dropped due to the depth cap, present + only when `truncated` is `true` - `target`: Information about the operation target - `endpoint`: HTTP endpoint path - `method`: HTTP method diff --git a/docs/server/docs.go b/docs/server/docs.go index 4664d2d337..f1a127a2b1 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -218,6 +218,10 @@ const docTemplate = `{ "maxDataSize": { "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", "type": "integer" + }, + "maxDelegationDepth": { + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegationChain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:default=10\n+optional", + "type": "integer" } }, "type": "object" diff --git a/docs/server/swagger.json b/docs/server/swagger.json index 3f423b83f8..b16b3af016 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -211,6 +211,10 @@ "maxDataSize": { "description": "MaxDataSize limits the size of request/response data included in audit logs (in bytes).\n+kubebuilder:default=1024\n+optional", "type": "integer" + }, + "maxDelegationDepth": { + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegationChain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:default=10\n+optional", + "type": "integer" } }, "type": "object" diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index e44af9d64d..35b73f19c2 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -222,6 +222,14 @@ components: +kubebuilder:default=1024 +optional type: integer + maxDelegationDepth: + description: |- + MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + recorded in an audit event's delegationChain. Deeper chains are + truncated (marked with truncated=true). Defaults to 10 when unset. + +kubebuilder:default=10 + +optional + type: integer type: object github_com_stacklok_toolhive_pkg_auth_awssts.Config: description: AWSStsConfig contains AWS STS token exchange configuration for diff --git a/pkg/audit/auditor.go b/pkg/audit/auditor.go index 42bffb53f8..f321edc988 100644 --- a/pkg/audit/auditor.go +++ b/pkg/audit/auditor.go @@ -113,6 +113,18 @@ func (a *Auditor) Close() error { return nil } +// SetLogWriterForTest redirects the auditor's log output to w. It is intended +// for tests in other packages (e.g. integration tests) that need to capture +// emitted audit events without reimplementing the auditor. +// +// Deprecated: this is test-only surface on a production type. A future +// NewAuditorWithWriter constructor accepting an explicit io.Writer should +// replace it; keep usage confined to tests. +func (a *Auditor) SetLogWriterForTest(w io.Writer) { + a.auditLogger = NewAuditLogger(w) + a.logWriter = w +} + // isSSETransport checks if the current transport is SSE func (a *Auditor) isSSETransport() bool { return a.transportType == types.TransportTypeSSE.String() @@ -321,6 +333,9 @@ func (a *Auditor) logAuditEvent(r *http.Request, rw *responseWriter, requestData // Create the audit event event := NewAuditEvent(eventType, source, outcome, subjects, component) + // Attach the RFC 8693 delegation chain, if the caller used a delegated token + event.WithDelegationChain(a.extractDelegationChain(r)) + // Add target information target := a.extractTarget(r, eventType) if len(target) > 0 { @@ -542,21 +557,65 @@ func extractSubjectsFromIdentity(identity *auth.Identity) map[string]string { return subjects } +// extractDelegationChainFromIdentity returns the RFC 8693 delegation chain +// carried by the identity, re-bounded to maxDepth, or nil when the identity +// has no chain. An already-parsed chain is re-bounded by applying maxDepth to +// its actor list directly; an identity carrying only the raw "act" claim is +// parsed once via auth.ParseDelegationChain. In both cases the configured cap +// is enforced — there is no uncapped "honor as-is" fallback. +func extractDelegationChainFromIdentity(identity *auth.Identity, maxDepth int) *auth.DelegationChain { + if identity == nil { + return nil + } + if chain := identity.DelegationChain; chain != nil && len(chain.Actors) > 0 { + return rebindDelegationChain(chain, maxDepth) + } + if act, ok := identity.Claims["act"]; ok && act != nil { + chain := auth.ParseDelegationChain(act, maxDepth) + if len(chain.Actors) > 0 { + return &chain + } + } + return nil +} + +// rebindDelegationChain applies maxDepth to an already-parsed chain: actors +// beyond the cap are dropped, the chain is marked truncated, and the dropped +// count accounts for both actors truncated at parse time and actors dropped +// by this re-binding. +func rebindDelegationChain(chain *auth.DelegationChain, maxDepth int) *auth.DelegationChain { + if maxDepth <= 0 { + maxDepth = auth.DefaultMaxDelegationDepth + } + bound := *chain + if len(bound.Actors) > maxDepth { + bound.DroppedCount += len(bound.Actors) - maxDepth + bound.Actors = bound.Actors[:maxDepth] + bound.Truncated = true + } + return &bound +} + +// identityFromRequest resolves the authenticated identity for the request. +// The context value is present when an auth middleware runs OUTSIDE audit; +// the holder covers the audit-wraps-auth arrangement, where the identity +// attached for inner handlers is published back up via auth.WithIdentity. +func identityFromRequest(r *http.Request) (*auth.Identity, bool) { + if identity, ok := auth.IdentityFromContext(r.Context()); ok { + return identity, true + } + if holder, hok := auth.IdentityHolderFromContext(r.Context()); hok && holder.Identity != nil { + return holder.Identity, true + } + return nil, false +} + // extractSubjects extracts subject information from the HTTP request. func (*Auditor) extractSubjects(r *http.Request) map[string]string { subjects := make(map[string]string) - // Extract user information from Identity. The context value is present - // when an auth middleware runs OUTSIDE audit; the holder covers the - // audit-wraps-auth arrangement, where the identity attached for inner - // handlers is published back up via auth.WithIdentity. - identity, ok := auth.IdentityFromContext(r.Context()) - if !ok { - if holder, hok := auth.IdentityHolderFromContext(r.Context()); hok && holder.Identity != nil { - identity, ok = holder.Identity, true - } - } - if ok { + // Extract user information from Identity. + if identity, ok := identityFromRequest(r); ok { subjects = extractSubjectsFromIdentity(identity) } @@ -568,6 +627,16 @@ func (*Auditor) extractSubjects(r *http.Request) map[string]string { return subjects } +// extractDelegationChain extracts the RFC 8693 delegation chain from the +// HTTP request's identity, or nil when there is no identity or no chain. +func (a *Auditor) extractDelegationChain(r *http.Request) *auth.DelegationChain { + identity, ok := identityFromRequest(r) + if !ok { + return nil + } + return extractDelegationChainFromIdentity(identity, a.config.MaxDelegationDepthOrDefault()) +} + // determineComponent determines the component name based on the request. func (a *Auditor) determineComponent(_ *http.Request) string { // Use the component from configuration if set @@ -752,6 +821,9 @@ func (a *Auditor) logSSEConnectionEvent(r *http.Request, statusCode int) { // Create the audit event for SSE connection event := NewAuditEvent(EventTypeSSEConnection, source, a.determineOutcome(statusCode), subjects, component) + // Attach the RFC 8693 delegation chain, if the caller used a delegated token + event.WithDelegationChain(a.extractDelegationChain(r)) + // Add target information target := map[string]string{ "endpoint": r.URL.Path, diff --git a/pkg/audit/auditor_test.go b/pkg/audit/auditor_test.go index 4c9005abcd..5d2e8554b2 100644 --- a/pkg/audit/auditor_test.go +++ b/pkg/audit/auditor_test.go @@ -558,6 +558,150 @@ func TestExtractSubjects(t *testing.T) { assert.Equal(t, "anonymous", subjects[SubjectKeyUser]) }) + + t.Run("with delegation chain", func(t *testing.T) { + t.Parallel() + claims := jwt.MapClaims{ + "sub": "user123", + "name": "John Doe", + "act": map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, + } + + req := httptest.NewRequest("GET", "/test", nil) + parsed := auth.ParseDelegationChain(claims["act"], auth.DefaultMaxDelegationDepth) + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: claims["sub"].(string), + Name: claims["name"].(string), + Claims: claims, + DelegationChain: &parsed, + }, + } + ctx := auth.WithIdentity(req.Context(), identity) + req = req.WithContext(ctx) + + subjects := auditor.extractSubjects(req) + assert.Equal(t, "user123", subjects[SubjectKeyUserID]) + assert.Equal(t, "John Doe", subjects[SubjectKeyUser]) + + chain := auditor.extractDelegationChain(req) + require.NotNil(t, chain) + require.Len(t, chain.Actors, 2) + assert.False(t, chain.Truncated) + assert.Equal(t, "agent-1", chain.Actors[0].Subject) + assert.Equal(t, "agent-2", chain.Actors[1].Subject) + }) + + t.Run("delegation chain respects configured max depth", func(t *testing.T) { + t.Parallel() + maxDepth := 1 + depthAuditor, err := NewAuditorWithTransport(&Config{MaxDelegationDepth: &maxDepth}, "sse") + require.NoError(t, err) + + claims := jwt.MapClaims{ + "sub": "user123", + "act": map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, + } + + req := httptest.NewRequest("GET", "/test", nil) + parsed := auth.ParseDelegationChain(claims["act"], auth.DefaultMaxDelegationDepth) + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user123", + Claims: claims, + DelegationChain: &parsed, + }, + } + req = req.WithContext(auth.WithIdentity(req.Context(), identity)) + + chain := depthAuditor.extractDelegationChain(req) + require.NotNil(t, chain) + require.Len(t, chain.Actors, 1, "chain must be capped at the configured max depth") + assert.Equal(t, "agent-1", chain.Actors[0].Subject) + assert.True(t, chain.Truncated, "dropped trailing actors must mark the chain truncated") + assert.Equal(t, 1, chain.DroppedCount, "one dropped actor must be reported") + }) + + t.Run("no identity yields nil delegation chain", func(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", "/test", nil) + + assert.Nil(t, auditor.extractDelegationChain(req)) + }) +} + +func TestExtractDelegationChainFromIdentity(t *testing.T) { + t.Parallel() + + t.Run("nil identity", func(t *testing.T) { + t.Parallel() + assert.Nil(t, extractDelegationChainFromIdentity(nil, auth.DefaultMaxDelegationDepth)) + }) + + t.Run("identity without chain", func(t *testing.T) { + t.Parallel() + identity := &auth.Identity{PrincipalInfo: auth.PrincipalInfo{Subject: "user123"}} + assert.Nil(t, extractDelegationChainFromIdentity(identity, auth.DefaultMaxDelegationDepth)) + }) + + t.Run("programmatic chain without raw act claim is re-bounded to max depth", func(t *testing.T) { + t.Parallel() + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user123", + DelegationChain: &auth.DelegationChain{ + Actors: []auth.DelegatedActor{ + {Subject: "agent-1"}, + {Subject: "agent-2"}, + }, + }, + }, + } + chain := extractDelegationChainFromIdentity(identity, 1) + require.NotNil(t, chain) + require.Len(t, chain.Actors, 1, "the parsed chain must be capped at maxDepth") + assert.Equal(t, "agent-1", chain.Actors[0].Subject) + assert.True(t, chain.Truncated) + assert.Equal(t, 1, chain.DroppedCount) + }) + + t.Run("raw act claim without parsed chain is parsed with max depth", func(t *testing.T) { + t.Parallel() + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user123", + Claims: map[string]any{ + "act": map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, + }, + }, + } + chain := extractDelegationChainFromIdentity(identity, 1) + require.NotNil(t, chain) + require.Len(t, chain.Actors, 1, "the raw act claim must be parsed with the depth cap") + assert.Equal(t, "agent-1", chain.Actors[0].Subject) + assert.True(t, chain.Truncated) + assert.Equal(t, 1, chain.DroppedCount) + }) + + t.Run("no chain and no act claim yields nil", func(t *testing.T) { + t.Parallel() + identity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user123", + Claims: map[string]any{"sub": "user123"}, + }, + } + assert.Nil(t, extractDelegationChainFromIdentity(identity, auth.DefaultMaxDelegationDepth)) + }) } func TestDetermineComponent(t *testing.T) { @@ -1263,4 +1407,48 @@ func TestStreamOpenAuditEvents(t *testing.T) { "must not lose the connection event to a panic") assert.Equal(t, EventTypeSSEConnection, events[0]["type"]) }) + + t.Run("delegated token stream open carries the delegation chain", func(t *testing.T) { + t.Parallel() + auditor, logBuf := newBufferAuditor(t) + + act := map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + } + chain := auth.ParseDelegationChain(act, auth.DefaultMaxDelegationDepth) + delegated := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user-123", + Claims: map[string]any{"act": act}, + DelegationChain: &chain, + }, + } + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Emulate inner auth attaching a delegated identity before the stream starts. + _ = auth.WithIdentity(r.Context(), delegated) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("event: message\ndata: {}\n\n")) + }) + auditor.Middleware(handler).ServeHTTP(httptest.NewRecorder(), newStreamRequest()) + + events := decodeAuditEvents(t, logBuf) + require.Len(t, events, 1) + assert.Equal(t, EventTypeSSEConnection, events[0]["type"]) + + logged, ok := events[0]["delegation_chain"].(map[string]any) + require.True(t, ok, "the SSE connection event must carry the delegation chain") + assert.Equal(t, false, logged["truncated"]) + actors, ok := logged["actors"].([]any) + require.True(t, ok) + require.Len(t, actors, 2) + first, ok := actors[0].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-1", first["sub"]) + second, ok := actors[1].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-2", second["sub"]) + }) } diff --git a/pkg/audit/config.go b/pkg/audit/config.go index b7a7a0b728..7520e406f1 100644 --- a/pkg/audit/config.go +++ b/pkg/audit/config.go @@ -11,6 +11,8 @@ import ( "log/slog" "os" "path/filepath" + + "github.com/stacklok/toolhive/pkg/auth" ) // Config represents the audit logging configuration. @@ -52,6 +54,12 @@ type Config struct { // +kubebuilder:default=1024 // +optional MaxDataSize int `json:"maxDataSize,omitempty" yaml:"maxDataSize,omitempty"` + // MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + // recorded in an audit event's delegationChain. Deeper chains are + // truncated (marked with truncated=true). Defaults to 10 when unset. + // +kubebuilder:default=10 + // +optional + MaxDelegationDepth *int `json:"maxDelegationDepth,omitempty" yaml:"maxDelegationDepth,omitempty"` // LogFile specifies the file path for audit logs. If empty, logs to stdout. // +optional LogFile string `json:"logFile,omitempty" yaml:"logFile,omitempty"` @@ -94,6 +102,16 @@ func (c *Config) ShouldDetectApplicationErrors() bool { return *c.DetectApplicationErrors } +// MaxDelegationDepthOrDefault returns the configured cap on RFC 8693 +// delegation chain depth, or auth.DefaultMaxDelegationDepth when unset or +// non-positive. +func (c *Config) MaxDelegationDepthOrDefault() int { + if c == nil || c.MaxDelegationDepth == nil || *c.MaxDelegationDepth <= 0 { + return auth.DefaultMaxDelegationDepth + } + return *c.MaxDelegationDepth +} + // LoadFromFile loads audit configuration from a file. func LoadFromFile(path string) (*Config, error) { // Clean the path to prevent directory traversal diff --git a/pkg/audit/event.go b/pkg/audit/event.go index b93aff1eea..50e5cc5351 100644 --- a/pkg/audit/event.go +++ b/pkg/audit/event.go @@ -11,6 +11,8 @@ import ( "time" "github.com/google/uuid" + + "github.com/stacklok/toolhive/pkg/auth" ) // The following code is adapted from github.com/metal-toolbox/auditevent @@ -64,6 +66,10 @@ type AuditEvent struct { // e.g. who triggered the event? Additional information // may be added, such as group membership and/or role Subjects map[string]string `json:"subjects"` + // DelegationChain: when the caller authenticated with an RFC 8693 + // delegated token, this records the full chain of acting parties + // (outermost/most recent first) extracted from the token's "act" claim. + DelegationChain *auth.DelegationChain `json:"delegationChain,omitempty"` // Component: allows to determine in which component the event occurred // (Answering the "Where" question of section c in the NIST SP 800-53 // Revision 5.1 Control AU-3). @@ -144,6 +150,12 @@ func NewAuditEventWithID( } } +// WithDelegationChain sets the RFC 8693 delegation chain of the event. +func (e *AuditEvent) WithDelegationChain(chain *auth.DelegationChain) *AuditEvent { + e.DelegationChain = chain + return e +} + // WithTarget sets the target of the event. func (e *AuditEvent) WithTarget(target map[string]string) *AuditEvent { e.Target = target @@ -181,6 +193,11 @@ func (e *AuditEvent) LogTo(ctx context.Context, logger *slog.Logger, level slog. slog.Any("subjects", e.Subjects), } + // Add delegation chain if present + if e.DelegationChain != nil { + attrs = append(attrs, slog.Any("delegation_chain", e.DelegationChain)) + } + // Add target if present if e.Target != nil { attrs = append(attrs, slog.Any("target", e.Target)) diff --git a/pkg/audit/workflow_auditor.go b/pkg/audit/workflow_auditor.go index 8966a17cf0..5a12ae1331 100644 --- a/pkg/audit/workflow_auditor.go +++ b/pkg/audit/workflow_auditor.go @@ -70,6 +70,7 @@ func (w *WorkflowAuditor) LogWorkflowStarted( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -121,6 +122,7 @@ func (w *WorkflowAuditor) LogWorkflowCompleted( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -173,6 +175,7 @@ func (w *WorkflowAuditor) LogWorkflowFailed( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -212,6 +215,7 @@ func (w *WorkflowAuditor) LogWorkflowTimedOut( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -251,6 +255,7 @@ func (w *WorkflowAuditor) LogStepStarted( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -288,6 +293,7 @@ func (w *WorkflowAuditor) LogStepCompleted( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -327,6 +333,7 @@ func (w *WorkflowAuditor) LogStepFailed( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -364,6 +371,7 @@ func (w *WorkflowAuditor) LogStepSkipped( subjects, w.component, ) + w.attachDelegation(ctx, event) target := map[string]string{ TargetKeyWorkflowID: workflowID, @@ -408,3 +416,15 @@ func (*WorkflowAuditor) extractSubjects(ctx context.Context) map[string]string { return subjects } + +// attachDelegation attaches the RFC 8693 delegation chain from the context's +// identity to the event. It is a no-op when there is no identity or the +// identity carries no delegation chain. +func (w *WorkflowAuditor) attachDelegation(ctx context.Context, event *AuditEvent) { + identity, ok := auth.IdentityFromContext(ctx) + if !ok { + return + } + event.WithDelegationChain( + extractDelegationChainFromIdentity(identity, w.config.MaxDelegationDepthOrDefault())) +} diff --git a/pkg/audit/workflow_auditor_test.go b/pkg/audit/workflow_auditor_test.go index 7a0ec9581d..e2f71c6113 100644 --- a/pkg/audit/workflow_auditor_test.go +++ b/pkg/audit/workflow_auditor_test.go @@ -565,6 +565,31 @@ func TestWorkflowAuditor_ExtractSubjects(t *testing.T) { SubjectKeyUser: "johndoe", }, }, + { + name: "identity_with_delegation_chain", + identity: &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user-delegated", + Name: "Delegated User", + Claims: map[string]any{ + "act": map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, + }, + DelegationChain: &auth.DelegationChain{ + Actors: []auth.DelegatedActor{ + {Subject: "agent-1"}, + {Subject: "agent-2"}, + }, + }, + }, + }, + wantSubjects: map[string]string{ + SubjectKeyUserID: "user-delegated", + SubjectKeyUser: "Delegated User", + }, + }, { name: "anonymous_user", identity: nil, @@ -594,6 +619,102 @@ func TestWorkflowAuditor_ExtractSubjects(t *testing.T) { } } +func TestWorkflowAuditor_DelegationChain(t *testing.T) { + t.Parallel() + + delegatedChain := auth.ParseDelegationChain( + map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, auth.DefaultMaxDelegationDepth) + delegatedIdentity := &auth.Identity{ + PrincipalInfo: auth.PrincipalInfo{ + Subject: "user-delegated", + Name: "Delegated User", + Claims: map[string]any{ + "act": map[string]any{ + "sub": "agent-1", + "act": map[string]any{"sub": "agent-2"}, + }, + }, + DelegationChain: &delegatedChain, + }, + } + + t.Run("workflow event carries delegation chain", func(t *testing.T) { + t.Parallel() + auditor, writer := createTestAuditor(t, DefaultConfig()) + + ctx := auth.WithIdentity(context.Background(), delegatedIdentity) + auditor.LogWorkflowStarted(ctx, "wf-1", "wf", nil, time.Second) + + require.NotEmpty(t, writer.logs, "expected log entry") + entry := parseLogEntry(t, writer.getLastLog()) + + chain, ok := entry["delegation_chain"].(map[string]any) + require.True(t, ok, "delegation_chain should be present in the log output") + assert.Equal(t, false, chain["truncated"]) + actors, ok := chain["actors"].([]any) + require.True(t, ok) + require.Len(t, actors, 2) + first, ok := actors[0].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-1", first["sub"]) + second, ok := actors[1].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-2", second["sub"]) + }) + + t.Run("step event carries delegation chain", func(t *testing.T) { + t.Parallel() + auditor, writer := createTestAuditor(t, DefaultConfig()) + + ctx := auth.WithIdentity(context.Background(), delegatedIdentity) + auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "some-tool") + + require.NotEmpty(t, writer.logs, "expected log entry") + entry := parseLogEntry(t, writer.getLastLog()) + + chain, ok := entry["delegation_chain"].(map[string]any) + require.True(t, ok, "delegation_chain should be present in the log output") + actors, ok := chain["actors"].([]any) + require.True(t, ok) + assert.Len(t, actors, 2) + }) + + t.Run("no identity omits delegation chain", func(t *testing.T) { + t.Parallel() + auditor, writer := createTestAuditor(t, DefaultConfig()) + + auditor.LogWorkflowStarted(context.Background(), "wf-1", "wf", nil, time.Second) + + require.NotEmpty(t, writer.logs, "expected log entry") + entry := parseLogEntry(t, writer.getLastLog()) + + _, exists := entry["delegation_chain"] + assert.False(t, exists, "delegation_chain should be omitted without an identity") + }) + + t.Run("configured max depth truncates chain", func(t *testing.T) { + t.Parallel() + maxDepth := 1 + auditor, writer := createTestAuditor(t, &Config{MaxDelegationDepth: &maxDepth}) + + ctx := auth.WithIdentity(context.Background(), delegatedIdentity) + auditor.LogWorkflowStarted(ctx, "wf-1", "wf", nil, time.Second) + + require.NotEmpty(t, writer.logs, "expected log entry") + entry := parseLogEntry(t, writer.getLastLog()) + + chain, ok := entry["delegation_chain"].(map[string]any) + require.True(t, ok) + assert.Equal(t, true, chain["truncated"]) + actors, ok := chain["actors"].([]any) + require.True(t, ok) + assert.Len(t, actors, 1) + }) +} + func TestWorkflowAuditor_ExtractSource(t *testing.T) { t.Parallel() diff --git a/pkg/audit/zz_generated.deepcopy.go b/pkg/audit/zz_generated.deepcopy.go index 7af0eff790..1305e4a068 100644 --- a/pkg/audit/zz_generated.deepcopy.go +++ b/pkg/audit/zz_generated.deepcopy.go @@ -40,6 +40,11 @@ func (in *Config) DeepCopyInto(out *Config) { *out = new(bool) **out = **in } + if in.MaxDelegationDepth != nil { + in, out := &in.MaxDelegationDepth, &out.MaxDelegationDepth + *out = new(int) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. diff --git a/pkg/auth/context.go b/pkg/auth/context.go index 9065858244..6c3bddf8ed 100644 --- a/pkg/auth/context.go +++ b/pkg/auth/context.go @@ -203,6 +203,16 @@ func claimsToIdentity(claims jwt.MapClaims, token string) (*Identity, error) { identity.Email = email } + // Parse the RFC 8693 "act" claim (if present) into a delegation chain so + // downstream consumers (audit logs, authorizers) see the full chain of + // parties acting on behalf of the subject. + if act, ok := claims["act"]; ok && act != nil { + chain := ParseDelegationChain(act, DefaultMaxDelegationDepth) + if len(chain.Actors) > 0 { + identity.DelegationChain = &chain + } + } + return identity, nil } diff --git a/pkg/auth/context_test.go b/pkg/auth/context_test.go index 6300056032..8f920b406d 100644 --- a/pkg/auth/context_test.go +++ b/pkg/auth/context_test.go @@ -126,6 +126,56 @@ func TestClaimsToIdentity_PopulatesPlatformUserID(t *testing.T) { assert.Equal(t, "user123", id.PlatformUserID) } +// TestClaimsToIdentity_ParsesActClaim verifies that an RFC 8693 "act" claim is +// parsed into the identity's delegation chain (outermost actor first), and +// that tokens without an act claim carry an empty chain. +func TestClaimsToIdentity_ParsesActClaim(t *testing.T) { + t.Parallel() + + t.Run("nested act claim", func(t *testing.T) { + t.Parallel() + claims := jwt.MapClaims{ + "sub": "user123", + "act": map[string]any{ + "sub": "agent-1", + "iss": "https://issuer.example", + "act": map[string]any{"sub": "agent-2"}, + }, + } + + id, err := claimsToIdentity(claims, "tok") + require.NoError(t, err) + + require.NotNil(t, id.DelegationChain) + require.Len(t, id.DelegationChain.Actors, 2) + assert.False(t, id.DelegationChain.Truncated) + assert.Equal(t, "agent-1", id.DelegationChain.Actors[0].Subject) + assert.Equal(t, map[string]any{"iss": "https://issuer.example"}, id.DelegationChain.Actors[0].Claims) + assert.Equal(t, "agent-2", id.DelegationChain.Actors[1].Subject) + }) + + t.Run("no act claim", func(t *testing.T) { + t.Parallel() + id, err := claimsToIdentity(jwt.MapClaims{"sub": "user123"}, "tok") + require.NoError(t, err) + assert.Nil(t, id.DelegationChain) + }) + + t.Run("nil act claim", func(t *testing.T) { + t.Parallel() + id, err := claimsToIdentity(jwt.MapClaims{"sub": "user123", "act": nil}, "tok") + require.NoError(t, err) + assert.Nil(t, id.DelegationChain) + }) + + t.Run("non-map act claim", func(t *testing.T) { + t.Parallel() + id, err := claimsToIdentity(jwt.MapClaims{"sub": "user123", "act": "agent-1"}, "tok") + require.NoError(t, err) + assert.Nil(t, id.DelegationChain) + }) +} + // TestPlatformUserContext_StoreAndRetrieve verifies the dedicated platform-user key // round-trips and that an empty userID leaves the context (and the identity key) // untouched. diff --git a/pkg/auth/delegation.go b/pkg/auth/delegation.go new file mode 100644 index 0000000000..6e97b9d920 --- /dev/null +++ b/pkg/auth/delegation.go @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package auth + +// DefaultMaxDelegationDepth is the default cap on how many nested RFC 8693 +// "act" entries ParseDelegationChain will follow. It is aligned with the +// issuance-side cap in pkg/authserver/server/tokenexchange/handler.go +// (maxDelegationDepth) and the claim-nesting cap in +// pkg/authz/authorizers/cedar/entity.go (maxClaimNestingDepth), both 10. +const DefaultMaxDelegationDepth = 10 + +// DelegatedActor represents one acting party in an RFC 8693 §4.1 delegation +// chain (one "act" claim value). +type DelegatedActor struct { + // Subject identifies the acting party (the "sub" member of the act claim). + // Empty when the act claim carries no "sub". + Subject string `json:"sub,omitempty"` + + // Claims holds the remaining members of the act claim (e.g. "iss", + // "client_id"), preserving forward-compatibility with act claims that + // carry more than a subject. The "act_claims" tag disambiguates these + // per-actor members from the identity's top-level claims. + Claims map[string]any `json:"act_claims,omitempty"` +} + +// DelegationChain is the parsed form of a JWT's RFC 8693 "act" claim: the +// ordered list of parties that acted on behalf of the token subject. +type DelegationChain struct { + // Actors are the acting parties, outermost (most recent) first: Actors[0] + // is the direct delegate that presented the token, Actors[len-1] the + // earliest actor in the chain. + Actors []DelegatedActor `json:"actors"` + + // Truncated is true when the chain was deeper than the configured maximum + // depth and trailing actors were dropped. + Truncated bool `json:"truncated"` + + // DroppedCount reports how many actors were dropped due to the depth cap. + // Zero (and omitted from JSON) when nothing was dropped. + DroppedCount int `json:"dropped_count,omitempty"` +} + +// ParseDelegationChain parses a JWT "act" claim value into a DelegationChain. +// The act value is expected to be a map (as produced by JSON decoding); any +// other shape yields an empty, non-truncated chain. Nested "act" members are +// followed up to maxDepth actors; maxDepth <= 0 uses DefaultMaxDelegationDepth. +// A nil/absent act value yields the zero chain (no actors, not truncated). +func ParseDelegationChain(act any, maxDepth int) DelegationChain { + if maxDepth <= 0 { + maxDepth = DefaultMaxDelegationDepth + } + + chain := DelegationChain{} + current := act + for len(chain.Actors) < maxDepth { + m, ok := current.(map[string]any) + if !ok { + return chain + } + + actor := DelegatedActor{} + if sub, ok := m["sub"].(string); ok { + actor.Subject = sub + } + claims := make(map[string]any, len(m)) + for k, v := range m { + if k == "sub" || k == "act" { + continue + } + claims[k] = v + } + if len(claims) > 0 { + actor.Claims = claims + } + chain.Actors = append(chain.Actors, actor) + + next, ok := m["act"] + if !ok || next == nil { + return chain + } + current = next + } + + // The depth cap was reached. current now holds the last appended actor's + // nested "act" value: each further map entry is a dropped actor, so count + // them and mark the chain truncated when any remain. + for { + m, ok := current.(map[string]any) + if !ok { + break + } + chain.Truncated = true + chain.DroppedCount++ + next, ok := m["act"] + if !ok || next == nil { + break + } + current = next + } + + return chain +} diff --git a/pkg/auth/delegation_test.go b/pkg/auth/delegation_test.go new file mode 100644 index 0000000000..a1d303ded1 --- /dev/null +++ b/pkg/auth/delegation_test.go @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package auth + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// nestedAct builds an act claim value with the given actor subjects nested +// outermost-first: nestedAct("a", "b") => {"sub":"a","act":{"sub":"b"}}. +func nestedAct(subs ...string) map[string]any { + var current map[string]any + for i := len(subs) - 1; i >= 0; i-- { + m := map[string]any{"sub": subs[i]} + if current != nil { + m["act"] = current + } + current = m + } + return current +} + +func actorSubjects(chain DelegationChain) []string { + var subs []string + for _, a := range chain.Actors { + subs = append(subs, a.Subject) + } + return subs +} + +func TestParseDelegationChain(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + act any + maxDepth int + wantSubjects []string + wantTruncated bool + }{ + { + name: "no act claim", + act: nil, + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: nil, + }, + { + name: "single actor", + act: map[string]any{"sub": "agent-1"}, + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: []string{"agent-1"}, + }, + { + name: "nested three deep, outermost first", + act: nestedAct("agent-1", "agent-2", "agent-3"), + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: []string{"agent-1", "agent-2", "agent-3"}, + }, + { + name: "non-map act yields empty chain", + act: "agent-1", + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: nil, + }, + { + name: "non-map nested act stops the chain", + act: map[string]any{"sub": "agent-1", "act": "not-a-map"}, + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: []string{"agent-1"}, + }, + { + name: "exactly maxDepth actors is not truncated", + act: nestedAct("a1", "a2", "a3"), + maxDepth: 3, + wantSubjects: []string{"a1", "a2", "a3"}, + }, + { + name: "maxDepth plus one is truncated", + act: nestedAct("a1", "a2", "a3", "a4"), + maxDepth: 3, + wantSubjects: []string{"a1", "a2", "a3"}, + wantTruncated: true, + }, + { + name: "zero maxDepth uses default", + act: nestedAct("agent-1", "agent-2"), + maxDepth: 0, + wantSubjects: []string{"agent-1", "agent-2"}, + }, + { + name: "negative maxDepth uses default", + act: nestedAct("agent-1"), + maxDepth: -5, + wantSubjects: []string{"agent-1"}, + }, + { + name: "default depth accommodates the issuance cap", + act: nestedAct( + "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"), + maxDepth: 0, + wantSubjects: []string{ + "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"}, + }, + { + name: "act without sub keeps extra claims", + act: map[string]any{"iss": "https://issuer.example", "client_id": "c-1"}, + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: []string{""}, + }, + { + name: "explicit nil nested act ends the chain", + act: map[string]any{"sub": "agent-1", "act": nil}, + maxDepth: DefaultMaxDelegationDepth, + wantSubjects: []string{"agent-1"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + chain := ParseDelegationChain(tt.act, tt.maxDepth) + + assert.Equal(t, tt.wantSubjects, actorSubjects(chain)) + assert.Equal(t, tt.wantTruncated, chain.Truncated) + }) + } +} + +func TestParseDelegationChain_ActorClaims(t *testing.T) { + t.Parallel() + + act := map[string]any{ + "sub": "agent-1", + "iss": "https://issuer.example", + "client_id": "c-1", + "act": map[string]any{ + "sub": "agent-2", + }, + } + + chain := ParseDelegationChain(act, DefaultMaxDelegationDepth) + require.Len(t, chain.Actors, 2) + + assert.Equal(t, "agent-1", chain.Actors[0].Subject) + assert.Equal(t, map[string]any{ + "iss": "https://issuer.example", + "client_id": "c-1", + }, chain.Actors[0].Claims, "extra act members must be preserved, sub/act excluded") + + assert.Equal(t, "agent-2", chain.Actors[1].Subject) + assert.Empty(t, chain.Actors[1].Claims, "an act with only sub yields no extra claims") +} + +func TestParseDelegationChain_DefaultDepthTruncatesBeyondCap(t *testing.T) { + t.Parallel() + + subs := make([]string, 0, DefaultMaxDelegationDepth+1) + for i := 1; i <= DefaultMaxDelegationDepth+1; i++ { + subs = append(subs, fmt.Sprintf("a%d", i)) + } + + chain := ParseDelegationChain(nestedAct(subs...), DefaultMaxDelegationDepth) + + require.Len(t, chain.Actors, DefaultMaxDelegationDepth) + assert.True(t, chain.Truncated) + assert.Equal(t, 1, chain.DroppedCount) + assert.Equal(t, subs[:DefaultMaxDelegationDepth], actorSubjects(chain)) +} + +// TestParseDelegationChain_DroppedCount pins that the dropped count reports +// every actor cut by the depth cap, not just whether truncation happened. +func TestParseDelegationChain_DroppedCount(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + act any + maxDepth int + wantDropped int + }{ + { + name: "no truncation reports zero", + act: nestedAct("a1", "a2"), + maxDepth: 2, + wantDropped: 0, + }, + { + name: "one actor beyond the cap", + act: nestedAct("a1", "a2", "a3"), + maxDepth: 2, + wantDropped: 1, + }, + { + name: "several actors beyond the cap", + act: nestedAct("a1", "a2", "a3", "a4", "a5"), + maxDepth: 2, + wantDropped: 3, + }, + { + name: "non-map remainder counts as one dropped entry", + act: map[string]any{"sub": "a1", "act": map[string]any{"sub": "a2", "act": "not-a-map"}}, + maxDepth: 1, + wantDropped: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + chain := ParseDelegationChain(tt.act, tt.maxDepth) + + assert.Equal(t, tt.wantDropped, chain.DroppedCount) + assert.Equal(t, tt.wantDropped > 0, chain.Truncated) + }) + } +} diff --git a/pkg/auth/identity.go b/pkg/auth/identity.go index 80f795e572..2496b0ecdf 100644 --- a/pkg/auth/identity.go +++ b/pkg/auth/identity.go @@ -62,6 +62,11 @@ type PrincipalInfo struct { // Claims contains additional claims from the auth token. // This preserves all JWT claims for authorization policies. Claims map[string]any `json:"claims,omitempty"` + + // DelegationChain is the parsed RFC 8693 "act" claim: the ordered list of + // parties that acted on behalf of this identity's subject (outermost/most + // recent first). Nil when the token carries no act claim. + DelegationChain *DelegationChain `json:"delegation_chain,omitempty"` } // Identity represents an authenticated user or service account. @@ -183,6 +188,7 @@ func (i *Identity) MarshalJSON() ([]byte, error) { Email string `json:"email"` Groups []string `json:"groups"` Claims map[string]any `json:"claims"` + DelegationChain *DelegationChain `json:"delegationChain,omitempty"` Token string `json:"token"` TokenType string `json:"tokenType"` Metadata map[string]string `json:"metadata"` @@ -242,6 +248,7 @@ func (i *Identity) MarshalJSON() ([]byte, error) { Email: i.Email, Groups: i.Groups, Claims: claims, + DelegationChain: i.DelegationChain, Token: token, TokenType: i.TokenType, Metadata: i.Metadata, diff --git a/pkg/auth/identity_test.go b/pkg/auth/identity_test.go index 07480c08fc..4aa1a64718 100644 --- a/pkg/auth/identity_test.go +++ b/pkg/auth/identity_test.go @@ -511,6 +511,62 @@ func TestIdentity_MarshalJSON(t *testing.T) { assert.Equal(t, "org456", claims["org_id"], "org_id claim must be preserved") }, }, + { + name: "includes_delegation_chain", + identity: &Identity{ + PrincipalInfo: PrincipalInfo{ + Subject: "user123", + DelegationChain: &DelegationChain{ + Actors: []DelegatedActor{ + {Subject: "agent-1", Claims: map[string]any{"iss": "https://issuer.example"}}, + {Subject: "agent-2"}, + }, + }, + }, + }, + wantErr: false, + checkFunc: func(t *testing.T, data []byte) { + t.Helper() + + var result map[string]any + require.NoError(t, json.Unmarshal(data, &result)) + + chain, ok := result["delegationChain"].(map[string]any) + require.True(t, ok, "delegationChain should be a map") + assert.Equal(t, false, chain["truncated"]) + + actors, ok := chain["actors"].([]any) + require.True(t, ok, "actors should be an array") + require.Len(t, actors, 2) + + first, ok := actors[0].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-1", first["sub"]) + claims, ok := first["act_claims"].(map[string]any) + require.True(t, ok, "actor extra claims should be preserved under act_claims") + assert.Equal(t, "https://issuer.example", claims["iss"]) + + second, ok := actors[1].(map[string]any) + require.True(t, ok) + assert.Equal(t, "agent-2", second["sub"]) + }, + }, + { + name: "omits_empty_delegation_chain", + identity: &Identity{ + PrincipalInfo: PrincipalInfo{Subject: "user123"}, + }, + wantErr: false, + checkFunc: func(t *testing.T, data []byte) { + t.Helper() + + var result map[string]any + require.NoError(t, json.Unmarshal(data, &result)) + + _, exists := result["delegationChain"] + assert.False(t, exists, "delegationChain key should be omitted when no chain is present") + }, + }, { name: "marshals_claims_without_tsid_unchanged", identity: &Identity{ diff --git a/pkg/authserver/integration_test.go b/pkg/authserver/integration_test.go index 0c5f20e214..f83e406571 100644 --- a/pkg/authserver/integration_test.go +++ b/pkg/authserver/integration_test.go @@ -29,6 +29,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/stacklok/toolhive/pkg/audit" "github.com/stacklok/toolhive/pkg/auth" "github.com/stacklok/toolhive/pkg/auth/upstreamtoken" servercrypto "github.com/stacklok/toolhive/pkg/authserver/server/crypto" @@ -789,6 +790,193 @@ func TestIntegration_TokenExchange_ConfidentialClientHappyPath(t *testing.T) { "delegated token exp must be capped at the 15m delegation lifespan, not the subject token's 30m") } +// TestIntegration_TokenExchange_AuditDelegationChain proves the end-to-end +// audit story for RFC 8693 delegation: a delegated token minted by the real +// token-exchange handler is validated by the auth middleware, and the audit +// middleware emits an event whose delegationChain records the acting agent. +func TestIntegration_TokenExchange_AuditDelegationChain(t *testing.T) { + t.Parallel() + + const ( + agentClientID = "test-audit-agent-client" + agentClientSecret = "test-audit-agent-secret" + delegatedUserSub = "audit-delegated-user-sub" + ) + + agentClient, err := registration.New(registration.Config{ + ID: agentClientID, + Secret: agentClientSecret, + Public: false, + GrantTypes: []string{oauthproto.GrantTypeTokenExchange}, + Scopes: registration.DefaultScopes, + Audience: []string{testAudience}, + }) + require.NoError(t, err) + + m := startMockOIDC(t) + ts := setupTestServerWithMockOIDC(t, m, withExtraClient(agentClient)) + + // Mint the subject token (user) signed by the server's key. + signer, err := jose.NewSigner( + jose.SigningKey{Algorithm: jose.RS256, Key: ts.PrivateKey}, + (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "test-key"), + ) + require.NoError(t, err) + + now := time.Now() + subjectToken, err := jwt.Signed(signer). + Claims(jwt.Claims{ + Issuer: testIssuer, + Subject: delegatedUserSub, + Audience: jwt.Audience{testAudience}, + Expiry: jwt.NewNumericDate(now.Add(30 * time.Minute)), + IssuedAt: jwt.NewNumericDate(now), + }). + Claims(map[string]any{ + "client_id": agentClientID, + }). + Serialize() + require.NoError(t, err) + + // Exchange it for a delegated token carrying act.sub = agent. + resp := makeTokenRequest(t, ts.Server.URL, url.Values{ + "grant_type": {oauthproto.GrantTypeTokenExchange}, + "subject_token": {subjectToken}, + "subject_token_type": {oauthproto.TokenTypeAccessToken}, + "client_id": {agentClientID}, + "client_secret": {agentClientSecret}, + }) + defer resp.Body.Close() + body := parseTokenResponse(t, resp) + require.Equal(t, http.StatusOK, resp.StatusCode, + "token exchange should succeed, got %d (body: %v)", resp.StatusCode, body) + delegated, ok := body["access_token"].(string) + require.True(t, ok, "access_token should be a string") + require.NotEmpty(t, delegated) + + // Build a validator that trusts the server's issuer and keys, exactly like + // the middleware in front of a protected resource server. The in-process + // key provider avoids self-referential HTTP JWKS fetches. + validator, err := auth.NewTokenValidator(context.Background(), auth.TokenValidatorConfig{ + Issuer: testIssuer, + Audience: testAudience, + }, auth.WithKeyProvider(&testKeyProvider{key: ts.PrivateKey})) + require.NoError(t, err) + + // Chain: audit (outer) -> auth -> bare stub handler. The stub does NOT + // re-publish the identity: this test pins that TokenValidator.Middleware + // alone publishes the validated identity to the audit holder. + var auditBuf bytes.Buffer + auditor, err := audit.NewAuditorWithTransport(&audit.Config{}, "streamable-http") + require.NoError(t, err) + auditor.SetLogWriterForTest(&auditBuf) //nolint:staticcheck // test-only writer capture until NewAuditorWithWriter exists + + stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + req := httptest.NewRequest(http.MethodPost, "/messages", strings.NewReader("{}")) + req.Header.Set("Authorization", "Bearer "+delegated) + rr := httptest.NewRecorder() + auditor.Middleware(validator.Middleware(stub)).ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code, + "delegated token must validate through the auth middleware") + + // Exactly one audit event, carrying the delegation chain. + lines := strings.Split(strings.TrimSpace(auditBuf.String()), "\n") + require.Len(t, lines, 1, "expected exactly one audit event, got: %q", auditBuf.String()) + + var event map[string]any + require.NoError(t, json.Unmarshal([]byte(lines[0]), &event)) + + subjects, ok := event["subjects"].(map[string]any) + require.True(t, ok, "subjects should be a map") + assert.Equal(t, delegatedUserSub, subjects["user_id"], + "audit subject must be the delegated user, not the agent") + + chain, ok := event["delegation_chain"].(map[string]any) + require.True(t, ok, "delegation_chain must be present in the audit event") + assert.Equal(t, false, chain["truncated"]) + actors, ok := chain["actors"].([]any) + require.True(t, ok, "actors should be an array") + require.Len(t, actors, 1, "a single exchange yields a single actor") + actor, ok := actors[0].(map[string]any) + require.True(t, ok) + assert.Equal(t, agentClientID, actor["sub"], + "the delegation chain must record the acting agent client") +} + +// TestIntegration_AuditMiddleware_NonDelegatedTokenOmitsDelegationChain is the +// negative companion to TestIntegration_TokenExchange_AuditDelegationChain: a +// plain (non-delegated) token through the same audit(auth(stub)) chain must +// produce an audit event with NO delegation_chain member. +func TestIntegration_AuditMiddleware_NonDelegatedTokenOmitsDelegationChain(t *testing.T) { + t.Parallel() + + const plainUserSub = "audit-plain-user-sub" + + m := startMockOIDC(t) + ts := setupTestServerWithMockOIDC(t, m) + + // Mint a plain subject token signed by the server's key (no act claim). + signer, err := jose.NewSigner( + jose.SigningKey{Algorithm: jose.RS256, Key: ts.PrivateKey}, + (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "test-key"), + ) + require.NoError(t, err) + + now := time.Now() + plainToken, err := jwt.Signed(signer). + Claims(jwt.Claims{ + Issuer: testIssuer, + Subject: plainUserSub, + Audience: jwt.Audience{testAudience}, + Expiry: jwt.NewNumericDate(now.Add(30 * time.Minute)), + IssuedAt: jwt.NewNumericDate(now), + }). + Serialize() + require.NoError(t, err) + + validator, err := auth.NewTokenValidator(context.Background(), auth.TokenValidatorConfig{ + Issuer: testIssuer, + Audience: testAudience, + }, auth.WithKeyProvider(&testKeyProvider{key: ts.PrivateKey})) + require.NoError(t, err) + + var auditBuf bytes.Buffer + auditor, err := audit.NewAuditorWithTransport(&audit.Config{}, "streamable-http") + require.NoError(t, err) + auditor.SetLogWriterForTest(&auditBuf) //nolint:staticcheck // test-only writer capture until NewAuditorWithWriter exists + + stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + req := httptest.NewRequest(http.MethodPost, "/messages", strings.NewReader("{}")) + req.Header.Set("Authorization", "Bearer "+plainToken) + rr := httptest.NewRecorder() + auditor.Middleware(validator.Middleware(stub)).ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code, + "plain token must validate through the auth middleware") + + lines := strings.Split(strings.TrimSpace(auditBuf.String()), "\n") + require.Len(t, lines, 1, "expected exactly one audit event, got: %q", auditBuf.String()) + + var event map[string]any + require.NoError(t, json.Unmarshal([]byte(lines[0]), &event)) + + subjects, ok := event["subjects"].(map[string]any) + require.True(t, ok, "subjects should be a map") + assert.Equal(t, plainUserSub, subjects["user_id"], + "audit subject must be the authenticated user") + + _, exists := event["delegation_chain"] + assert.False(t, exists, + "a non-delegated token must not produce a delegation_chain member") +} + // ============================================================================ // Full PKCE Flow Integration Tests with Mock Upstream IDP (using mockoidc) // ============================================================================ From 7d0d4747f0987a84b3fd1997802e605f343bd551 Mon Sep 17 00:00:00 2001 From: Juan Antonio Osorio Date: Mon, 27 Jul 2026 22:06:21 +0300 Subject: [PATCH 2/2] Regenerate operator CRDs and CRD docs for maxDelegationDepth Run task operator-manifests and task crdref-gen to pick up the new maxDelegationDepth audit config field introduced in #6035. --- .../toolhive.stacklok.dev_virtualmcpservers.yaml | 14 ++++++++++++++ .../toolhive.stacklok.dev_virtualmcpservers.yaml | 14 ++++++++++++++ docs/operator/crd-api.md | 1 + 3 files changed, 29 insertions(+) diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml index ffd1118f61..4dade447ac 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -1184,6 +1184,13 @@ spec: description: MaxDataSize limits the size of request/response data included in audit logs (in bytes). type: integer + maxDelegationDepth: + default: 10 + description: |- + MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + recorded in an audit event's delegationChain. Deeper chains are + truncated (marked with truncated=true). Defaults to 10 when unset. + type: integer type: object backends: description: |- @@ -4631,6 +4638,13 @@ spec: description: MaxDataSize limits the size of request/response data included in audit logs (in bytes). type: integer + maxDelegationDepth: + default: 10 + description: |- + MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + recorded in an audit event's delegationChain. Deeper chains are + truncated (marked with truncated=true). Defaults to 10 when unset. + type: integer type: object backends: description: |- diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml index 5b79959d56..e708851674 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -1187,6 +1187,13 @@ spec: description: MaxDataSize limits the size of request/response data included in audit logs (in bytes). type: integer + maxDelegationDepth: + default: 10 + description: |- + MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + recorded in an audit event's delegationChain. Deeper chains are + truncated (marked with truncated=true). Defaults to 10 when unset. + type: integer type: object backends: description: |- @@ -4634,6 +4641,13 @@ spec: description: MaxDataSize limits the size of request/response data included in audit logs (in bytes). type: integer + maxDelegationDepth: + default: 10 + description: |- + MaxDelegationDepth caps how many nested RFC 8693 "act" entries are + recorded in an audit event's delegationChain. Deeper chains are + truncated (marked with truncated=true). Defaults to 10 when unset. + type: integer type: object backends: description: |- diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 4a87c88f16..7103df642d 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -42,6 +42,7 @@ _Appears in:_ | `includeResponseData` _boolean_ | IncludeResponseData determines whether to include response data in audit logs. | false | Optional: \{\}
| | `detectApplicationErrors` _boolean_ | DetectApplicationErrors controls whether the audit middleware inspects
JSON-RPC response bodies for application-level errors when the HTTP
status code indicates success (2xx). When enabled, a small prefix of
the response body is buffered to detect JSON-RPC error fields,
independent of the IncludeResponseData setting. | true | Optional: \{\}
| | `maxDataSize` _integer_ | MaxDataSize limits the size of request/response data included in audit logs (in bytes). | 1024 | Optional: \{\}
| +| `maxDelegationDepth` _integer_ | MaxDelegationDepth caps how many nested RFC 8693 "act" entries are
recorded in an audit event's delegationChain. Deeper chains are
truncated (marked with truncated=true). Defaults to 10 when unset. | 10 | Optional: \{\}
| | `logFile` _string_ | LogFile specifies the file path for audit logs. If empty, logs to stdout. | | Optional: \{\}
|