From 0f8ee34ddc92456174b340aaabf86fdc22272d7e Mon Sep 17 00:00:00 2001 From: Radoslav Dimitrov Date: Fri, 20 Nov 2026 23:09:34 +0200 Subject: [PATCH 1/3] feat(identitybroker): limit each agent's gateway calls to its definition's tools The broker now checks design step (6) check 7: each gateway call's exact server and tool must be inside the acting agent's effective ceiling. - The definition loader resolves each definition's ceiling against the servers the gateway routes. A server the definition's mcpServers references is granted whole, minus the tools its disallowedTools names; tools selects no MCP tools, as in the harness. Built-ins name every routed server. No tool list is needed, since listing tools needs a user's grant. - Registration stores each instance's effective ceiling: its definition's, narrowed by its parent's effective ceiling, computed once and never widened. - Check 7 runs after the gateway route check and refuses with PERMISSION_DENIED, recording the ceiling it checked. A call whose tool is not named for its server is now an invalid request, and gateway server names are limited to letters, digits, and single underscores, so "." and "mcp____" each name one server. - A helper that runs a named definition, as a subagent or team member, now gets the session's gateway tools for the servers its definition references, minus excluded tools, removing #2555's shortcut. A test checks the harness and the broker resolve each definition the same way. Records the resolution rule in mcp-authorization.md and updates the identity broker row in the mecak8s operator docs. Closes #2842. Co-Authored-By: Claude Opus 5.5 --- .../identity_broker_delegations_test.go | 9 +- cmd/mecak8s/identity_broker_harness_test.go | 20 ++- cmd/mecak8s/identity_broker_helpers_test.go | 16 +- cmd/mecak8s/identity_broker_real_as1_test.go | 2 +- .../identity_broker_tool_limit_test.go | 100 +++++++++++ .../agent-identity/mcp-authorization.md | 2 + internal/adapter/mcpbroker/runtime.go | 3 + internal/app/agentdef_root.go | 2 +- internal/app/agentdefs.go | 41 ++++- internal/app/build.go | 13 +- internal/app/defgatewaytools_test.go | 96 +++++++++++ internal/app/identitybroker.go | 39 +++-- ...on_scoped_agent_identity_scenario1_test.go | 2 +- .../adapter/definitionloader/loader.go | 65 +++++++- .../adapter/definitionloader/loader_test.go | 47 ++++++ internal/identitybroker/agents.go | 26 ++- internal/identitybroker/authorize.go | 13 +- .../identitybroker/authorize_checks_test.go | 15 +- internal/identitybroker/authorize_test.go | 6 +- internal/identitybroker/broker.go | 2 +- internal/identitybroker/ceiling.go | 138 ++++++++++++++++ .../identitybroker/ceiling_internal_test.go | 91 ++++++++++ internal/identitybroker/ceiling_test.go | 156 ++++++++++++++++++ .../identitybroker/conformance/conformance.go | 27 ++- internal/identitybroker/definition.go | 11 +- internal/identitybroker/gateway.go | 23 ++- internal/identitybroker/recorder.go | 6 +- internal/identitybroker/service.go | 14 +- .../mecak8s/identity-and-client-access.md | 2 +- 29 files changed, 911 insertions(+), 76 deletions(-) create mode 100644 cmd/mecak8s/identity_broker_tool_limit_test.go create mode 100644 internal/app/defgatewaytools_test.go create mode 100644 internal/identitybroker/ceiling.go create mode 100644 internal/identitybroker/ceiling_internal_test.go create mode 100644 internal/identitybroker/ceiling_test.go diff --git a/cmd/mecak8s/identity_broker_delegations_test.go b/cmd/mecak8s/identity_broker_delegations_test.go index 0dac2aa794..c5721eacc9 100644 --- a/cmd/mecak8s/identity_broker_delegations_test.go +++ b/cmd/mecak8s/identity_broker_delegations_test.go @@ -62,12 +62,13 @@ type delegationServe struct { session string } -func serveDelegations(t *testing.T) *delegationServe { +// serveDelegations serves mecak8s with extraArgs as further flags. +func serveDelegations(t *testing.T, extraArgs ...string) *delegationServe { t.Helper() d := &delegationServe{diag: &gatewayCallDiagnostics{}, script: filepath.Join(t.TempDir(), "script.json")} model := newLateScript(d.script) d.gatewayServe = serveGatewayIdentityBroker(t, notesRoute(t), - []string{"--enable-parallel", "--enable-teams", "--workspace", t.TempDir()}, + append([]string{"--enable-parallel", "--enable-teams", "--workspace", t.TempDir()}, extraArgs...), func(cfg *app.Config) { cfg.MockProvider = model cfg.Diagnostics = d.diag @@ -137,8 +138,8 @@ func TestIdentityBrokerParallelBranchGatewayCall(t *testing.T) { // TestIdentityBrokerTeamMemberGatewayCall pins that a member of a team the // Team tool starts makes gateway calls under its reported delegation. The -// members are generic: a member running a named definition gets no gateway -// tools yet (#2842). They share the mock script, so which calls first varies. +// members are generic, so each gets every gateway tool; they share the mock +// script, so which calls first varies. func TestIdentityBrokerTeamMemberGatewayCall(t *testing.T) { d := serveDelegations(t) d.writeScript(t, gatewayTurn("main-call"), diff --git a/cmd/mecak8s/identity_broker_harness_test.go b/cmd/mecak8s/identity_broker_harness_test.go index 5240686927..70cde4bbfb 100644 --- a/cmd/mecak8s/identity_broker_harness_test.go +++ b/cmd/mecak8s/identity_broker_harness_test.go @@ -401,7 +401,7 @@ func TestIdentityBrokerGatewayCallAgainstRealAS1(t *testing.T) { call := func(operation string) (identitybroker.Authorization, error) { return built.IdentityBroker.AuthorizeCall(t.Context(), identitybroker.AuthorizeCallRequest{ SessionID: opened.ID, Credential: agent.Credential, OperationID: operation, RunID: "R1", RunOwner: opened.Owner, - Method: identitybroker.MethodToolsCall, Server: "calendar", Tool: "echo", ArgumentsSHA256: strings.Repeat("ab", 32), + Method: identitybroker.MethodToolsCall, Server: "calendar", Tool: "calendar.echo", ArgumentsSHA256: strings.Repeat("ab", 32), }) } first, err := call("op-1") @@ -1127,6 +1127,24 @@ func createSession(t *testing.T, api, token string) string { return created.ID } +// toolResult returns the result of call in Alice's session id, failing t if +// it has none. +func (gw *gatewayServe) toolResult(t *testing.T, id session.SessionID, call session.ToolCallID) session.ToolResult { + t.Helper() + owner := session.WithPrincipal(t.Context(), &session.Principal{Issuer: gw.h.IdP.Issuer(), Subject: identityharness.Alice, GrantType: session.GrantTypeUser}) + sess, err := gw.built.Service.GetSession(owner, id) + if err != nil { + t.Fatalf("GetSession(%s): %v", id, err) + } + for _, m := range sess.Conversation.Messages { + if m.ToolResult != nil && m.ToolResult.CallID == call { + return *m.ToolResult + } + } + t.Fatalf("session %s has no result for %s", id, call) + return session.ToolResult{} +} + // listSessionOwners maps each listed session to its owner. func listSessionOwners(t *testing.T, api, token string) map[string]identitybroker.Owner { t.Helper() diff --git a/cmd/mecak8s/identity_broker_helpers_test.go b/cmd/mecak8s/identity_broker_helpers_test.go index d1d90d56c6..cc698420e6 100644 --- a/cmd/mecak8s/identity_broker_helpers_test.go +++ b/cmd/mecak8s/identity_broker_helpers_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/stacklok/mecatl/engine/session" - "github.com/stacklok/mecatl/internal/testutil/identityharness" ) // helperGatewayScript has the main agent delegate to a default subagent, @@ -37,23 +36,12 @@ func TestIdentityBrokerHelperGatewayCallCarriesItsOwnIdentity(t *testing.T) { t.Fatal(err) } gw := serveGatewayIdentityBroker(t, notesRoute(t), []string{"--mock-script", script}, nil) - h, api, built, alice := gw.h, gw.api, gw.built, gw.alice + api, alice := gw.api, gw.alice created := createSession(t, api, alice) - owner := session.WithPrincipal(t.Context(), &session.Principal{Issuer: h.IdP.Issuer(), Subject: identityharness.Alice, GrantType: session.GrantTypeUser}) toolResult := func(id session.SessionID, call session.ToolCallID) session.ToolResult { t.Helper() - sess, err := built.Service.GetSession(owner, id) - if err != nil { - t.Fatalf("GetSession(%s): %v", id, err) - } - for _, m := range sess.Conversation.Messages { - if m.ToolResult != nil && m.ToolResult.CallID == call { - return *m.ToolResult - } - } - t.Fatalf("session %s has no result for %s", id, call) - return session.ToolResult{} + return gw.toolResult(t, id, call) } promptApprovingAsks(t, api, alice, created, "delegate", nil) diff --git a/cmd/mecak8s/identity_broker_real_as1_test.go b/cmd/mecak8s/identity_broker_real_as1_test.go index 9a4da894c9..a5491bb01f 100644 --- a/cmd/mecak8s/identity_broker_real_as1_test.go +++ b/cmd/mecak8s/identity_broker_real_as1_test.go @@ -118,7 +118,7 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) { } if _, err := built.IdentityBroker.AuthorizeCall(t.Context(), identitybroker.AuthorizeCallRequest{ SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", RunID: "R42", RunOwner: aliceCompany, - Method: identitybroker.MethodToolsCall, Server: "gateway", Tool: "search", ArgumentsSHA256: strings.Repeat("ab", 32), + Method: identitybroker.MethodToolsCall, Server: "gateway", Tool: "gateway.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_tool_limit_test.go b/cmd/mecak8s/identity_broker_tool_limit_test.go new file mode 100644 index 0000000000..4851b64c90 --- /dev/null +++ b/cmd/mecak8s/identity_broker_tool_limit_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stacklok/mecatl/engine/session" +) + +// TestIdentityBrokerNamedHelperGetsItsDefinitionsGatewayTools runs subagents +// that run named definitions through mecak8s's startup, the real AS-1 and +// AS-2, and the embedded vMCP (#2842). One referencing the gateway's server +// calls its tool under its own identity; one that excludes the tool by name +// and one that references no server do not get it, so they never reach the +// gateway, matching the ceilings the broker resolved for them. Its stand-ins +// are listed on TestIdentityBrokerGatewayCallAgainstRealAS1. +func TestIdentityBrokerNamedHelperGetsItsDefinitionsGatewayTools(t *testing.T) { + agents := t.TempDir() + for name, frontmatter := range map[string]string{ + "calendar-reader": "mcpServers: [calendar]\n", + "no-echo": "mcpServers: [calendar]\ndisallowedTools: [mcp__calendar__echo]\n", + "no-servers": "", + } { + content := "---\nname: " + name + "\ndescription: A " + name + " specialist.\n" + frontmatter + "---\nYou help.\n" + if err := os.WriteFile(filepath.Join(agents, name+".md"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + d := serveDelegations(t, "--agents-dir", agents) + subagent := func(id, agent string) string { + return `{"tool_calls":[{"id":"` + id + `","name":"Subagent","args":{"prompt":"call the calendar","agent":"` + agent + `"}}]}` + } + // Each child calls the tool, then answers; the main agent starts the + // next child. + d.writeScript(t, gatewayTurn("main-call"), + subagent("reader", "calendar-reader"), gatewayTurn("reader-call"), scriptText, + subagent("excluded", "no-echo"), gatewayTurn("excluded-call"), scriptText, + subagent("serverless", "no-servers"), gatewayTurn("serverless-call"), scriptText) + promptApprovingAsks(t, d.api, d.alice, d.session, "go", nil) + + // Only the main agent's and the calendar reader's calls reached the + // gateway, the reader's under its own identity. + d.wantHelperGatewayCalls(t, 1) + if ops := d.diag.operations(d.session); len(ops) != 2 { + t.Fatalf("%d gateway calls, want the main agent's and the calendar reader's", len(ops)) + } + result := func(id session.SessionID, call session.ToolCallID) session.ToolResult { + t.Helper() + return d.toolResult(t, id, call) + } + for delegate, call := range map[session.ToolCallID]session.ToolCallID{"excluded": "excluded-call", "serverless": "serverless-call"} { + // The parent's Subagent result names the child's session. + _, child, ok := strings.Cut(result(session.SessionID(d.session), delegate).Content, "agentId: ") + if !ok { + t.Fatalf("the %s Subagent result names no child session", delegate) + } + child, _, _ = strings.Cut(child, "\n") + if res := result(session.SessionID(child), call); !res.IsError { + t.Fatalf("%s's gateway tool call = %+v, want an error for a tool missing from its catalog", delegate, res) + } + } +} + +// TestIdentityBrokerNamedTeamMemberGetsItsDefinitionsGatewayTools pins the +// same for a team member that runs a named definition: one referencing the +// gateway's server calls its tool under its own identity; one that excludes +// the tool never reaches the gateway. +func TestIdentityBrokerNamedTeamMemberGetsItsDefinitionsGatewayTools(t *testing.T) { + agents := t.TempDir() + for name, frontmatter := range map[string]string{ + "calendar-reader": "mcpServers: [calendar]\n", + "no-echo": "mcpServers: [calendar]\ndisallowedTools: [mcp__calendar__echo]\n", + } { + content := "---\nname: " + name + "\ndescription: A " + name + " specialist.\n" + frontmatter + "---\nYou help.\n" + if err := os.WriteFile(filepath.Join(agents, name+".md"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + team := func(agent string) string { + return `{"tool_calls":[{"id":"team","name":"Team","args":{"goal":"call the calendar","members":[{"name":"member","role":"call","agent":"` + agent + `"}]}}]}` + } + + t.Run("referencing the server", func(t *testing.T) { + d := serveDelegations(t, "--agents-dir", agents) + d.writeScript(t, gatewayTurn("main-call"), team("calendar-reader"), gatewayTurn("member-call"), scriptText) + promptApprovingAsks(t, d.api, d.alice, d.session, "go", nil) + d.wantHelperGatewayCalls(t, 1) + }) + + t.Run("excluding the tool", func(t *testing.T) { + d := serveDelegations(t, "--agents-dir", agents) + d.writeScript(t, gatewayTurn("main-call"), team("no-echo"), gatewayTurn("member-call"), scriptText) + promptApprovingAsks(t, d.api, d.alice, d.session, "go", nil) + if ops := d.diag.operations(d.session); len(ops) != 1 { + t.Fatalf("%d gateway calls, want only the main agent's", len(ops)) + } + }) +} diff --git a/docs/drafts/agent-identity/mcp-authorization.md b/docs/drafts/agent-identity/mcp-authorization.md index e5a434d1ff..a358e68142 100644 --- a/docs/drafts/agent-identity/mcp-authorization.md +++ b/docs/drafts/agent-identity/mcp-authorization.md @@ -8,6 +8,8 @@ The broker authorizes each protected MCP call and issues the gateway access toke Trusted definition admission resolves the existing `Tools`, `DisallowedTools`, and `MCPServers` semantics against registered MCP servers and their tools into permitted server/tool pairs. Resolution must preserve existing selection and exclusion semantics, including defaults, rather than interpreting a raw tool list as grants. A tool name alone cannot identify an authorized pair across servers. Unresolved or ambiguous references cannot grant access. +Registered MCP servers are the servers the gateway routes, from the operator's MCP configuration. A server that `MCPServers` references resolves to all of its tools except those `DisallowedTools` names, kept as one server-wide entry that each call's exact server and tool are checked against. `Tools` selects no MCP tools in the harness, so it grants none. An inline server, or a reference to a server the gateway does not route, grants nothing. Built-in definitions name every registered server. Resolution needs no tool list: listing a server's tools needs a user's grant, and the list can differ per user. + Cedar policies are generated deterministically from that resolved ceiling and tied to the fixed admitted definition source and revision. The same admitted inputs produce the same ceiling and generated policy revision. Generation uses structured definition facts, never an LLM or inferred intent from `Body`, descriptions, skills, or other prose. Retain the resolution inputs and generated policy revision so that the decision can be explained after the source changes. Each call is evaluated against the acting instance's effective ceiling, defined under [delegated authority](#delegated-authority). Representation, including the Cedar schema and entity/action/resource layout, is left to the implementer. After authenticating the instance, the broker obtains its definition, stored effective ceiling, and policy association from trusted registration records. Caller-supplied definition names, revisions, policy identifiers, or tool lists cannot select a more privileged ceiling. The main instance also needs an explicit resolved ceiling; `main`, `system`, or a root identity grants no name-based privilege. diff --git a/internal/adapter/mcpbroker/runtime.go b/internal/adapter/mcpbroker/runtime.go index f24ed1316a..a93e992c45 100644 --- a/internal/adapter/mcpbroker/runtime.go +++ b/internal/adapter/mcpbroker/runtime.go @@ -656,6 +656,9 @@ func (t *sessionTool) HelperGatewayTool() (tool.Tool, bool) { return t, true } +// GatewayServer names the gateway server t's calls are routed to. +func (t *sessionTool) GatewayServer() string { return t.route.backend } + func (t *sessionTool) Spec() tool.ToolSpec { return copySpec(t.route.spec) } func (t *sessionTool) ReadOnly() bool { return t.route.readOnly } diff --git a/internal/app/agentdef_root.go b/internal/app/agentdef_root.go index 39b8bd6b89..0f531ef24c 100644 --- a/internal/app/agentdef_root.go +++ b/internal/app/agentdef_root.go @@ -73,7 +73,7 @@ func buildAgentDefRootEngine( // resolveAgentMemoryHead's docs. model := providerModel.ModelID cat, pc, hooks, mcpClose, _, resources, _ := resolvedAgentDefCatalog( - ctx, cfg, def, source, model, base, true /*allowMutating*/, allowShell, skillIdx, defaultHooks, runner, mainMgr, sessionRoot) + ctx, cfg, def, source, model, base, true /*allowMutating*/, allowShell, skillIdx, defaultHooks, runner, mainMgr, sessionRoot, nil) deps := engineDepsForProvider(cfg, provider, providerModel, windowFn, store, policy, hooks, mcpProvider, instructions) deps.Catalog = cat diff --git a/internal/app/agentdefs.go b/internal/app/agentdefs.go index c3d65ed761..0aa3367151 100644 --- a/internal/app/agentdefs.go +++ b/internal/app/agentdefs.go @@ -588,6 +588,38 @@ func shellScopeMissReason(cfg Config) string { } } +// gatewayServerTool is a gateway tool that names the gateway server its calls +// are routed to. +type gatewayServerTool interface { + GatewayServer() string +} + +// defGatewayTools returns the gateway tools in helperTools, a session's, that +// a helper running def gets (#2842): those of each server def's mcpServers +// names by reference, minus each tool its disallowedTools names. The identity +// broker resolves def's ceiling to the same servers and tools +// (definitionloader.resolveCeiling) and refuses any other call, so this keeps +// the helper's catalog to what it may call. +// +// Shortcut: the harness resolves the definition's gateway tools again rather than reading the ceiling the broker recorded; removed by #2548 (the harness builds agents from the broker's records). +func defGatewayTools(def agents.AgentDef, helperTools []tool.Tool) []tool.Tool { + referenced := map[string]bool{} + for _, e := range def.MCPServers { + if e.IsReference() { + referenced[strings.TrimSpace(e.Name)] = true + } + } + var out []tool.Tool + for _, t := range helperTools { + g, ok := t.(gatewayServerTool) + if !ok || !referenced[g.GatewayServer()] || defDisallowsTool(def, t.Spec().Name) { + continue + } + out = append(out, t) + } + return out +} + // defDisallowsTool reports whether def explicitly excludes the named tool. It is // the one exclusion test shared by name scoping's callers for tools registered // after scoping (MCP tools and the automatic ShellStatus companion). @@ -1089,7 +1121,7 @@ func buildAgentDefEngine(ctx context.Context, cfg Config, def agents.AgentDef, r // A Subagent-delegate child has no placement of its own distinct from its // parent's, so "project" memory binds to cfg.Workspace — unchanged from // pre-ADR-0353 behavior (see resolveAgentMemoryHead's sessionRoot docs). - cat, pc, hooks, mcpClose, names, resourceCapabilities, skillCount := resolvedAgentDefCatalog(ctx, cfg, def, source, model, base, allowMutating, allowShell, skillIdx, defaultHooks, runner, mainMgr, cfg.Workspace) + cat, pc, hooks, mcpClose, names, resourceCapabilities, skillCount := resolvedAgentDefCatalog(ctx, cfg, def, source, model, base, allowMutating, allowShell, skillIdx, defaultHooks, runner, mainMgr, cfg.Workspace, defGatewayTools(def, cfg.helperTools)) // ProgressiveTools deliberately OFF: child catalogs are tiny and a ToolSearch // tool would not be in the def allowlist. newChildEngineForProvider leaves it at // its zero value (off), matching the original explicit omission, AND routes the @@ -1120,7 +1152,11 @@ func buildAgentDefEngine(ctx context.Context, cfg Config, def agents.AgentDef, r // sessionRoot is threaded straight through to resolveAgentMemoryHead (see its // docs): a Subagent-delegate caller passes cfg.Workspace, a session-root // caller passes THIS session's own bound placement root. -func resolvedAgentDefCatalog(ctx context.Context, cfg Config, def agents.AgentDef, source, model string, base map[string]tool.Tool, allowMutating, allowShell bool, skillIdx skillIndex, defaultHooks port.HookRunner, runner tool.CommandRunner, mainMgr *mcp.Manager, sessionRoot string) (cat *tool.Catalog, pc prompt.Config, hooks port.HookRunner, mcpClose func() error, names []string, resourceCapabilities []string, skillCount int) { +// +// gatewayTools are the identity broker gateway tools a helper running def +// gets (defGatewayTools); a session root passes none, since a session bound +// to a named agent definition does not attach to the MCP broker. +func resolvedAgentDefCatalog(ctx context.Context, cfg Config, def agents.AgentDef, source, model string, base map[string]tool.Tool, allowMutating, allowShell bool, skillIdx skillIndex, defaultHooks port.HookRunner, runner tool.CommandRunner, mainMgr *mcp.Manager, sessionRoot string, gatewayTools []tool.Tool) (cat *tool.Catalog, pc prompt.Config, hooks port.HookRunner, mcpClose func() error, names []string, resourceCapabilities []string, skillCount int) { var diags []scopeDiag names, diags = scopedToolNamesMode(def, base, allowMutating, allowShell, shellScopeMissReason(cfg)) for _, d := range diags { @@ -1177,6 +1213,7 @@ func resolvedAgentDefCatalog(ctx context.Context, cfg Config, def agents.AgentDe } names = append(names, mt.Spec().Name) } + names = append(names, registerHelperTools(classified, gatewayTools, cfg.diag())...) mustValidateClassifiedCatalog(classified, "specialist agent tool catalog", mcpClose) bodies, missing := preloadedSkillBodies(def, skillIdx) diff --git a/internal/app/build.go b/internal/app/build.go index 2e0b8b21db..1da834ae1e 100644 --- a/internal/app/build.go +++ b/internal/app/build.go @@ -694,11 +694,11 @@ type Config struct { // delegation engines. Internal-purpose classifier/reviewer/judge engines clear it. operatorProfileSource prompt.OperatorProfileSource // helperTools are the identity broker gateway tools of the session whose - // catalog is being assembled, which its def-less helper agents (the - // default and writable explorers, parallel branches, and generic team - // members) also get (#2555). Empty outside such a per-session catalog. - // - // Shortcut: helpers that run a named definition get no gateway tools, since their definition decides their tools; removed by #2842. + // catalog is being assembled. Its def-less helper agents (the default and + // writable explorers, parallel branches, and generic team members) get + // them all (#2555); a helper that runs a named definition gets those of + // the servers its definition references (defGatewayTools, #2842). Empty + // outside such a per-session catalog. helperTools []tool.Tool // enableDurableEvidence is derived from the actual EventLog selected by Build. // Every user-facing engine inherits it; Sink is deliberately not a proxy. @@ -8646,6 +8646,9 @@ func buildMemberSelectorEngine(cfg Config, provReg *providerRegistry, provider p "member", spec.Name, "agent", def.Name, "tool", mt.Spec().Name, "err", err) } } + // Gateway tools, like the def's own MCP tools, touch only the remote + // server, so the read-only-member backstop exempts them too. + names2 = append(names2, registerHelperTools(classified, defGatewayTools(def, cfg.helperTools), cfg.diag())...) mcpClose, mcpNames = cl, names2 memberLimits = defLimits(def, session.Limits{}) // only def-set fields; AddMember merges with the team default // Resolve the def's (provider, model, window) via the SHARED helper: a diff --git a/internal/app/defgatewaytools_test.go b/internal/app/defgatewaytools_test.go new file mode 100644 index 0000000000..081cbce3c6 --- /dev/null +++ b/internal/app/defgatewaytools_test.go @@ -0,0 +1,96 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" + + agents "github.com/stacklok/mecatl/engine/adapter/agentfs" + "github.com/stacklok/mecatl/engine/session" + "github.com/stacklok/mecatl/engine/tool" + "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/adapter/definitionloader" +) + +// fakeGatewayTool is a session gateway tool of server, named as the harness +// names it. +type fakeGatewayTool struct{ server, name string } + +func (f fakeGatewayTool) Spec() tool.ToolSpec { + return tool.ToolSpec{Name: "mcp__" + f.server + "__" + f.name} +} +func (fakeGatewayTool) ReadOnly() bool { return true } +func (fakeGatewayTool) Execute(context.Context, session.ToolCall, tool.Environment) (session.ToolResult, error) { + return session.ToolResult{}, nil +} +func (f fakeGatewayTool) GatewayServer() string { return f.server } + +// TestDefGatewayToolsAgreesWithTheBrokersCeiling is the design's cross-check +// between the harness and the broker: for each definition, the gateway tools +// the harness gives a helper running it (defGatewayTools) are exactly the +// tools the broker's loader resolves its ceiling to allow. The two read the +// same files with their own parsers, so a change to either side's rule that +// the other does not follow fails here. +func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { + definitions := map[string]string{ + "one-server": "mcpServers: [calendar]\n", + "two-excluded": "mcpServers: [calendar, github]\ndisallowedTools: [mcp__calendar__echo, mcp__github__merge, Write]\n", + "inline": "mcpServers:\n - name: calendar\n url: https://inline.example.com/mcp\n", + "unrouted": "mcpServers: [jira]\n", + "tools-only": "tools: [mcp__calendar__echo]\n", + "no-servers": "", + "other-excluded": "mcpServers: [calendar]\ndisallowedTools: [mcp__github__read]\n", + } + dir := t.TempDir() + for name, frontmatter := range definitions { + content := "---\nname: " + name + "\ndescription: A " + name + " specialist.\n" + frontmatter + "---\nYou help.\n" + if err := os.WriteFile(filepath.Join(dir, name+".md"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + servers := []string{"calendar", "github"} + sessionTools := []tool.Tool{ + fakeGatewayTool{"calendar", "echo"}, fakeGatewayTool{"calendar", "lookup"}, + fakeGatewayTool{"github", "merge"}, fakeGatewayTool{"github", "read"}, + } + + records, _, err := definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{dir}, Servers: servers}) + if err != nil { + t.Fatal(err) + } + ceilings := map[string]identitybroker.Ceiling{} + for _, r := range records { + if r.Ref.Source == identitybroker.SourceGlobal { + ceilings[r.Ref.Name] = r.Ceiling + } + } + discovered, skipped, err := agents.DirSource{Dir: dir}.Agents(t.Context()) + if err != nil || len(skipped) != 0 { + t.Fatalf("harness discovery: %v, skipped %v", err, skipped) + } + if len(discovered) != len(definitions) || len(ceilings) != len(definitions) { + t.Fatalf("the harness found %d definitions and the broker %d, want %d each", len(discovered), len(ceilings), len(definitions)) + } + for _, d := range discovered { + var harness []string + for _, gt := range defGatewayTools(d.Def, sessionTools) { + harness = append(harness, gt.Spec().Name) + } + var broker []string + for _, grant := range ceilings[d.Def.Name].Servers() { + for _, st := range sessionTools { + ft := st.(fakeGatewayTool) + if ft.server == grant.Server && !slices.Contains(grant.ExceptTools, ft.name) { + broker = append(broker, ft.Spec().Name) + } + } + } + slices.Sort(harness) + slices.Sort(broker) + if !slices.Equal(harness, broker) { + t.Errorf("%s: the harness gives %v, the broker allows %v", d.Def.Name, harness, broker) + } + } +} diff --git a/internal/app/identitybroker.go b/internal/app/identitybroker.go index 9e8cabde65..e6fdf31cca 100644 --- a/internal/app/identitybroker.go +++ b/internal/app/identitybroker.go @@ -275,8 +275,9 @@ func buildIdentityBroker(ctx context.Context, cfg Config, target *gatewayIDJAGTa } else { // An injected core is a test's; the server still sends the references // of the definitions this configuration loads, as it does for the - // real broker. - definitions, err := loadIdentityBrokerDefinitions(ctx, cfg) + // real broker. Only the references are used, so no ceiling is + // resolved. + definitions, err := loadIdentityBrokerDefinitions(ctx, cfg, nil) if err != nil { return identityBrokerParts{}, fmt.Errorf("build identity broker: %w", err) } @@ -479,7 +480,17 @@ func identityBrokerConfig(cfg Config) identitybroker.Config { // it again at each build. func newIdentityBroker(ctx context.Context, cfg Config) (identityBroker, error) { config := identityBrokerConfig(cfg) - definitions, err := loadIdentityBrokerDefinitions(ctx, cfg) + as1 := cfg.IdentityBrokerAS1 + // A gateway needs AS-1 to issue its ID-JAGs, so without an AS-1 there is + // none. + // Shortcut: production configures no gateway entry, so gateway calls are refused as not configured; removed by #2533 (AS-2 trusts AS-1 in production, gateway from configuration). + var gatewayServers []string + if as1 != nil { + gatewayServers = slices.Clone(cfg.IdentityBrokerGatewayServers) + } + // Each definition's ceiling is resolved against the servers the gateway + // routes. + definitions, err := loadIdentityBrokerDefinitions(ctx, cfg, gatewayServers) if err != nil { return identityBroker{}, err } @@ -487,7 +498,6 @@ func newIdentityBroker(ctx context.Context, cfg Config) (identityBroker, error) if err != nil { return identityBroker{}, fmt.Errorf("generate signing key: %w", err) } - as1 := cfg.IdentityBrokerAS1 var clientKey *ecdsa.PrivateKey if as1 != nil { clientKey = as1.ClientKey @@ -504,8 +514,6 @@ func newIdentityBroker(ctx context.Context, cfg Config) (identityBroker, error) // Records are kept in memory (the shortcut on identitybroker.MemoryRecorder). recorder := identitybroker.NewMemoryRecorder() opts := []identitybroker.Option{identitybroker.WithRecorder(recorder)} - gateway := false - var gatewayServers []string if as1 != nil { as1Client, err := authserverclient.New(authserverclient.Config{ Issuer: as1.Issuer, TokenEndpoint: as1.TokenEndpoint, Assertions: client, HTTPClient: as1.HTTPClient, Now: as1.AssertionNow, @@ -517,12 +525,8 @@ func newIdentityBroker(ctx context.Context, cfg Config) (identityBroker, error) if as1.Now != nil { opts = append(opts, identitybroker.WithClock(as1.Now)) } - // A gateway needs AS-1 to issue its ID-JAGs, so without an AS-1 there - // is none. - // Shortcut: production configures no gateway entry, so gateway calls are refused as not configured; removed by #2533 (AS-2 trusts AS-1 in production, gateway from configuration). - if cfg.IdentityBrokerGatewayServers != nil { - opts = append(opts, identitybroker.WithGateway(identitybroker.Gateway{Servers: cfg.IdentityBrokerGatewayServers})) - gateway, gatewayServers = true, append([]string(nil), cfg.IdentityBrokerGatewayServers...) + if gatewayServers != nil { + opts = append(opts, identitybroker.WithGateway(identitybroker.Gateway{Servers: gatewayServers})) } } core, err := identitybroker.New(config, definitions, key, opts...) @@ -534,15 +538,16 @@ func newIdentityBroker(ctx context.Context, cfg Config) (identityBroker, error) return identityBroker{}, fmt.Errorf("bind AS-1's actor-token check: %w", err) } } - return identityBroker{core: core, definitions: definitions, client: client, recorder: recorder, gateway: gateway, gatewayServers: gatewayServers}, nil + return identityBroker{core: core, definitions: definitions, client: client, recorder: recorder, gateway: gatewayServers != nil, gatewayServers: gatewayServers}, nil } // loadIdentityBrokerDefinitions loads the identity broker's definition // records: the built-ins of this build and the global definitions in -// cfg.AgentsDirs. A definition left out or adjusted is logged, without its -// contents; a directory that cannot be read fails the load. -func loadIdentityBrokerDefinitions(ctx context.Context, cfg Config) ([]identitybroker.DefinitionRecord, error) { - records, problems, err := definitionloader.Load(ctx, definitionloader.Config{Dirs: cfg.AgentsDirs, BuildID: buildinfo.BuildID}) +// cfg.AgentsDirs, with ceilings resolved against gatewayServers. A definition +// left out or adjusted is logged, without its contents; a directory that +// cannot be read fails the load. +func loadIdentityBrokerDefinitions(ctx context.Context, cfg Config, gatewayServers []string) ([]identitybroker.DefinitionRecord, error) { + records, problems, err := definitionloader.Load(ctx, definitionloader.Config{Dirs: cfg.AgentsDirs, BuildID: buildinfo.BuildID, Servers: gatewayServers}) for _, p := range problems { outcome := "definition adjusted and loaded" if p.Dropped { diff --git a/internal/app/session_scoped_agent_identity_scenario1_test.go b/internal/app/session_scoped_agent_identity_scenario1_test.go index 32276ab742..72cb654974 100644 --- a/internal/app/session_scoped_agent_identity_scenario1_test.go +++ b/internal/app/session_scoped_agent_identity_scenario1_test.go @@ -93,7 +93,7 @@ func TestSessionScopedAgentIdentity_Scenario1_ResolvedCatalog(t *testing.T) { tc.def.MCPServers[0].URL = newMCPTestServer(t) } cat, _, _, mcpClose, _, _, _ := resolvedAgentDefCatalog(context.Background(), cfg, tc.def, "test", - "model-x", tc.base, true /*allowMutating*/, false /*allowShell*/, nil, hookexec.New(nil), nil, nil, cfg.Workspace) + "model-x", tc.base, true /*allowMutating*/, false /*allowShell*/, nil, hookexec.New(nil), nil, nil, cfg.Workspace, nil) if mcpClose != nil { t.Cleanup(func() { _ = mcpClose() }) } diff --git a/internal/identitybroker/adapter/definitionloader/loader.go b/internal/identitybroker/adapter/definitionloader/loader.go index bf1f43e83a..98a2c46153 100644 --- a/internal/identitybroker/adapter/definitionloader/loader.go +++ b/internal/identitybroker/adapter/definitionloader/loader.go @@ -119,6 +119,10 @@ type Config struct { // BuildID is the Mecatl build stamp (buildinfo.BuildID); see // BuiltinRevision. BuildID string + // Servers are the gateway servers, by name: the registered MCP servers + // each definition's ceiling is resolved against (see resolveCeiling). + // With none, every ceiling allows no call. + Servers []string } // Problem reports one definition that was left out or adjusted while loading. @@ -160,8 +164,9 @@ func Load(ctx context.Context, cfg Config) ([]identitybroker.DefinitionRecord, [ problems []Problem ) revision := BuiltinRevision(cfg.BuildID) + servers := serverSet(cfg.Servers) for _, def := range builtins() { - rec, err := builtinRecord(def, revision) + rec, err := builtinRecord(def, revision, servers) if err != nil { // The built-ins are fixed; a failure here is a programming error // that every test run would catch. @@ -197,7 +202,7 @@ func Load(ctx context.Context, cfg Config) ([]identitybroker.DefinitionRecord, [ // runs this file's definition under the name, so the broker must // not record a later file's definition for it. kept[f.def.Name] = f.path - rec, err := globalRecord(f) + rec, err := globalRecord(f, servers) if err != nil { problems = append(problems, Problem{Location: f.path, Reason: err.Error(), Dropped: true}) continue @@ -281,7 +286,7 @@ func readFile(path string) ([]byte, time.Time, error) { return content, info.ModTime(), nil } -func builtinRecord(def agentdef.Definition, revision string) (identitybroker.DefinitionRecord, error) { +func builtinRecord(def agentdef.Definition, revision string, servers map[string]bool) (identitybroker.DefinitionRecord, error) { digest, err := definitionDigest(def) if err != nil { return identitybroker.DefinitionRecord{}, err @@ -296,6 +301,7 @@ func builtinRecord(def agentdef.Definition, revision string) (identitybroker.Def SourceDigest: digest, DefinitionDigest: digest, }, + Ceiling: builtinCeiling(servers), } return rec, rec.Validate() } @@ -304,7 +310,7 @@ func builtinRecord(def agentdef.Definition, revision string) (identitybroker.Def // SourceDigest covers the bytes read; its DefinitionDigest covers the // definition (agentdef.Digest), so reformatting the file changes only // SourceDigest. -func globalRecord(f file) (identitybroker.DefinitionRecord, error) { +func globalRecord(f file, servers map[string]bool) (identitybroker.DefinitionRecord, error) { // The YAML parser reads an invalid byte in the frontmatter as U+FFFD, so // two different files could parse to one definition. The parser itself // accepts them, as the harness's copy does, so the whole file is checked @@ -328,10 +334,61 @@ func globalRecord(f file) (identitybroker.DefinitionRecord, error) { SourceDigest: sha256Digest(f.content), DefinitionDigest: digest, }, + Ceiling: resolveCeiling(f.def, servers), } return rec, rec.Validate() } +// serverSet returns the non-blank names in servers as a set. +func serverSet(servers []string) map[string]bool { + set := make(map[string]bool, len(servers)) + for _, s := range servers { + if s = strings.TrimSpace(s); s != "" { + set[s] = true + } + } + return set +} + +// builtinCeiling is a built-in definition's ceiling: every gateway server, +// whole. The main agent of a session started without a named definition +// calls any of them, as the main conversation does; a built-in helper's +// parent's ceiling narrows it at registration. +func builtinCeiling(servers map[string]bool) identitybroker.Ceiling { + grants := make([]identitybroker.CeilingServer, 0, len(servers)) + for s := range servers { + grants = append(grants, identitybroker.CeilingServer{Server: s}) + } + return identitybroker.NewCeiling(grants...) +} + +// resolveCeiling resolves a global definition's ceiling against the gateway +// servers, with the harness's meaning (internal/app/agentdefs.go): each +// server the definition's mcpServers names by reference is granted with all +// its tools, except each tool its disallowedTools names by its catalog name, +// mcp____. tools cannot select MCP tools in the harness, so it +// grants none here. An inline server, or a reference to a server the gateway +// does not route, grants nothing. A disallowed name is matched against every +// granted server, so one that could belong to two servers is excluded from +// both: an exclusion only ever narrows. +func resolveCeiling(def agentdef.Definition, servers map[string]bool) identitybroker.Ceiling { + var grants []identitybroker.CeilingServer + for _, ref := range def.MCPServers { + name := strings.TrimSpace(ref.Name) + if !ref.IsReference() || !servers[name] { + continue + } + grant := identitybroker.CeilingServer{Server: name} + for _, disallowed := range def.DisallowedTools { + if tool, ok := strings.CutPrefix(disallowed, "mcp__"+name+"__"); ok { + grant.ExceptTools = append(grant.ExceptTools, tool) + } + } + grants = append(grants, grant) + } + return identitybroker.NewCeiling(grants...) +} + // definitionDigest returns the agentdef digest of d as a broker digest. func definitionDigest(d agentdef.Definition) (identitybroker.Digest, error) { value, err := agentdef.Digest(d) diff --git a/internal/identitybroker/adapter/definitionloader/loader_test.go b/internal/identitybroker/adapter/definitionloader/loader_test.go index 528af7f8b2..52d33ee836 100644 --- a/internal/identitybroker/adapter/definitionloader/loader_test.go +++ b/internal/identitybroker/adapter/definitionloader/loader_test.go @@ -592,3 +592,50 @@ func digestOf(s string) identitybroker.Digest { func sha256Value(v string) identitybroker.Digest { return identitybroker.Digest{Algorithm: identitybroker.DigestSHA256, Value: v} } + +// TestLoadResolvesCeilings pins how a definition's ceiling is resolved +// against the gateway servers: every built-in gets every server whole; a +// global definition gets each server it references that the gateway routes, +// minus the tools its disallowedTools names by catalog name; an inline +// server, an unrouted reference, and tools, even naming a routed server's +// tool, grant nothing. +func TestLoadResolvesCeilings(t *testing.T) { + dir := t.TempDir() + writeDef(t, dir, "reviewer.md", "---\nname: reviewer\ndescription: Reviews\n"+ + "tools: [mcp__calendar__lookup, mcp__slack__post]\n"+ + "disallowedTools: [mcp__github__merge_pr, mcp__github__delete_repo, mcp__calendar__unused, Write]\n"+ + "mcpServers:\n - github\n - jira\n - name: inline\n url: https://inline.example.com/mcp\n---\n") + writeDef(t, dir, "plain.md", "---\nname: plain\ndescription: No servers\n---\n") + records, _, err := definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{dir}, Servers: []string{"github", "calendar", "inline", " "}}) + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, r := range records { + got[r.Ref.Source+"/"+r.Ref.Name] = r.Ceiling.String() + } + want := map[string]string{ + "system/main": "calendar; github; inline", + "system/explorer": "calendar; github; inline", + "system/branch": "calendar; github; inline", + "system/member": "calendar; github; inline", + "global/reviewer": "github except delete_repo,merge_pr", + "global/plain": "none", + } + for name, ceiling := range want { + if got[name] != ceiling { + t.Errorf("%s ceiling = %q, want %q", name, got[name], ceiling) + } + } + + // With no gateway servers, every ceiling allows nothing. + records, _, err = definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{dir}}) + if err != nil { + t.Fatal(err) + } + for _, r := range records { + if c := r.Ceiling.String(); c != "none" { + t.Errorf("%s ceiling with no gateway servers = %q, want none", r.Ref.Name, c) + } + } +} diff --git a/internal/identitybroker/agents.go b/internal/identitybroker/agents.go index 1f68ac40c5..1d37b61545 100644 --- a/internal/identitybroker/agents.go +++ b/internal/identitybroker/agents.go @@ -23,6 +23,10 @@ type agentRecord struct { incarnation string definition DefinitionRef parent AgentRef + // ceiling is the instance's effective ceiling: its definition's, narrowed + // by its parent's effective ceiling, computed when the instance first + // registers and never recomputed or widened. + ceiling Ceiling // credentials holds the credentials issued since the instance last moved // to another broker session, by SHA-256 of the token, with their expiry; // at most maxIssuedCredentials. Only these verify, so reopening a session @@ -141,14 +145,27 @@ func (b *Broker) recordRegistration(workload Workload, req RegisterAgentRequest, return Registration{}, true, nil } } - t.recordLocked(identity, s.ID, req, credential, expiresAt) + t.recordLocked(identity, s.ID, req, b.effectiveCeilingLocked(req), credential, expiresAt) return Registration{Agent: AgentRef{Subject: identity.subject}, Credential: credential, ExpiresAt: expiresAt}, false, nil } +// effectiveCeilingLocked returns the effective ceiling of a new instance +// registering with req: its definition's ceiling, intersected with its +// parent's effective ceiling when it has a parent. The caller holds t.mu and +// has checked req, so the definition is loaded and the parent registered. +func (b *Broker) effectiveCeilingLocked(req RegisterAgentRequest) Ceiling { + ceiling := b.definitions[req.Definition].Ceiling + if req.Parent.IsZero() { + return ceiling + } + return ceiling.intersect(b.sessions.agents[req.Parent.Subject].ceiling) +} + // recordLocked records a registration of identity in session sessionID, with -// the credential just issued, which always verifies afterwards. The caller -// holds t.mu. -func (t *sessionTable) recordLocked(identity agentIdentity, sessionID string, req RegisterAgentRequest, credential Token, expiresAt time.Time) { +// the credential just issued, which always verifies afterwards. A new +// instance gets ceiling as its effective ceiling; one registered before +// keeps its own. The caller holds t.mu. +func (t *sessionTable) recordLocked(identity agentIdentity, sessionID string, req RegisterAgentRequest, ceiling Ceiling, credential Token, expiresAt time.Time) { rec, ok := t.agents[identity.subject] switch { case !ok: @@ -159,6 +176,7 @@ func (t *sessionTable) recordLocked(identity agentIdentity, sessionID string, re incarnation: req.Incarnation, definition: req.Definition, parent: req.Parent, + ceiling: ceiling, } t.agents[identity.subject] = rec t.incarnations[req.Incarnation] = identity.subject diff --git a/internal/identitybroker/authorize.go b/internal/identitybroker/authorize.go index 24fda19334..c98cae8ec1 100644 --- a/internal/identitybroker/authorize.go +++ b/internal/identitybroker/authorize.go @@ -54,14 +54,23 @@ func (b *Broker) AuthorizeCall(ctx context.Context, workload Workload, req Autho return Authorization{}, b.refuse(ctx, rec, err) } - // Shortcut: step (6) check 7 (ceiling) accepts its input; removed by the authority work (docs/drafts/agent-identity/README.md, "Order of work"). - // 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")) } + // Check 7: the agent's stored effective ceiling allows the exact server + // and tool. + t.mu.Lock() + ceiling := t.agents[agent.Agent.Subject].ceiling + t.mu.Unlock() + rec.Ceiling = ceiling.String() + // Validate checked that a call's tool is named for its server. + if err := checkCeiling(ceiling, req.Method, req.Server, strings.TrimPrefix(req.Tool, req.Server+".")); err != nil { + return Authorization{}, b.refuse(ctx, rec, err) + } + // AS-2 may not be bound yet (the #2560 shortcut on BindGatewayAS2). as2, release, ok := b.acquireAS2() if !ok { diff --git a/internal/identitybroker/authorize_checks_test.go b/internal/identitybroker/authorize_checks_test.go index e82534a543..14ea8780fd 100644 --- a/internal/identitybroker/authorize_checks_test.go +++ b/internal/identitybroker/authorize_checks_test.go @@ -74,9 +74,14 @@ func TestNewRefusesAnInvalidGateway(t *testing.T) { } as2 := identitybroker.GatewayAS2{Issuer: "https://as2.example.com", Resource: "https://vmcp.example.com/mcp", AuthServer: &fakeAS2{}} for name, g := range map[string]identitybroker.Gateway{ - "no servers": {}, - "an empty server": {Servers: []string{""}}, - "a spaced server": {Servers: []string{"git hub"}}, + "no servers": {}, + "an empty server": {Servers: []string{""}}, + "a spaced server": {Servers: []string{"git hub"}}, + // A dot or a double underscore would let one server's name begin + // another's in "." and "mcp____". + "a dotted server": {Servers: []string{"github", "github.ent"}}, + "a double underscore": {Servers: []string{"github__ent"}}, + "a hyphenated server": {Servers: []string{"git-hub"}}, "a repeat": {Servers: []string{"github", "calendar", "github"}}, "an AS-2 issuer only": {Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer}}, "an AS-2 without a port": {Servers: []string{"github"}, AS2: identitybroker.GatewayAS2{Issuer: as2.Issuer, Resource: as2.Resource}}, @@ -141,7 +146,7 @@ func TestAuthorizeCallRefusesAnInvalidCredential(t *testing.T) { f := openGranted(t, gateway, identitybroker.WithRecorder(rec)) *f.clock = f.clock.Add(6 * time.Minute) req := callRequest(f.s.ID, f.cred) - req.Server = "calendar" + req.Server, req.Tool = "calendar", "calendar.pull_request_read" _, err := f.authorize(req) wantError(t, err, identitybroker.CodeUnauthenticated, identitybroker.ReasonSVIDExpired, f.cred) d := rec.Decisions() @@ -176,7 +181,7 @@ func TestAuthorizeCallUnroutedServerIsDenied(t *testing.T) { // A routed server passes check 6. req := callRequest(f.s.ID, f.cred) - req.Server = "calendar" + req.Server, req.Tool = "calendar", "calendar.pull_request_read" _, err = f.authorize(req) var e *identitybroker.Error if !errors.As(err, &e) || strings.Contains(e.Detail, "no gateway routes") { diff --git a/internal/identitybroker/authorize_test.go b/internal/identitybroker/authorize_test.go index 3f4af1dd7e..145a54885e 100644 --- a/internal/identitybroker/authorize_test.go +++ b/internal/identitybroker/authorize_test.go @@ -1212,7 +1212,11 @@ func TestAuthorizeCallRejectedTokenRetry(t *testing.T) { {"method", func(r *identitybroker.AuthorizeCallRequest) { r.Method, r.Tool, r.ArgumentsSHA256 = identitybroker.MethodToolsList, "", "" }}, - {"server", func(r *identitybroker.AuthorizeCallRequest) { r.Server = "calendar" }}, + // The tool keeps its server's name, so the call passes check 7 and + // reaches the rejected attempt. + {"server", func(r *identitybroker.AuthorizeCallRequest) { + r.Server, r.Tool = "calendar", "calendar.pull_request_read" + }}, {"tool", func(r *identitybroker.AuthorizeCallRequest) { r.Tool = "github.issue_write" }}, {"arguments hash", func(r *identitybroker.AuthorizeCallRequest) { r.ArgumentsSHA256 = strings.Repeat("cd", 32) }}, {"agent", func(r *identitybroker.AuthorizeCallRequest) { diff --git a/internal/identitybroker/broker.go b/internal/identitybroker/broker.go index 1d7f517bf4..a027ac2ec9 100644 --- a/internal/identitybroker/broker.go +++ b/internal/identitybroker/broker.go @@ -219,7 +219,7 @@ func snapshotDefinitions(records []DefinitionRecord) (map[DefinitionRef]Definiti } if existing, ok := snapshot[rec.Ref]; ok { if !existing.equal(rec) { - return nil, fmt.Errorf("%w: record %d repeats %+v with different provenance", ErrConflictingDefinition, i, rec.Ref) + return nil, fmt.Errorf("%w: record %d repeats %+v with different provenance or ceiling", ErrConflictingDefinition, i, rec.Ref) } continue } diff --git a/internal/identitybroker/ceiling.go b/internal/identitybroker/ceiling.go new file mode 100644 index 0000000000..b39bffe7a9 --- /dev/null +++ b/internal/identitybroker/ceiling.go @@ -0,0 +1,138 @@ +package identitybroker + +import ( + "fmt" + "maps" + "slices" + "strings" +) + +// Ceiling is the limit on an agent's gateway calls (design step (6), check +// 7): the gateway servers it may call, each with the tools on that server it +// may not. A server is granted whole, minus named tools, because a +// definition grants a server by naming it and excludes tools by name; the +// broker needs no server's tool list, which only a signed-in user can list +// and which can differ per user. +// +// A Ceiling is immutable once made, so it can be shared and compared. The +// zero Ceiling allows no call. +type Ceiling struct { + // servers maps each granted server to the tools on it that are excluded, + // by their name on the server. A nil set excludes nothing. + servers map[string]map[string]struct{} +} + +// CeilingServer is one server a ceiling grants and the tools on it the +// ceiling excludes, by their name on the server, such as "merge_pr" for the +// tool the gateway names "github.merge_pr". +type CeilingServer struct { + Server string + ExceptTools []string +} + +// NewCeiling returns the ceiling granting each of servers, minus its +// excluded tools. A server listed twice is granted once, with the union of +// its exclusions. Blank server and tool names are ignored. +func NewCeiling(servers ...CeilingServer) Ceiling { + c := Ceiling{servers: map[string]map[string]struct{}{}} + for _, s := range servers { + name := strings.TrimSpace(s.Server) + if name == "" { + continue + } + except := c.servers[name] + for _, tool := range s.ExceptTools { + if tool = strings.TrimSpace(tool); tool == "" { + continue + } + if except == nil { + except = map[string]struct{}{} + } + except[tool] = struct{}{} + } + c.servers[name] = except + } + return c +} + +// Servers returns the servers c grants, sorted, each with its excluded tools +// sorted. +func (c Ceiling) Servers() []CeilingServer { + out := make([]CeilingServer, 0, len(c.servers)) + for _, name := range slices.Sorted(maps.Keys(c.servers)) { + out = append(out, CeilingServer{Server: name, ExceptTools: slices.Sorted(maps.Keys(c.servers[name]))}) + } + return out +} + +// allowsServer reports whether c grants server at all. +func (c Ceiling) allowsServer(server string) bool { + _, ok := c.servers[server] + return ok +} + +// allows reports whether c allows a call of tool, by its name on server. +func (c Ceiling) allows(server, tool string) bool { + except, ok := c.servers[server] + if !ok { + return false + } + _, excluded := except[tool] + return !excluded +} + +// intersect returns the ceiling allowing exactly the calls both c and o +// allow: the servers both grant, each excluding what either excludes. +func (c Ceiling) intersect(o Ceiling) Ceiling { + out := Ceiling{servers: map[string]map[string]struct{}{}} + for name, except := range c.servers { + other, ok := o.servers[name] + if !ok { + continue + } + union := make(map[string]struct{}, len(except)+len(other)) + maps.Copy(union, except) + maps.Copy(union, other) + out.servers[name] = union + } + return out +} + +// equal reports whether c and o allow the same calls. +func (c Ceiling) equal(o Ceiling) bool { + return maps.EqualFunc(c.servers, o.servers, maps.Equal[map[string]struct{}]) +} + +// String is c in a canonical form for records: each granted server, sorted, +// followed by the tools it excludes, as in "calendar; github except +// delete_repo,merge_pr". It is "none" for a ceiling that grants nothing. +func (c Ceiling) String() string { + servers := c.Servers() + if len(servers) == 0 { + return "none" + } + parts := make([]string, len(servers)) + for i, s := range servers { + parts[i] = s.Server + if len(s.ExceptTools) > 0 { + parts[i] += " except " + strings.Join(s.ExceptTools, ",") + } + } + return strings.Join(parts, "; ") +} + +// checkCeiling is design step (6) check 7: the acting agent's stored +// effective ceiling allows the call's exact server and tool, by its name on +// the server, or, for a listing, the server. It is one function so generated +// Cedar policy (#2849) replaces only its body. +// +// Shortcut: the ceiling is a plain set check, not generated Cedar policy, and decision records name no policy revision; removed by #2849. +func checkCeiling(c Ceiling, method, server, tool string) error { + switch { + case method == MethodToolsList && c.allowsServer(server): + return nil + case method == MethodToolsCall && c.allows(server, tool): + return nil + } + return deniedError(fmt.Sprintf("the agent's tool limit (%s) does not allow the call", c)) +} diff --git a/internal/identitybroker/ceiling_internal_test.go b/internal/identitybroker/ceiling_internal_test.go new file mode 100644 index 0000000000..3939ec9d5a --- /dev/null +++ b/internal/identitybroker/ceiling_internal_test.go @@ -0,0 +1,91 @@ +package identitybroker + +import ( + "math/rand/v2" + "testing" +) + +func TestCeilingAllowsExactPairs(t *testing.T) { + c := NewCeiling(CeilingServer{Server: "github", ExceptTools: []string{"merge_pr"}}, CeilingServer{Server: "calendar"}) + for _, tc := range []struct { + server, tool string + want bool + }{ + {"github", "read_pr", true}, + {"github", "merge_pr", false}, + {"calendar", "merge_pr", true}, // the same tool name on another server is its own pair + {"slack", "read_pr", false}, // a server the ceiling does not grant + } { + if got := c.allows(tc.server, tc.tool); got != tc.want { + t.Errorf("allows(%q, %q) = %v, want %v", tc.server, tc.tool, got, tc.want) + } + } + if (Ceiling{}).allows("github", "read_pr") || NewCeiling().allowsServer("github") { + t.Fatal("an empty ceiling allows a call") + } + if got := c.String(); got != "calendar; github except merge_pr" { + t.Fatalf("String = %q", got) + } + if got := (Ceiling{}).String(); got != "none" { + t.Fatalf("empty String = %q", got) + } +} + +func TestCheckCeilingListsOnlyGrantedServers(t *testing.T) { + c := NewCeiling(CeilingServer{Server: "github", ExceptTools: []string{"merge_pr"}}) + if err := checkCeiling(c, MethodToolsList, "github", ""); err != nil { + t.Fatalf("listing a granted server: %v", err) + } + if err := checkCeiling(c, MethodToolsList, "calendar", ""); err == nil { + t.Fatal("listing a server the ceiling does not grant was allowed") + } + if err := checkCeiling(c, MethodToolsCall, "github", "merge_pr"); err == nil { + t.Fatal("an excluded tool was allowed") + } + if err := checkCeiling(c, MethodToolsCall, "github", "read_pr"); err != nil { + t.Fatalf("a granted tool: %v", err) + } + if err := checkCeiling(c, "resources/read", "github", "read_pr"); err == nil { + t.Fatal("an unknown method was allowed") + } +} + +// TestCeilingIntersectionIsWithinBoth is the design's property test: an +// effective ceiling, a definition's intersected with a parent's, allows a +// call only when both do, and every call both allow. +func TestCeilingIntersectionIsWithinBoth(t *testing.T) { + servers := []string{"github", "calendar", "slack"} + tools := []string{"read", "write", "merge", "delete"} + r := rand.New(rand.NewPCG(1, 2)) + random := func() Ceiling { + var grants []CeilingServer + for _, s := range servers { + if r.IntN(3) == 0 { + continue + } + g := CeilingServer{Server: s} + for _, tool := range tools { + if r.IntN(3) == 0 { + g.ExceptTools = append(g.ExceptTools, tool) + } + } + grants = append(grants, g) + } + return NewCeiling(grants...) + } + for range 500 { + definition, parent := random(), random() + effective := definition.intersect(parent) + for _, s := range append(servers, "other") { + for _, tool := range append(tools, "other") { + want := definition.allows(s, tool) && parent.allows(s, tool) + if got := effective.allows(s, tool); got != want { + t.Fatalf("definition %s, parent %s: effective %s allows(%s, %s) = %v, want %v", definition, parent, effective, s, tool, got, want) + } + } + } + if !effective.equal(parent.intersect(definition)) { + t.Fatalf("intersection of %s and %s is not symmetric", definition, parent) + } + } +} diff --git a/internal/identitybroker/ceiling_test.go b/internal/identitybroker/ceiling_test.go new file mode 100644 index 0000000000..7bbd3d5f83 --- /dev/null +++ b/internal/identitybroker/ceiling_test.go @@ -0,0 +1,156 @@ +package identitybroker_test + +import ( + "context" + "testing" + + "github.com/stacklok/mecatl/internal/identitybroker" + "github.com/stacklok/mecatl/internal/identitybroker/conformance" +) + +// ceilingFixture is a per-call fixture with a chain of agents, each in a run +// delegated from its parent's: a code reviewer under the main agent (R42 to +// R43, D1), a deployer under the reviewer (R43 to R44, D2), and a built-in +// explorer under the deployer (R44 to R45, D3); and a tool-less agent under +// the main agent (R42 to R46, D4). +type ceilingFixture struct { + perCallFixture + main, reviewer, deployer, explorer, toolLess identitybroker.AgentRef + reviewerCred, deployerCred, explorerCred, toolLessCred identitybroker.Token +} + +func newCeilingFixture(t *testing.T) ceilingFixture { + t.Helper() + f := ceilingFixture{perCallFixture: newPerCall(t)} + main, err := f.b.RegisterAgent(context.Background(), testWorkload, mainAgent(f.s)) + if err != nil { + t.Fatalf("RegisterAgent main: %v", err) + } + f.main = main.Agent + register := func(host, incarnation string, def identitybroker.DefinitionRef, parent identitybroker.AgentRef, parentHost string) identitybroker.Registration { + t.Helper() + reg, err := f.b.RegisterAgent(context.Background(), testWorkload, identitybroker.RegisterAgentRequest{ + SessionID: f.s.ID, HostSessionID: host, Owner: testOwner, Incarnation: incarnation, + Definition: def, Parent: parent, ParentHostSessionID: parentHost, + }) + if err != nil { + t.Fatalf("RegisterAgent %s: %v", def.Name, err) + } + return reg + } + reviewer := register("hostS-reviewer", "inc_cbcdefghijklmnopqrstuvwxya", conformance.ReviewerDefinition, f.main, f.s.HostSessionID) + deployer := register("hostS-deployer", "inc_dbcdefghijklmnopqrstuvwxya", conformance.DeployerDefinition, reviewer.Agent, "hostS-reviewer") + explorer := register("hostS-explorer", "inc_ebcdefghijklmnopqrstuvwxya", conformance.ExplorerDefinition, deployer.Agent, "hostS-deployer") + // An empty ceiling still registers; its calls all deny. + toolLess := register("hostS-tool-less", "inc_fbcdefghijklmnopqrstuvwxya", conformance.ToolLessDefinition, f.main, f.s.HostSessionID) + f.reviewer, f.reviewerCred = reviewer.Agent, reviewer.Credential + f.deployer, f.deployerCred = deployer.Agent, deployer.Credential + f.explorer, f.explorerCred = explorer.Agent, explorer.Credential + f.toolLess, f.toolLessCred = toolLess.Agent, toolLess.Credential + for _, d := range []identitybroker.ReportDelegationRequest{ + {DelegationID: "D1", DelegatingRun: "R42", DelegatingAgent: f.main, ReceivingRun: "R43", ReceivingAgent: f.reviewer}, + {DelegationID: "D2", DelegatingRun: "R43", DelegatingAgent: f.reviewer, ReceivingRun: "R44", ReceivingAgent: f.deployer}, + {DelegationID: "D3", DelegatingRun: "R44", DelegatingAgent: f.deployer, ReceivingRun: "R45", ReceivingAgent: f.explorer}, + {DelegationID: "D4", DelegatingRun: "R42", DelegatingAgent: f.main, ReceivingRun: "R46", ReceivingAgent: f.toolLess}, + } { + d.SessionID, d.Owner = f.s.ID, testOwner + if err := f.b.ReportDelegation(context.Background(), testWorkload, d); err != nil { + t.Fatalf("ReportDelegation(%s): %v", d.DelegationID, err) + } + } + return f +} + +// call is a github call of tool by the agent with cred, in run under +// delegation, as operation. +func (f ceilingFixture) call(cred identitybroker.Token, run, delegation, operation, tool string) identitybroker.AuthorizeCallRequest { + req := callRequest(f.s.ID, cred) + req.RunID, req.DelegationID, req.OperationID, req.Tool = run, delegation, operation, "github."+tool + return req +} + +// wantAllowed fails t unless req is authorized and its decision record names +// ceiling as the one it was checked against. +func (f ceilingFixture) wantAllowed(t *testing.T, req identitybroker.AuthorizeCallRequest, ceiling string) { + t.Helper() + if _, err := f.authorize(req); err != nil { + t.Fatalf("AuthorizeCall(%s): %v", req.Tool, err) + } + d := f.rec.Decisions() + if last := d[len(d)-1]; last.Outcome != identitybroker.OutcomeSuccess || last.Ceiling != ceiling { + t.Fatalf("decision = %+v, want allowed under ceiling %q", last, ceiling) + } +} + +// wantCeilingDenied fails t unless req is refused at check 7 before any +// exchange, with a denial recorded naming ceiling. +func (f ceilingFixture) wantCeilingDenied(t *testing.T, req identitybroker.AuthorizeCallRequest, ceiling string) { + t.Helper() + exchanges, redemptions := len(f.issuer.requests()), len(f.as2.redeemed()) + _, err := f.authorize(req) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred, f.reviewerCred, f.deployerCred, f.explorerCred, f.toolLessCred) + wantDetail(t, err, "tool limit") + f.wantCounts(t, exchanges, redemptions) + d := f.rec.Decisions() + if last := d[len(d)-1]; last.Reason != identitybroker.ReasonDenied || last.Ceiling != ceiling || last.Tool != req.Tool { + t.Fatalf("decision = %+v, want a denial of %s under ceiling %q", last, req.Tool, ceiling) + } +} + +// TestAuthorizeCallChecksTheEffectiveCeiling pins check 7 and the effective +// ceiling: the main agent's built-in ceiling grants every gateway server; a +// read-only reviewer's excludes merge; and a deployer started by the +// reviewer cannot merge, whatever its own definition allows, because its +// effective ceiling is its definition's narrowed by the reviewer's. +func TestAuthorizeCallChecksTheEffectiveCeiling(t *testing.T) { + f := newCeilingFixture(t) + const ( + full = "calendar; github" + narrowed = "calendar; github except " + conformance.ReviewerExcludedTool + ) + f.wantAllowed(t, f.call(f.cred, "R42", "", "op-main", conformance.ReviewerExcludedTool), full) + + f.wantAllowed(t, f.call(f.reviewerCred, "R43", "D1", "op-reviewer-read", "pull_request_read"), narrowed) + f.wantCeilingDenied(t, f.call(f.reviewerCred, "R43", "D1", "op-reviewer-merge", conformance.ReviewerExcludedTool), narrowed) + + f.wantAllowed(t, f.call(f.deployerCred, "R44", "D2", "op-deployer-read", "pull_request_read"), narrowed) + f.wantCeilingDenied(t, f.call(f.deployerCred, "R44", "D2", "op-deployer-merge", conformance.ReviewerExcludedTool), narrowed) + + // The explorer's built-in ceiling grants everything, but it is narrowed + // by the deployer's effective ceiling, not the deployer's definition's, + // so the reviewer's exclusion carries down two levels. + f.wantAllowed(t, f.call(f.explorerCred, "R45", "D3", "op-explorer-read", "pull_request_read"), narrowed) + f.wantCeilingDenied(t, f.call(f.explorerCred, "R45", "D3", "op-explorer-merge", conformance.ReviewerExcludedTool), narrowed) + + // An agent whose ceiling is empty registered, and every call it makes + // is refused. + f.wantCeilingDenied(t, f.call(f.toolLessCred, "R46", "D4", "op-tool-less", "pull_request_read"), "none") +} + +// TestAuthorizeCallToolMustBeNamedForItsServer pins that a call names the +// exact pair: a tool named for another server, or with no server, is an +// invalid request, refused before any check, so check 7 always sees a tool +// of the call's server. +func TestAuthorizeCallToolMustBeNamedForItsServer(t *testing.T) { + f := newCeilingFixture(t) + for _, tool := range []string{"pull_request_read", "calendar.pull_request_read", "github."} { + req := callRequest(f.s.ID, f.cred) + req.OperationID, req.Tool = "op-"+tool, tool + _, err := f.authorize(req) + wantError(t, err, identitybroker.CodeInvalidArgument, "", f.cred) + } +} + +// TestAuthorizeCallGatewayRouteIsCheckedBeforeTheCeiling pins the design's +// order: a server no gateway routes is refused at check 6, before the +// ceiling is consulted. +func TestAuthorizeCallGatewayRouteIsCheckedBeforeTheCeiling(t *testing.T) { + f := newCeilingFixture(t) + req := callRequest(f.s.ID, f.cred) + req.Server, req.Tool = "slack", "slack.post" + _, err := f.authorize(req) + wantDetail(t, err, "no gateway routes the server") + if d := f.rec.Decisions(); d[len(d)-1].Ceiling != "" { + t.Fatalf("a call refused at check 6 names ceiling %q", d[len(d)-1].Ceiling) + } +} diff --git a/internal/identitybroker/conformance/conformance.go b/internal/identitybroker/conformance/conformance.go index 73edd8c72a..47382e4aba 100644 --- a/internal/identitybroker/conformance/conformance.go +++ b/internal/identitybroker/conformance/conformance.go @@ -41,6 +41,10 @@ type Factory func(t *testing.T, now func() time.Time) Implementation var ( MainDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceSystem, Name: identitybroker.BuiltinMain, Revision: "v1"} ReviewerDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceGlobal, Name: "code-reviewer", Revision: "r1"} + // DeployerDefinition's ceiling allows every github tool, merge included. + DeployerDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceGlobal, Name: "deployer", Revision: "d1"} + // ToolLessDefinition's ceiling grants nothing. + ToolLessDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceGlobal, Name: "tool-less", Revision: "t1"} // The built-ins of helper agents that run no named definition. ExplorerDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceSystem, Name: identitybroker.BuiltinExplorer, Revision: "v1"} BranchDefinition = identitybroker.DefinitionRef{Source: identitybroker.SourceSystem, Name: identitybroker.BuiltinBranch, Revision: "v1"} @@ -51,21 +55,36 @@ var ( // in the same order: what an implementation under test has loaded. Each call // returns a new slice. func DefinitionRefs() []identitybroker.DefinitionRef { - return []identitybroker.DefinitionRef{MainDefinition, ReviewerDefinition, ExplorerDefinition, BranchDefinition, MemberDefinition} + return []identitybroker.DefinitionRef{MainDefinition, ReviewerDefinition, DeployerDefinition, ToolLessDefinition, ExplorerDefinition, BranchDefinition, MemberDefinition} } +// ReviewerExcludedTool is the one tool the code reviewer's ceiling excludes, +// by its name on the github server. +const ReviewerExcludedTool = "pull_request_merge" + // Definitions returns the definition records an implementation under test -// loads: one for each of DefinitionRefs, the built-ins a release ships and a -// global code reviewer. Each call returns new records. +// loads: one for each of DefinitionRefs, the built-ins a release ships, a +// global code reviewer, deployer, and tool-less agent. Every ceiling but the +// tool-less agent's, which grants nothing, grants the github and calendar +// servers; the reviewer's excludes ReviewerExcludedTool on github. Each call +// returns new records. func Definitions() []identitybroker.DefinitionRecord { record := func(ref identitybroker.DefinitionRef) identitybroker.DefinitionRecord { source := sha256.Sum256([]byte("source " + ref.Name)) accepted := sha256.Sum256([]byte("definition " + ref.Name)) + github := identitybroker.CeilingServer{Server: "github"} + if ref == ReviewerDefinition { + github.ExceptTools = []string{ReviewerExcludedTool} + } + ceiling := identitybroker.NewCeiling(github, identitybroker.CeilingServer{Server: "calendar"}) + if ref == ToolLessDefinition { + ceiling = identitybroker.Ceiling{} + } return identitybroker.DefinitionRecord{Ref: ref, Provenance: identitybroker.Provenance{ Profile: "conformance/v1", SourceDigest: identitybroker.Digest{Algorithm: identitybroker.DigestSHA256, Value: hex.EncodeToString(source[:])}, DefinitionDigest: identitybroker.Digest{Algorithm: identitybroker.DigestSHA256, Value: hex.EncodeToString(accepted[:])}, - }} + }, Ceiling: ceiling} } refs := DefinitionRefs() records := make([]identitybroker.DefinitionRecord, len(refs)) diff --git a/internal/identitybroker/definition.go b/internal/identitybroker/definition.go index 7791a38283..abe872f028 100644 --- a/internal/identitybroker/definition.go +++ b/internal/identitybroker/definition.go @@ -112,11 +112,16 @@ type Provenance struct { } // DefinitionRecord is one loaded definition as the identity core sees it: the -// reference and its provenance. It deliberately carries no instructions, -// tools, or execution settings. +// reference, its provenance, and the ceiling the loader resolved for it. It +// deliberately carries no instructions or execution settings. type DefinitionRecord struct { Ref DefinitionRef Provenance Provenance + // Ceiling is the definition's limit on gateway calls, resolved by the + // loader from its MCP servers and excluded tools against the gateway's + // servers. An instance's effective ceiling is this one, narrowed by its + // parent's at registration. The zero Ceiling allows no call. + Ceiling Ceiling } // Validate reports whether r is a well-formed definition record, applying the @@ -161,7 +166,7 @@ func (r DefinitionRecord) clone() DefinitionRecord { } func (r DefinitionRecord) equal(o DefinitionRecord) bool { - return r.Ref == o.Ref && + return r.Ref == o.Ref && r.Ceiling.equal(o.Ceiling) && r.Provenance.Profile == o.Provenance.Profile && r.Provenance.SourceDigest == o.Provenance.SourceDigest && r.Provenance.DefinitionDigest == o.Provenance.DefinitionDigest && diff --git a/internal/identitybroker/gateway.go b/internal/identitybroker/gateway.go index 663ffdafb6..3bae878797 100644 --- a/internal/identitybroker/gateway.go +++ b/internal/identitybroker/gateway.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "strings" "sync" "sync/atomic" "time" @@ -225,8 +226,8 @@ func (g *Gateway) validate() error { } 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 !isGatewayServerName(s) { + return fmt.Errorf("gateway server %q must be letters, digits, and single underscores", s) } if seen[s] { return fmt.Errorf("gateway server %q is listed twice", s) @@ -236,6 +237,24 @@ func (g *Gateway) validate() error { return nil } +// isGatewayServerName reports whether s is a server name the gateway may +// route: letters, digits, and underscores, never two underscores together, as +// Mecatl's MCP configuration requires of server names. A call's tool is named +// "." and a definition excludes one as "mcp____", +// so a dot or a double underscore in a server name would let one server's +// name begin another's, and a tool of one pass as a tool of the other. +func isGatewayServerName(s string) bool { + if s == "" || strings.Contains(s, "__") { + return false + } + for _, r := range s { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' { + return false + } + } + return true +} + // 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 index 46291b16ca..63262f88af 100644 --- a/internal/identitybroker/recorder.go +++ b/internal/identitybroker/recorder.go @@ -86,7 +86,11 @@ type DecisionRecord struct { Server string Tool string ArgumentsSHA256 string - Outcome DecisionOutcome + // Ceiling is the acting agent's effective ceiling the call was checked + // against (check 7), in Ceiling.String's form; empty when the call was + // refused before that check. + Ceiling string + Outcome DecisionOutcome // Code and Reason are the refusal's; empty on success. Code Code Reason Reason diff --git a/internal/identitybroker/service.go b/internal/identitybroker/service.go index c6726bed09..6da6166edc 100644 --- a/internal/identitybroker/service.go +++ b/internal/identitybroker/service.go @@ -3,6 +3,7 @@ package identitybroker import ( "context" "fmt" + "strings" "time" ) @@ -123,7 +124,12 @@ type Service interface { // that is not a root instance; a run naming a delegation not reported // for this run and agent; or a run owner that is not the run's owner // and the grant's owner: CodePermissionDenied, ReasonDenied; - // - a server no gateway routes: CodePermissionDenied, ReasonDenied. + // - a server no gateway routes: CodePermissionDenied, ReasonDenied; + // - a call the acting agent's effective ceiling does not allow (its + // definition's ceiling, narrowed by its parent's when it registered): + // a tool the ceiling excludes or on a server it does not grant, or a + // listing of a server it does not grant: CodePermissionDenied, + // ReasonDenied, recorded with the ceiling checked. // // A call that passes the run checks records a run the broker had not // seen: as a root run of the acting agent with the reported owner, or, for @@ -427,7 +433,8 @@ type AuthorizeCallRequest struct { // 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. + // "github.pull_request_read": the server's name, a dot, and the tool's + // name on the server. Set for tools/call only. Tool string // ArgumentsSHA256 is the argument hash, 64 lowercase hex characters, as // credentials-and-lifecycle.md step (8), "The argument hash", defines it: @@ -464,6 +471,9 @@ func (r AuthorizeCallRequest) Validate() error { if !isToken(r.Tool) { return invalid("a tools/call must name its tool in printable text without spaces") } + if name, ok := strings.CutPrefix(r.Tool, r.Server+"."); !ok || name == "" { + return invalid("a tools/call must name its tool as its server's name, a dot, and the tool's name on the server") + } if !isSHA256Hex(r.ArgumentsSHA256) { return invalid("a tools/call must carry its arguments' SHA-256 as 64 lowercase hex characters") } diff --git a/user-docs/operating/mecak8s/identity-and-client-access.md b/user-docs/operating/mecak8s/identity-and-client-access.md index d63da450c3..27a0be2dbe 100644 --- a/user-docs/operating/mecak8s/identity-and-client-access.md +++ b/user-docs/operating/mecak8s/identity-and-client-access.md @@ -237,7 +237,7 @@ identityBroker: |Value|Flag|Meaning| |-|-|-| -|`identityBroker.enabled`|`--enable-identity-broker`|Starts the identity broker. Requires `replicaCount: 1`, `oidc.ownerIdentity: sub_id` when OIDC is enabled, and no shell in the process: `--no-shell` in `extraArgs`, or `--shell=` with `execution.enabled` to keep the remote Shell. The chart refuses to render without one. The Deployment rolls out with `Recreate`. This value is the only way to start the broker: the chart refuses `--enable-identity-broker` in `extraArgs`. With protected MCP servers configured, turning it on or off changes the audience of the MCP gateway's tokens, so those servers must be [enrolled](/features/security-and-execution/mcp-oauth-and-credentials.md) again. Each session's main agent gets its own agent identity, and so does each [subagent, parallel branch, and team member](/features/agent-behavior/subagents-and-teams.md) it starts. Helpers that run no named agent can call the MCP gateway's tools under their own identity; a helper never gets another MCP broker tool, and one running a named agent gets none. The broker accepts only built-in agents or a [named agent](/features/agent-behavior/named-agents.md#choose-where-definitions-are-discovered) from a directory passed with `--agents-dir` in `extraArgs` and mounted with `extraVolumes` and `extraVolumeMounts`. A session that uses a named agent from any other location cannot run, a subagent or team member that names one cannot start, and a `--agents-dir` directory that does not exist stops startup. With an operator [`harness_context`](/operating/settings.md#select-harness-context-sources) policy, which can let another source win an agent name, only built-in agents can run.| +|`identityBroker.enabled`|`--enable-identity-broker`|Starts the identity broker. Requires `replicaCount: 1`, `oidc.ownerIdentity: sub_id` when OIDC is enabled, and no shell in the process: `--no-shell` in `extraArgs`, or `--shell=` with `execution.enabled` to keep the remote Shell. The chart refuses to render without one. The Deployment rolls out with `Recreate`. This value is the only way to start the broker: the chart refuses `--enable-identity-broker` in `extraArgs`. With protected MCP servers configured, turning it on or off changes the audience of the MCP gateway's tokens, so those servers must be [enrolled](/features/security-and-execution/mcp-oauth-and-credentials.md) again. Each session's main agent gets its own agent identity, and so does each [subagent, parallel branch, and team member](/features/agent-behavior/subagents-and-teams.md) it starts. Helpers call the MCP gateway's tools under their own identity. A helper that runs no named agent gets all of them; one running a named agent gets the tools of each server its `mcpServers` lists, minus those its `disallowedTools` names. A helper never gets another MCP broker tool. The broker refuses a gateway call outside an agent's limit: the tools its agent allows, as above, narrowed by the limit of the agent that started it. The broker accepts only built-in agents or a [named agent](/features/agent-behavior/named-agents.md#choose-where-definitions-are-discovered) from a directory passed with `--agents-dir` in `extraArgs` and mounted with `extraVolumes` and `extraVolumeMounts`. A session that uses a named agent from any other location cannot run, a subagent or team member that names one cannot start, and a `--agents-dir` directory that does not exist stops startup. With an operator [`harness_context`](/operating/settings.md#select-harness-context-sources) policy, which can let another source win an agent name, only built-in agents can run.| |`identityBroker.subjectClaim`|`--identity-broker-subject-claim`|The company IdP's ID-token claim that names each user. Required with `identityBroker.as1.issuer`, and allowed only with it.| |`identityBroker.as1.issuer`|`--identity-broker-as1-issuer`|AS-1's HTTPS issuer URL. Setting it hosts AS-1 and requires `oidc.enabled`, `oidc.audience`, and `oidc.resource`. AS-1 accepts only an absolute `http` or `https` URL with a host and no fragment as the audience, such as `https://mecatl.example.com/api`.| |`identityBroker.as1.tuiClientID`|`--identity-broker-as1-tui-client-id`|The client ID `mecatui` uses at AS-1.| From 29b94ce6f030738392d8e0d85b5b700ce3063ecf Mon Sep 17 00:00:00 2001 From: Radoslav Dimitrov Date: Sat, 21 Nov 2026 19:50:10 +0200 Subject: [PATCH 2/3] fix(identitybroker): tighten the tool limit after review - A gateway call is refused unless the gateway routes it to the tool's own backend, so the harness and the broker always mean the same server. - Ceilings match tool names exactly, as the harness does; records quote names holding a separator; a refusal no longer shows the ceiling. - A built-in definition that sets tool fields fails to load instead of having them ignored. - An effective ceiling is computed only for a new instance. - Shortcut markers for restart recomputation (#2563) and reported definitions (#2551). - The agreement test uses the broker's own check and covers built-ins and the main agent as parent; new cases for dotted, mixed-case, and ambiguous names, and a child under an empty ceiling. - Docs: the server list the limit resolves against until #2533, whole-server entries, no backfill while state is in memory, the tool-naming refusal, unlimited listings until #2729, and the operator row's accuracy. Co-Authored-By: Claude Opus 5.5 --- .../agent-identity/agent-definitions.md | 2 +- .../credentials-and-lifecycle.md | 3 +- docs/drafts/agent-identity/implementation.md | 2 +- .../agent-identity/mcp-authorization.md | 6 +- internal/adapter/mcpbroker/gateway.go | 8 +- internal/adapter/mcpbroker/gateway_call.go | 7 ++ .../adapter/mcpbroker/gateway_call_test.go | 30 +++++- internal/adapter/mcpbroker/runtime.go | 4 +- internal/app/build.go | 4 + internal/app/defgatewaytools_test.go | 98 ++++++++++++++----- .../adapter/definitionloader/loader.go | 9 +- .../definitionloader/loader_internal_test.go | 22 +++++ .../adapter/definitionloader/loader_test.go | 18 ++++ internal/identitybroker/agents.go | 10 +- internal/identitybroker/authorize.go | 1 + internal/identitybroker/ceiling.go | 45 ++++++--- .../identitybroker/ceiling_internal_test.go | 56 ++++++++++- internal/identitybroker/ceiling_test.go | 44 ++++++++- internal/identitybroker/gateway.go | 9 +- .../mecak8s/identity-and-client-access.md | 2 +- 20 files changed, 321 insertions(+), 59 deletions(-) diff --git a/docs/drafts/agent-identity/agent-definitions.md b/docs/drafts/agent-identity/agent-definitions.md index e9430b7b7b..d652665bbc 100644 --- a/docs/drafts/agent-identity/agent-definitions.md +++ b/docs/drafts/agent-identity/agent-definitions.md @@ -156,7 +156,7 @@ The table shows how the design handles each event. Today, a turn that was in pro | Instance credential expires | Renew the credential for the registered identity after the required checks. Renewal does not widen authority. | | Fork or clear | Register a distinct identity. A fork or a clear creates a new root instance in a new host session, which opens its own broker session. The source session keeps its broker session. | | Fresh incarnation | Register a distinct identity. Reusing a session name or a definition name does not inherit the old instance's authority. | -| Authority work switched on | The broker computes a ceiling once for each live instance, parents before children. It marks the ceiling as backfilled. Until then, an instance with no ceiling is denied every MCP call. An instance whose definition or parent cannot be resolved gets a ceiling that denies every MCP call. That instance must register again. | +| Authority work switched on | The broker computes a ceiling once for each live instance, parents before children. It marks the ceiling as backfilled. Until then, an instance with no ceiling is denied every MCP call. An instance whose definition or parent cannot be resolved gets a ceiling that denies every MCP call. That instance must register again. While broker state is in memory, no instance outlives the broker that registered it, so there is nothing to backfill; revisit with #2559 and #2563. | A continued run keeps its original bounds. A new restriction can narrow them. So can the withdrawal of a permission. Credential renewal and policy changes must not widen recovered authority. If the original identity or definition cannot be recovered, restoration fails closed. It never substitutes another instance or definition. diff --git a/docs/drafts/agent-identity/credentials-and-lifecycle.md b/docs/drafts/agent-identity/credentials-and-lifecycle.md index a9f9038f50..59b3205d11 100644 --- a/docs/drafts/agent-identity/credentials-and-lifecycle.md +++ b/docs/drafts/agent-identity/credentials-and-lifecycle.md @@ -491,7 +491,7 @@ Local permissions and hooks run before each call. } ``` -The request names the tool as the gateway routes it, exactly as the MCP client sends it in `params.name` (`github.pull_request_read`, where the embedded vMCP prefixes each backend's tools), and the server as the gateway's name for the backend that route resolves to (`github`). It also names the method: `tools/call`, or a list method such as `tools/list`, which names the server but no tool or argument hash. The request carries the agent's SVID and no separate acting-session field. +The request names the tool as the gateway routes it, exactly as the MCP client sends it in `params.name` (`github.pull_request_read`, where the embedded vMCP prefixes each backend's tools), and the server as the gateway's name for the backend that route resolves to (`github`). The tool must be the server's name, a dot, and the tool's name on that server, so the ceiling check sees exactly one server and tool; a gateway that names tools another way maps them to this form before it asks. It also names the method: `tools/call`, or a list method such as `tools/list`, which names the server but no tool or argument hash. The request carries the agent's SVID and no separate acting-session field. **Checks, at the broker,** before any exchange or dispatch: @@ -511,6 +511,7 @@ The broker takes `RT-A42` from `A42`'s record only after checks 3 to 5 have pass | Check | Response | Retry | | --- | --- | --- | +| Request, a `tools/call` tool not named `.` | `INVALID_ARGUMENT` | No; a gateway naming fault. | | 1 | Step (2)'s codes | Only an expired workload credential. | | 2, session closed | The closing reason the broker recorded, with that reason's status from [error reasons](#error-reasons) | mecak8s acts on the reason; see [error reasons](#error-reasons). | | 2, no refresh token | `FAILED_PRECONDITION` with `no_grant` | No. The session gets a refresh token when a request carrying the user's access token opens it again ([step (3)](#3-session-open-and-the-broker-refresh-token)). | diff --git a/docs/drafts/agent-identity/implementation.md b/docs/drafts/agent-identity/implementation.md index 969461401f..d6c5714289 100644 --- a/docs/drafts/agent-identity/implementation.md +++ b/docs/drafts/agent-identity/implementation.md @@ -364,7 +364,7 @@ The **identity work** establishes who acts and records it: The **authority work** decides what each agent may do: -- the definition loader resolving each loaded definition's ceiling into permitted MCP server/tool pairs; a definition the broker did not load gets no ceiling of its own and inherits the ceiling of the instance that creates it; +- the definition loader resolving each loaded definition's ceiling into server-wide entries, each permitting a referenced server's tools except those the definition excludes by name; a definition the broker did not load gets no ceiling of its own and inherits the ceiling of the instance that creates it; - each instance's effective ceiling, its definition ceiling narrowed by its parent's; - Cedar policy generation and a ceiling check on every call; - grants scoped to a run the user started, replacing the session's standing refresh token, so that sessions of absent users carry no authority; diff --git a/docs/drafts/agent-identity/mcp-authorization.md b/docs/drafts/agent-identity/mcp-authorization.md index a358e68142..d90c71b918 100644 --- a/docs/drafts/agent-identity/mcp-authorization.md +++ b/docs/drafts/agent-identity/mcp-authorization.md @@ -6,9 +6,9 @@ The broker authorizes each protected MCP call and issues the gateway access toke ## Definition-derived ceiling -Trusted definition admission resolves the existing `Tools`, `DisallowedTools`, and `MCPServers` semantics against registered MCP servers and their tools into permitted server/tool pairs. Resolution must preserve existing selection and exclusion semantics, including defaults, rather than interpreting a raw tool list as grants. A tool name alone cannot identify an authorized pair across servers. Unresolved or ambiguous references cannot grant access. +Trusted definition admission resolves the existing `Tools`, `DisallowedTools`, and `MCPServers` semantics against registered MCP servers and their tools into the server/tool pairs it permits. Resolution must preserve existing selection and exclusion semantics, including defaults, rather than interpreting a raw tool list as grants. A tool name alone cannot identify an authorized pair across servers. Unresolved or ambiguous references cannot grant access. -Registered MCP servers are the servers the gateway routes, from the operator's MCP configuration. A server that `MCPServers` references resolves to all of its tools except those `DisallowedTools` names, kept as one server-wide entry that each call's exact server and tool are checked against. `Tools` selects no MCP tools in the harness, so it grants none. An inline server, or a reference to a server the gateway does not route, grants nothing. Built-in definitions name every registered server. Resolution needs no tool list: listing a server's tools needs a user's grant, and the list can differ per user. +Registered MCP servers are the servers the gateway routes, from the operator's MCP configuration. Until #2533 builds the gateway from that configuration, the broker resolves against the servers its gateway entry routes, the same list that decides which helper tools take the gateway path; production configures none, so every gateway call is refused before this check. A server that `MCPServers` references resolves to all of its tools except those `DisallowedTools` names, kept as one server-wide entry that each call's exact server and tool are checked against. The entry permits the server's tools as they are when each call is checked, so a tool the server adds later is permitted unless a definition excludes it by name. Exclusions are parsed from their `mcp____` names once, at resolution; calls are not. `Tools` selects no MCP tools in the harness, so it grants none. An inline server, or a reference to a server the gateway does not route, grants nothing. Built-in definitions name every registered server. Resolution needs no tool list: listing a server's tools needs a user's grant, and the list can differ per user. Cedar policies are generated deterministically from that resolved ceiling and tied to the fixed admitted definition source and revision. The same admitted inputs produce the same ceiling and generated policy revision. Generation uses structured definition facts, never an LLM or inferred intent from `Body`, descriptions, skills, or other prose. Retain the resolution inputs and generated policy revision so that the decision can be explained after the source changes. Each call is evaluated against the acting instance's effective ceiling, defined under [delegated authority](#delegated-authority). Representation, including the Cedar schema and entity/action/resource layout, is left to the implementer. @@ -102,7 +102,7 @@ For each call, the broker authenticates to AS-1 as OAuth client `mecatl` with `p **Why mecak8s sends the call.** The broker decides and issues tokens; it does not proxy MCP. Sending a call needs the MCP protocol, vMCP sessions, streaming, cancellation, and server-initiated requests such as elicitation, and putting those in the broker would make the most trusted component large and tie it to every change in MCP. A `V` bound to one approved call gives the protection that sending from the broker would: mecak8s holds only a credential for the call the broker just approved, usable once. The harness holds no credential it can use for any other call. -**Tool discovery.** mecak8s's MCP client also lists the gateway's tools, with a `V` the broker issues for that listing after the same session, workload, and actor checks; its entry names the server and the `tools/list` method instead of a tool and argument hash. Listing tools needs no sign-in beyond Alice's sign-in at AS-1. +**Tool discovery.** mecak8s's MCP client also lists the gateway's tools, with a `V` the broker issues for that listing after the same session, workload, and actor checks; its entry names the server and the `tools/list` method instead of a tool and argument hash. Listing tools needs no sign-in beyond Alice's sign-in at AS-1. Until #2729, mecak8s lists a session's gateway tools with the MCP broker's own sign-in, not a `V`, so the broker neither authorizes a listing nor applies a ceiling to it; the harness gives a helper only its definition's gateway tools from that listing. **Why the binding lives in `V`.** The alternative was two tokens: a `V` scoped to the acting instance's effective ceiling and cached by the broker, plus a per-call token the broker signs, valid for seconds, in the pattern of OAuth Transaction Tokens. That saves the AS-1 exchange and AS-2 redemption on each call, but the vMCP would have to trust the broker's signing key as well as AS-2's. An external gateway administers its own trust, and transaction tokens are meant for one trust domain. Binding `V` keeps every gateway trusting only its own AS-2. diff --git a/internal/adapter/mcpbroker/gateway.go b/internal/adapter/mcpbroker/gateway.go index b6a5f7a005..d6a4224ffc 100644 --- a/internal/adapter/mcpbroker/gateway.go +++ b/internal/adapter/mcpbroker/gateway.go @@ -29,8 +29,12 @@ type Gateway interface { Resource() string // HTTPClient carries every request of a call. HTTPClient() *http.Client - // Route returns the gateway backend and the tool name the gateway routes - // for the model-visible tool name on backend. + // Route returns the gateway server and the tool name the gateway routes + // for the model-visible tool name on backend. The server must be backend, + // the name operators and agent definitions use, and the tool must be + // ".", with the tool's name on the server: the identity + // broker checks both against the acting agent's tool limit and refuses + // any other form. Route(backend, modelVisibleName string) (server, tool string, err error) // ListTools lists the tools the gateway routes to server, each under its // name on that server, sent with credential as the bearer. The gateway diff --git a/internal/adapter/mcpbroker/gateway_call.go b/internal/adapter/mcpbroker/gateway_call.go index bb8cd47da4..8d1e2b8eab 100644 --- a/internal/adapter/mcpbroker/gateway_call.go +++ b/internal/adapter/mcpbroker/gateway_call.go @@ -134,6 +134,13 @@ func (g *gatewayCall) run(ctx context.Context) (session.ToolResult, string, erro g.cause = "route: " + err.Error() return fail(outcomeInternal) } + // The harness gives a helper the tools of the servers its definition + // names by backend, and the broker checks the server Route names, so the + // two must be the same name. + if g.server != g.t.route.backend { + g.cause = "route: the gateway named a server other than the tool's backend" + return fail(outcomeInternal) + } // The argument hash is checked before anything is authorized. if g.args, g.hash, err = argumentsSHA256(g.call.Args); err != nil { return fail(refused(err)) diff --git a/internal/adapter/mcpbroker/gateway_call_test.go b/internal/adapter/mcpbroker/gateway_call_test.go index 8732f039be..19cd92b3c5 100644 --- a/internal/adapter/mcpbroker/gateway_call_test.go +++ b/internal/adapter/mcpbroker/gateway_call_test.go @@ -123,13 +123,19 @@ type testGateway struct { resource string client *http.Client list func(server string, credential oauth2.TokenSource) ([]GatewayTool, error) + // server, when set, is the server Route names for every call. + server string } func (g testGateway) Endpoint() string { return g.endpoint } func (g testGateway) Resource() string { return g.resource } func (g testGateway) HTTPClient() *http.Client { return g.client } -func (testGateway) Route(backend, name string) (string, string, error) { - return embeddedGateway{}.Route(backend, name) +func (g testGateway) Route(backend, name string) (string, string, error) { + server, routed, err := embeddedGateway{}.Route(backend, name) + if g.server != "" { + server = g.server + } + return server, routed, err } func (g testGateway) ListTools(ctx context.Context, server string, credential oauth2.TokenSource) ([]GatewayTool, error) { if g.list != nil { @@ -251,6 +257,8 @@ type gatewayFixtureOptions struct { noGateway bool tokenPrefix string agentToken string + // routeServer, when set, is the server the gateway's Route names. + routeServer string } func newGatewayFixture(t *testing.T, opts gatewayFixtureOptions) *gatewayFixture { @@ -292,7 +300,7 @@ func newGatewayFixture(t *testing.T, opts gatewayFixtureOptions) *gatewayFixture harness.runtime.diag = f.diag if !opts.noGateway { WithGatewayCalls( - testGateway{endpoint: f.g.URL(), resource: f.g.URL(), client: &http.Client{Transport: f.wire, Timeout: 10 * time.Second}}, + testGateway{endpoint: f.g.URL(), resource: f.g.URL(), client: &http.Client{Transport: f.wire, Timeout: 10 * time.Second}, server: opts.routeServer}, GatewayCalls{Authorizer: f.auth, Credentials: f.creds, Servers: opts.servers}, )(harness.runtime) } @@ -402,6 +410,22 @@ func TestSendOnceKeysByOperation(t *testing.T) { } } +// TestGatewayCallRefusesARouteToAnotherServer refuses a call whose gateway +// names a server other than the tool's backend, before anything is +// authorized: the harness picked the tool by backend and the broker checks +// the routed server, so they must agree. +func TestGatewayCallRefusesARouteToAnotherServer(t *testing.T) { + f := newGatewayFixture(t, gatewayFixtureOptions{routeServer: "calendar"}) + res, err := f.execute(mainAgent(t), t, "call-1", gatewayTestArgs) + wantRow(t, res, err, outcomeInternal) + if n := len(f.auth.calls()); n != 0 { + t.Fatalf("authorize calls = %d, want none", n) + } + if got := f.diag.String(); !strings.Contains(got, "a server other than the tool's backend") { + t.Fatalf("diagnostics = %s, want the route mismatch", got) + } +} + func TestGatewayCallLogsTheBrokerRefusal(t *testing.T) { f := newGatewayFixture(t, gatewayFixtureOptions{}) detail := "identitybroker: the authorization server refused the request: HTTP 400 invalid_request (sub_id_missing)" diff --git a/internal/adapter/mcpbroker/runtime.go b/internal/adapter/mcpbroker/runtime.go index a93e992c45..8d48c77704 100644 --- a/internal/adapter/mcpbroker/runtime.go +++ b/internal/adapter/mcpbroker/runtime.go @@ -656,7 +656,9 @@ func (t *sessionTool) HelperGatewayTool() (tool.Tool, bool) { return t, true } -// GatewayServer names the gateway server t's calls are routed to. +// GatewayServer names the backend t's calls are routed to. A gateway call is +// refused unless the gateway's Route names this backend as the call's server, +// so it is the server the identity broker checks. func (t *sessionTool) GatewayServer() string { return t.route.backend } func (t *sessionTool) Spec() tool.ToolSpec { return copySpec(t.route.spec) } diff --git a/internal/app/build.go b/internal/app/build.go index 1da834ae1e..6520cc57d2 100644 --- a/internal/app/build.go +++ b/internal/app/build.go @@ -2381,6 +2381,10 @@ func Build(ctx context.Context, cfg Config) (*Built, error) { identity.as1Issuer = cfg.IdentityBrokerAS1.Issuer } if ib.gateway && len(ib.gatewayServers) != 0 && agentCredentials != nil { + // One list for both sides: the MCP broker sends only these + // servers' tools through the gateway, so they are the only helper + // gateway tools defGatewayTools can pick, and the identity broker + // resolved every definition's ceiling against the same list. identity.gatewayCalls = &mcpBrokerGatewayCalls{service: ib.service, credentials: agentCredentials, servers: ib.gatewayServers} } if err == nil { diff --git a/internal/app/defgatewaytools_test.go b/internal/app/defgatewaytools_test.go index 081cbce3c6..9aafcb469d 100644 --- a/internal/app/defgatewaytools_test.go +++ b/internal/app/defgatewaytools_test.go @@ -28,11 +28,19 @@ func (fakeGatewayTool) Execute(context.Context, session.ToolCall, tool.Environme func (f fakeGatewayTool) GatewayServer() string { return f.server } // TestDefGatewayToolsAgreesWithTheBrokersCeiling is the design's cross-check -// between the harness and the broker: for each definition, the gateway tools -// the harness gives a helper running it (defGatewayTools) are exactly the -// tools the broker's loader resolves its ceiling to allow. The two read the -// same files with their own parsers, so a change to either side's rule that -// the other does not follow fails here. +// between the harness and the broker. Both read the same definition files +// (the harness through agentfs, the broker through its loader, both on +// agentdef) and apply their own rule: the harness picks a helper's gateway +// tools (defGatewayTools), the broker resolves a ceiling (resolveCeiling) +// and checks calls against it (Ceiling.Allows). For each definition, the +// tools the harness gives are exactly the tools the broker allows, so a +// change to either rule that the other does not follow fails here. +// +// It also covers the parent: a helper's gateway tools come from its root's, +// which today is always the built-in main agent (named helpers start no +// helpers, and named roots get no gateway tools, #2938), so its effective +// ceiling is its definition's intersected with system/main's. And it covers +// the built-in helpers, whose catalogs hold every gateway tool. func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { definitions := map[string]string{ "one-server": "mcpServers: [calendar]\n", @@ -42,6 +50,8 @@ func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { "tools-only": "tools: [mcp__calendar__echo]\n", "no-servers": "", "other-excluded": "mcpServers: [calendar]\ndisallowedTools: [mcp__github__read]\n", + "exact-names": "mcpServers: [calendar, github]\ndisallowedTools: [mcp__github__pr.merge, mcp__GitHub__read, mcp__calendar__Echo, \"mcp__calendar__ lookup\"]\n", + "ambiguous": "mcpServers: [git]\ndisallowedTools: [mcp__git___x]\n", } dir := t.TempDir() for name, frontmatter := range definitions { @@ -50,10 +60,35 @@ func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { t.Fatal(err) } } - servers := []string{"calendar", "github"} + servers := []string{"calendar", "github", "git"} sessionTools := []tool.Tool{ - fakeGatewayTool{"calendar", "echo"}, fakeGatewayTool{"calendar", "lookup"}, - fakeGatewayTool{"github", "merge"}, fakeGatewayTool{"github", "read"}, + fakeGatewayTool{"calendar", "echo"}, fakeGatewayTool{"calendar", "lookup"}, fakeGatewayTool{"calendar", "Echo"}, + fakeGatewayTool{"github", "merge"}, fakeGatewayTool{"github", "read"}, fakeGatewayTool{"github", "pr.merge"}, + fakeGatewayTool{"git", "_x"}, fakeGatewayTool{"git", "y"}, + } + // allowed returns the names of the session tools every ceiling allows. + allowed := func(ceilings ...identitybroker.Ceiling) []string { + var out []string + for _, st := range sessionTools { + ft := st.(fakeGatewayTool) + ok := true + for _, c := range ceilings { + ok = ok && c.Allows(ft.server, ft.name) + } + if ok { + out = append(out, ft.Spec().Name) + } + } + slices.Sort(out) + return out + } + names := func(tools []tool.Tool) []string { + var out []string + for _, gt := range tools { + out = append(out, gt.Spec().Name) + } + slices.Sort(out) + return out } records, _, err := definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{dir}, Servers: servers}) @@ -61,9 +96,13 @@ func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { t.Fatal(err) } ceilings := map[string]identitybroker.Ceiling{} + builtins := map[string]identitybroker.Ceiling{} for _, r := range records { - if r.Ref.Source == identitybroker.SourceGlobal { + switch r.Ref.Source { + case identitybroker.SourceGlobal: ceilings[r.Ref.Name] = r.Ceiling + case identitybroker.SourceSystem: + builtins[r.Ref.Name] = r.Ceiling } } discovered, skipped, err := agents.DirSource{Dir: dir}.Agents(t.Context()) @@ -73,24 +112,35 @@ func TestDefGatewayToolsAgreesWithTheBrokersCeiling(t *testing.T) { if len(discovered) != len(definitions) || len(ceilings) != len(definitions) { t.Fatalf("the harness found %d definitions and the broker %d, want %d each", len(discovered), len(ceilings), len(definitions)) } + main, ok := builtins[identitybroker.BuiltinMain] + if !ok { + t.Fatal("the broker loaded no system/main") + } for _, d := range discovered { - var harness []string - for _, gt := range defGatewayTools(d.Def, sessionTools) { - harness = append(harness, gt.Spec().Name) + harness := names(defGatewayTools(d.Def, sessionTools)) + if broker := allowed(ceilings[d.Def.Name]); !slices.Equal(harness, broker) { + t.Errorf("%s: the harness gives %v, the broker allows %v", d.Def.Name, harness, broker) } - var broker []string - for _, grant := range ceilings[d.Def.Name].Servers() { - for _, st := range sessionTools { - ft := st.(fakeGatewayTool) - if ft.server == grant.Server && !slices.Contains(grant.ExceptTools, ft.name) { - broker = append(broker, ft.Spec().Name) - } - } + if effective := allowed(ceilings[d.Def.Name], main); !slices.Equal(harness, effective) { + t.Errorf("%s under the main agent: the harness gives %v, the broker's effective ceiling allows %v", d.Def.Name, harness, effective) } - slices.Sort(harness) - slices.Sort(broker) - if !slices.Equal(harness, broker) { - t.Errorf("%s: the harness gives %v, the broker allows %v", d.Def.Name, harness, broker) + } + + all := names(sessionTools) + catalogs := map[string]*tool.Catalog{ + "read-only explorer": readOnlyExplorerCatalog(nil, sessionTools), + "writable explorer": writableExplorerCatalog(nil, "test catalog", sessionTools), + } + for name, ceiling := range builtins { + if got := allowed(ceiling); !slices.Equal(got, all) { + t.Errorf("%s: the broker allows %v, want every gateway tool %v", name, got, all) + } + } + for name, cat := range catalogs { + for _, tn := range all { + if _, ok := cat.Lookup(tn); !ok { + t.Errorf("%s lacks gateway tool %s, which the built-in ceiling allows", name, tn) + } } } } diff --git a/internal/identitybroker/adapter/definitionloader/loader.go b/internal/identitybroker/adapter/definitionloader/loader.go index 98a2c46153..c0568b9193 100644 --- a/internal/identitybroker/adapter/definitionloader/loader.go +++ b/internal/identitybroker/adapter/definitionloader/loader.go @@ -287,6 +287,11 @@ func readFile(path string) ([]byte, time.Time, error) { } func builtinRecord(def agentdef.Definition, revision string, servers map[string]bool) (identitybroker.DefinitionRecord, error) { + // builtinCeiling gives a built-in every gateway server, so a built-in + // that set tool fields would have them ignored without a word. + if len(def.Tools) != 0 || len(def.DisallowedTools) != 0 || len(def.MCPServers) != 0 { + return identitybroker.DefinitionRecord{}, fmt.Errorf("built-in definition %s sets tool fields, which builtinCeiling does not resolve", def.Name) + } digest, err := definitionDigest(def) if err != nil { return identitybroker.DefinitionRecord{}, err @@ -351,7 +356,9 @@ func serverSet(servers []string) map[string]bool { } // builtinCeiling is a built-in definition's ceiling: every gateway server, -// whole. The main agent of a session started without a named definition +// whole, as the harness gives a built-in helper every gateway tool +// (readOnlyExplorerCatalog, writableExplorerCatalog). Built-ins set no tool +// fields; builtinRecord refuses one that does. The main agent of a session started without a named definition // calls any of them, as the main conversation does; a built-in helper's // parent's ceiling narrows it at registration. func builtinCeiling(servers map[string]bool) identitybroker.Ceiling { diff --git a/internal/identitybroker/adapter/definitionloader/loader_internal_test.go b/internal/identitybroker/adapter/definitionloader/loader_internal_test.go index c0dabbd8c0..5a7e292694 100644 --- a/internal/identitybroker/adapter/definitionloader/loader_internal_test.go +++ b/internal/identitybroker/adapter/definitionloader/loader_internal_test.go @@ -3,6 +3,8 @@ package definitionloader import ( "testing" "time" + + "github.com/stacklok/mecatl/agentdef" ) // TestFileRevision pins the revision to UTC whatever zone the time carries. @@ -16,3 +18,23 @@ func TestFileRevision(t *testing.T) { t.Errorf("fileRevision = %q, want %q", got, want) } } + +// TestBuiltinRecordRefusesToolFields fails a built-in that sets tool fields, +// which builtinCeiling would ignore, rather than giving it every server. +func TestBuiltinRecordRefusesToolFields(t *testing.T) { + t.Parallel() + servers := map[string]bool{"github": true} + for name, def := range map[string]agentdef.Definition{ + "tools": {Tools: []string{"Read"}}, + "disallowedTools": {DisallowedTools: []string{"mcp__github__merge"}}, + "mcpServers": {MCPServers: []agentdef.MCPServer{{Name: "github"}}}, + } { + def.Name, def.Description = "system-test", "A built-in." + if _, err := builtinRecord(def, "rev", servers); err == nil { + t.Errorf("%s: a built-in setting it was accepted", name) + } + } + if _, err := builtinRecord(agentdef.Definition{Name: "system-test", Description: "A built-in."}, "rev", servers); err != nil { + t.Fatalf("a built-in with no tool fields: %v", err) + } +} diff --git a/internal/identitybroker/adapter/definitionloader/loader_test.go b/internal/identitybroker/adapter/definitionloader/loader_test.go index 52d33ee836..88ce26b492 100644 --- a/internal/identitybroker/adapter/definitionloader/loader_test.go +++ b/internal/identitybroker/adapter/definitionloader/loader_test.go @@ -628,6 +628,24 @@ func TestLoadResolvesCeilings(t *testing.T) { } } + // Exclusions match exactly: case and dots are part of a name, + // and an exclusion that could belong to git or git_ narrows both. + names := t.TempDir() + writeDef(t, names, "names.md", "---\nname: names\ndescription: Names\n"+ + "disallowedTools: [mcp__git___x, mcp__github__pr.merge, mcp__GitHub__read]\n"+ + "mcpServers: [git, git_, github]\n---\n") + records, _, err = definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{names}, Servers: []string{"git", "git_", "github"}}) + if err != nil { + t.Fatal(err) + } + for _, r := range records { + if r.Ref.Name == "names" { + if got, want := r.Ceiling.String(), `git except _x; git_ except x; github except pr.merge`; got != want { + t.Errorf("names ceiling = %s, want %s", got, want) + } + } + } + // With no gateway servers, every ceiling allows nothing. records, _, err = definitionloader.Load(t.Context(), definitionloader.Config{Dirs: []string{dir}}) if err != nil { diff --git a/internal/identitybroker/agents.go b/internal/identitybroker/agents.go index 1d37b61545..72f0d0c9f2 100644 --- a/internal/identitybroker/agents.go +++ b/internal/identitybroker/agents.go @@ -145,7 +145,13 @@ func (b *Broker) recordRegistration(workload Workload, req RegisterAgentRequest, return Registration{}, true, nil } } - t.recordLocked(identity, s.ID, req, b.effectiveCeilingLocked(req), credential, expiresAt) + // A new instance's effective ceiling is computed once, here; one + // registered before keeps its own. + var ceiling Ceiling + if _, registered := t.agents[identity.subject]; !registered { + ceiling = b.effectiveCeilingLocked(req) + } + t.recordLocked(identity, s.ID, req, ceiling, credential, expiresAt) return Registration{Agent: AgentRef{Subject: identity.subject}, Credential: credential, ExpiresAt: expiresAt}, false, nil } @@ -153,6 +159,8 @@ func (b *Broker) recordRegistration(workload Workload, req RegisterAgentRequest, // registering with req: its definition's ceiling, intersected with its // parent's effective ceiling when it has a parent. The caller holds t.mu and // has checked req, so the definition is loaded and the parent registered. +// +// Shortcut: broker state is in memory, so after a restart each instance registers again and its ceiling is computed afresh against the definitions and gateway servers loaded then; a longer server list can widen it under the same definition revision; removed by #2563 (durable broker state keeps each effective ceiling and its resolution inputs). func (b *Broker) effectiveCeilingLocked(req RegisterAgentRequest) Ceiling { ceiling := b.definitions[req.Definition].Ceiling if req.Parent.IsZero() { diff --git a/internal/identitybroker/authorize.go b/internal/identitybroker/authorize.go index c98cae8ec1..be46d18127 100644 --- a/internal/identitybroker/authorize.go +++ b/internal/identitybroker/authorize.go @@ -62,6 +62,7 @@ func (b *Broker) AuthorizeCall(ctx context.Context, workload Workload, req Autho // Check 7: the agent's stored effective ceiling allows the exact server // and tool. + // Shortcut: the ceiling follows the definition the agent reported at registration, so a root reporting system/main gets every gateway server, and a child reporting a built-in gets its parent's whole ceiling rather than a narrower one; removed by #2551 (root eligibility and nesting checks). t.mu.Lock() ceiling := t.agents[agent.Agent.Subject].ceiling t.mu.Unlock() diff --git a/internal/identitybroker/ceiling.go b/internal/identitybroker/ceiling.go index b39bffe7a9..3047db8e87 100644 --- a/internal/identitybroker/ceiling.go +++ b/internal/identitybroker/ceiling.go @@ -1,9 +1,9 @@ package identitybroker import ( - "fmt" "maps" "slices" + "strconv" "strings" ) @@ -32,7 +32,10 @@ type CeilingServer struct { // NewCeiling returns the ceiling granting each of servers, minus its // excluded tools. A server listed twice is granted once, with the union of -// its exclusions. Blank server and tool names are ignored. +// its exclusions. Blank server names are ignored and server names are +// trimmed, as the harness trims a definition's server references; tool names +// are kept exactly, as the harness matches exclusions exactly, and an empty +// one is ignored. func NewCeiling(servers ...CeilingServer) Ceiling { c := Ceiling{servers: map[string]map[string]struct{}{}} for _, s := range servers { @@ -42,7 +45,7 @@ func NewCeiling(servers ...CeilingServer) Ceiling { } except := c.servers[name] for _, tool := range s.ExceptTools { - if tool = strings.TrimSpace(tool); tool == "" { + if tool == "" { continue } if except == nil { @@ -71,8 +74,8 @@ func (c Ceiling) allowsServer(server string) bool { return ok } -// allows reports whether c allows a call of tool, by its name on server. -func (c Ceiling) allows(server, tool string) bool { +// Allows reports whether c allows a call of tool, by its name on server. +func (c Ceiling) Allows(server, tool string) bool { except, ok := c.servers[server] if !ok { return false @@ -105,7 +108,10 @@ func (c Ceiling) equal(o Ceiling) bool { // String is c in a canonical form for records: each granted server, sorted, // followed by the tools it excludes, as in "calendar; github except -// delete_repo,merge_pr". It is "none" for a ceiling that grants nothing. +// delete_repo,merge_pr". A tool name other than letters, digits, '_', '-', +// and '.' is quoted as a Go string, so a name holding a separator cannot be +// read as two. Server names are gateway server names, which hold none. It +// is "none" for a ceiling that grants nothing. func (c Ceiling) String() string { servers := c.Servers() if len(servers) == 0 { @@ -115,24 +121,39 @@ func (c Ceiling) String() string { for i, s := range servers { parts[i] = s.Server if len(s.ExceptTools) > 0 { - parts[i] += " except " + strings.Join(s.ExceptTools, ",") + names := make([]string, len(s.ExceptTools)) + for j, tool := range s.ExceptTools { + names[j] = recordToolName(tool) + } + parts[i] += " except " + strings.Join(names, ",") } } return strings.Join(parts, "; ") } +// recordToolName is tool as String records it: bare when it is letters, +// digits, '_', '-', and '.', quoted otherwise. +func recordToolName(tool string) string { + for _, r := range tool { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' && r != '-' && r != '.' { + return strconv.Quote(tool) + } + } + return tool +} + // checkCeiling is design step (6) check 7: the acting agent's stored // effective ceiling allows the call's exact server and tool, by its name on -// the server, or, for a listing, the server. It is one function so generated -// Cedar policy (#2849) replaces only its body. +// the server, or, for a listing, the server. Its refusal does not name the +// ceiling, which can hold a parent's exclusions; the decision record does. // -// Shortcut: the ceiling is a plain set check, not generated Cedar policy, and decision records name no policy revision; removed by #2849. +// Shortcut: the ceiling is a plain set check, not generated Cedar policy, and decision records name no policy revision; removed by #2849, which also replaces the Ceiling value and its intersection with generated policy. func checkCeiling(c Ceiling, method, server, tool string) error { switch { case method == MethodToolsList && c.allowsServer(server): return nil - case method == MethodToolsCall && c.allows(server, tool): + case method == MethodToolsCall && c.Allows(server, tool): return nil } - return deniedError(fmt.Sprintf("the agent's tool limit (%s) does not allow the call", c)) + return deniedError("the agent's tool limit does not allow the call") } diff --git a/internal/identitybroker/ceiling_internal_test.go b/internal/identitybroker/ceiling_internal_test.go index 3939ec9d5a..d86fa1d39a 100644 --- a/internal/identitybroker/ceiling_internal_test.go +++ b/internal/identitybroker/ceiling_internal_test.go @@ -2,6 +2,7 @@ package identitybroker import ( "math/rand/v2" + "strings" "testing" ) @@ -16,11 +17,11 @@ func TestCeilingAllowsExactPairs(t *testing.T) { {"calendar", "merge_pr", true}, // the same tool name on another server is its own pair {"slack", "read_pr", false}, // a server the ceiling does not grant } { - if got := c.allows(tc.server, tc.tool); got != tc.want { + if got := c.Allows(tc.server, tc.tool); got != tc.want { t.Errorf("allows(%q, %q) = %v, want %v", tc.server, tc.tool, got, tc.want) } } - if (Ceiling{}).allows("github", "read_pr") || NewCeiling().allowsServer("github") { + if (Ceiling{}).Allows("github", "read_pr") || NewCeiling().allowsServer("github") { t.Fatal("an empty ceiling allows a call") } if got := c.String(); got != "calendar; github except merge_pr" { @@ -31,6 +32,53 @@ func TestCeilingAllowsExactPairs(t *testing.T) { } } +// TestCeilingMatchesToolNamesExactly keeps tool names as given, as the +// harness matches a definition's exclusions: case, surrounding spaces, dots, +// and underscores are part of the name. +func TestCeilingMatchesToolNamesExactly(t *testing.T) { + c := NewCeiling(CeilingServer{Server: " github ", ExceptTools: []string{" merge", "Delete", "pr.merge", "_x"}}) + for _, tc := range []struct { + tool string + want bool + }{ + {"merge", true}, // " merge" is another name + {" merge", false}, + {"delete", true}, // case matters + {"Delete", false}, + {"pr.merge", false}, + {"pr", true}, + {"_x", false}, + {"x", true}, + } { + if got := c.Allows("github", tc.tool); got != tc.want { + t.Errorf("Allows(github, %q) = %v, want %v", tc.tool, got, tc.want) + } + } +} + +// TestCeilingStringIsUnambiguous quotes a tool name holding a separator, so +// a recorded ceiling reads back one way. +func TestCeilingStringIsUnambiguous(t *testing.T) { + c := NewCeiling( + CeilingServer{Server: "github", ExceptTools: []string{"a,b", "c; calendar", "x except y", "pr.merge"}}, + CeilingServer{Server: "calendar"}, + ) + want := `calendar; github except "a,b","c; calendar",pr.merge,"x except y"` + if got := c.String(); got != want { + t.Fatalf("String = %s, want %s", got, want) + } +} + +// TestCheckCeilingRefusalHidesTheCeiling keeps the ceiling, which can hold +// a parent's exclusions, out of the refusal the caller sees. +func TestCheckCeilingRefusalHidesTheCeiling(t *testing.T) { + c := NewCeiling(CeilingServer{Server: "github", ExceptTools: []string{"secret_parent_exclusion"}}) + err := checkCeiling(c, MethodToolsCall, "github", "secret_parent_exclusion") + if err == nil || strings.Contains(err.Error(), "secret_parent_exclusion") || strings.Contains(err.Error(), "github") { + t.Fatalf("refusal = %v, want one that names no part of the ceiling", err) + } +} + func TestCheckCeilingListsOnlyGrantedServers(t *testing.T) { c := NewCeiling(CeilingServer{Server: "github", ExceptTools: []string{"merge_pr"}}) if err := checkCeiling(c, MethodToolsList, "github", ""); err != nil { @@ -78,8 +126,8 @@ func TestCeilingIntersectionIsWithinBoth(t *testing.T) { effective := definition.intersect(parent) for _, s := range append(servers, "other") { for _, tool := range append(tools, "other") { - want := definition.allows(s, tool) && parent.allows(s, tool) - if got := effective.allows(s, tool); got != want { + want := definition.Allows(s, tool) && parent.Allows(s, tool) + if got := effective.Allows(s, tool); got != want { t.Fatalf("definition %s, parent %s: effective %s allows(%s, %s) = %v, want %v", definition, parent, effective, s, tool, got, want) } } diff --git a/internal/identitybroker/ceiling_test.go b/internal/identitybroker/ceiling_test.go index 7bbd3d5f83..dee1876282 100644 --- a/internal/identitybroker/ceiling_test.go +++ b/internal/identitybroker/ceiling_test.go @@ -133,7 +133,7 @@ func TestAuthorizeCallChecksTheEffectiveCeiling(t *testing.T) { // of the call's server. func TestAuthorizeCallToolMustBeNamedForItsServer(t *testing.T) { f := newCeilingFixture(t) - for _, tool := range []string{"pull_request_read", "calendar.pull_request_read", "github."} { + for _, tool := range []string{"pull_request_read", "calendar.pull_request_read", "github.", "GitHub.pull_request_read", "github_pull_request_read"} { req := callRequest(f.s.ID, f.cred) req.OperationID, req.Tool = "op-"+tool, tool _, err := f.authorize(req) @@ -154,3 +154,45 @@ func TestAuthorizeCallGatewayRouteIsCheckedBeforeTheCeiling(t *testing.T) { t.Fatalf("a call refused at check 6 names ceiling %q", d[len(d)-1].Ceiling) } } + +// TestAuthorizeCallSplitsOnlyTheServerPrefix takes everything after the +// server's name and dot as the tool's name on the server, so dots and double +// underscores in a tool name are part of it. +func TestAuthorizeCallSplitsOnlyTheServerPrefix(t *testing.T) { + f := newCeilingFixture(t) + const full = "calendar; github" + for i, tool := range []string{"pr.merge", "a__b", "a.b__c"} { + f.wantAllowed(t, f.call(f.cred, "R42", "", "op-split-"+string(rune('a'+i)), tool), full) + } + // The reviewer's exclusion is the exact name, not a prefix of a dotted + // one. + const narrowed = "calendar; github except " + conformance.ReviewerExcludedTool + f.wantAllowed(t, f.call(f.reviewerCred, "R43", "D1", "op-reviewer-dotted", conformance.ReviewerExcludedTool+".dry_run"), narrowed) +} + +// TestAuthorizeCallChildCannotGainAServerItsParentLacks registers a child +// whose definition grants github under a parent whose ceiling is empty: its +// effective ceiling is empty, so its calls are refused. +func TestAuthorizeCallChildCannotGainAServerItsParentLacks(t *testing.T) { + f := newCeilingFixture(t) + child, err := f.b.RegisterAgent(context.Background(), testWorkload, identitybroker.RegisterAgentRequest{ + SessionID: f.s.ID, HostSessionID: "hostS-under-tool-less", Owner: testOwner, Incarnation: "inc_gbcdefghijklmnopqrstuvwxya", + Definition: conformance.DeployerDefinition, Parent: f.toolLess, ParentHostSessionID: "hostS-tool-less", + }) + if err != nil { + t.Fatalf("RegisterAgent: %v", err) + } + if err := f.b.ReportDelegation(context.Background(), testWorkload, identitybroker.ReportDelegationRequest{ + SessionID: f.s.ID, Owner: testOwner, DelegationID: "D5", + DelegatingRun: "R46", DelegatingAgent: f.toolLess, ReceivingRun: "R47", ReceivingAgent: child.Agent, + }); err != nil { + t.Fatalf("ReportDelegation: %v", err) + } + exchanges, redemptions := len(f.issuer.requests()), len(f.as2.redeemed()) + _, err = f.authorize(f.call(child.Credential, "R47", "D5", "op-child", "pull_request_read")) + wantError(t, err, identitybroker.CodePermissionDenied, identitybroker.ReasonDenied, f.cred, child.Credential) + f.wantCounts(t, exchanges, redemptions) + if d := f.rec.Decisions(); d[len(d)-1].Ceiling != "none" { + t.Fatalf("decision = %+v, want a refusal under ceiling none", d[len(d)-1]) + } +} diff --git a/internal/identitybroker/gateway.go b/internal/identitybroker/gateway.go index 3bae878797..e11a7aebfa 100644 --- a/internal/identitybroker/gateway.go +++ b/internal/identitybroker/gateway.go @@ -240,9 +240,12 @@ func (g *Gateway) validate() error { // isGatewayServerName reports whether s is a server name the gateway may // route: letters, digits, and underscores, never two underscores together, as // Mecatl's MCP configuration requires of server names. A call's tool is named -// "." and a definition excludes one as "mcp____", -// so a dot or a double underscore in a server name would let one server's -// name begin another's, and a tool of one pass as a tool of the other. +// ".", so with no dot in a server name a call names exactly one +// server and tool. A definition excludes a tool as "mcp____", +// which one rule cannot keep unambiguous while the configuration allows a +// trailing underscore: "mcp__git___x" is tool "_x" on git and tool "x" on +// git_. The loader then excludes it from both, so an ambiguous exclusion only +// narrows. func isGatewayServerName(s string) bool { if s == "" || strings.Contains(s, "__") { return false diff --git a/user-docs/operating/mecak8s/identity-and-client-access.md b/user-docs/operating/mecak8s/identity-and-client-access.md index 27a0be2dbe..e2b60acc02 100644 --- a/user-docs/operating/mecak8s/identity-and-client-access.md +++ b/user-docs/operating/mecak8s/identity-and-client-access.md @@ -237,7 +237,7 @@ identityBroker: |Value|Flag|Meaning| |-|-|-| -|`identityBroker.enabled`|`--enable-identity-broker`|Starts the identity broker. Requires `replicaCount: 1`, `oidc.ownerIdentity: sub_id` when OIDC is enabled, and no shell in the process: `--no-shell` in `extraArgs`, or `--shell=` with `execution.enabled` to keep the remote Shell. The chart refuses to render without one. The Deployment rolls out with `Recreate`. This value is the only way to start the broker: the chart refuses `--enable-identity-broker` in `extraArgs`. With protected MCP servers configured, turning it on or off changes the audience of the MCP gateway's tokens, so those servers must be [enrolled](/features/security-and-execution/mcp-oauth-and-credentials.md) again. Each session's main agent gets its own agent identity, and so does each [subagent, parallel branch, and team member](/features/agent-behavior/subagents-and-teams.md) it starts. Helpers call the MCP gateway's tools under their own identity. A helper that runs no named agent gets all of them; one running a named agent gets the tools of each server its `mcpServers` lists, minus those its `disallowedTools` names. A helper never gets another MCP broker tool. The broker refuses a gateway call outside an agent's limit: the tools its agent allows, as above, narrowed by the limit of the agent that started it. The broker accepts only built-in agents or a [named agent](/features/agent-behavior/named-agents.md#choose-where-definitions-are-discovered) from a directory passed with `--agents-dir` in `extraArgs` and mounted with `extraVolumes` and `extraVolumeMounts`. A session that uses a named agent from any other location cannot run, a subagent or team member that names one cannot start, and a `--agents-dir` directory that does not exist stops startup. With an operator [`harness_context`](/operating/settings.md#select-harness-context-sources) policy, which can let another source win an agent name, only built-in agents can run.| +|`identityBroker.enabled`|`--enable-identity-broker`|Starts the identity broker. Requires `replicaCount: 1`, `oidc.ownerIdentity: sub_id` when OIDC is enabled, and no shell in the process: `--no-shell` in `extraArgs`, or `--shell=` with `execution.enabled` to keep the remote Shell. The chart refuses to render without one. The Deployment rolls out with `Recreate`. This value is the only way to start the broker: the chart refuses `--enable-identity-broker` in `extraArgs`. With protected MCP servers configured, turning it on or off changes the audience of the MCP gateway's tokens, so those servers must be [enrolled](/features/security-and-execution/mcp-oauth-and-credentials.md) again. Each session's main agent gets its own agent identity, and so does each [subagent, parallel branch, and team member](/features/agent-behavior/subagents-and-teams.md) it starts. Helpers call the MCP gateway's tools under their own identity. A helper that runs no named agent gets all of them. One running a named agent gets the tools of each server its `mcpServers` names by reference, minus each tool its `disallowedTools` names as `mcp____`; an inline server entry and the `tools` list add no gateway tools. A helper never gets another MCP broker tool. The broker refuses a gateway call outside an agent's limit: the tools its agent allows, as above, narrowed by the limit of the agent that started it. These gateway calls need a gateway the broker routes, which the chart doesn't configure yet, so for now helpers get no gateway tools. The broker accepts only built-in agents or a [named agent](/features/agent-behavior/named-agents.md#choose-where-definitions-are-discovered) from a directory passed with `--agents-dir` in `extraArgs` and mounted with `extraVolumes` and `extraVolumeMounts`. A session that uses a named agent from any other location cannot run, a subagent or team member that names one cannot start, and a `--agents-dir` directory that does not exist stops startup. With an operator [`harness_context`](/operating/settings.md#select-harness-context-sources) policy, which can let another source win an agent name, only built-in agents can run.| |`identityBroker.subjectClaim`|`--identity-broker-subject-claim`|The company IdP's ID-token claim that names each user. Required with `identityBroker.as1.issuer`, and allowed only with it.| |`identityBroker.as1.issuer`|`--identity-broker-as1-issuer`|AS-1's HTTPS issuer URL. Setting it hosts AS-1 and requires `oidc.enabled`, `oidc.audience`, and `oidc.resource`. AS-1 accepts only an absolute `http` or `https` URL with a host and no fragment as the audience, such as `https://mecatl.example.com/api`.| |`identityBroker.as1.tuiClientID`|`--identity-broker-as1-tui-client-id`|The client ID `mecatui` uses at AS-1.| From aa312f57be9467ded07ff96fd34f5076eb6b96ae Mon Sep 17 00:00:00 2001 From: Radoslav Dimitrov Date: Sat, 21 Nov 2026 21:10:42 +0200 Subject: [PATCH 3/3] fix(app): keep a file-less team member to its definition's tool limit A team member without a filesystem skipped its agent definition entirely, so it got every server-global MCP tool and every gateway tool, including ones its definition excludes, and registered with the identity broker as the built-in member, so the broker allowed them too. With the broker on, file-less is the only setup outside Kubernetes execution (#2875). A file-less member that names a definition now gets the file-less core tools its definition does not exclude, its definition's own MCP servers instead of the server-global ones and CallMcpWithQuery, and its servers' gateway tools, and reports the definition, so the broker checks the same limit. The rest of the definition stays file-oriented and is not applied. The named team member end-to-end test runs again, file-less. Co-Authored-By: Claude Opus 5.5 --- .../identity_broker_tool_limit_test.go | 37 ++++++++++++ internal/app/build.go | 37 +++++++++--- internal/app/catalog.go | 34 +++++++++++ internal/app/defgatewaytools_test.go | 6 +- internal/app/nofs_team_test.go | 56 +++++++++++++++++++ user-docs/features/sessions/tools.md | 4 +- 6 files changed, 162 insertions(+), 12 deletions(-) diff --git a/cmd/mecak8s/identity_broker_tool_limit_test.go b/cmd/mecak8s/identity_broker_tool_limit_test.go index 6ae80f7393..cce2d6fe77 100644 --- a/cmd/mecak8s/identity_broker_tool_limit_test.go +++ b/cmd/mecak8s/identity_broker_tool_limit_test.go @@ -68,3 +68,40 @@ func TestIdentityBrokerNamedHelperGetsItsDefinitionsGatewayTools(t *testing.T) { } } } + +// TestIdentityBrokerNamedTeamMemberGetsItsDefinitionsGatewayTools pins the +// same for a team member that runs a named definition, in the file-less +// sessions the broker runs without Kubernetes execution: one referencing the +// gateway's server calls its tool under its own identity; one that excludes +// the tool never reaches the gateway. +func TestIdentityBrokerNamedTeamMemberGetsItsDefinitionsGatewayTools(t *testing.T) { + agents := t.TempDir() + for name, frontmatter := range map[string]string{ + "calendar-reader": "mcpServers: [calendar]\n", + "no-echo": "mcpServers: [calendar]\ndisallowedTools: [mcp__calendar__echo]\n", + } { + content := "---\nname: " + name + "\ndescription: A " + name + " specialist.\n" + frontmatter + "---\nYou help.\n" + if err := os.WriteFile(filepath.Join(agents, name+".md"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + team := func(agent string) string { + return `{"tool_calls":[{"id":"team","name":"Team","args":{"goal":"call the calendar","members":[{"name":"member","role":"call","agent":"` + agent + `"}]}}]}` + } + + t.Run("referencing the server", func(t *testing.T) { + d := serveDelegations(t, "--agents-dir", agents) + d.writeScript(t, gatewayTurn("main-call"), team("calendar-reader"), gatewayTurn("member-call"), scriptText) + promptApprovingAsks(t, d.api, d.alice, d.session, "go", nil) + d.wantHelperGatewayCalls(t, 1) + }) + + t.Run("excluding the tool", func(t *testing.T) { + d := serveDelegations(t, "--agents-dir", agents) + d.writeScript(t, gatewayTurn("main-call"), team("no-echo"), gatewayTurn("member-call"), scriptText) + promptApprovingAsks(t, d.api, d.alice, d.session, "go", nil) + if ops := d.diag.operations(d.session); len(ops) != 1 { + t.Fatalf("%d gateway calls, want only the main agent's", len(ops)) + } + }) +} diff --git a/internal/app/build.go b/internal/app/build.go index d5d0e101b7..e73847bb7f 100644 --- a/internal/app/build.go +++ b/internal/app/build.go @@ -8476,12 +8476,15 @@ func modelCfgFor(cfg Config, model string) Config { // buildForceCopyRunner), so untrust withholds ONLY the worktree shell — the // asymmetry the trust-gate tests pin. // NO-FS PROFILE (issue #55): with noFS true every member — lead included, -// Mutating or not, def or not — gets the SAME file-less surface: the no-FS child -// catalog (memory six + WebFetch + global MCP) + the team coordination tools, -// with the noFSMemberNote prompt posture and no cwd/shell/git in its . -// Agent-def adoption is deliberately SKIPPED on this branch (a def's scoped -// catalog is file-oriented — same rationale as buildNoFSSubagentTool); the -// member still resolves its model through the def-less chain. The catalog's +// Mutating or not — gets the file-less surface: the no-FS child catalog +// (memory six + WebFetch + global MCP) + the team coordination tools, with the +// noFSMemberNote prompt posture and no cwd/shell/git in its . A member +// that names a def keeps to the def's tool limit (newNoFSDefinedMemberCatalog: +// its exclusions, its own MCP servers, its servers' gateway tools) and reports +// the def, so the identity broker checks the same limit; the rest of the def +// (prompt, model, hooks) stays file-oriented and is SKIPPED, the same rationale +// as buildNoFSSubagentTool, and the member resolves its model through the +// def-less chain. The catalog's // non-read-only tools (Remember/RememberUser, MCP) ride MemberBuild.MCPToolNames // — the supervisor's documented exemption for non-WORKSPACE mutators — so the // base-sharing read-only-member backstop stays sound. `a` is read only when noFS. @@ -8526,7 +8529,21 @@ func buildMemberSelectorEngine(cfg Config, provReg *providerRegistry, provider p } windowFn = childWindowFor(cfg, provReg, childProviderID, model) } - classified := newNoFSClassifiedChildCatalog(context.Background(), cfg, a) + // A member that names a definition keeps to its tool limit even + // without a filesystem: its catalog follows the definition's + // exclusions and MCP servers, and it reports the definition, so the + // identity broker checks its calls against the same limit. The rest + // of the definition (prompt, model, hooks) stays file-oriented and + // is not applied here. + var classified *classifiedCatalog + var defClose func() error + var definitionName string + if def, defined := lookupMemberDef(cfg.diag(), reg, spec); defined { + classified, defClose = newNoFSDefinedMemberCatalog(context.Background(), cfg, a, def, mainMgr) + definitionName = def.Name + } else { + classified = newNoFSClassifiedChildCatalog(context.Background(), cfg, a) + } cat := classified.catalog // Exempt the catalog's non-workspace mutators (memory writers, MCP // tools) BEFORE the coordination tools are added (those are exempted @@ -8540,7 +8557,11 @@ func buildMemberSelectorEngine(cfg Config, provReg *providerRegistry, provider p mustValidateClassifiedCatalog(classified, "no-FS team member tool catalog") pc := applyNoFSPosture(promptConfig(modelCfgFor(cfg, model), ""), noFSMemberNote) eng := newChildEngineForProvider(cfg, "member:"+spec.Name, childProvider, session.ProviderModelID{ProviderID: childProviderID, ModelID: model}, windowFn, cat, pc, nil) - return agent.MemberBuild{Engine: eng, Provider: childProviderID, Close: generationClose, MCPToolNames: exempt} + memberClose := generationClose + if defClose != nil { + memberClose = sync.OnceValue(func() error { return errors.Join(defClose(), generationClose()) }) + } + return agent.MemberBuild{Engine: eng, Provider: childProviderID, Close: memberClose, MCPToolNames: exempt, DefinitionName: definitionName} } classified := newClassifiedCatalog() cat := classified.catalog diff --git a/internal/app/catalog.go b/internal/app/catalog.go index 358dca53a4..a9fbb1034e 100644 --- a/internal/app/catalog.go +++ b/internal/app/catalog.go @@ -834,6 +834,40 @@ func newNoFSClassifiedChildCatalog(ctx context.Context, cfg Config, a catalogAss return classified } +// newNoFSDefinedMemberCatalog is the file-less catalog of a team member +// that runs def: the file-less core and memory tools def does not exclude, +// def's own MCP tools (defMCPTools: its referenced and inline servers, minus +// its exclusions) in place of the server-global ones and CallMcpWithQuery, +// and the session's gateway tools of the servers def references +// (defGatewayTools). It is the tool limit a defined member keeps with a +// filesystem, so the definition narrows the member the same way either way. +// The returned func closes def's inline MCP servers; it may be nil. +func newNoFSDefinedMemberCatalog(ctx context.Context, cfg Config, a catalogAssets, def agents.AgentDef, mainMgr *mcp.Manager) (*classifiedCatalog, func() error) { + base, baseAssets := cfg, a + base.helperTools, baseAssets.globalMgr = nil, nil + generic := newNoFSClassifiedChildCatalog(ctx, base, baseAssets) + out := newClassifiedCatalog() + for _, t := range generic.catalog.Tools() { + name := t.Spec().Name + if defDisallowsTool(def, name) { + continue + } + entry := generic.entries[name] + out.mustRegister(t, &entry) + } + mcpTools, _, _, closeFn := defMCPTools(ctx, cfg.diag(), def, mainMgr) + mcpEntry := classification(server.KindDerived, + "member agent-definition MCP tools are scoped to this already authorized team member") + for _, mt := range mcpTools { + if err := out.register(mt, mcpEntry); err != nil { + cfg.diag().Log(ctx, port.LevelWarn, "no-FS team member agent def MCP tool registration failed; skipped", + "agent", def.Name, "tool", mt.Spec().Name, "err", err) + } + } + registerHelperTools(out, defGatewayTools(def, cfg.helperTools), cfg.diag()) + return out, closeFn +} + func noFSChildCatalog(ctx context.Context, cfg Config, a catalogAssets) *tool.Catalog { classified := newNoFSClassifiedChildCatalog(ctx, cfg, a) mustValidateClassifiedCatalog(classified, "no-FS child tool catalog") diff --git a/internal/app/defgatewaytools_test.go b/internal/app/defgatewaytools_test.go index fee051b752..1e16d6adc2 100644 --- a/internal/app/defgatewaytools_test.go +++ b/internal/app/defgatewaytools_test.go @@ -166,9 +166,9 @@ func (c countingGatewayTool) Execute(_ context.Context, call session.ToolCall, _ // running a named definition through the member factory with the session's // gateway tools (#2842): it gets the tools of the server its definition // references, minus the one it excludes, and the excluded tool never runs. -// The broker's own end-to-end tests cannot start a team member running a -// named definition: that needs a workspace, which the broker allows only -// with Kubernetes execution. +// This is the member path with a filesystem, which the broker allows only +// with Kubernetes execution, so its end-to-end tests reach only the +// file-less one. func TestNamedMemberGetsItsDefinitionsGatewayTools(t *testing.T) { var lookups, echoes atomic.Int32 cfg := Config{Workspace: t.TempDir(), Model: "m"} diff --git a/internal/app/nofs_team_test.go b/internal/app/nofs_team_test.go index 9dc55a4717..06c0f3ca91 100644 --- a/internal/app/nofs_team_test.go +++ b/internal/app/nofs_team_test.go @@ -5,6 +5,7 @@ import ( "errors" "strings" "sync" + "sync/atomic" "testing" agents "github.com/stacklok/mecatl/engine/adapter/agentfs" @@ -188,3 +189,58 @@ func TestNoFSTeamLeadSynthesisSmoke(t *testing.T) { } } } + +// TestNoFSDefinedMemberKeepsToItsToolLimit pins that a file-less team member +// that names a definition keeps to the definition's tool limit, as it does +// with a filesystem: the gateway tools of the server it references minus the +// one it excludes, its own MCP servers instead of the server-global ones and +// CallMcpWithQuery, the core tools it does not exclude, and the definition +// reported for the identity broker. A generic member keeps the whole file-less +// surface. +func TestNoFSDefinedMemberKeepsToItsToolLimit(t *testing.T) { + a := noFSTeamAssets(t) + var calls atomic.Int32 + cfg := Config{Model: "mock", Diagnostics: port.NopDiagnostics{}} + cfg.helperTools = []tool.Tool{ + countingGatewayTool{fakeGatewayTool{"calendar", "lookup"}, &calls}, + countingGatewayTool{fakeGatewayTool{"calendar", "echo"}, &calls}, + } + def := agents.AgentDef{ + Name: "scoped", + Description: "a member whose definition limits its tools", + DisallowedTools: []string{"mcp__calendar__echo", "WebFetch"}, + MCPServers: []agents.AgentMCPServer{{Name: "calendar"}}, + } + provider := mockllm.New(mockllm.TextTurn("ok")) + factory := buildMemberEngine(cfg, regForTest(provider, providerMock, cfg.Model), provider, providerMock, cfg.Model, + nil, regOf(def), nil, nil, nil, false, a.globalMgr, a, true) + tm := team.New("nofs-team") + + defined := factory(tm, agent.MemberSpec{Name: "scout", AgentType: "scoped", InitialPrompt: "go"}, "") + if defined.Engine == nil { + t.Fatal("no engine for the defined member") + } + if defined.DefinitionName != "scoped" { + t.Fatalf("DefinitionName = %q, want the definition the member keeps to", defined.DefinitionName) + } + for _, name := range []string{"mcp__calendar__lookup", "Remember"} { + if !defined.Engine.HasTool(name) { + t.Errorf("the defined member lacks %q", name) + } + } + for _, name := range []string{"mcp__calendar__echo", "WebFetch", "mcp__globe__echo", "CallMcpWithQuery"} { + if defined.Engine.HasTool(name) { + t.Errorf("the defined member has %q, which its definition does not allow", name) + } + } + + generic := factory(tm, agent.MemberSpec{Name: "generic", InitialPrompt: "go"}, "") + if generic.DefinitionName != "" { + t.Fatalf("a generic member reports definition %q", generic.DefinitionName) + } + for _, name := range []string{"mcp__calendar__lookup", "mcp__calendar__echo", "WebFetch", "mcp__globe__echo", "CallMcpWithQuery"} { + if !generic.Engine.HasTool(name) { + t.Errorf("the generic member lacks %q", name) + } + } +} diff --git a/user-docs/features/sessions/tools.md b/user-docs/features/sessions/tools.md index 25b1ccb181..ff51d9844d 100644 --- a/user-docs/features/sessions/tools.md +++ b/user-docs/features/sessions/tools.md @@ -207,7 +207,9 @@ calls. Mecatl cancels them when the run ends. A session created with `execution: {none: {}}` removes `Read`/`ListDir`/`Write`/`Edit`/`Copy`/`Move`/`Remove`/`Grep`/`Glob`/`Shell`/`ShellStatus`/`Parallel`/`SkillDraft` from the catalog. `WebFetch`, `WebSearch`, memory, and MCP tools remain. -Children inherit the file-less catalog. Clients choose execution when creating +Children inherit the file-less catalog. A team member that names an agent +definition still keeps to its tool limits: its `disallowedTools` and its own +`mcpServers` apply, and the rest of the definition does not. Clients choose execution when creating the session; the model cannot change it. See [Execution environments](/features/security-and-execution/execution-environments.md) for filesystem and no-filesystem placement.