From 13ee11378ff017ec29f0b29917a166e04042ae18 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Fri, 27 Nov 2026 12:48:21 +0000 Subject: [PATCH 1/4] api, envoy: check the MCP tool name as the backend receives it The HTTP inspection of an MCP tools/call removed the spaces around the tool name and a "scheme://service/" prefix before a task rule checked the name against allowed_tools. The backend receives the body unchanged, so the name that was checked was not the name that the backend got. The service of the prefix was also ignored: with allowed_tools [get_pr] on mcp://github, a call of "mcp://gitlab/get_pr" passed as get_pr of github. A backend that serves tools of more than one service under such names would run a tool that the rule does not allow. InspectJSONRPCMCPBody now returns the name as the body states it, as the check on a /mesh/mcp stream already does. A name with a prefix or with spaces is not in allowed_tools, so a task rule with allowed_tools denies it. ValidateTaskAuthorizationRule refuses an allowed_tools entry with a slash, so no rule can allow the prefixed name. A request under a credential with no allowed_tools does not change. No client of this repository puts a prefixed name in params.name: the node and the SDKs split "mcp://service/tool" before they send the call. --- api/mcp.go | 17 +++--- api/mcp_test.go | 56 ++++++++++++++++++- internal/envoy/envoy_test.go | 2 +- internal/envoy/server.go | 5 +- internal/node/sts_test.go | 2 +- .../contributing/security-architecture.md | 5 +- 6 files changed, 70 insertions(+), 17 deletions(-) diff --git a/api/mcp.go b/api/mcp.go index 4956a4c1..c415d84a 100644 --- a/api/mcp.go +++ b/api/mcp.go @@ -41,7 +41,7 @@ const ( const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20 // InspectJSONRPCMCPBody inspects a JSON-RPC 2.0 request body for MCP methods -// and extracts the bare tool name when present, or sets allowStreamInit for +// and extracts the tool name when present, or sets allowStreamInit for // session handshake, capability discovery, and protocol notification methods // that precede a tool call. // @@ -50,6 +50,12 @@ const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20 // body that is not one JSON object, or that states "method", "params" or the // tool "name" more than once (uniqueJSONMembers), names no tool and no // handshake method: a task rule with allowed_tools denies it. +// +// The tool name is the string of the body, unchanged. A name with spaces +// around it, or with a "scheme://service/" prefix, is not the tool of +// allowed_tools that it resembles: the backend receives the name as the body +// states it, and the service of the prefix is not the service that was +// checked. func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { if len(bytes.TrimSpace(body)) == 0 { return "", false @@ -71,14 +77,7 @@ func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { if err != nil { return "", false } - rawTool := strings.TrimSpace(name) - if rawTool == "" { - return "", false - } - if _, stripped, err := SplitToolName(rawTool); err == nil { - return stripped, false - } - return rawTool, false + return name, false default: return "", false } diff --git a/api/mcp_test.go b/api/mcp_test.go index b0e8f84d..f6a736ec 100644 --- a/api/mcp_test.go +++ b/api/mcp_test.go @@ -15,11 +15,13 @@ package api import ( + "encoding/json" "io" "net/http" "net/http/httptest" "strings" "testing" + "time" ) func TestInspectJSONRPCMCPBody(t *testing.T) { @@ -35,10 +37,18 @@ func TestInspectJSONRPCMCPBody(t *testing.T) { wantTool: "read_file", wantAllow: false, }, + // The backend receives the name as the body states it. A name that + // only resembles a tool of allowed_tools is not that tool. { - name: "tools/call namespaced tool", + name: "tools/call with a service prefix keeps the name of the body", body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp://github/get_pr"}}`, - wantTool: "get_pr", + wantTool: "mcp://github/get_pr", + wantAllow: false, + }, + { + name: "tools/call with spaces around the name keeps the name of the body", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":" read_file "}}`, + wantTool: " read_file ", wantAllow: false, }, { @@ -151,8 +161,48 @@ func TestInspectJSONRPCMCPBody(t *testing.T) { } } +// A task rule checks the tool that the backend receives. A name with a +// service prefix, or with spaces around it, is not the tool of allowed_tools +// that it resembles: the backend gets the name with the prefix and the +// spaces, and the service of the prefix is not the service that was checked. +func TestTaskRuleChecksTheToolNameAsTheBodyStatesIt(t *testing.T) { + rules := []*TaskAuthorizationRule{{Rules: []*TaskRule{{ + AllowedServices: []string{"mcp://github"}, + Operation: &TaskOperation{AllowedTools: []string{"get_pr"}}, + }}}} + for _, tc := range []struct { + name string + tool string + wantDenied bool + }{ + {name: "the allowed tool", tool: "get_pr"}, + {name: "prefix of the same service", tool: "mcp://github/get_pr", wantDenied: true}, + {name: "prefix of another service", tool: "mcp://gitlab/get_pr", wantDenied: true}, + {name: "space before", tool: " get_pr", wantDenied: true}, + {name: "line feed after", tool: "get_pr\n", wantDenied: true}, + } { + t.Run(tc.name, func(t *testing.T) { + name, err := json.Marshal(tc.tool) + if err != nil { + t.Fatalf("encode tool name %q: %v", tc.tool, err) + } + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":` + string(name) + `}}` + tool, allowInit := InspectJSONRPCMCPBody([]byte(body)) + err = EvaluateTaskRules(rules, TaskRequestContext{ + ServiceType: "mcp", + ServiceName: "github", + MCPTool: tool, + AllowMCPStreamInit: allowInit, + }, time.Now()) + if denied := err != nil; denied != tc.wantDenied { + t.Fatalf("tools/call of %q, checked as %q: denied = %v (%v), want %v", tc.tool, tool, denied, err, tc.wantDenied) + } + }) + } +} + func TestInspectMCPHTTPRequestBody(t *testing.T) { - body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp://git/status"}}` + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"status"}}` req := httptest.NewRequest(http.MethodPost, "/mcp/git", strings.NewReader(body)) tool, allowInit, err := InspectMCPHTTPRequestBody(req, 1024) if err != nil { diff --git a/internal/envoy/envoy_test.go b/internal/envoy/envoy_test.go index 6b8fa32a..332249bf 100644 --- a/internal/envoy/envoy_test.go +++ b/internal/envoy/envoy_test.go @@ -108,7 +108,7 @@ func TestGatewayServer_ExtAuthzHTTPAndGRPC(t *testing.T) { addr := startH2CGatewayTestServer(t, gw) // 1. HTTP ext_authz allow & deny - reqAllow := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", strings.NewReader(`{"jsonrpc":"2.0","method":"tools/call","params":{"name":"mcp://github/get_pr"}}`)) + reqAllow := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", strings.NewReader(`{"jsonrpc":"2.0","method":"tools/call","params":{"name":"get_pr"}}`)) reqAllow.Header.Set("Authorization", "Bearer valid-token") recAllow := httptest.NewRecorder() gw.HandleExtAuthzHTTP(recAllow, reqAllow) diff --git a/internal/envoy/server.go b/internal/envoy/server.go index 5a85bb79..7b9b11da 100644 --- a/internal/envoy/server.go +++ b/internal/envoy/server.go @@ -556,8 +556,9 @@ func isMCPRoute(path, targetService string) bool { } // InspectJSONRPCMCPBody inspects a JSON-RPC 2.0 request body for MCP methods -// and extracts the bare tool name when present, or sets allowStreamInit for -// session handshake, capability discovery, and protocol notification methods. +// and extracts the tool name as the body states it, or sets allowStreamInit +// for session handshake, capability discovery, and protocol notification +// methods. func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { return api.InspectJSONRPCMCPBody(body) } diff --git a/internal/node/sts_test.go b/internal/node/sts_test.go index 6abc4935..e8ba6dfb 100644 --- a/internal/node/sts_test.go +++ b/internal/node/sts_test.go @@ -916,7 +916,7 @@ func TestExtAuthzUpstreamCredentialNeedsTrustedTransport(t *testing.T) { } func TestInspectMCPHTTPRequestBody(t *testing.T) { - body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp://github/get_pr"}}` + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_pr"}}` req := httptest.NewRequest(http.MethodPost, "/mcp/github", strings.NewReader(body)) tool, allowInit, err := inspectMCPHTTPRequestBody(req) if err != nil { diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md index e6f0cc97..3ae64e5a 100644 --- a/site/content/docs/contributing/security-architecture.md +++ b/site/content/docs/contributing/security-architecture.md @@ -288,7 +288,10 @@ match at least one `TaskRule` in every appended block. The enforcement point reads the method and the tool name (`params.name`) from a JSON-RPC message that the backend then reads with its own parser. The two -must read the same call. A message that states +must read the same call. The tool name is checked as the message states it: +a name with spaces around it, or with a `scheme://service/` prefix, is not +the tool of `allowed_tools` that it resembles, because the backend receives +that name unchanged. A message that states `method`, `params` or the tool `name` more than once, or in a different letter case (`"METHOD"`, which a case-insensitive JSON parser reads as `method`), names no tool and no handshake method. A rule with `allowed_tools` then denies From 61b9c26f9af23b4ed2aa63ecd593beb467cbce40 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Fri, 27 Nov 2026 14:44:16 +0000 Subject: [PATCH 2/4] api, node: allow the same MCP session requests on HTTP and on a stream A task rule with allowed_tools allows the requests that open or keep a session, and a tools/call of a listed tool. The two enforcement points had their own list of session requests. The check on a /mesh/mcp stream allowed initialize, ping and tools/list. The HTTP inspection also allowed server/discover, resources/list and prompts/list. A credential that grants one tool could thus read the list of the resources and of the prompts of the service on HTTP (router ingress, the node, the Envoy filters), and not on a stream. api.MCPSessionMethod is now the one list: initialize, server/discover, ping and tools/list. Both enforcement points use it. On HTTP, resources/list and prompts/list are denied under allowed_tools, as every other request that is not a tools/call of a listed tool. On a stream nothing changes for a caller: the pass-through answers server/discover itself before the task check. The notifications do not change: HTTP allows notifications/initialized and notifications/cancelled, and a stream allows a notifications/ method with no id. An MCP client that lists resources or prompts when it connects through an ingress or a gateway, with a credential that has allowed_tools, now gets 403 for those two requests. A credential with no allowed_tools does not change. --- api/mcp.go | 29 ++++++--- api/mcp_test.go | 14 +++++ internal/envoy/server.go | 3 +- internal/node/mcp_service.go | 6 +- internal/node/mcp_service_test.go | 61 +++++++++++++++++++ .../contributing/security-architecture.md | 2 +- 6 files changed, 102 insertions(+), 13 deletions(-) diff --git a/api/mcp.go b/api/mcp.go index c415d84a..ff6b5df7 100644 --- a/api/mcp.go +++ b/api/mcp.go @@ -41,9 +41,9 @@ const ( const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20 // InspectJSONRPCMCPBody inspects a JSON-RPC 2.0 request body for MCP methods -// and extracts the tool name when present, or sets allowStreamInit for -// session handshake, capability discovery, and protocol notification methods -// that precede a tool call. +// and extracts the tool name when present, or sets allowStreamInit for a +// method that opens or keeps a session (MCPSessionMethod) and for the two +// notifications that a client sends in a session. // // The backend receives the same bytes and reads them with its own parser, so // the method and the tool read here must be the ones every parser reads. A @@ -68,11 +68,10 @@ func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { if err := json.Unmarshal(members["method"], &method); err != nil { return "", false } - switch method { - case "initialize", "notifications/initialized", "server/discover", "ping", - "tools/list", "resources/list", "prompts/list", "notifications/cancelled": + switch { + case MCPSessionMethod(method), method == "notifications/initialized", method == "notifications/cancelled": return "", true - case "tools/call": + case method == "tools/call": name, err := MCPToolCallName(members["params"]) if err != nil { return "", false @@ -83,6 +82,22 @@ func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { } } +// MCPSessionMethod reports whether method is an MCP request that opens or +// keeps a session and names no tool, resource or prompt of the service. A +// task rule with allowed_tools allows these requests and a tools/call of a +// tool that it lists, and denies every other request. allowed_tools grants +// tools: it does not grant the lists of the resources or of the prompts. +// +// Every enforcement point takes the list from here, so a request that is +// denied on a /mesh/mcp stream is denied on HTTP too. +func MCPSessionMethod(method string) bool { + switch method { + case "initialize", "server/discover", "ping", "tools/list": + return true + } + return false +} + // MCPToolCallName returns the tool that the params of an MCP tools/call name. // It fails when params is not one JSON object with one "name" member that // holds a non-empty string (uniqueJSONMembers), so the tool an enforcement diff --git a/api/mcp_test.go b/api/mcp_test.go index f6a736ec..adac8d29 100644 --- a/api/mcp_test.go +++ b/api/mcp_test.go @@ -75,6 +75,20 @@ func TestInspectJSONRPCMCPBody(t *testing.T) { wantTool: "", wantAllow: true, }, + // allowed_tools grants tools. A list of the resources or of the + // prompts is not a session method, as on a /mesh/mcp stream. + { + name: "resources/list is not a session method", + body: `{"jsonrpc":"2.0","id":1,"method":"resources/list"}`, + wantTool: "", + wantAllow: false, + }, + { + name: "prompts/list is not a session method", + body: `{"jsonrpc":"2.0","id":1,"method":"prompts/list"}`, + wantTool: "", + wantAllow: false, + }, { name: "resources/read is not auth-free", body: `{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"file:///secret"}}`, diff --git a/internal/envoy/server.go b/internal/envoy/server.go index 7b9b11da..c7b07fd7 100644 --- a/internal/envoy/server.go +++ b/internal/envoy/server.go @@ -557,8 +557,7 @@ func isMCPRoute(path, targetService string) bool { // InspectJSONRPCMCPBody inspects a JSON-RPC 2.0 request body for MCP methods // and extracts the tool name as the body states it, or sets allowStreamInit -// for session handshake, capability discovery, and protocol notification -// methods. +// for a method that opens or keeps a session (api.MCPSessionMethod). func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { return api.InspectJSONRPCMCPBody(body) } diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go index f13b996e..c853e430 100644 --- a/internal/node/mcp_service.go +++ b/internal/node/mcp_service.go @@ -395,8 +395,8 @@ func (m *MCPService) authorizeMCPRequest(req *jsonrpc.Request, reqCtx RequestCon logger.Warnf("[MCPService] %s: TAR dropped %q with no id from %s: %v", svcName, req.Method, reqCtx.PeerID, err) return taskDenied(req.ID, req.Method+" with no id", err) } - switch req.Method { - case "initialize", "ping", "tools/list": + switch { + case api.MCPSessionMethod(req.Method): if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{ ServiceType: "mcp", ServiceName: svcName, @@ -406,7 +406,7 @@ func (m *MCPService) authorizeMCPRequest(req *jsonrpc.Request, reqCtx RequestCon return taskDenied(req.ID, req.Method, err) } return nil - case "tools/call": + case req.Method == "tools/call": // The params go to the backend as the same bytes: the tool checked // here must be the one tool they name to every parser. name, err := api.MCPToolCallName(req.Params) diff --git a/internal/node/mcp_service_test.go b/internal/node/mcp_service_test.go index 2054305f..b430db94 100644 --- a/internal/node/mcp_service_test.go +++ b/internal/node/mcp_service_test.go @@ -21,6 +21,7 @@ import ( "net/http/httptest" "sync/atomic" "testing" + "time" "github.com/google/agentmesh/api" "github.com/modelcontextprotocol/go-sdk/jsonrpc" @@ -111,6 +112,66 @@ func TestMCPService_TaskCheckAllowsOnlyANotificationWithNoID(t *testing.T) { } } +// A task rule with allowed_tools decides a request in the same way on a +// /mesh/mcp stream and on HTTP: the two enforcement points take the session +// methods from api.MCPSessionMethod. allowed_tools grants tools, so a list of +// the resources or of the prompts is denied on both. +func TestMCPService_TaskCheckDecidesARequestAsTheHTTPInspection(t *testing.T) { + svc := &MCPService{baseService: baseService{ + info: &api.ServiceInfo{Name: "weather", Type: api.ServiceType_SERVICE_TYPE_MCP}, + }} + rules := []*api.TaskAuthorizationRule{{ + Name: "only-get-weather", + Rules: []*api.TaskRule{{ + AllowedServices: []string{"mcp://weather"}, + Operation: &api.TaskOperation{AllowedTools: []string{"get_weather"}}, + }}, + }} + id, err := jsonrpc.MakeID(float64(1)) + if err != nil { + t.Fatalf("MakeID: %v", err) + } + + for _, tc := range []struct { + name string + method string + params string + wantAllowed bool + }{ + {name: "initialize", method: "initialize", wantAllowed: true}, + {name: "server/discover", method: "server/discover", wantAllowed: true}, + {name: "ping", method: "ping", wantAllowed: true}, + {name: "tools/list", method: "tools/list", wantAllowed: true}, + {name: "call of an allowed tool", method: "tools/call", params: `{"name":"get_weather"}`, wantAllowed: true}, + {name: "call of a forbidden tool", method: "tools/call", params: `{"name":"drop_table"}`}, + {name: "resources/list", method: "resources/list"}, + {name: "prompts/list", method: "prompts/list"}, + {name: "resources/read", method: "resources/read", params: `{"uri":"file:///etc/passwd"}`}, + {name: "prompt with the name of an allowed tool", method: "prompts/get", params: `{"name":"get_weather"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + onStream := svc.authorizeMCPRequest(&jsonrpc.Request{ID: id, Method: tc.method, Params: []byte(tc.params)}, RequestContext{TaskRules: rules}) == nil + + body := `{"jsonrpc":"2.0","id":1,"method":"` + tc.method + `"` + if tc.params != "" { + body += `,"params":` + tc.params + } + body += "}" + tool, allowInit := api.InspectJSONRPCMCPBody([]byte(body)) + onHTTP := api.EvaluateTaskRules(rules, api.TaskRequestContext{ + ServiceType: "mcp", + ServiceName: "weather", + MCPTool: tool, + AllowMCPStreamInit: allowInit, + }, time.Now()) == nil + + if onStream != tc.wantAllowed || onHTTP != tc.wantAllowed { + t.Fatalf("%s: allowed on a stream = %v, allowed on HTTP = %v, want %v on both", tc.method, onStream, onHTTP, tc.wantAllowed) + } + }) + } +} + // newProbeBackend serves a real MCP server that exposes no tools at all. func newProbeBackend(t *testing.T) *httptest.Server { t.Helper() diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md index 3ae64e5a..8288ba28 100644 --- a/site/content/docs/contributing/security-architecture.md +++ b/site/content/docs/contributing/security-architecture.md @@ -281,7 +281,7 @@ match at least one `TaskRule` in every appended block. | Service type | `allowed_services` | `operation.allowed_tools` | `operation.allowed_methods` & `allowed_paths` | `operation.allowed_permissions` & `allowed_resources` | | :--- | :--- | :--- | :--- | :--- | -| **`mcp://`** | Enforced on stream handshake & HTTP | Enforced on `tools/call` (`params.name`). At stream open (`initialize`, `tools/list`), tool name is not yet present so `allowed_tools` does not block opening the stream. | Enforced if the rule sets `allowed_methods` or `allowed_paths` (a raw libp2p stream has no HTTP facts, so HTTP constraints deny raw streams). | Ignored by wire PEP (consumed by `CloudTokenExchanger`). | +| **`mcp://`** | Enforced on stream handshake & HTTP | Enforced on `tools/call` (`params.name`). The requests that open or keep a session (`initialize`, `server/discover`, `ping`, `tools/list`) name no tool, so `allowed_tools` does not block them. Every other request is denied, on a stream and on HTTP: `allowed_tools` grants tools, not `resources/list` or `prompts/list`. | Enforced if the rule sets `allowed_methods` or `allowed_paths` (a raw libp2p stream has no HTTP facts, so HTTP constraints deny raw streams). | Ignored by wire PEP (consumed by `CloudTokenExchanger`). | | **`inference://`**, **`a2a://`** | Enforced on HTTP request | A rule with non-empty `allowed_tools` requires an MCP tool name and does not match plain HTTP requests. | Enforced against request `Method` and `Path` when non-empty. | Ignored by wire PEP. | | **`egress://`** | Enforced on HTTP request & TCP `CONNECT` | Must be empty for an HTTP or TCP rule to match. | Enforced against `Method` and `Path` when non-empty (a TCP `CONNECT` tunnel has `Method: "CONNECT"` and `Path: ""`, so any rule with `allowed_paths` denies a tunnel). | Intersected across blocks `1..k` and translated by `CloudTokenExchanger` at egress. | | **`system://`** | Enforced on stream handshake | Enforced when a tool call is made. | Same as `mcp://`. | Ignored by wire PEP. | From f3ef7ada4ab58d8395759bdc4d54351517cab856 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Fri, 27 Nov 2026 15:24:45 +0000 Subject: [PATCH 3/4] sdk/js, sdk/python: allow an MCP request with no tool only on the provider's word Under a task rule with allowed_tools, authorizeCaller and authorize_caller allowed a request that names no tool when it had no HTTP method and its protocol was /mesh/mcp/1.0.0. The authorizers took such a request for the open of an MCP stream. agentmesh-node makes the same allowance, and then checks each message of the stream. The SDKs serve no MCP and have no such check, so an application that serves MCP on the exported authorizer authorized the stream one time and then passed every tools/call. A request for a method that is not a tools/call, authorized with an empty tool, also passed. AuthorizeRequest has a new field, allowMCPStreamInit (allow_mcp_stream_init), false by default. A request with no tool passes a rule with allowed_tools only with this field. The authorizers infer nothing from the protocol, so the application states which request opens or keeps the session, and a request with no tool and no flag is denied. No path that the SDKs ship changes: their one caller of the authorizer is the /libp2p-http handler, which always gives an HTTP method. --- sdk/README.md | 6 +++- sdk/js/src/authorizer.test.ts | 24 ++++++++++++++ sdk/js/src/authorizer.ts | 11 ++++++- sdk/python/src/agent_mesh/authorizer.py | 10 +++++- sdk/python/tests/test_authorizer.py | 33 +++++++++++++++++++ .../contributing/security-architecture.md | 9 +++++ 6 files changed, 90 insertions(+), 3 deletions(-) diff --git a/sdk/README.md b/sdk/README.md index a80992b6..9c7bc9ca 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -414,7 +414,11 @@ service, no directory record, no catalog entry. The reasons: - **One inbound protocol.** A2A is the protocol for talking to an agent, and the A2A SDKs serve one agent card each. One ingress means one authorizer path to audit in three languages instead of two ingress - protocols times a registry of services. + protocols times a registry of services. The exported authorizer + (`authorizeCaller`, `authorize_caller`) decides one request. Under a task + rule with `allowed_tools` it allows a request that names no tool only with + `allowMCPStreamInit` (`allow_mcp_stream_init`), so an application that + serves MCP on it must authorize each message of a session. - **The browser.** A browser cannot listen. An agent in a browser is reachable through a router's relay and nothing else, which is what `accept_a2a` is. The JS SDK runs in a page: it reaches the router over diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.ts index 18546bcc..5e4da619 100644 --- a/sdk/js/src/authorizer.test.ts +++ b/sdk/js/src/authorizer.test.ts @@ -285,6 +285,30 @@ test("attenuateBiscuit and sealBiscuit narrow authority across hops", async () = ); }); +// A task rule with allowed_tools allows a request that names no tool only +// when the provider says that the request opens or keeps the session. The +// authorizer infers nothing from the protocol: a provider that serves MCP +// must authorize each request, so a request with no tool and no flag is +// denied. +test("a credential narrowed to tools passes with no tool only as a session request", async () => { + const root = nodeToken(CALLER, [`granted_service_all_types(true)`, `target_unrestricted(true)`]); + const narrowed = await attenuateBiscuit( + root, + { name: "only-add", rules: [{ allowedServices: ["mcp://calc"], operation: { allowedTools: ["add"] } }] }, + [cpKey], + ); + const req = request(narrowed, "mcp://calc"); + + await assert.rejects(authorizeCaller(req, options([])), AuthorizationError, "no tool and no flag"); + await authorizeCaller({ ...req, allowMCPStreamInit: true }, options([])); + await authorizeCaller({ ...req, mcpTool: "add" }, options([])); + await assert.rejects( + authorizeCaller({ ...req, allowMCPStreamInit: true, mcpTool: "multiply" }, options([])), + AuthorizationError, + "the flag does not allow a tool that the rule leaves out", + ); +}); + // An appended block may carry exactly one tar_block fact. Anything else a // holder writes there (a rule, a check, a second fact) is refused before the // Datalog runs, whatever the authority block grants. diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.ts index 334c2d72..41522651 100644 --- a/sdk/js/src/authorizer.ts +++ b/sdk/js/src/authorizer.ts @@ -42,6 +42,15 @@ export interface AuthorizeRequest { path?: string; /** The MCP tool name when evaluating a specific MCP tools/call invocation. */ mcpTool?: string; + /** + * True for an MCP request that opens or keeps a session and names no tool: + * initialize, server/discover, ping or tools/list. A task rule with + * allowed_tools allows a request with no mcpTool only with this flag. The + * allowance is for that one request, not for the requests that follow it on + * the stream: a provider that serves MCP authorizes each tools/call with + * mcpTool set to its params.name, and every other request with neither. + */ + allowMCPStreamInit?: boolean; } export interface ProviderAuthorizerOptions { @@ -182,7 +191,7 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu method: req.method ?? "", path: req.path ?? "", mcpTool, - allowMCPStreamInit: req.method === undefined && mcpTool === "" && req.protocol === "/mesh/mcp/1.0.0", + allowMCPStreamInit: req.allowMCPStreamInit === true, }, now, ); diff --git a/sdk/python/src/agent_mesh/authorizer.py b/sdk/python/src/agent_mesh/authorizer.py index c3c6d332..985a8db2 100644 --- a/sdk/python/src/agent_mesh/authorizer.py +++ b/sdk/python/src/agent_mesh/authorizer.py @@ -61,6 +61,14 @@ class AuthorizeRequest: path: str = "" # The MCP tool name when evaluating a specific MCP tools/call invocation. mcp_tool: str = "" + # True for an MCP request that opens or keeps a session and names no tool: + # initialize, server/discover, ping or tools/list. A task rule with + # allowed_tools allows a request with no mcp_tool only with this flag. The + # allowance is for that one request, not for the requests that follow it + # on the stream: a provider that serves MCP authorizes each tools/call + # with mcp_tool set to its params.name, and every other request with + # neither. + allow_mcp_stream_init: bool = False @dataclass(frozen=True) @@ -153,7 +161,7 @@ def authorize_caller(req: AuthorizeRequest, options: ProviderAuthorizerOptions) method=req.method or "", path=req.path, mcp_tool=req.mcp_tool, - allow_mcp_stream_init=req.method is None and not req.mcp_tool and req.protocol == "/mesh/mcp/1.0.0", + allow_mcp_stream_init=req.allow_mcp_stream_init, ), now, ) diff --git a/sdk/python/tests/test_authorizer.py b/sdk/python/tests/test_authorizer.py index 971e3dd8..bce9f516 100644 --- a/sdk/python/tests/test_authorizer.py +++ b/sdk/python/tests/test_authorizer.py @@ -267,6 +267,39 @@ def test_attenuate_biscuit_narrows_authority_across_hops(): ) +def test_a_credential_narrowed_to_tools_passes_with_no_tool_only_as_a_session_request(): + """A task rule with allowed_tools allows a request that names no tool only + when the provider says that the request opens or keeps the session. The + authorizer infers nothing from the protocol: a provider that serves MCP + must authorize each request, so a request with no tool and no flag is + denied.""" + root = node_token(CALLER, ["granted_service_all_types(true)", "target_unrestricted(true)"]) + narrowed = attenuate_biscuit( + root, + agentmesh_pb2.TaskAuthorizationRule( + name="only-add", + rules=[ + agentmesh_pb2.TaskRule( + allowed_services=["mcp://calc"], + operation=agentmesh_pb2.TaskOperation(allowed_tools=["add"]), + ) + ], + ), + [CP_KEY], + ) + + def ask(**fields) -> AuthorizeRequest: + return AuthorizeRequest(biscuit=narrowed, peer_id=CALLER, target_service="mcp://calc", protocol="/mesh/mcp/1.0.0", **fields) + + with pytest.raises(AuthorizationError): + authorize_caller(ask(), options([])) + authorize_caller(ask(allow_mcp_stream_init=True), options([])) + authorize_caller(ask(mcp_tool="add"), options([])) + # The flag does not allow a tool that the rule leaves out. + with pytest.raises(AuthorizationError): + authorize_caller(ask(allow_mcp_stream_init=True, mcp_tool="multiply"), options([])) + + def test_appended_blocks_carrying_anything_but_one_tar_block_fact_are_refused(): """An appended block may carry exactly one tar_block fact. Anything else a holder writes there (a rule, a check, a second fact) is refused before the diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md index 8288ba28..f6a079ef 100644 --- a/site/content/docs/contributing/security-architecture.md +++ b/site/content/docs/contributing/security-architecture.md @@ -305,6 +305,15 @@ MCP service reads one message for each line of its standard input, so the node removes the line breaks between the JSON tokens of a message before it writes the message there. +The node applies these checks to each message of a session. +The TypeScript and Python SDKs do not serve MCP. Their authorizer +(`authorizeCaller`, `authorize_caller`) decides one request: under a rule with +`allowed_tools` it allows a request that names no tool only when the +application sets `allowMCPStreamInit` (`allow_mcp_stream_init`), and it infers +nothing from the protocol. An application that serves MCP on that authorizer +must authorize each message: a session request with the flag, a `tools/call` +with its `params.name`, and every other request with neither. + #### One authorizer assembly for every PEP Every enforcement point builds its Datalog authorizer through From 7036ca5ff1fd69f49778272e41907ee39ae6999a Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Fri, 27 Nov 2026 16:14:27 +0000 Subject: [PATCH 4/4] api: do not read an authorizer time limit as a denial in two tests TestIngressDatalogPolicyEvaluation and TestBuildPolicyRulesWithStructuredBindingClaims built their authorizer with the default time limit of biscuit-go, 2 ms, and compared the result of Authorize with nil. Under the race detector on a loaded machine a run takes longer than 2 ms. The error of the limit then read as a denial, and the test failed with "expected ... to be allowed" and no cause. The test check of a pull request failed in this way. The failure reproduces on one CPU: taskset -c 0 stress -p 8 on the race build of the api tests gave 1 failure in 150 runs of TestIngressDatalogPolicyEvaluation, each time at a different assertion. The two tests now give the authorizer the 5 s limit that the other tests of the package use, and a time limit stops the test with the error of the authorizer. The same stress loop is clean for 308 runs. --- api/claims_test.go | 13 +++++++++++-- api/ingress_test.go | 14 ++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/api/claims_test.go b/api/claims_test.go index d6521976..d017511c 100644 --- a/api/claims_test.go +++ b/api/claims_test.go @@ -18,14 +18,17 @@ import ( "crypto/ed25519" "crypto/rand" "encoding/json" + "errors" "fmt" "math" "reflect" "slices" "strings" "testing" + "time" "github.com/eclipse-biscuit/biscuit-go/v2" + "github.com/eclipse-biscuit/biscuit-go/v2/datalog" "github.com/eclipse-biscuit/biscuit-go/v2/parser" ) @@ -221,7 +224,9 @@ func TestBuildPolicyRulesWithStructuredBindingClaims(t *testing.T) { if err != nil { t.Fatal(err) } - auth, err := tok.Authorizer(pub) + // The default time limit of the authorizer is 2 ms. A run that takes + // longer returns an error, and that error is not a denial. + auth, err := tok.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(5*time.Second))) if err != nil { t.Fatal(err) } @@ -234,7 +239,11 @@ func TestBuildPolicyRulesWithStructuredBindingClaims(t *testing.T) { Body: []biscuit.Predicate{{Name: FactRole, IDs: []biscuit.Term{biscuit.String("workstation-caller")}}}, }}, }) - return auth.Authorize() == nil + err = auth.Authorize() + if errors.Is(err, datalog.ErrWorldRunLimitTimeout) { + t.Fatalf("authorize %q with claims %v: %v, want a decision", email, claims, err) + } + return err == nil } if !eval("bob@corp.example", map[string][]string{"iss": {"https://idp.corp.example"}, "device.trust_tier": {"high"}, "device.type": {"managed_workstation"}}) { diff --git a/api/ingress_test.go b/api/ingress_test.go index f7a904bd..16dc00c7 100644 --- a/api/ingress_test.go +++ b/api/ingress_test.go @@ -17,10 +17,13 @@ package api import ( "crypto/ed25519" "crypto/rand" + "errors" "slices" "testing" + "time" "github.com/eclipse-biscuit/biscuit-go/v2" + "github.com/eclipse-biscuit/biscuit-go/v2/datalog" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" ) @@ -309,7 +312,10 @@ func TestIngressDatalogPolicyEvaluation(t *testing.T) { } check := func(svcType, svcName, mode string) bool { - auth, err := tok.Authorizer(pub) + t.Helper() + // The default time limit of the authorizer is 2 ms. A run that takes + // longer returns an error, and that error is not a denial. + auth, err := tok.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(5*time.Second))) if err != nil { t.Fatalf("Authorizer: %v", err) } @@ -320,7 +326,11 @@ func TestIngressDatalogPolicyEvaluation(t *testing.T) { for _, p := range IngressPolicies { auth.AddPolicy(p) } - return auth.Authorize() == nil + err = auth.Authorize() + if errors.Is(err, datalog.ErrWorldRunLimitTimeout) { + t.Fatalf("authorize %s://%s %s: %v, want a decision", svcType, svcName, mode, err) + } + return err == nil } if !check("a2a", "assistant", IngressAuthModeStringEdge) {