Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions cmd/mecak8s/identity_broker_delegations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,15 @@ type delegationServe struct {
session string
}

func serveDelegations(t *testing.T) *delegationServe {
// serveDelegations serves mecak8s with teams on and extraArgs as further
// flags.
func serveDelegations(t *testing.T, extraArgs ...string) *delegationServe {
t.Helper()
return serveDelegationsWith(t, append([]string{"--enable-teams"}, extraArgs...)...)
}

// serveDelegationsWith serves mecak8s with args as its only further flags.
func serveDelegationsWith(t *testing.T, args ...string) *delegationServe {
t.Helper()
d := &delegationServe{diag: &gatewayCallDiagnostics{}, script: filepath.Join(t.TempDir(), "script.json")}
model := newLateScript(d.script)
Expand All @@ -67,7 +75,7 @@ func serveDelegations(t *testing.T) *delegationServe {
// Kubernetes execution, which this suite cannot start. They report their
// delegations through the same RegisterHelper path these tests drive.
d.gatewayServe = serveGatewayIdentityBroker(t, notesRoute(t),
[]string{"--enable-teams"},
args,
func(cfg *app.Config) {
cfg.MockProvider = model
cfg.Diagnostics = d.diag
Expand Down Expand Up @@ -126,8 +134,8 @@ func (d *delegationServe) wantHelperGatewayCalls(t *testing.T, minHelperCalls in

// 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"),
Expand Down
20 changes: 19 additions & 1 deletion cmd/mecak8s/identity_broker_harness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,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")
Expand Down Expand Up @@ -1146,6 +1146,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()
Expand Down
16 changes: 2 additions & 14 deletions cmd/mecak8s/identity_broker_helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cmd/mecak8s/identity_broker_real_as1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
107 changes: 107 additions & 0 deletions cmd/mecak8s/identity_broker_tool_limit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package main

import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/alicebob/miniredis/v2"

"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)
}
}
// Named definitions run only in sessions with a workspace, and the broker
// allows one only through a placement provider, so sessions use the Redis
// filesystem.
mr := miniredis.RunT(t)
d := serveDelegationsWith(t, "--agents-dir", agents, "--redis-url", mr.Addr(), "--redis-allow-plaintext", "--redis-filesystem")
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, 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))
}
})
}
2 changes: 1 addition & 1 deletion docs/drafts/agent-identity/agent-definitions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion docs/drafts/agent-identity/credentials-and-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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 `<server>.<tool>` | `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)). |
Expand Down
2 changes: 1 addition & 1 deletion docs/drafts/agent-identity/implementation.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,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;
Expand Down
Loading
Loading