Skip to content
Merged
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
13 changes: 11 additions & 2 deletions api/claims_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
}
Expand All @@ -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"}}) {
Expand Down
14 changes: 12 additions & 2 deletions api/ingress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
}
Expand All @@ -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) {
Expand Down
44 changes: 29 additions & 15 deletions api/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,21 @@ 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
// 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
// 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
Expand All @@ -62,28 +68,36 @@ 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
}
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
}
}

// 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
Expand Down
70 changes: 67 additions & 3 deletions api/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
package api

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestInspectJSONRPCMCPBody(t *testing.T) {
Expand All @@ -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,
},
{
Expand All @@ -65,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"}}`,
Expand Down Expand Up @@ -151,8 +175,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 {
Expand Down
2 changes: 1 addition & 1 deletion internal/envoy/envoy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions internal/envoy/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,8 +556,8 @@ 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 a method that opens or keeps a session (api.MCPSessionMethod).
func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) {
return api.InspectJSONRPCMCPBody(body)
}
Expand Down
6 changes: 3 additions & 3 deletions internal/node/mcp_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand Down
61 changes: 61 additions & 0 deletions internal/node/mcp_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"net/http/httptest"
"sync/atomic"
"testing"
"time"

"github.com/google/agentmesh/api"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion internal/node/sts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 5 additions & 1 deletion sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading