diff --git a/api/directory_keys.go b/api/directory_keys.go index 9a97b40c..301c3e90 100644 --- a/api/directory_keys.go +++ b/api/directory_keys.go @@ -36,6 +36,16 @@ const DirectoryKeyBytes = 34 // DirectoryMaxAddrs bounds the addresses one record carries. const DirectoryMaxAddrs = 32 +// DirectoryMaxAddrBytes bounds the text of one address in a record. The +// count includes the "/p2p/" suffix that the address has in an +// answer. The longest address a libp2p host announces is a circuit relay +// address through a router that has a DNS name of 253 bytes. With both peer +// IDs it is 530 bytes over WebTransport, which has two certhashes, and 660 +// bytes over TLS when the address repeats the name as its SNI. 1024 is one +// and a half times the longest. DirectoryMaxAddrs addresses of this length +// are 32 KiB, half of the 64 KiB frame of the directory protocol. +const DirectoryMaxAddrBytes = 1024 + // directoryKey is the sha256 multihash of a name: the two-byte multihash // header (sha2-256, 32 bytes) and the digest. go-libp2p-kad-dht keys // provider records by this multihash, so a record a member announces here diff --git a/api/directory_keys_test.go b/api/directory_keys_test.go index 6c6e3e26..5ea1c9b1 100644 --- a/api/directory_keys_test.go +++ b/api/directory_keys_test.go @@ -17,9 +17,11 @@ package api import ( "bytes" "encoding/hex" + "strings" "testing" "github.com/libp2p/go-libp2p/core/peer" + "github.com/multiformats/go-multiaddr" ) // The keys are the sha256 multihash of a fixed name, so a record a member @@ -69,6 +71,38 @@ func TestDirectoryKeys(t *testing.T) { } } +// DirectoryMaxAddrBytes holds the longest addresses a libp2p host +// announces: a circuit relay address, with both peer IDs, through a router +// that has a DNS name of the maximum length. +func TestDirectoryMaxAddrBytesHoldsRealAddresses(t *testing.T) { + const ( + router = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB" + member = "12D3KooWNT6DHUiBT3881d46esEcB6RzCuN9a74pdK8Gx2jXb8ww" + certhash = "uEiDDq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g" + ) + label := strings.Repeat("a", 63) + name := strings.Join([]string{label, label, label, label[:61]}, ".") + if len(name) != 253 { + t.Fatalf("the DNS name is %d bytes, want 253", len(name)) + } + relayed := "/p2p/" + router + "/p2p-circuit/p2p/" + member + for desc, addr := range map[string]string{ + "TLS and WebSocket": "/dns4/" + name + "/tcp/65535/tls/ws" + relayed, + "TLS with an SNI and WebSocket": "/dns4/" + name + "/tcp/65535/tls/sni/" + name + "/ws" + relayed, + "WebTransport with two certhashes": "/dns6/" + name + "/udp/65535/quic-v1/webtransport/certhash/" + certhash + "/certhash/" + certhash + relayed, + } { + t.Run(desc, func(t *testing.T) { + ma, err := multiaddr.NewMultiaddr(addr) + if err != nil { + t.Fatalf("NewMultiaddr(%s): %v", addr, err) + } + if got := len(ma.String()); got > DirectoryMaxAddrBytes { + t.Errorf("the address is %d bytes, want at most DirectoryMaxAddrBytes = %d", got, DirectoryMaxAddrBytes) + } + }) + } +} + // A record is the provider's own, under its peer key, or a service's, by // name or by type, and the key must be that of the service it names. func TestServiceOfRecord(t *testing.T) { diff --git a/api/mcp.go b/api/mcp.go index b379a25a..4956a4c1 100644 --- a/api/mcp.go +++ b/api/mcp.go @@ -17,6 +17,7 @@ package api import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -43,29 +44,34 @@ const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20 // 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. +// +// 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. func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { if len(bytes.TrimSpace(body)) == 0 { return "", false } - var rpc struct { - Method string `json:"method"` - Params json.RawMessage `json:"params"` + members, err := uniqueJSONMembers(body, "method", "params") + if err != nil { + return "", false } - if err := json.Unmarshal(body, &rpc); err != nil { + var method string + if err := json.Unmarshal(members["method"], &method); err != nil { return "", false } - switch rpc.Method { + switch method { case "initialize", "notifications/initialized", "server/discover", "ping", "tools/list", "resources/list", "prompts/list", "notifications/cancelled": return "", true case "tools/call": - var params struct { - Name string `json:"name"` - } - if err := json.Unmarshal(rpc.Params, ¶ms); err != nil { + name, err := MCPToolCallName(members["params"]) + if err != nil { return "", false } - rawTool := strings.TrimSpace(params.Name) + rawTool := strings.TrimSpace(name) if rawTool == "" { return "", false } @@ -78,6 +84,65 @@ func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) { } } +// 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 +// point checks is the tool the backend runs. +func MCPToolCallName(params []byte) (string, error) { + members, err := uniqueJSONMembers(params, "name") + if err != nil { + return "", fmt.Errorf("params: %w", err) + } + var name string + if err := json.Unmarshal(members["name"], &name); err != nil || name == "" { + return "", errors.New(`params: no "name" member with a non-empty string`) + } + return name, nil +} + +// uniqueJSONMembers returns the values of the named members of the JSON +// object doc. It fails when doc does not say the same thing to every JSON +// parser: when it is not one valid JSON object and nothing else, when a named +// member occurs more than once, and when a member differs from a name only in +// letter case. A case-insensitive parser, encoding/json among them, reads +// such a member as the named one and keeps the last; most others ignore it. +func uniqueJSONMembers(doc []byte, names ...string) (map[string]json.RawMessage, error) { + // One value and nothing after it: the decoder below reads the first + // value of a stream and does not look at what follows it. + if !json.Valid(doc) { + return nil, errors.New("not one valid JSON value") + } + dec := json.NewDecoder(bytes.NewReader(doc)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return nil, errors.New("not a JSON object") + } + members := make(map[string]json.RawMessage, len(names)) + for dec.More() { + tok, err := dec.Token() + key, isString := tok.(string) + if err != nil || !isString { + return nil, errors.New("not a JSON object") + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return nil, err + } + for _, name := range names { + if !strings.EqualFold(key, name) { + continue + } + if key != name { + return nil, fmt.Errorf("member %q differs from %q only in letter case", key, name) + } + if _, seen := members[name]; seen { + return nil, fmt.Errorf("member %q occurs more than once", name) + } + members[name] = value + } + } + return members, nil +} + // InspectMCPHTTPRequestBody buffers and restores r.Body up to maxBytes // (defaulting to DefaultMaxMCPBodyInspectBytes when maxBytes <= 0) and extracts // the MCP tool name and stream initialization flag. diff --git a/api/mcp_test.go b/api/mcp_test.go index d9fad8e3..b0e8f84d 100644 --- a/api/mcp_test.go +++ b/api/mcp_test.go @@ -83,6 +83,62 @@ func TestInspectJSONRPCMCPBody(t *testing.T) { wantTool: "", wantAllow: false, }, + // The body goes to the backend as the same bytes. A member that two + // parsers read differently names no tool and no handshake method. + { + name: "method again in upper case", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"METHOD":"ping"}`, + wantTool: "", + wantAllow: false, + }, + { + name: "params again in upper case", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"PARAMS":{"name":"read_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "tool name again in upper case", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file","NAME":"read_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "params again with a letter that folds to s", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"paramÅ¿":{"name":"read_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "method twice", + body: `{"jsonrpc":"2.0","id":1,"method":"ping","method":"tools/call","params":{"name":"read_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "method twice, one escaped", + body: `{"jsonrpc":"2.0","id":1,"\u006dethod":"ping","method":"tools/call","params":{"name":"read_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "tool name twice", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","name":"delete_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "second message after the first", + body: `{"jsonrpc":"2.0","id":1,"method":"ping"} {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"delete_file"}}`, + wantTool: "", + wantAllow: false, + }, + { + name: "arguments may repeat the member names", + body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","arguments":{"name":"a","NAME":"b","method":"ping","params":{}}}}`, + wantTool: "read_file", + wantAllow: false, + }, } for _, tc := range cases { diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go index 29cafc01..3c405dda 100644 --- a/internal/controlplane/server.go +++ b/internal/controlplane/server.go @@ -2074,16 +2074,24 @@ func nodeRoles(nodeRecord *storage.EnrolledNode, bindings []*api.PolicyBinding) return roles, nil } +// nodeRoles is the role set of the node from the stored bindings. When it +// cannot resolve the custom roles it logs the cause and returns the enrolled +// role alone. That set is never wider than the full one and each caller +// grants per role, so the fallback cannot grant more. func (s *Server) nodeRoles(ctx context.Context, nodeRecord *storage.EnrolledNode) []string { if nodeRecord == nil { return nil } _, bindings, err := s.store.GetMeshPolicy(ctx) if err != nil { + if !errors.Is(err, storage.ErrNotFound) { + logger.Warnw("Custom roles not resolved, using the enrolled role alone: mesh policy not read", "peer_id", nodeRecord.PeerID, "role", nodeRecord.Role, "error", err) + } return []string{nodeRecord.Role} } roles, err := nodeRoles(nodeRecord, bindings) if err != nil { + logger.Warnw("Custom roles not resolved, using the enrolled role alone: enrollment claims not parsed", "peer_id", nodeRecord.PeerID, "role", nodeRecord.Role, "error", err) return []string{nodeRecord.Role} } return roles diff --git a/internal/controlplane/sts.go b/internal/controlplane/sts.go index 54487ea5..fba99266 100644 --- a/internal/controlplane/sts.go +++ b/internal/controlplane/sts.go @@ -29,6 +29,7 @@ import ( "fmt" "html/template" "io" + "math" "net" "net/http" "net/url" @@ -1020,34 +1021,42 @@ func (s *Server) HandleSTSToken(w http.ResponseWriter, r *http.Request) { return } + // Read the egress policy once. The served_by check, the audience and the + // Biscuit authorization below must decide on the same data, and none of + // them can decide without it. + destHost := api.NormalizeMeshHost(strings.TrimPrefix(strings.TrimSpace(req.Destination), api.EgressServicePrefix)) + egressList, err := s.store.GetEgressDestinations(r.Context()) + if err != nil && !errors.Is(err, storage.ErrNotFound) { + logger.Errorw("STS token refused: egress policy not read", "actor_node", nodeRecord.PeerID, "destination", req.Destination, "error", err) + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + // Verify that if the destination is configured in PolicyConfig.egress with // served_by constraints, the calling agentmesh-node is authorized to serve it. - destHost := api.NormalizeMeshHost(strings.TrimPrefix(strings.TrimSpace(req.Destination), api.EgressServicePrefix)) - if egressList, err := s.store.GetEgressDestinations(r.Context()); err == nil { - for _, d := range egressList { - if d != nil && d.GetName() == destHost { - if len(d.GetServedBy()) > 0 { - callingRoles := s.nodeRoles(r.Context(), nodeRecord) - if !api.EgressServedBy(d, callingRoles, nodeRecord.Labels) { - reason := fmt.Sprintf("calling node %s is not in served_by for egress://%s", nodeRecord.PeerID, destHost) - logSTSDenyBeforeBiscuit(nodeRecord.PeerID, &req, reason) - http.Error(w, reason, http.StatusForbidden) - return - } + for _, d := range egressList { + if d != nil && d.GetName() == destHost { + if len(d.GetServedBy()) > 0 { + callingRoles := s.nodeRoles(r.Context(), nodeRecord) + if !api.EgressServedBy(d, callingRoles, nodeRecord.Labels) { + reason := fmt.Sprintf("calling node %s is not in served_by for egress://%s", nodeRecord.PeerID, destHost) + logSTSDenyBeforeBiscuit(nodeRecord.PeerID, &req, reason) + http.Error(w, reason, http.StatusForbidden) + return } - break } + break } } - audience, audErr := s.resolveEgressAudience(r.Context(), req.Destination, req.Audience) + audience, audErr := resolveEgressAudience(egressList, destHost, req.Audience) if audErr != nil { logSTSDenyBeforeBiscuit(nodeRecord.PeerID, &req, audErr.Error()) http.Error(w, audErr.Error(), http.StatusForbidden) return } - claims, status, err := s.authorizeBiscuitForEgress(r.Context(), req.Biscuit, req.Destination) + claims, status, err := s.authorizeBiscuitForEgress(r.Context(), req.Biscuit, req.Destination, egressList) if err != nil { clientPeerID := "" if claims != nil { @@ -1165,33 +1174,44 @@ func logSTSDenyBeforeBiscuit(actorNode string, req *api.STSTokenRequest, reason ) } -func (s *Server) resolveEgressAudience(ctx context.Context, destination, reqAudience string) (string, error) { - destHost := api.NormalizeMeshHost(strings.TrimPrefix(strings.TrimSpace(destination), api.EgressServicePrefix)) - reqAud := strings.TrimSpace(reqAudience) - if egressList, err := s.store.GetEgressDestinations(ctx); err == nil { - for _, d := range egressList { - if d != nil && d.GetName() == destHost { - if fed := d.GetBroker().GetOidcFederation(); fed != nil && strings.TrimSpace(fed.GetAudience()) != "" { - policyAud := strings.TrimSpace(fed.GetAudience()) - if reqAud != "" && reqAud != policyAud { - return "", fmt.Errorf("requested audience %q does not match policy audience for egress://%s", reqAud, destHost) - } - return policyAud, nil - } - if aws := d.GetBroker().GetAwsAssumeRole(); aws != nil && strings.TrimSpace(aws.GetRoleArn()) != "" { - if reqAud != "" && reqAud != "sts.amazonaws.com" { - return "", fmt.Errorf("requested audience %q does not match AWS STS audience \"sts.amazonaws.com\" for egress://%s", reqAud, destHost) - } - return "sts.amazonaws.com", nil - } - break +// pinnedEgressAudience returns the audience that the broker of d pins, or "" +// when d has no broker that takes a border JWT. +func pinnedEgressAudience(d *api.EgressDestination) string { + if aud := strings.TrimSpace(d.GetBroker().GetOidcFederation().GetAudience()); aud != "" { + return aud + } + if strings.TrimSpace(d.GetBroker().GetAwsAssumeRole().GetRoleArn()) != "" { + return "sts.amazonaws.com" + } + return "" +} + +// resolveEgressAudience returns the aud claim of a border JWT for destHost. +// The audience comes from the egress policy alone: the audience that the +// broker of the destination pins, else the default https://. The +// calling node cannot choose it: a requested audience must equal that value. +// The default is refused when the policy pins the same value for another +// destination, so a grant on one name cannot yield the audience of another. +func resolveEgressAudience(egress []*api.EgressDestination, destHost, reqAudience string) (string, error) { + policyAud := "" + for _, d := range egress { + if d != nil && d.GetName() == destHost { + policyAud = pinnedEgressAudience(d) + break + } + } + if policyAud == "" { + policyAud = "https://" + destHost + for _, d := range egress { + if d != nil && pinnedEgressAudience(d) == policyAud { + return "", fmt.Errorf("default audience %q for egress://%s is the audience that the policy pins for egress://%s", policyAud, destHost, d.GetName()) } } } - if reqAud != "" { - return reqAud, nil + if reqAud := strings.TrimSpace(reqAudience); reqAud != "" && reqAud != policyAud { + return "", fmt.Errorf("requested audience %q does not match policy audience for egress://%s", reqAud, destHost) } - return "https://" + destHost, nil + return policyAud, nil } var stsDestinationRules = []biscuit.Rule{ @@ -1212,10 +1232,11 @@ func mustParseSTSRule(s string) biscuit.Rule { } // authorizeBiscuitForEgress verifies the caller's Biscuit and its tar_block chain -// against egress://. Once the Biscuit has verified, it returns the -// claims even when it refuses the request, so the caller's Border Crossing line -// can name the origin peer the Biscuit is bound to. -func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byte, destination string) (*identity.VerifiedBiscuitClaims, int, error) { +// against egress://, with egressDests as the egress policy. Once +// the Biscuit has verified, it returns the claims even when it refuses the +// request, so the caller's Border Crossing line can name the origin peer the +// Biscuit is bound to. +func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byte, destination string, egressDests []*api.EgressDestination) (*identity.VerifiedBiscuitClaims, int, error) { trustedKeys, err := s.store.GetAllValidPublicKeys(ctx) if err != nil { return nil, http.StatusInternalServerError, fmt.Errorf("failed to load signing keys: %w", err) @@ -1246,10 +1267,6 @@ func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byt if err != nil && err != storage.ErrNotFound { return claims, http.StatusInternalServerError, fmt.Errorf("failed to load mesh policy: %w", err) } - egressDests, err := s.store.GetEgressDestinations(ctx) - if err != nil && err != storage.ErrNotFound { - return claims, http.StatusInternalServerError, fmt.Errorf("failed to load egress destinations: %w", err) - } policyRules, _ := api.BuildPolicyRules(roles, bindings) policyRules = append(policyRules, api.BuildEgressServingRules(egressDests)...) meshRules := make([]biscuit.Rule, 0, len(policyRules)) @@ -1688,6 +1705,11 @@ func (s *Server) handleOAuthAuthCodeGrant(w http.ResponseWriter, r *http.Request }) } +// maxExpiresInSeconds is the largest expires_in that converts to a +// time.Duration without overflow. A larger value is reduced to this one. The +// result does not change: expires_in can only shorten the lifetime. +const maxExpiresInSeconds = int64(math.MaxInt64 / time.Second) + func (s *Server) handleOAuthTokenExchangeGrant(w http.ResponseWriter, r *http.Request) { subjectToken := strings.TrimSpace(r.Form.Get("subject_token")) subjectTokenType := strings.TrimSpace(r.Form.Get("subject_token_type")) @@ -1699,7 +1721,7 @@ func (s *Server) handleOAuthTokenExchangeGrant(w http.ResponseWriter, r *http.Re var reqTTL int64 if ttlStr := strings.TrimSpace(r.Form.Get("expires_in")); ttlStr != "" { if parsed, err := strconv.ParseInt(ttlStr, 10, 64); err == nil && parsed > 0 { - reqTTL = parsed + reqTTL = min(parsed, maxExpiresInSeconds) } } diff --git a/internal/controlplane/sts_test.go b/internal/controlplane/sts_test.go index 476f737b..57907fef 100644 --- a/internal/controlplane/sts_test.go +++ b/internal/controlplane/sts_test.go @@ -25,13 +25,16 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" + "path/filepath" "slices" "strconv" "strings" + "sync/atomic" "testing" "time" @@ -290,7 +293,16 @@ func TestOIDCIssuerJWKSAndSTSToken(t *testing.T) { {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}}, {Role: "analyst", Members: []string{"user:alice-sub"}}, } - if err := store.SavePolicyDocument(ctx, roles, bindings, nil); err != nil { + // The aud claim comes from the egress policy: the broker pins the audience + // that the /sts/token requests below name. + const wifAudience = "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/agentmesh/providers/cp" + egress := []*api.EgressDestination{{ + Name: "bigquery.googleapis.com", + Broker: &api.CredentialBroker{Kind: &api.CredentialBroker_OidcFederation{ + OidcFederation: &api.OIDCFederation{TokenEndpoint: "https://sts.googleapis.com/v1/token", Audience: wifAudience}, + }}, + }} + if err := store.SavePolicyDocument(ctx, roles, bindings, egress); err != nil { t.Fatalf("SavePolicyDocument: %v", err) } @@ -353,7 +365,7 @@ func TestOIDCIssuerJWKSAndSTSToken(t *testing.T) { stsReq := &api.STSTokenRequest{ Biscuit: exResp.BiscuitToken, Destination: "bigquery.googleapis.com", - Audience: "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/agentmesh/providers/cp", + Audience: wifAudience, ChallengeUnixMs: stsTs, ChallengeSignature: stsSig, } @@ -735,7 +747,7 @@ func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) { if inspected.NodePeerID != nodePeerID.String() { t.Fatalf("expected InspectVerifiedBiscuit to canonicalize NodePeerID to %q, got %q", nodePeerID.String(), inspected.NodePeerID) } - if _, status, err := srv.authorizeBiscuitForEgress(ctx, nonCanonicalBiscuit, "bigquery.googleapis.com"); err == nil || status != http.StatusForbidden || !strings.Contains(err.Error(), "is banned") { + if _, status, err := srv.authorizeBiscuitForEgress(ctx, nonCanonicalBiscuit, "bigquery.googleapis.com", nil); err == nil || status != http.StatusForbidden || !strings.Contains(err.Error(), "is banned") { t.Fatalf("expected authorizeBiscuitForEgress to reject banned CIDv1 peer ID with 403 'is banned', got status=%d err=%v", status, err) } } @@ -991,6 +1003,96 @@ func TestOAuthAndControlPlaneHardening(t *testing.T) { } } +// expires_in may only shorten the lifetime of a delegated Biscuit. A value +// above 9223372036 seconds overflowed time.Duration to a negative number and +// put an expiration before 1970 into the Biscuit (GHSA-qg99-6frq-2h5m). +func TestOAuthTokenExchangeBoundsExpiresIn(t *testing.T) { + issuer, mintOIDC := startCustomMockOIDC(t) + srv, store, baseURL := setupTestServer(t, issuer) + t.Cleanup(func() { _ = srv.Close() }) + + ctx := context.Background() + if err := store.SavePolicyDocument(ctx, + []*api.PolicyRole{{Name: api.RoleNode, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}}}, + []*api.PolicyBinding{{Role: api.RoleNode, Members: []string{api.SystemAuthenticated}}}, nil); err != nil { + t.Fatalf("SavePolicyDocument: %v", err) + } + keys, err := store.GetAllValidPublicKeys(ctx) + if err != nil { + t.Fatalf("GetAllValidPublicKeys: %v", err) + } + maxTTL := srv.config.DelegatedBiscuitTTL + + for _, tc := range []struct { + name string + expiresIn string + resource string + // The Biscuit lapses more than longerThan and at most noLongerThan + // after the request. + longerThan time.Duration + noLongerThan time.Duration + }{ + {name: "60 shortens the lifetime", expiresIn: "60", noLongerThan: time.Minute}, + {name: "largest value a time.Duration holds", expiresIn: "9223372036", longerThan: time.Minute, noLongerThan: maxTTL}, + {name: "value that overflowed time.Duration", expiresIn: "9223372037", longerThan: time.Minute, noLongerThan: maxTTL}, + {name: "value that overflowed time.Duration, with a task rule", expiresIn: "9223372037", resource: "mcp://weather", longerThan: time.Minute, noLongerThan: maxTTL}, + } { + t.Run(tc.name, func(t *testing.T) { + form := url.Values{ + "grant_type": {api.GrantTypeTokenExchange}, + "subject_token": {mintOIDC(map[string]interface{}{"sub": "alice-sub", "email": "alice@example.com", "email_verified": true})}, + "subject_token_type": {api.TokenTypeIDToken}, + "expires_in": {tc.expiresIn}, + } + if tc.resource != "" { + form.Set("resource", tc.resource) + } + before := time.Now() + resp, err := http.PostForm(baseURL+"/oauth/token", form) + if err != nil { + t.Fatalf("POST /oauth/token: %v", err) + } + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if err != nil { + t.Fatalf("read /oauth/token response: %v", err) + } + after := time.Now() + if resp.StatusCode != http.StatusOK { + t.Fatalf("POST /oauth/token with expires_in=%s returned %d, want 200: %s", tc.expiresIn, resp.StatusCode, body) + } + var out struct { + AccessToken string `json:"access_token"` + } + if err := json.Unmarshal(body, &out); err != nil { + t.Fatalf("parse /oauth/token response: %v", err) + } + raw, err := base64.StdEncoding.DecodeString(out.AccessToken) + if err != nil { + t.Fatalf("decode access_token: %v", err) + } + + claims, err := identity.InspectVerifiedBiscuit(raw, keys, srv.config.BiscuitTimeout) + if err != nil { + t.Fatalf("InspectVerifiedBiscuit refused the Biscuit minted for expires_in=%s: %v", tc.expiresIn, err) + } + if !claims.Expiration.After(before.Add(tc.longerThan)) || claims.Expiration.After(after.Add(tc.noLongerThan)) { + t.Errorf("expires_in=%s: Biscuit lapses %s after the request, want more than %s and at most %s", + tc.expiresIn, claims.Expiration.Sub(before).Round(time.Second), tc.longerThan, tc.noLongerThan) + } + if tc.resource == "" { + return + } + if len(claims.TaskRules) != 1 { + t.Fatalf("Biscuit carries %d task rules, want 1", len(claims.TaskRules)) + } + if exp := claims.TaskRules[0].GetExpireTime(); !exp.IsValid() || !exp.AsTime().After(after) { + t.Errorf("task rule expire_time = %v, want an instant after the request", exp.AsTime()) + } + }) + } +} + // Expired revocations leave the in-memory set as writes accumulate, not only // when /revocations is read, and the set stays bounded by its live entries. func TestRevokeBiscuitIDPrunesExpiredEntries(t *testing.T) { @@ -1030,7 +1132,16 @@ func TestSTSTokenBorderCrossingNamesTheOriginPeer(t *testing.T) { bindings := []*api.PolicyBinding{ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}}, } - if err := store.SavePolicyDocument(context.Background(), roles, bindings, nil); err != nil { + // The aud claim comes from the egress policy: the broker pins the audience + // that the allowed request below names. + const wifAudience = "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/agentmesh/providers/cp" + egress := []*api.EgressDestination{{ + Name: "bigquery.googleapis.com", + Broker: &api.CredentialBroker{Kind: &api.CredentialBroker_OidcFederation{ + OidcFederation: &api.OIDCFederation{TokenEndpoint: "https://sts.googleapis.com/v1/token", Audience: wifAudience}, + }}, + }} + if err := store.SavePolicyDocument(context.Background(), roles, bindings, egress); err != nil { t.Fatalf("SavePolicyDocument: %v", err) } @@ -1104,7 +1215,7 @@ func TestSTSTokenBorderCrossingNamesTheOriginPeer(t *testing.T) { return resp.StatusCode } - if status := postSTS("bigquery.googleapis.com", "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/agentmesh/providers/cp"); status != http.StatusOK { + if status := postSTS("bigquery.googleapis.com", wifAudience); status != http.StatusOK { t.Fatalf("POST /sts/token for bigquery.googleapis.com returned %d, want 200", status) } if status := postSTS("api.github.com", "https://api.github.com"); status != http.StatusForbidden { @@ -1266,6 +1377,12 @@ func TestSTSTokenBorderCrossingDeniesBeforeBiscuit(t *testing.T) { audience: "https://evil.example.com", reason: `requested audience "https://evil.example.com" does not match policy audience for egress://` + audienceDest, }, + { + name: "audience, destination with no broker", + destination: "api.example.com", + audience: policyAud, + reason: `requested audience "` + policyAud + `" does not match policy audience for egress://api.example.com`, + }, } for _, tc := range cases { if status := postSTS(tc.destination, tc.audience); status != http.StatusForbidden { @@ -1301,3 +1418,228 @@ func TestSTSTokenBorderCrossingDeniesBeforeBiscuit(t *testing.T) { case <-time.After(200 * time.Millisecond): } } + +// postSTSToken calls POST /sts/token as the node that holds priv and cred, with +// cred as the caller's Biscuit. It returns the status and, for a 200, the aud +// claim of the minted JWT. +func postSTSToken(t *testing.T, baseURL string, priv crypto.PrivKey, id peer.ID, cred []byte, destination, audience string) (int, string) { + t.Helper() + ts := time.Now().UnixMilli() + sig, err := priv.Sign(api.STSTokenChallenge(id.String(), ts)) + if err != nil { + t.Fatalf("sign the STS challenge: %v", err) + } + reqBytes, err := proto.Marshal(&api.STSTokenRequest{ + Biscuit: cred, + Destination: destination, + Audience: audience, + ChallengeUnixMs: ts, + ChallengeSignature: sig, + }) + if err != nil { + t.Fatalf("marshal STSTokenRequest: %v", err) + } + req, err := http.NewRequest(http.MethodPost, baseURL+"/sts/token", bytes.NewReader(reqBytes)) + if err != nil { + t.Fatalf("build POST /sts/token: %v", err) + } + req.Header.Set("Content-Type", "application/x-protobuf") + req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(cred)) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("POST /sts/token for %s: %v", destination, err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read the /sts/token response for %s: %v", destination, err) + } + if resp.StatusCode != http.StatusOK { + return resp.StatusCode, "" + } + var out api.STSTokenResponse + if err := proto.Unmarshal(body, &out); err != nil { + t.Fatalf("unmarshal STSTokenResponse: %v", err) + } + var claims jwt.MapClaims + if _, _, err := jwt.NewParser().ParseUnverified(out.GetJwt(), &claims); err != nil { + t.Fatalf("parse the minted JWT: %v", err) + } + aud, ok := claims["aud"].(string) + if !ok { + t.Fatalf("minted JWT aud = %v, want one string", claims["aud"]) + } + return resp.StatusCode, aud +} + +// TestSTSTokenAudienceComesFromPolicy checks that the aud claim of a border +// JWT is the audience the egress policy gives the destination, and that a +// node cannot ask for another one. Before the fix, a node that might reach a +// destination with no broker received a JWT with the audience that the broker +// of another destination pins, although served_by of that destination +// excluded the node. +func TestSTSTokenAudienceComesFromPolicy(t *testing.T) { + const ( + // No egress entry, so no broker and no pinned audience. + openDest = "api.example.com" + // Served by the gateway alone. Its broker pins pinnedAud. + pinnedDest = "storage.googleapis.com" + pinnedAud = "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/agentmesh/providers/cp" + // No egress entry. Its default audience is the one vaultDest pins. + shadowDest = "internal.example.com" + vaultDest = "vault.example.com" + ) + issuer, mintOIDC := startCustomMockOIDC(t) + srv, store, baseURL := setupTestServer(t, issuer) + t.Cleanup(func() { _ = srv.Close() }) + + ctx := context.Background() + nodeRole := &api.PolicyRole{Name: api.RoleNode, AllowedServices: []string{"egress://*"}, AllowedTargets: []string{"*"}} + nodeBinding := &api.PolicyBinding{Role: api.RoleNode, Members: []string{api.SystemAuthenticated}} + if err := store.SavePolicyDocument(ctx, []*api.PolicyRole{nodeRole}, []*api.PolicyBinding{nodeBinding}, nil); err != nil { + t.Fatalf("SavePolicyDocument: %v", err) + } + gatewayPriv, gatewayID, gatewayBiscuit, _ := enrollTestNodeForSTS(t, baseURL, mintOIDC) + otherPriv, otherID, otherBiscuit, _ := enrollTestNodeForSTS(t, baseURL, mintOIDC) + + federation := func(audience string) *api.CredentialBroker { + return &api.CredentialBroker{Kind: &api.CredentialBroker_OidcFederation{ + OidcFederation: &api.OIDCFederation{TokenEndpoint: "https://sts.googleapis.com/v1/token", Audience: audience}, + }} + } + if err := store.SavePolicyDocument(ctx, + []*api.PolicyRole{nodeRole, {Name: "egress-gateway", AllowedServices: []string{"egress://*"}, AllowedTargets: []string{"*"}}}, + []*api.PolicyBinding{nodeBinding, {Role: "egress-gateway", Members: []string{"node:" + gatewayID.String()}}}, + []*api.EgressDestination{ + {Name: pinnedDest, ServedBy: []string{"egress-gateway"}, Broker: federation(pinnedAud)}, + {Name: vaultDest, ServedBy: []string{"egress-gateway"}, Broker: federation("https://" + shadowDest)}, + }, + ); err != nil { + t.Fatalf("SavePolicyDocument: %v", err) + } + + for _, tc := range []struct { + name string + gateway bool // the gateway node calls, else a node outside served_by + destination string + audience string + wantStatus int + wantAud string + }{ + {name: "no broker, the audience another destination pins", destination: openDest, audience: pinnedAud, wantStatus: http.StatusForbidden}, + {name: "no broker, an arbitrary audience", destination: openDest, audience: "https://evil.example.com", wantStatus: http.StatusForbidden}, + {name: "no broker, no audience", destination: openDest, wantStatus: http.StatusOK, wantAud: "https://" + openDest}, + {name: "no broker, the default audience", destination: openDest, audience: "https://" + openDest, wantStatus: http.StatusOK, wantAud: "https://" + openDest}, + {name: "broker, its pinned audience", gateway: true, destination: pinnedDest, audience: pinnedAud, wantStatus: http.StatusOK, wantAud: pinnedAud}, + {name: "broker, no audience", gateway: true, destination: pinnedDest, wantStatus: http.StatusOK, wantAud: pinnedAud}, + {name: "broker, another audience", gateway: true, destination: pinnedDest, audience: "https://" + pinnedDest, wantStatus: http.StatusForbidden}, + {name: "no broker, the default is the audience another destination pins", destination: shadowDest, wantStatus: http.StatusForbidden}, + } { + t.Run(tc.name, func(t *testing.T) { + priv, id, cred := otherPriv, otherID, otherBiscuit + if tc.gateway { + priv, id, cred = gatewayPriv, gatewayID, gatewayBiscuit + } + status, aud := postSTSToken(t, baseURL, priv, id, cred, tc.destination, tc.audience) + if status != tc.wantStatus { + t.Fatalf("POST /sts/token for %s with audience %q returned %d (aud %q), want %d", tc.destination, tc.audience, status, aud, tc.wantStatus) + } + if aud != tc.wantAud { + t.Errorf("POST /sts/token for %s with audience %q minted aud %q, want %q", tc.destination, tc.audience, aud, tc.wantAud) + } + }) + } +} + +// failingEgressStore is a store whose next reads of the egress policy fail, +// the way a database that stopped answering looks to the control plane. +type failingEgressStore struct { + storage.Store + failNext atomic.Int32 +} + +func (f *failingEgressStore) GetEgressDestinations(ctx context.Context) ([]*api.EgressDestination, error) { + if f.failNext.Add(-1) >= 0 { + return nil, errors.New("store: connection refused") + } + return f.Store.GetEgressDestinations(ctx) +} + +// TestSTSTokenRefusesWhenEgressPolicyReadFails checks that /sts/token mints +// nothing when it cannot read the egress policy. Before the fix, a failed read +// skipped the served_by check and the audience check, and a later read that +// succeeded let the request through. +func TestSTSTokenRefusesWhenEgressPolicyReadFails(t *testing.T) { + const destination = "s3.amazonaws.com" + issuer, mintOIDC := startCustomMockOIDC(t) + dbPath := filepath.Join(t.TempDir(), "control-plane.db") + sqlStore, err := storage.NewSQLStore("sqlite", dbPath) + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + store := &failingEgressStore{Store: sqlStore} + srv, err := NewServer(Options{ + ListenAddr: "127.0.0.1:0", DriverName: "sqlite", DataSourceName: dbPath, + OIDCIssuer: issuer, AllowedAudiences: []string{"agentmesh-audience"}, + InsecureSkipTLSVerify: true, BiscuitTimeout: 10 * time.Second, + }, store) + if err != nil { + t.Fatalf("NewServer: %v", err) + } + if err := srv.Start(); err != nil { + t.Fatalf("start the control plane: %v", err) + } + t.Cleanup(func() { + _ = srv.Close() + _ = sqlStore.Close() + }) + baseURL := "http://" + srv.listener.Addr().String() + + ctx := context.Background() + nodeRole := &api.PolicyRole{Name: api.RoleNode, AllowedServices: []string{"egress://" + destination}, AllowedTargets: []string{"*"}} + nodeBinding := &api.PolicyBinding{Role: api.RoleNode, Members: []string{api.SystemAuthenticated}} + if err := store.SavePolicyDocument(ctx, []*api.PolicyRole{nodeRole}, []*api.PolicyBinding{nodeBinding}, nil); err != nil { + t.Fatalf("SavePolicyDocument: %v", err) + } + gatewayPriv, gatewayID, gatewayBiscuit, _ := enrollTestNodeForSTS(t, baseURL, mintOIDC) + otherPriv, otherID, otherBiscuit, _ := enrollTestNodeForSTS(t, baseURL, mintOIDC) + if err := store.SavePolicyDocument(ctx, + []*api.PolicyRole{nodeRole, {Name: "egress-gateway", AllowedServices: []string{"egress://" + destination}, AllowedTargets: []string{"*"}}}, + []*api.PolicyBinding{nodeBinding, {Role: "egress-gateway", Members: []string{"node:" + gatewayID.String()}}}, + []*api.EgressDestination{{ + Name: destination, + ServedBy: []string{"egress-gateway"}, + Broker: &api.CredentialBroker{Kind: &api.CredentialBroker_AwsAssumeRole{ + AwsAssumeRole: &api.AWSAssumeRole{RoleArn: "arn:aws:iam::123456789012:role/agentmesh-s3"}, + }}, + }}, + ); err != nil { + t.Fatalf("SavePolicyDocument: %v", err) + } + + for _, tc := range []struct { + name string + gateway bool // the gateway node calls, else a node outside served_by + audience string + failures int32 + want int + }{ + {name: "gateway, the store answers", gateway: true, want: http.StatusOK}, + {name: "outside served_by, the store answers", want: http.StatusForbidden}, + {name: "outside served_by, the first read fails", failures: 1, want: http.StatusInternalServerError}, + {name: "gateway, foreign audience, two reads fail", gateway: true, audience: "https://evil.example.com", failures: 2, want: http.StatusInternalServerError}, + {name: "gateway, every read fails", gateway: true, failures: 1000, want: http.StatusInternalServerError}, + } { + t.Run(tc.name, func(t *testing.T) { + priv, id, cred := otherPriv, otherID, otherBiscuit + if tc.gateway { + priv, id, cred = gatewayPriv, gatewayID, gatewayBiscuit + } + store.failNext.Store(tc.failures) + status, aud := postSTSToken(t, baseURL, priv, id, cred, destination, tc.audience) + if status != tc.want { + t.Fatalf("POST /sts/token with %d failing reads of the egress policy returned %d (aud %q), want %d", tc.failures, status, aud, tc.want) + } + }) + } +} diff --git a/internal/envoy/envoy_test.go b/internal/envoy/envoy_test.go index 09f14f10..6b8fa32a 100644 --- a/internal/envoy/envoy_test.go +++ b/internal/envoy/envoy_test.go @@ -32,6 +32,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strconv" "strings" "sync" "testing" @@ -87,7 +88,7 @@ func TestGatewayServer_ExtAuthzHTTPAndGRPC(t *testing.T) { Message: "missing or invalid token", } } - if in.Headers[strings.ToLower(HeaderMeshMCPTool)] == "merge_pr" { + if in.MCPTool == "merge_pr" { return CheckResult{ Allowed: false, HTTPStatus: http.StatusForbidden, @@ -252,9 +253,161 @@ func TestGatewayServer_ExtAuthzHTTPAndGRPC(t *testing.T) { } } +// The evaluator returns an upstream credential only to a caller that the +// transport authenticates as the gateway (GHSA-2g97-3v45-p9f4). Each entry +// point must hand it that fact from the connection of the request. +func TestGatewayServer_TrustedTransport(t *testing.T) { + const seenHeader = "X-Test-Trusted-Transport" + eval := func(_ context.Context, in CheckInput) CheckResult { + return CheckResult{ + Allowed: true, + HTTPStatus: http.StatusOK, + ResponseHeaders: map[string]string{seenHeader: strconv.FormatBool(in.TrustedTransport)}, + } + } + seenIn := func(headers []*corev3.HeaderValueOption) string { + for _, h := range headers { + if h.GetHeader().GetKey() == seenHeader { + return h.GetHeader().GetValue() + string(h.GetHeader().GetRawValue()) + } + } + return "" + } + verifiedClientCert := func(r *http.Request) bool { + return r.TLS != nil && len(r.TLS.VerifiedChains) > 0 + } + + gw := NewGatewayServer(eval) + gw.TrustedTransport = verifiedClientCert + plainAddr := startH2CGatewayTestServer(t, gw) + + serverCert, caPEM, _ := generateTestCerts(t) + caPool := x509.NewCertPool() + if !caPool.AppendCertsFromPEM(caPEM) { + t.Fatalf("failed to parse the test CA certificate") + } + mux := http.NewServeMux() + gw.RegisterRoutes(mux) + mtlsServer := httptest.NewUnstartedServer(mux) + mtlsServer.EnableHTTP2 = true + mtlsServer.TLS = &tls.Config{ + Certificates: []tls.Certificate{serverCert}, + ClientAuth: tls.RequireAndVerifyClientCert, + ClientCAs: caPool, + } + mtlsServer.StartTLS() + t.Cleanup(mtlsServer.Close) + clientTLS := &tls.Config{RootCAs: caPool, Certificates: []tls.Certificate{serverCert}} + + transports := []struct { + name string + addr string + baseURL string + httpClient *http.Client + grpcCreds credentials.TransportCredentials + want string + }{ + { + name: "plain TCP", + addr: plainAddr, + baseURL: "http://" + plainAddr, + httpClient: &http.Client{}, + grpcCreds: insecure.NewCredentials(), + want: "false", + }, + { + name: "verified client certificate", + addr: mtlsServer.Listener.Addr().String(), + baseURL: mtlsServer.URL, + httpClient: &http.Client{Transport: &http.Transport{TLSClientConfig: clientTLS, ForceAttemptHTTP2: true}}, + grpcCreds: credentials.NewTLS(clientTLS), + want: "true", + }, + } + entryPoints := []struct { + name string + seen func(ctx context.Context, httpClient *http.Client, baseURL string, conn *grpc.ClientConn) (string, error) + }{ + {"HTTP ext_authz", func(ctx context.Context, httpClient *http.Client, baseURL string, _ *grpc.ClientConn) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/ext_authz/", nil) + if err != nil { + return "", err + } + resp, err := httpClient.Do(req) + if err != nil { + return "", err + } + _ = resp.Body.Close() + return resp.Header.Get(seenHeader), nil + }}, + {"gRPC Check v3", func(ctx context.Context, _ *http.Client, _ string, conn *grpc.ClientConn) (string, error) { + resp, err := authv3.NewAuthorizationClient(conn).Check(ctx, &authv3.CheckRequest{}) + if err != nil { + return "", err + } + return seenIn(resp.GetOkResponse().GetHeaders()), nil + }}, + {"gRPC Check v2", func(ctx context.Context, _ *http.Client, _ string, conn *grpc.ClientConn) (string, error) { + var resp authv3.CheckResponse + if err := conn.Invoke(ctx, ExtAuthzV2MethodPath, &authv3.CheckRequest{}, &resp); err != nil { + return "", err + } + return seenIn(resp.GetOkResponse().GetHeaders()), nil + }}, + {"gRPC ext_proc", func(ctx context.Context, _ *http.Client, _ string, conn *grpc.ClientConn) (string, error) { + stream, err := extprocv3.NewExternalProcessorClient(conn).Process(ctx) + if err != nil { + return "", err + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{EndOfStream: true}, + }, + }); err != nil { + return "", err + } + resp, err := stream.Recv() + if err != nil { + return "", err + } + return seenIn(resp.GetRequestHeaders().GetResponse().GetHeaderMutation().GetSetHeaders()), nil + }}, + } + for _, tr := range transports { + conn, err := grpc.NewClient("passthrough:///"+tr.addr, grpc.WithTransportCredentials(tr.grpcCreds)) + if err != nil { + t.Fatalf("grpc.NewClient over %s: %v", tr.name, err) + } + t.Cleanup(func() { _ = conn.Close() }) + for _, ep := range entryPoints { + t.Run(tr.name+"/"+ep.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + got, err := ep.seen(ctx, tr.httpClient, tr.baseURL, conn) + if err != nil { + t.Fatalf("%s over %s: %v", ep.name, tr.name, err) + } + if got != tr.want { + t.Errorf("the evaluator saw TrustedTransport = %q, want %q", got, tr.want) + } + }) + } + } + + t.Run("no transport is trusted when the server has no rule", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/ext_authz/", nil) + req.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}} + rec := httptest.NewRecorder() + NewGatewayServer(eval).HandleExtAuthzHTTP(rec, req) + if got := rec.Header().Get(seenHeader); got != "false" { + t.Errorf("the evaluator saw TrustedTransport = %q, want %q", got, "false") + } + }) +} + func TestGatewayServer_ExtProcProcess(t *testing.T) { gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { - if in.Headers[strings.ToLower(HeaderMeshMCPTool)] == "merge_pr" { + if in.MCPTool == "merge_pr" { return CheckResult{ Allowed: false, HTTPStatus: http.StatusForbidden, @@ -385,6 +538,157 @@ func TestGatewayServer_ExtProcProcess(t *testing.T) { _ = stream.CloseSend() } +// The body names the tool of an MCP tools/call. A client can set any request +// header, so a header that names another tool must not change the decision of +// any of the three check services. +func TestGatewayServer_BodyDecidesMCPTool(t *testing.T) { + // The evaluator stands for a task rule with allowed_tools: [get_pr]. + gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { + if in.MCPTool == "get_pr" || (in.MCPTool == "" && in.AllowMCPStreamInit) { + return CheckResult{Allowed: true, HTTPStatus: http.StatusOK} + } + return CheckResult{Allowed: false, HTTPStatus: http.StatusForbidden, Message: "tool " + in.MCPTool + " is not allowed"} + }) + addr := startH2CGatewayTestServer(t, gw) + conn, err := grpc.NewClient("passthrough:///"+addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + procClient := extprocv3.NewExternalProcessorClient(conn) + + const clientHeader = "x-mesh-mcp-tool" + + // extProc sends one request through ext_proc. It reports whether the + // processor asked Envoy for the body and whether it refused the request. + extProc := func(t *testing.T, path, headerTool, body string) (buffered, denied bool) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + stream, err := procClient.Process(ctx) + if err != nil { + t.Fatalf("Process: %v", err) + } + hdrs := []*corev3.HeaderValue{{Key: ":method", Value: "POST"}, {Key: ":path", Value: path}} + if headerTool != "" { + hdrs = append(hdrs, &corev3.HeaderValue{Key: clientHeader, Value: headerTool}) + } + if err := stream.Send(&extprocv3.ProcessingRequest{Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{Headers: &corev3.HeaderMap{Headers: hdrs}}, + }}); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + r1, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + if r1.GetImmediateResponse() != nil { + return false, true + } + if r1.GetModeOverride().GetRequestBodyMode() != extprocv3http.ProcessingMode_BUFFERED { + // Envoy sends no body: the answer to the headers was the decision. + return false, false + } + if err := stream.Send(&extprocv3.ProcessingRequest{Request: &extprocv3.ProcessingRequest_RequestBody{ + RequestBody: &extprocv3.HttpBody{Body: []byte(body), EndOfStream: true}, + }}); err != nil { + t.Fatalf("Send RequestBody: %v", err) + } + r2, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestBody: %v", err) + } + return true, r2.GetImmediateResponse() != nil + } + + for _, tc := range []struct { + name string + path string + headerTool string + bodyTool string + wantDenied bool + }{ + {name: "allowed tool in the body", path: "/mesh/mcp/github", bodyTool: "get_pr"}, + {name: "refused tool in the body", path: "/mesh/mcp/github", bodyTool: "merge_pr", wantDenied: true}, + {name: "refused tool in the body, allowed tool in a header", path: "/mesh/mcp/github", headerTool: "get_pr", bodyTool: "merge_pr", wantDenied: true}, + {name: "allowed tool in the body, refused tool in a header", path: "/mesh/mcp/github", headerTool: "merge_pr", bodyTool: "get_pr"}, + {name: "service type in upper case, refused tool in the body, allowed tool in a header", path: "/mesh/MCP/github", headerTool: "get_pr", bodyTool: "merge_pr", wantDenied: true}, + {name: "service type in upper case, allowed tool in the body", path: "/mesh/MCP/github", bodyTool: "get_pr"}, + } { + t.Run(tc.name, func(t *testing.T) { + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tc.bodyTool + `"}}` + + httpReq := httptest.NewRequest(http.MethodPost, "/ext_authz"+tc.path, strings.NewReader(body)) + if tc.headerTool != "" { + httpReq.Header.Set(clientHeader, tc.headerTool) + } + rec := httptest.NewRecorder() + gw.HandleExtAuthzHTTP(rec, httpReq) + if denied := rec.Code != http.StatusOK; denied != tc.wantDenied { + t.Errorf("HTTP ext_authz: status %d, denied = %v, want %v", rec.Code, denied, tc.wantDenied) + } + + grpcHeaders := map[string]string{} + if tc.headerTool != "" { + grpcHeaders[clientHeader] = tc.headerTool + } + resp, err := gw.Check(context.Background(), &authv3.CheckRequest{Attributes: &authv3.AttributeContext{ + Request: &authv3.AttributeContext_Request{Http: &authv3.AttributeContext_HttpRequest{ + Method: http.MethodPost, Path: tc.path, Headers: grpcHeaders, Body: body, + }}, + }}) + if err != nil { + t.Fatalf("Check: %v", err) + } + if denied := resp.GetStatus().GetCode() != int32(codes.OK); denied != tc.wantDenied { + t.Errorf("gRPC ext_authz: status code %d, denied = %v, want %v", resp.GetStatus().GetCode(), denied, tc.wantDenied) + } + + buffered, denied := extProc(t, tc.path, tc.headerTool, body) + if !buffered { + t.Errorf("ext_proc: the processor did not ask Envoy for the request body") + } + if denied != tc.wantDenied { + t.Errorf("ext_proc: denied = %v, want %v", denied, tc.wantDenied) + } + }) + } +} + +// The tool of an MCP tools/call is in the body. An ext_authz check for a POST +// that carries no body names no tool and is not a handshake, so the evaluator +// refuses it for a rule with allowed_tools. A GET or a DELETE carries no call. +func TestGatewayServer_ExtAuthzWithoutBody(t *testing.T) { + var got CheckInput + gw := NewGatewayServer(func(_ context.Context, in CheckInput) CheckResult { + got = in + return CheckResult{Allowed: true, HTTPStatus: http.StatusOK} + }) + for _, tc := range []struct { + method string + wantHandshake bool + }{ + {method: http.MethodPost, wantHandshake: false}, + {method: http.MethodGet, wantHandshake: true}, + {method: http.MethodDelete, wantHandshake: true}, + } { + t.Run(tc.method, func(t *testing.T) { + gw.HandleExtAuthzHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, "/ext_authz/mesh/mcp/github", nil)) + if got.MCPTool != "" || got.AllowMCPStreamInit != tc.wantHandshake { + t.Errorf("HTTP ext_authz with no body: tool %q, handshake %v, want no tool and handshake %v", got.MCPTool, got.AllowMCPStreamInit, tc.wantHandshake) + } + if _, err := gw.Check(context.Background(), &authv3.CheckRequest{Attributes: &authv3.AttributeContext{ + Request: &authv3.AttributeContext_Request{Http: &authv3.AttributeContext_HttpRequest{Method: tc.method, Path: "/mesh/mcp/github"}}, + }}); err != nil { + t.Fatalf("Check: %v", err) + } + if got.MCPTool != "" || got.AllowMCPStreamInit != tc.wantHandshake { + t.Errorf("gRPC ext_authz with no body: tool %q, handshake %v, want no tool and handshake %v", got.MCPTool, got.AllowMCPStreamInit, tc.wantHandshake) + } + }) + } +} + type referenceCalloutServer struct { extprocv3.UnimplementedExternalProcessorServer diff --git a/internal/envoy/server.go b/internal/envoy/server.go index 0fdaa29f..5a85bb79 100644 --- a/internal/envoy/server.go +++ b/internal/envoy/server.go @@ -37,10 +37,6 @@ import ( ) const ( - // HeaderMeshMCPTool lets an external proxy (or ext_proc filter) pass the - // extracted MCP tool name during an ext_authz check. - HeaderMeshMCPTool = "X-Mesh-Mcp-Tool" - // ExtProcMethodPath is the gRPC HTTP/2 path for Envoy ExternalProcessor.Process. ExtProcMethodPath = "/envoy.service.ext_proc.v3.ExternalProcessor/Process" // ExtAuthzV3MethodPath is the gRPC HTTP/2 path for Envoy v3 Authorization.Check. @@ -57,12 +53,21 @@ const ( // CheckInput represents a normalized authorization check request from Envoy // HTTP ext_authz, gRPC ext_authz, or gRPC ext_proc. type CheckInput struct { - Method string - Path string - Host string - Headers map[string]string - Body []byte + Method string + Path string + Host string + Headers map[string]string + Body []byte + // MCPTool is the tool of an MCP tools/call, and AllowMCPStreamInit says + // that the request is an MCP handshake. The server reads both from the + // request body that Envoy sent, and from nothing else: a client can set + // any request header, so no header names the tool. + MCPTool string AllowMCPStreamInit bool + // TrustedTransport reports that the check arrived on a transport that + // authenticates the caller as the gateway. The Evaluator returns an + // upstream credential only when it is set. + TrustedTransport bool } // CheckResult represents the policy decision and header mutations returned by @@ -85,6 +90,12 @@ type GatewayServer struct { eval Evaluator grpcServer *grpc.Server + + // TrustedTransport reports whether a request arrived on a transport that + // authenticates the caller as the gateway. Each entry point passes the + // answer to the Evaluator in CheckInput.TrustedTransport. Set it before + // the server handles requests. Nil trusts no transport. + TrustedTransport func(*http.Request) bool } // NewGatewayServer constructs a GatewayServer backed by a google.golang.org/grpc @@ -112,6 +123,19 @@ func (s *GatewayServer) RegisterRoutes(mux *http.ServeMux) { mux.HandleFunc(ExtProcMethodPath, s.ServeGRPC) } +type trustedTransportKey struct{} + +func (s *GatewayServer) trustedTransport(r *http.Request) bool { + return s.TrustedTransport != nil && s.TrustedTransport(r) +} + +// trustedTransportFromContext reads the transport fact that ServeGRPC stored. +// A context that did not pass through ServeGRPC is not trusted. +func trustedTransportFromContext(ctx context.Context) bool { + trusted, _ := ctx.Value(trustedTransportKey{}).(bool) + return trusted +} + // ServeGRPC dispatches an incoming HTTP/2 gRPC request to the underlying // google.golang.org/grpc server, normalizing Envoy v2 ext_authz paths to v3. func (s *GatewayServer) ServeGRPC(w http.ResponseWriter, r *http.Request) { @@ -119,6 +143,9 @@ func (s *GatewayServer) ServeGRPC(w http.ResponseWriter, r *http.Request) { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } + // grpc.Server.ServeHTTP derives the context of Check and Process from the + // request context, so the transport fact travels in it. + r = r.WithContext(context.WithValue(r.Context(), trustedTransportKey{}, s.trustedTransport(r))) if r.URL.Path == ExtAuthzV2MethodPath { r2 := new(http.Request) *r2 = *r @@ -163,14 +190,7 @@ func (s *GatewayServer) HandleExtAuthzHTTP(w http.ResponseWriter, r *http.Reques } bodyBytes = b } - allowInit := headers[strings.ToLower(HeaderMeshMCPTool)] == "" - if len(bodyBytes) > 0 && headers[strings.ToLower(HeaderMeshMCPTool)] == "" { - tool, isInit := InspectJSONRPCMCPBody(bodyBytes) - if tool != "" { - headers[strings.ToLower(HeaderMeshMCPTool)] = tool - } - allowInit = isInit - } + mcpTool, allowInit := mcpCallOfBody(method, bodyBytes) res := s.eval(r.Context(), CheckInput{ Method: method, @@ -178,7 +198,9 @@ func (s *GatewayServer) HandleExtAuthzHTTP(w http.ResponseWriter, r *http.Reques Host: r.Host, Headers: headers, Body: bodyBytes, + MCPTool: mcpTool, AllowMCPStreamInit: allowInit, + TrustedTransport: s.trustedTransport(r), }) if !res.Allowed { status := res.HTTPStatus @@ -207,15 +229,7 @@ func (s *GatewayServer) Check(ctx context.Context, req *authv3.CheckRequest) (*a } else if httpReq.GetBody() != "" { body = []byte(httpReq.GetBody()) } - - allowInit := headers[strings.ToLower(HeaderMeshMCPTool)] == "" - if len(body) > 0 && headers[strings.ToLower(HeaderMeshMCPTool)] == "" { - tool, isInit := InspectJSONRPCMCPBody(body) - if tool != "" { - headers[strings.ToLower(HeaderMeshMCPTool)] = tool - } - allowInit = isInit - } + mcpTool, allowInit := mcpCallOfBody(httpReq.GetMethod(), body) res := s.eval(ctx, CheckInput{ Method: httpReq.GetMethod(), @@ -223,7 +237,9 @@ func (s *GatewayServer) Check(ctx context.Context, req *authv3.CheckRequest) (*a Host: httpReq.GetHost(), Headers: headers, Body: body, + MCPTool: mcpTool, AllowMCPStreamInit: allowInit, + TrustedTransport: trustedTransportFromContext(ctx), }) if res.Allowed { var hdrs []*corev3.HeaderValueOption @@ -304,15 +320,14 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer capturedHost = capturedHeaders["host"] } - targetHdr := strings.ToLower(capturedHeaders[strings.ToLower(api.HeaderMeshTargetService)]) - isMCPRoute := strings.HasPrefix(capturedPath, "/mcp") || - strings.Contains(capturedPath, "/mcp/") || - strings.HasPrefix(targetHdr, api.ServiceTypeStringMCP+"://") + // The tool of an MCP tools/call is in the body, so ext_proc asks + // Envoy for the body of a POST to an MCP service and decides when + // it arrives. Every other request is decided now, with no tool and + // no handshake allowance: a task rule with allowed_tools denies it. if !phase.RequestHeaders.GetEndOfStream() && strings.EqualFold(capturedMethod, http.MethodPost) && - capturedHeaders[strings.ToLower(HeaderMeshMCPTool)] == "" && - isMCPRoute { - preResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, false, true) + isMCPRoute(capturedPath, capturedHeaders[strings.ToLower(api.HeaderMeshTargetService)]) { + preResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, true) if preResp.GetImmediateResponse() != nil { resp = preResp } else { @@ -331,21 +346,14 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer } } } else { - resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, false, false) + resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false) } case *extprocv3.ProcessingRequest_RequestBody: - var allowStreamInit bool - if len(phase.RequestBody.GetBody()) > 0 && capturedHeaders != nil { - tool, allowInit := InspectJSONRPCMCPBody(phase.RequestBody.GetBody()) - if tool != "" { - capturedHeaders[strings.ToLower(HeaderMeshMCPTool)] = tool - } - allowStreamInit = allowInit - } if pendingCheck { pendingCheck = false - resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, true, allowStreamInit) + mcpTool, allowStreamInit := InspectJSONRPCMCPBody(phase.RequestBody.GetBody()) + resp = s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, mcpTool, true, allowStreamInit) } else { resp = &extprocv3.ProcessingResponse{ Response: &extprocv3.ProcessingResponse_RequestBody{ @@ -361,7 +369,7 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer case *extprocv3.ProcessingRequest_ResponseHeaders: if pendingCheck { pendingCheck = false - if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, false, false); denyResp.GetImmediateResponse() != nil { + if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false); denyResp.GetImmediateResponse() != nil { resp = denyResp break } @@ -390,7 +398,7 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer case *extprocv3.ProcessingRequest_RequestTrailers: if pendingCheck { pendingCheck = false - if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, false, false); denyResp.GetImmediateResponse() != nil { + if denyResp := s.evaluateExtProcDecision(stream.Context(), capturedMethod, capturedPath, capturedHost, capturedHeaders, "", false, false); denyResp.GetImmediateResponse() != nil { resp = denyResp break } @@ -420,13 +428,15 @@ func (s *GatewayServer) Process(stream extprocv3.ExternalProcessor_ProcessServer } } -func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, path, host string, headers map[string]string, isBodyPhase, allowMCPStreamInit bool) *extprocv3.ProcessingResponse { +func (s *GatewayServer) evaluateExtProcDecision(ctx context.Context, method, path, host string, headers map[string]string, mcpTool string, isBodyPhase, allowMCPStreamInit bool) *extprocv3.ProcessingResponse { res := s.eval(ctx, CheckInput{ Method: method, Path: path, Host: host, Headers: headers, + MCPTool: mcpTool, AllowMCPStreamInit: allowMCPStreamInit, + TrustedTransport: trustedTransportFromContext(ctx), }) if !res.Allowed { status := typev3.StatusCode_Forbidden @@ -521,6 +531,30 @@ func spoofedMeshHeadersToRemove(inbound, responseHeaders map[string]string) []st return remove } +// mcpCallOfBody reads the MCP call of an ext_authz check: the tool of a +// tools/call, or a handshake. The tool is in the body, and Envoy sends the +// body to ext_authz only when its filter sets with_request_body. A POST with +// no body names no tool and is not a handshake, so a task rule with +// allowed_tools refuses it. A GET opens a stream and a DELETE ends a session: +// they carry no call, as api.InspectMCPHTTPRequestBody also decides. +func mcpCallOfBody(method string, body []byte) (mcpTool string, allowStreamInit bool) { + if len(body) == 0 { + return "", strings.EqualFold(method, http.MethodGet) || strings.EqualFold(method, http.MethodDelete) + } + return InspectJSONRPCMCPBody(body) +} + +// isMCPRoute reports whether a request is for an MCP service, by its path or +// by X-Mesh-Target-Service, so that ext_proc asks Envoy for the body. It +// ignores letter case, as the evaluator does when it resolves the service. +func isMCPRoute(path, targetService string) bool { + path = strings.ToLower(path) + target := strings.ToLower(strings.TrimSpace(targetService)) + return strings.HasPrefix(path, "/mcp") || + strings.Contains(path, "/mcp/") || + strings.HasPrefix(target, api.ServiceTypeStringMCP+"://") +} + // 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. diff --git a/internal/identity/authorize.go b/internal/identity/authorize.go index ab044f62..f3592ab3 100644 --- a/internal/identity/authorize.go +++ b/internal/identity/authorize.go @@ -15,6 +15,8 @@ package identity import ( + "time" + "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" "github.com/libp2p/go-libp2p/core/peer" @@ -90,7 +92,9 @@ type MeshPolicy struct { // every enforcement point uses and runs it. The authorizer must already be // built on the credential under the key that verified it; the caller // checks revocation, bans and the authority-block binding before, and -// evaluates TaskAuthorizationRules (req.TaskRequest) after. +// evaluates TaskAuthorizationRules (req.TaskRequest) after. It also refuses a +// credential whose expiration() fact is missing or not after the current +// time, which the Datalog check alone does not guarantee. func AuthorizeMeshRequest(authorizer biscuit.Authorizer, req MeshRequest, pol MeshPolicy) error { authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ Name: api.FactService, @@ -157,7 +161,11 @@ func AuthorizeMeshRequest(authorizer biscuit.Authorizer, req MeshRequest, pol Me authorizer.AddRule(r) } - return authorizer.Authorize() + if err := authorizer.Authorize(); err != nil { + return err + } + // The Datalog check admits an expiration before 1970, so check it in Go. + return requireUnexpired(authorizer, time.Now()) } // TaskRequest is req as TaskAuthorizationRule evaluation sees it, so the diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.go index ef156b56..74793ad7 100644 --- a/internal/identity/biscuit.go +++ b/internal/identity/biscuit.go @@ -210,7 +210,9 @@ func ExtractTaskRules(biscuitData []byte) ([]*api.TaskAuthorizationRule, error) // authorizer. Every path that admits a biscuit must call this: expiry is a // Datalog check over a time fact, so an authorizer built without the fact // silently accepts expired tokens (see #296). A token carrying no expiration() -// fact fails the check, so this is fail-closed. +// fact fails the check, so this is fail-closed. The check does not refuse an +// expiration before 1970, so the path must also check the expiration in Go +// after the authorizer passes: see requireUnexpired. func EnforceExpiration(authorizer biscuit.Authorizer) { authorizer.AddFact(biscuit.Fact{ Predicate: biscuit.Predicate{ @@ -273,7 +275,20 @@ func requireAuthorityFact(b *biscuit.Biscuit, factName, value string) error { return nil } +// validateExpiration refuses an expiration at or before the Unix epoch. +// Datalog stores a date as unsigned seconds since the epoch. It reads an +// earlier instant as a far future date, so the expiration check of +// EnforceExpiration passes for it and the token does not lapse. The epoch +// itself is the value of an unset Unix time, so it is refused too. +func validateExpiration(expiration time.Time) error { + if expiration.Unix() <= 0 { + return fmt.Errorf("%s %s is not after the Unix epoch: Datalog dates are unsigned", api.FactExpiration, expiration.UTC().Format(time.RFC3339)) + } + return nil +} + // expirationOf reports the expiration() fact of an already-authorized token. +// It refuses an expiration that validateExpiration refuses. func expirationOf(authorizer biscuit.Authorizer) (time.Time, error) { facts, err := authorizer.Query(biscuit.Rule{ Head: biscuit.Predicate{Name: "get_exp", IDs: []biscuit.Term{biscuit.Variable("e")}}, @@ -285,6 +300,7 @@ func expirationOf(authorizer biscuit.Authorizer) (time.Time, error) { // A token may carry several; the earliest is the one that binds. var earliest time.Time + found := false for _, fact := range facts { if len(fact.IDs) != 1 { continue @@ -293,16 +309,34 @@ func expirationOf(authorizer biscuit.Authorizer) (time.Time, error) { if !ok { continue } - if t := time.Time(date); earliest.IsZero() || t.Before(earliest) { - earliest = t + if t := time.Time(date); !found || t.Before(earliest) { + earliest, found = t, true } } - if earliest.IsZero() { + if !found { return time.Time{}, fmt.Errorf("no %s fact in token", api.FactExpiration) } + if err := validateExpiration(earliest); err != nil { + return time.Time{}, err + } return earliest, nil } +// requireUnexpired checks in Go that an already-authorized token carries an +// expiration() fact and that the expiration is after now. The Datalog check +// of EnforceExpiration is not sufficient alone: it admits an expiration +// before 1970 (see validateExpiration). +func requireUnexpired(authorizer biscuit.Authorizer, now time.Time) error { + expiry, err := expirationOf(authorizer) + if err != nil { + return err + } + if !expiry.After(now) { + return fmt.Errorf("token expired at %s", expiry.UTC().Format(time.RFC3339)) + } + return nil +} + // MintBiscuitToken generates a signed Biscuit token for a peer with policy rules based on JWT claims. // labels are control-plane-attested key=value claims (canonical, pre-validated); empty means no claims. func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID, biscuitExpiry time.Time, roles []string, policyRoles []*api.PolicyRole, labels map[string]string) ([]byte, []string, error) { @@ -377,6 +411,10 @@ func mintBiscuitWithBinding(signingKey ed25519.PrivateKey, remotePeer peer.ID, d } func mintBiscuitWithBindingAndRand(rng io.Reader, signingKey ed25519.PrivateKey, remotePeer peer.ID, delegated bool, roles []string, expiration time.Time, claims jwt.MapClaims, policyRoles []*api.PolicyRole, labels map[string]string, attestedClaims map[string][]string) ([]byte, error) { + if err := validateExpiration(expiration); err != nil { + return nil, fmt.Errorf("cannot mint biscuit: %w", err) + } + builder := biscuit.NewBuilder(signingKey, biscuit.WithRNG(rng)) addedFacts := make(map[string]bool) addFact := func(fact biscuit.Fact) error { @@ -641,7 +679,8 @@ func verifyBiscuit(biscuitData []byte, expectedPeer peer.ID, trustedPublicKeys [ } // EnforceExpiration already passed, so the fact is there; a failure here is - // a query error, and fails closed rather than caching an admission forever. + // a query error or an expiration at or before the Unix epoch, and fails + // closed rather than caching an admission forever. expiry, err := expirationOf(authorizer) if err != nil { return nil, nil, time.Time{}, err @@ -777,6 +816,11 @@ func extractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData []byte, ti if !verified { return "", fmt.Errorf("signature verification failed: %v", lastErr) } + if enforceExpiry { + if err := requireUnexpired(authorizer, time.Now()); err != nil { + return "", err + } + } // Extract the peer ID using Datalog query facts, err := authorizer.Query(biscuit.Rule{ diff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.go index da7a3ce1..590a2422 100644 --- a/internal/identity/biscuit_test.go +++ b/internal/identity/biscuit_test.go @@ -583,6 +583,41 @@ func TestVerifyAndExtractPeerID_MultipleTrustedKeys(t *testing.T) { } } +// beforeEpoch is an expiration before 1970, like the one that +// GHSA-qg99-6frq-2h5m put into a Biscuit. +var beforeEpoch = time.Date(1734, time.August, 16, 0, 0, 0, 0, time.UTC) + +// Datalog stores a date as unsigned seconds since the Unix epoch. An earlier +// expiration reads as a far future date and the token does not lapse, so the +// mint refuses it. An expiration in the recent past is a valid date and stays +// mintable: other tests and the refresh flow need expired tokens. +func TestMintRefusesExpirationAtOrBeforeEpoch(t *testing.T) { + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + actor := newTestPeer(t) + + for _, tc := range []struct { + name string + expiry time.Time + wantErr bool + }{ + {name: "one hour from now", expiry: time.Now().Add(time.Hour)}, + {name: "two seconds ago", expiry: time.Now().Add(-2 * time.Second)}, + {name: "the Unix epoch", expiry: time.Unix(0, 0), wantErr: true}, + {name: "before 1970", expiry: beforeEpoch, wantErr: true}, + {name: "unset", expiry: time.Time{}, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := MintDelegatedBiscuitToken(priv, jwt.MapClaims{"sub": "alice"}, actor, tc.expiry, nil, nil, nil, false) + if (err != nil) != tc.wantErr { + t.Errorf("MintDelegatedBiscuitToken(expiration %s) error = %v, wantErr %v", tc.expiry.UTC().Format(time.RFC3339), err, tc.wantErr) + } + }) + } +} + // TestExtractPeerIDExpiry pins that adding the expiration check still rejects an // expired token even though neither variant adds a policy, i.e. that a failed // check outranks ErrNoMatchingPolicy. @@ -617,6 +652,23 @@ func TestExtractPeerIDExpiry(t *testing.T) { t.Error("expired token accepted by the expiry-enforcing variant") } + // Datalog reads an expiration before 1970 as a far future date, so the + // Datalog check passes. The expiry-enforcing variant must check in Go. + builder := biscuit.NewBuilder(priv) + mustAddAuthorityFact(t, builder, api.FactNode, biscuit.String(dummyPeer.String())) + mustAddAuthorityFact(t, builder, api.FactExpiration, biscuit.Date(beforeEpoch)) + token, err := builder.Build() + if err != nil { + t.Fatal(err) + } + beforeEpochToken, err := token.Serialize() + if err != nil { + t.Fatal(err) + } + if _, err := VerifyAndExtractPeerID(trustedKeys, beforeEpochToken, testTimeout); err == nil { + t.Errorf("token with expiration %s accepted by the expiry-enforcing variant", beforeEpoch.Format(time.RFC3339)) + } + // The refresh flow depends on the exempt variant staying permissive. if got, err := VerifyExpiredAndExtractPeerID(trustedKeys, expired, testTimeout); err != nil { t.Errorf("expired token rejected by the refresh variant: %v", err) @@ -768,6 +820,10 @@ func TestVerifyBiscuitAndGetExpiry(t *testing.T) { if _, err := VerifyBiscuitAndGetExpiry(mint(), peerID, keys, testTimeout); err == nil { t.Error("token without an expiration admitted") } + // The earliest expiration binds also when it is the zero time.Time. + if _, err := VerifyBiscuitAndGetExpiry(mint(time.Time{}, soon), peerID, keys, testTimeout); err == nil { + t.Error("token with an unset expiration and a valid one admitted") + } if _, err := VerifyBiscuitAndGetExpiry(mint(soon), newTestPeer(t), keys, testTimeout); err == nil { t.Error("token bound to another peer admitted") } diff --git a/internal/node/compliance_test.go b/internal/node/compliance_test.go index 43992806..eab1bad8 100644 --- a/internal/node/compliance_test.go +++ b/internal/node/compliance_test.go @@ -228,11 +228,13 @@ func TestWorkstationPEPPostureIsolationTaskScopeAndProvenance(t *testing.T) { }, } + // The tool of an MCP call is in the request body. + const getPRCall = `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_pr"}}` + for _, tc := range cases { t.Run("ext_authz/"+tc.name, func(t *testing.T) { - req := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", nil) + req := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", strings.NewReader(getPRCall)) req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(tc.biscuit)) - req.Header.Set(HeaderMeshMCPTool, "get_pr") rec := httptest.NewRecorder() handleExtAuthzHTTP(h.node, rec, req) if rec.Code != tc.wantStatus { @@ -267,12 +269,12 @@ func TestWorkstationPEPPostureIsolationTaskScopeAndProvenance(t *testing.T) { Http: &authv3.AttributeContext_HttpRequest{ Method: "POST", Path: "/mcp/github", + Body: getPRCall, Headers: map[string]string{ - "authorization": "Bearer " + base64.StdEncoding.EncodeToString(managedMobileBiscuit), - strings.ToLower(HeaderMeshMCPTool): "get_pr", - "x-mesh-spoofed": "attacker", - "x-mesh-claims": "forged=true", - "x-peer-id": "forged-peer", + "authorization": "Bearer " + base64.StdEncoding.EncodeToString(managedMobileBiscuit), + "x-mesh-spoofed": "attacker", + "x-mesh-claims": "forged=true", + "x-peer-id": "forged-peer", }, }, }, diff --git a/internal/node/egress_inspect_test.go b/internal/node/egress_inspect_test.go index 56ed49c7..518b6007 100644 --- a/internal/node/egress_inspect_test.go +++ b/internal/node/egress_inspect_test.go @@ -630,43 +630,71 @@ func TestGatewayExtProcServer(t *testing.T) { } _ = stream2.CloseSend() - // 3. Egress route via ext_proc injects brokered Authorization header. - stream3, err := epClient.Process(context.Background()) + // 3. Egress route via ext_proc on the node's own listeners. The header + // mutations carry the brokered Authorization header, so the node answers + // the Unix socket and refuses plain TCP. + socketPath := filepath.Join(t.TempDir(), "node.sock") + sidecar, err := StartSidecarServer(node, "127.0.0.1:0", socketPath, "api-token", "", "", "") if err != nil { - t.Fatalf("Process 3: %v", err) + t.Fatalf("StartSidecarServer: %v", err) } - _ = stream3.Send(&extprocv3.ProcessingRequest{ - Request: &extprocv3.ProcessingRequest_RequestHeaders{ - RequestHeaders: &extprocv3.HttpHeaders{ - EndOfStream: true, - Headers: &corev3.HeaderMap{ - Headers: []*corev3.HeaderValue{ - {Key: ":method", Value: "POST"}, - {Key: ":path", Value: "/mesh/egress/api.github.com/repos/google/agentmesh"}, - {Key: "authorization", Value: "Bearer " + b64Biscuit}, + t.Cleanup(func() { _ = sidecar.Close() }) + + for _, tc := range []struct { + name string + target string + wantAuth string + wantStatus typev3.StatusCode + }{ + {name: "plain TCP", target: node.BoundHTTPAddr, wantStatus: typev3.StatusCode_Forbidden}, + {name: "Unix socket", target: "unix:" + socketPath, wantAuth: "Bearer gateway-injected-github-token"}, + } { + t.Run("egress route over "+tc.name, func(t *testing.T) { + conn, err := grpc.NewClient(tc.target, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + defer func() { _ = conn.Close() }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + stream, err := extprocv3.NewExternalProcessorClient(conn).Process(ctx) + if err != nil { + t.Fatalf("Process: %v", err) + } + if err := stream.Send(&extprocv3.ProcessingRequest{ + Request: &extprocv3.ProcessingRequest_RequestHeaders{ + RequestHeaders: &extprocv3.HttpHeaders{ + EndOfStream: true, + Headers: &corev3.HeaderMap{ + Headers: []*corev3.HeaderValue{ + {Key: ":method", Value: "POST"}, + {Key: ":path", Value: "/mesh/egress/api.github.com/repos/google/agentmesh"}, + {Key: "authorization", Value: "Bearer " + b64Biscuit}, + }, + }, }, }, - }, - }, - }) - resp3Hdr, err := stream3.Recv() - if err != nil { - t.Fatalf("Recv RequestHeaders 3: %v", err) - } - foundAuth := false - for _, h := range resp3Hdr.GetRequestHeaders().GetResponse().GetHeaderMutation().GetSetHeaders() { - val := h.GetHeader().GetValue() - if val == "" { - val = string(h.GetHeader().GetRawValue()) - } - if strings.EqualFold(h.GetHeader().GetKey(), "Authorization") && val == "Bearer gateway-injected-github-token" { - foundAuth = true - } - } - if !foundAuth { - t.Fatalf("expected brokered Authorization header in ext_proc response, got %+v", resp3Hdr) + }); err != nil { + t.Fatalf("Send RequestHeaders: %v", err) + } + resp, err := stream.Recv() + if err != nil { + t.Fatalf("Recv RequestHeaders: %v", err) + } + var gotAuth string + for _, h := range resp.GetRequestHeaders().GetResponse().GetHeaderMutation().GetSetHeaders() { + if strings.EqualFold(h.GetHeader().GetKey(), "Authorization") { + gotAuth = h.GetHeader().GetValue() + string(h.GetHeader().GetRawValue()) + } + } + if gotAuth != tc.wantAuth { + t.Errorf("Authorization in the header mutations = %q, want %q", gotAuth, tc.wantAuth) + } + if got := resp.GetImmediateResponse().GetStatus().GetCode(); got != tc.wantStatus { + t.Errorf("immediate response status = %v, want %v (answer %+v)", got, tc.wantStatus, resp) + } + }) } - _ = stream3.CloseSend() } func TestBoundedResponseRecorderOverflow(t *testing.T) { diff --git a/internal/node/ext_authz.go b/internal/node/ext_authz.go index 94a78f96..74288362 100644 --- a/internal/node/ext_authz.go +++ b/internal/node/ext_authz.go @@ -29,12 +29,17 @@ import ( ) const ( - // HeaderMeshMCPTool lets an external proxy (or ext_proc filter) pass the - // extracted MCP tool name during an ext_authz check. - HeaderMeshMCPTool = envoy.HeaderMeshMCPTool - // ExtProcMethodPath is the gRPC HTTP/2 path for Envoy ExternalProcessor.Process. ExtProcMethodPath = envoy.ExtProcMethodPath + + // upstreamCredentialTransportRule is the reason of a refused check: the + // answer would carry the credential of an egress destination, and the + // transport does not authenticate the caller as the gateway. + upstreamCredentialTransportRule = "the upstream credential is returned only over the Unix socket (--socket-path) or to a verified client certificate (--tls-ca)" + + // borderJWTTransportRule is the reason of a refused request for a border + // JWT at /oauth/token, on the same condition. + borderJWTTransportRule = "a border JWT is returned only over the Unix socket (--socket-path) or to a verified client certificate (--tls-ca)" ) type extAuthzCheckInput = envoy.CheckInput @@ -43,9 +48,11 @@ type extAuthzCheckResult = envoy.CheckResult // newNodeEnvoyGateway creates an Envoy ext_authz + ext_proc GatewayServer backed // by this node's Biscuit PDP and credential broker. func newNodeEnvoyGateway(node *AgentMeshNode) *envoy.GatewayServer { - return envoy.NewGatewayServer(func(ctx context.Context, in envoy.CheckInput) envoy.CheckResult { + gw := envoy.NewGatewayServer(func(ctx context.Context, in envoy.CheckInput) envoy.CheckResult { return evaluateExtAuthz(ctx, node, in) }) + gw.TrustedTransport = fromTrustedTransport + return gw } func handleExtAuthzHTTP(node *AgentMeshNode, w http.ResponseWriter, r *http.Request) { @@ -129,7 +136,7 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck PeerID: callerPeer, Protocol: "ext_authz", Target: target, - MCPTool: in.Headers[strings.ToLower(HeaderMeshMCPTool)], + MCPTool: in.MCPTool, AllowMCPStreamInit: in.AllowMCPStreamInit, HTTP: &HTTPRequestFacts{Method: method, Path: reqPath}, Local: isLocal, @@ -186,6 +193,16 @@ func evaluateExtAuthz(ctx context.Context, node *AgentMeshNode, in extAuthzCheck if after, ok := strings.CutPrefix(target, api.EgressServicePrefix); ok && node.services != nil { if svc, ok := node.services.GetTyped(api.ServiceType_SERVICE_TYPE_EGRESS, after); ok { if es, ok := svc.(*EgressService); ok && es.exchanger != nil { + // An application on the same host can send this check too. + // Only the transport tells it from the gateway. + if !in.TrustedTransport { + logger.Warnf("[ExtAuthz] Check for %s by %s refused: %s", target, claims.Principal(), upstreamCredentialTransportRule) + return extAuthzCheckResult{ + Allowed: false, + HTTPStatus: http.StatusForbidden, + Message: "Forbidden: " + upstreamCredentialTransportRule, + } + } authHdr, _, bErr := es.resolveAuthorization(WithCallerBiscuit(ctx, rawBiscuit)) if bErr != nil { return extAuthzCheckResult{ diff --git a/internal/node/gate_test.go b/internal/node/gate_test.go index 32b5a526..b2257549 100644 --- a/internal/node/gate_test.go +++ b/internal/node/gate_test.go @@ -19,6 +19,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "time" @@ -28,6 +29,7 @@ import ( "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/protocol" + "github.com/modelcontextprotocol/go-sdk/jsonrpc" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -548,6 +550,7 @@ func TestHandleMCPStream_TAREnforcesAllowedTools(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() + var dropTableRuns atomic.Int32 upstream := httptest.NewServer(mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { srv := mcp.NewServer(&mcp.Implementation{Name: "weather-srv", Version: "0.0.1"}, nil) srv.AddTool(&mcp.Tool{Name: "get_weather", Description: "allowed tool", InputSchema: map[string]any{"type": "object"}}, @@ -556,6 +559,7 @@ func TestHandleMCPStream_TAREnforcesAllowedTools(t *testing.T) { }) srv.AddTool(&mcp.Tool{Name: "drop_table", Description: "forbidden tool", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + dropTableRuns.Add(1) return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "dropped"}}}, nil }) return srv @@ -603,7 +607,8 @@ func TestHandleMCPStream_TAREnforcesAllowedTools(t *testing.T) { defer func() { _ = s.Close() }() client := mcp.NewClient(&mcp.Implementation{Name: "tc", Version: "0.0.1"}, nil) - session, err := client.Connect(ctx, NewStreamTransport(s), nil) + transport := NewStreamTransport(s) + session, err := client.Connect(ctx, transport, nil) if err != nil { t.Fatalf("client.Connect: %v", err) } @@ -622,4 +627,22 @@ func TestHandleMCPStream_TAREnforcesAllowedTools(t *testing.T) { if _, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "drop_table", Arguments: map[string]any{}}); err == nil { t.Fatal("expected CallTool(drop_table) to be denied by TAR") } + + // A tools/call with no id gets no answer, so the node cannot refuse it + // with one. The node must drop it and keep the stream open. The node + // reads the stream in order, so the answer to the call after it shows + // that the node is done with the message. + if err := transport.Write(ctx, &jsonrpc.Request{Method: "tools/call", Params: []byte(`{"name":"drop_table","arguments":{}}`)}); err != nil { + t.Fatalf("write a tools/call with no id: %v", err) + } + res, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "get_weather", Arguments: map[string]any{}}) + if err != nil { + t.Fatalf("CallTool(get_weather) after a tools/call with no id: %v, want the stream still open", err) + } + if tc, ok := res.Content[0].(*mcp.TextContent); !ok || tc.Text != "sunny" { + t.Fatalf("after a tools/call with no id got %v, want text %q", res.Content, "sunny") + } + if got := dropTableRuns.Load(); got != 0 { + t.Fatalf("the backend ran drop_table %d times, want 0", got) + } } diff --git a/internal/node/identity_evidence.go b/internal/node/identity_evidence.go index 805cc26c..12c17d98 100644 --- a/internal/node/identity_evidence.go +++ b/internal/node/identity_evidence.go @@ -103,7 +103,7 @@ func (n *AgentMeshNode) stillTrustsKey(selected trustedKeySnapshot) bool { func requireIdentityEvidenceTransport(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !fromLocalSocket(r) && (r.TLS == nil || len(r.TLS.VerifiedChains) == 0) { + if !fromTrustedTransport(r) { writeEvidenceError(w, http.StatusForbidden, "Strong transport required") return } diff --git a/internal/node/mcp.go b/internal/node/mcp.go index 44250fc2..abc538d2 100644 --- a/internal/node/mcp.go +++ b/internal/node/mcp.go @@ -289,6 +289,13 @@ func (n *AgentMeshNode) connectMCPSessionWithRetry(ctx context.Context, targetPe var ErrAuthRejected = errors.New("auth rejected") func (n *AgentMeshNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, targetService string, requiredLabels map[string]string) (*mcp.ClientSession, func(), error) { + // The AuthFrame below carries the caller's credential, so the provider is + // verified first over AuthProtocolID with this node's own, as the HTTP + // path does: an unverified peer never receives the caller's Biscuit. + if err := n.VerifyProvider(ctx, targetPeer, requiredLabels, targetService); err != nil { + return nil, nil, err + } + // Open stream logger.Debugf("Dialing %s for MCP...\n", targetPeer) // For discovery, we want a fast failure, but for tool calls, we can wait a bit. We'll use the context's deadline, diff --git a/internal/node/mcp_provider_gate_test.go b/internal/node/mcp_provider_gate_test.go new file mode 100644 index 00000000..55706b49 --- /dev/null +++ b/internal/node/mcp_provider_gate_test.go @@ -0,0 +1,163 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package node + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "sync" + "testing" + "time" + + jwt "github.com/golang-jwt/jwt/v5" + "github.com/google/agentmesh/api" + "github.com/google/agentmesh/internal/identity" + "github.com/libp2p/go-libp2p" + "github.com/libp2p/go-libp2p/core/network" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/protocol" + "github.com/libp2p/go-msgio" + "google.golang.org/protobuf/proto" +) + +// recordingPeer is a libp2p peer that answers the auth handshake with a fixed +// response and records every AuthFrame it receives, per protocol. +type recordingPeer struct { + mu sync.Mutex + frames map[protocol.ID][]*api.AuthFrame +} + +func startRecordingPeer(t *testing.T, reply func() *api.AuthResponse) (peer.AddrInfo, *recordingPeer) { + t.Helper() + h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) + if err != nil { + t.Fatalf("start recording peer: %v", err) + } + t.Cleanup(func() { _ = h.Close() }) + rec := &recordingPeer{frames: map[protocol.ID][]*api.AuthFrame{}} + for _, id := range []protocol.ID{api.AuthProtocolID, api.MCPProtocolID} { + h.SetStreamHandler(id, rec.handle(id, reply)) + } + return peer.AddrInfo{ID: h.ID(), Addrs: h.Addrs()}, rec +} + +func (r *recordingPeer) handle(id protocol.ID, reply func() *api.AuthResponse) network.StreamHandler { + return func(s network.Stream) { + defer func() { _ = s.Close() }() + msg, err := msgio.NewVarintReaderSize(s, 64*1024).ReadMsg() + if err != nil { + return + } + var frame api.AuthFrame + if err := proto.Unmarshal(msg, &frame); err != nil { + return + } + r.mu.Lock() + r.frames[id] = append(r.frames[id], &frame) + r.mu.Unlock() + out, err := proto.Marshal(reply()) + if err != nil { + return + } + _ = msgio.NewVarintWriter(s).WriteMsg(out) + } +} + +func (r *recordingPeer) received(id protocol.ID) []*api.AuthFrame { + r.mu.Lock() + defer r.mu.Unlock() + return append([]*api.AuthFrame(nil), r.frames[id]...) +} + +// TestConnectMCPSessionVerifiesProviderBeforeSendingCallerBiscuit pins that a +// peer which is not a verified provider of the service never receives the +// caller's Biscuit: only this node's own credential goes out, on the auth +// handshake, and the MCP stream is never opened. +func TestConnectMCPSessionVerifiesProviderBeforeSendingCallerBiscuit(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + nodeA, cleanup := startBareNode(t, ctx) + defer cleanup() + rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate root key: %v", err) + } + if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil { + t.Fatalf("save node A biscuit: %v", err) + } + nodeA.keysMu.Lock() + nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()}) + nodeA.keysMu.Unlock() + + callerBiscuit, err := identity.MintDelegatedBiscuitToken(rootPriv, jwt.MapClaims{ + "sub": "user-42", + "email": "alice@example.com", + }, nodeA.Host.ID(), time.Now().Add(time.Hour), []string{"user"}, nil, nil, false) + if err != nil { + t.Fatalf("mint caller biscuit: %v", err) + } + + tests := []struct { + name string + reply func(rogue peer.ID) *api.AuthResponse + }{ + { + name: "peer with no credential", + reply: func(peer.ID) *api.AuthResponse { return &api.AuthResponse{Success: true} }, + }, + { + name: "enrolled node not granted the service", + reply: func(rogue peer.ID) *api.AuthResponse { + b, err := identity.MintBootstrapBiscuitToken(rootPriv, rogue, api.RoleNode, time.Now().Add(time.Hour), nil, nil) + if err != nil { + t.Errorf("mint rogue biscuit: %v", err) + } + return &api.AuthResponse{Success: true, Biscuit: b} + }, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var rogueID peer.ID + info, rec := startRecordingPeer(t, func() *api.AuthResponse { return tc.reply(rogueID) }) + rogueID = info.ID + if err := nodeA.Host.Connect(ctx, info); err != nil { + t.Fatalf("connect to rogue: %v", err) + } + + session, closeSession, err := nodeA.ConnectMCPSession(WithCallerBiscuit(ctx, callerBiscuit), rogueID, "mcp://code-reviewer", nil) + if err == nil { + closeSession() + _ = session.Close() + t.Fatal("ConnectMCPSession succeeded against an unverified peer, want an error") + } + + if got := rec.received(api.MCPProtocolID); len(got) != 0 { + t.Fatalf("rogue received %d frame(s) on %s, want 0", len(got), api.MCPProtocolID) + } + for i, f := range rec.received(api.AuthProtocolID) { + if bytes.Equal(f.Biscuit, callerBiscuit) { + t.Fatalf("auth frame %d carried the caller's Biscuit, want node A's own", i) + } + if !bytes.Equal(f.Biscuit, nodeA.GetIdentity()) { + t.Fatalf("auth frame %d carried an unknown credential, want node A's own", i) + } + } + }) + } +} diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go index 7a4ffde9..f13b996e 100644 --- a/internal/node/mcp_service.go +++ b/internal/node/mcp_service.go @@ -16,11 +16,11 @@ package node import ( "context" - "encoding/json" "errors" "fmt" "os/exec" "sort" + "strings" "sync" "time" @@ -326,6 +326,11 @@ func (m *MCPService) HandleStreamPassThrough(s network.Stream, reqCtx RequestCon } if req, ok := msg.(*jsonrpc.Request); ok && len(reqCtx.TaskRules) > 0 { if errResp := m.authorizeMCPRequest(req, reqCtx); errResp != nil { + // JSON-RPC forbids an answer to a message with no id. + // The node drops it: authorizeMCPRequest logged why. + if !req.IsCall() { + continue + } if werr := clientConn.Write(ctx, errResp); werr != nil { logger.Debugf("[MCPService] %s: failed to write TAR rejection: %v", m.info.Name, werr) clientErrc <- werr @@ -372,11 +377,24 @@ func taskDenied(id jsonrpc.ID, what string, err error) *jsonrpc.Response { // authorizeMCPRequest evaluates reqCtx.TaskRules against an inbound JSON-RPC // request on an MCP stream. Returns a JSON-RPC error response when denied, or // nil when allowed. +// +// A message with no id is allowed only when its method is a notification. +// JSON-RPC forbids an answer to a message with no id, so the caller must not +// send the response for a denied one. func (m *MCPService) authorizeMCPRequest(req *jsonrpc.Request, reqCtx RequestContext) *jsonrpc.Response { + svcName := m.info.GetName() if !req.IsCall() { - return nil + // The official MCP SDK servers do not run a tools/call that has no + // id. A backend on a generic JSON-RPC library can, because JSON-RPC + // lets a server process a notification, and it would run the + // request with no task check. + if strings.HasPrefix(req.Method, "notifications/") { + return nil + } + err := errors.New("only a notifications/ method may have no id") + 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) } - svcName := m.info.GetName() switch req.Method { case "initialize", "ping", "tools/list": if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{ @@ -389,19 +407,20 @@ func (m *MCPService) authorizeMCPRequest(req *jsonrpc.Request, reqCtx RequestCon } return nil case "tools/call": - var params struct { - Name string `json:"name"` - } - if len(req.Params) == 0 || json.Unmarshal(req.Params, ¶ms) != nil || params.Name == "" { - return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "tools/call requires a non-empty tool name"}} + // 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) + if err != nil { + logger.Warnf("[MCPService] %s: refused tools/call from %s that does not name one tool: %v", svcName, reqCtx.PeerID, err) + return &jsonrpc.Response{ID: req.ID, Error: &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "tools/call must name one tool: " + err.Error()}} } if err := api.EvaluateTaskRules(reqCtx.TaskRules, api.TaskRequestContext{ ServiceType: "mcp", ServiceName: svcName, - MCPTool: params.Name, + MCPTool: name, }, time.Now()); err != nil { - logger.Warnf("[MCPService] %s: TAR denied tools/call %q from %s: %v", svcName, params.Name, reqCtx.PeerID, err) - return taskDenied(req.ID, fmt.Sprintf("tool %q", params.Name), err) + logger.Warnf("[MCPService] %s: TAR denied tools/call %q from %s: %v", svcName, name, reqCtx.PeerID, err) + return taskDenied(req.ID, fmt.Sprintf("tool %q", name), err) } return nil default: diff --git a/internal/node/mcp_service_test.go b/internal/node/mcp_service_test.go index d994b1cb..2054305f 100644 --- a/internal/node/mcp_service_test.go +++ b/internal/node/mcp_service_test.go @@ -16,15 +16,101 @@ package node import ( "context" + "errors" "net/http" "net/http/httptest" "sync/atomic" "testing" "github.com/google/agentmesh/api" + "github.com/modelcontextprotocol/go-sdk/jsonrpc" "github.com/modelcontextprotocol/go-sdk/mcp" ) +// The params of a tools/call go to the backend as the same bytes. When they +// state the tool name twice, the task check must refuse the call: the name it +// would check is not the name every backend reads. +func TestMCPService_TaskCheckRefusesAToolNamedTwice(t *testing.T) { + svc := &MCPService{baseService: baseService{ + info: &api.ServiceInfo{Name: "weather", Type: api.ServiceType_SERVICE_TYPE_MCP}, + }} + reqCtx := RequestContext{TaskRules: []*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 + params string + wantDenied bool + }{ + {name: "allowed tool", params: `{"name":"get_weather"}`}, + {name: "allowed name after another name in upper case", params: `{"name":"drop_table","NAME":"get_weather"}`, wantDenied: true}, + {name: "allowed name after another name", params: `{"name":"drop_table","name":"get_weather"}`, wantDenied: true}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := svc.authorizeMCPRequest(&jsonrpc.Request{ID: id, Method: "tools/call", Params: []byte(tc.params)}, reqCtx) + if !tc.wantDenied { + if resp != nil { + t.Fatalf("tools/call with params %s was refused: %v, want it allowed", tc.params, resp.Error) + } + return + } + if resp == nil { + t.Fatalf("tools/call with params %s was allowed, want it refused", tc.params) + } + var rpcErr *jsonrpc.Error + if !errors.As(resp.Error, &rpcErr) || rpcErr.Code != jsonrpc.CodeInvalidParams { + t.Fatalf("tools/call with params %s got error %v, want code %d (invalid params)", tc.params, resp.Error, jsonrpc.CodeInvalidParams) + } + }) + } +} + +// A message with no id gets no answer, and a server must not run a request +// that comes as one. A backend on a generic JSON-RPC library can run it. +// Under a task-scoped credential, a message with no id goes to the backend +// only when its method is a notification. +func TestMCPService_TaskCheckAllowsOnlyANotificationWithNoID(t *testing.T) { + svc := &MCPService{baseService: baseService{ + info: &api.ServiceInfo{Name: "weather", Type: api.ServiceType_SERVICE_TYPE_MCP}, + }} + reqCtx := RequestContext{TaskRules: []*api.TaskAuthorizationRule{{ + Name: "only-get-weather", + Rules: []*api.TaskRule{{ + AllowedServices: []string{"mcp://weather"}, + Operation: &api.TaskOperation{AllowedTools: []string{"get_weather"}}, + }}, + }}} + + for _, tc := range []struct { + name string + method string + params string + wantAllowed bool + }{ + {name: "initialized notification", method: "notifications/initialized", wantAllowed: true}, + {name: "cancelled notification", method: "notifications/cancelled", params: `{"requestId":1}`, wantAllowed: true}, + {name: "call of a forbidden tool", method: "tools/call", params: `{"name":"drop_table"}`}, + {name: "call of an allowed tool", method: "tools/call", params: `{"name":"get_weather"}`}, + {name: "method that the task denies with an id", method: "resources/read", params: `{"uri":"file:///etc/passwd"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := svc.authorizeMCPRequest(&jsonrpc.Request{Method: tc.method, Params: []byte(tc.params)}, reqCtx) + if allowed := resp == nil; allowed != tc.wantAllowed { + t.Fatalf("%s with no id: allowed = %v, want %v", tc.method, allowed, 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/internal/node/sidecar.go b/internal/node/sidecar.go index 0bca8f55..14791968 100644 --- a/internal/node/sidecar.go +++ b/internal/node/sidecar.go @@ -308,6 +308,13 @@ func fromLocalSocket(r *http.Request) bool { return authorized } +// fromTrustedTransport reports whether the transport authenticates the caller: +// the node's Unix socket, or TLS with a verified client certificate. The API +// token does not count, because applications hold it. +func fromTrustedTransport(r *http.Request) bool { + return fromLocalSocket(r) || (r.TLS != nil && len(r.TLS.VerifiedChains) > 0) +} + // StartUnauthSidecarServer serves the enrollment-only API of a node that has no // identity yet, on a TCP address, on a Unix socket, or on both. func StartUnauthSidecarServer(controlPlaneURL, addr, socketPath, certFile, keyFile string) (*http.Server, error) { diff --git a/internal/node/stdio_bridge.go b/internal/node/stdio_bridge.go index 680d1056..b2ecba0e 100644 --- a/internal/node/stdio_bridge.go +++ b/internal/node/stdio_bridge.go @@ -16,6 +16,7 @@ package node import ( "bufio" + "bytes" "context" "encoding/json" "io" @@ -295,9 +296,14 @@ func (b *StdioBridge) writeReply(w http.ResponseWriter, id, result json.RawMessa _, _ = w.Write(encoded) } -// writeBackend hands one line to the backend, answering the caller itself -// when it cannot. It reports whether the line was written. -func (b *StdioBridge) writeBackend(w http.ResponseWriter, line []byte) bool { +// writeBackend hands one message to the backend as one line, answering the +// caller itself when it cannot. It reports whether the line was written. +// +// A stdio MCP server reads one message per line, and JSON allows a line +// break between two tokens. Written as it came, a message with such a line +// break is several messages to the backend, and no enforcement point read +// those. Compact removes every line break that valid JSON can hold. +func (b *StdioBridge) writeBackend(w http.ResponseWriter, msg []byte) bool { b.mu.Lock() isClosed := b.closed b.mu.Unlock() @@ -305,11 +311,18 @@ func (b *StdioBridge) writeBackend(w http.ResponseWriter, line []byte) bool { http.Error(w, "Backend process is no longer running", http.StatusServiceUnavailable) return false } + var line bytes.Buffer + if err := json.Compact(&line, msg); err != nil { + logger.Warnf("[StdioBridge] refused a message that is not valid JSON: %v", err) + http.Error(w, "Body must be a JSON-RPC message", http.StatusBadRequest) + return false + } + line.WriteByte('\n') // If the backend closes between the check and the write, the write // fails or lands in a dead pipe; either way the reader's shutdown has // closed call.reply and roundTrip's select answers 503. b.writeMu.Lock() - _, err := b.stdin.Write(append(line, '\n')) + _, err := b.stdin.Write(line.Bytes()) b.writeMu.Unlock() if err != nil { http.Error(w, "Failed to write to process stdin", http.StatusInternalServerError) diff --git a/internal/node/stdio_bridge_test.go b/internal/node/stdio_bridge_test.go index e04caa34..39bc5945 100644 --- a/internal/node/stdio_bridge_test.go +++ b/internal/node/stdio_bridge_test.go @@ -65,6 +65,13 @@ func (s *syncBuffer) lines() []string { return strings.Split(text, "\n") } +// text returns every byte the backend's stdin received. +func (s *syncBuffer) text() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.buf.String() +} + // waitFor polls cond until it holds; fails the test after 2s. func waitFor(t *testing.T, what string, cond func() bool) { t.Helper() @@ -121,6 +128,70 @@ func TestStdioBridge_ServeHTTP_POSTNotificationReturnsAccepted(t *testing.T) { } } +// hiddenCall is a complete tools/call. The tests below send it as the params +// value of another message, on a line of its own. JSON allows a line break +// between two tokens, so an enforcement point reads the outer message only. A +// reader that takes one message per line, as a stdio MCP server does, reads +// hiddenCall as a message that no enforcement point checked. +const hiddenCall = `{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"drop_table","arguments":{}}}` + +// GHSA-g9hr-vm84-pjjr: the bridge wrote the body of a message with no id to +// the backend as it came. The backend must get one line for one message. +func TestStdioBridge_ServeHTTP_NotificationIsWrittenAsOneLine(t *testing.T) { + const want = `{"jsonrpc":"2.0","method":"notifications/cancelled","params":` + hiddenCall + "}\n" + for _, tc := range []struct { + name string + body string + }{ + { + name: "line feeds", + body: "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":\n" + hiddenCall + "\n}", + }, + { + // A reader in universal newlines mode, as the Python MCP SDK + // uses on stdin, also ends a line at a carriage return. + name: "carriage returns", + body: "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":\r" + hiddenCall + "\r}", + }, + } { + t.Run(tc.name, func(t *testing.T) { + b, stdoutWriter, stdinBuf := newPipeBridge() + defer func() { _ = stdoutWriter.Close() }() + + rec := httptest.NewRecorder() + b.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(tc.body))) + + if rec.Code != http.StatusAccepted { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusAccepted) + } + if got := stdinBuf.text(); got != want { + t.Fatalf("backend stdin got %q, want the one line %q", got, want) + } + }) + } +} + +// A call takes another path to the backend's stdin than a message with no id. +// It must write one line for one message too. +func TestStdioBridge_ServeHTTP_CallIsWrittenAsOneLine(t *testing.T) { + b, stdoutWriter, stdinBuf := newPipeBridge() + defer func() { _ = stdoutWriter.Close() }() + + rec, done := post(b, "{\"jsonrpc\":\"2.0\",\"id\":\"c\",\"method\":\"tools/list\",\"params\":\n"+hiddenCall+"\n}") + bridgeID := bridgeIDOf(t, stdinBuf, 1) + // The bridge writes the members in the order of their names, under its own id. + want := `{"id":` + bridgeID + `,"jsonrpc":"2.0","method":"tools/list","params":` + hiddenCall + "}\n" + if got := stdinBuf.text(); got != want { + t.Fatalf("backend stdin got %q, want the one line %q", got, want) + } + + _, _ = stdoutWriter.Write([]byte(`{"jsonrpc":"2.0","id":` + bridgeID + `,"result":{"tools":[]}}` + "\n")) + await(t, done) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s, want %d", rec.Code, rec.Body.String(), http.StatusOK) + } +} + func TestStdioBridge_ServeHTTP_POSTCallWaitsForMatchingReply(t *testing.T) { b, stdoutWriter, stdinBuf := newPipeBridge() defer func() { _ = stdoutWriter.Close() }() diff --git a/internal/node/sts.go b/internal/node/sts.go index 2ce4adf0..dd7f4bff 100644 --- a/internal/node/sts.go +++ b/internal/node/sts.go @@ -480,6 +480,9 @@ func withCallerOrTokenAuth(node *AgentMeshNode, token string, allowAuthorization // // A client_assertion on any grant also authenticates the caller, so a token // exchange without a subject_token narrows the assertion's own identity. +// +// requested_token_type=jwt asks for a border JWT for an egress:// resource. +// The node returns one only on a trusted transport (fromTrustedTransport). func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { writeNodeOAuthError(w, http.StatusMethodNotAllowed, "invalid_request", "Method not allowed") @@ -541,6 +544,16 @@ func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.Respo audience := strings.TrimSpace(r.FormValue("audience")) seal := sealParam == "true" || sealParam == "1" + // A border JWT is a bearer credential for an egress destination: its + // holder can exchange it at the cloud provider. An application on the + // same host can send this request too, and only the transport tells it + // from the gateway. Refuse before any exchange with the control plane. + if requestedTokenType == api.TokenTypeJWT && !fromTrustedTransport(r) { + logger.Warnf("[OAuth] Border JWT for %q refused: %s", truncateForLog(strings.Join(resources, ",")), borderJWTTransportRule) + writeNodeOAuthError(w, http.StatusForbidden, "access_denied", borderJWTTransportRule) + return + } + tar, err := api.BuildTARFromOAuthParams("oauth-task", options, resources, scope, nil) if err != nil { writeNodeOAuthError(w, http.StatusBadRequest, "invalid_request", err.Error()) diff --git a/internal/node/sts_test.go b/internal/node/sts_test.go index 0f8fab25..6abc4935 100644 --- a/internal/node/sts_test.go +++ b/internal/node/sts_test.go @@ -19,6 +19,8 @@ import ( "context" "crypto/ed25519" "crypto/rand" + "crypto/tls" + "crypto/x509" "encoding/base64" "encoding/hex" "encoding/json" @@ -26,6 +28,8 @@ import ( "net/http" "net/http/httptest" "net/url" + "os" + "path/filepath" "slices" "strings" "sync/atomic" @@ -736,9 +740,8 @@ func TestExtAuthzHTTPAndGRPC(t *testing.T) { narrowedB64 := base64.StdEncoding.EncodeToString(narrowed) // 1. HTTP ext_authz allow: mcp://github + tool get_pr - reqAllow := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", nil) + reqAllow := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_pr"}}`)) reqAllow.Header.Set("Authorization", "Bearer "+narrowedB64) - reqAllow.Header.Set(HeaderMeshMCPTool, "get_pr") recAllow := httptest.NewRecorder() handleExtAuthzHTTP(h.node, recAllow, reqAllow) if recAllow.Code != http.StatusOK { @@ -752,9 +755,8 @@ func TestExtAuthzHTTPAndGRPC(t *testing.T) { } // 2. HTTP ext_authz deny: mcp://github + tool merge_pr - reqDeny := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", nil) + reqDeny := httptest.NewRequest(http.MethodPost, "/ext_authz/mcp/github", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"merge_pr"}}`)) reqDeny.Header.Set("Authorization", "Bearer "+narrowedB64) - reqDeny.Header.Set(HeaderMeshMCPTool, "merge_pr") recDeny := httptest.NewRecorder() handleExtAuthzHTTP(h.node, recDeny, reqDeny) if recDeny.Code != http.StatusForbidden { @@ -780,26 +782,136 @@ func TestExtAuthzHTTPAndGRPC(t *testing.T) { t.Fatalf("expected HTTP ext_authz 403 Forbidden for malformed X-Mesh-Target-Service, got %d: %s", recBadTarget.Code, recBadTarget.Body.String()) } - // 3. gRPC ext_authz Check (/envoy.service.auth.v3.Authorization/Check) - grpcResp, err := newNodeEnvoyGateway(h.node).Check(context.Background(), &authv3.CheckRequest{ - Attributes: &authv3.AttributeContext{ - Request: &authv3.AttributeContext_Request{ - Http: &authv3.AttributeContext_HttpRequest{ - Method: "POST", - Path: "/mcp/github", - Headers: map[string]string{ - "authorization": "Bearer " + narrowedB64, - strings.ToLower(HeaderMeshMCPTool): "get_pr", + // 3. gRPC ext_authz Check (/envoy.service.auth.v3.Authorization/Check). The tool is in the body, + // so a check with no body for a POST cannot name it: a credential with allowed_tools is refused. + // A GET opens a stream and carries no call, so it is decided for the service alone. + for _, tc := range []struct { + name, method, body string + wantCode codes.Code + }{ + {name: "POST with the allowed tool in the body", method: "POST", body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_pr"}}`, wantCode: codes.OK}, + {name: "POST with no body", method: "POST", wantCode: codes.PermissionDenied}, + {name: "GET with no body", method: "GET", wantCode: codes.OK}, + } { + grpcResp, err := newNodeEnvoyGateway(h.node).Check(context.Background(), &authv3.CheckRequest{ + Attributes: &authv3.AttributeContext{ + Request: &authv3.AttributeContext_Request{ + Http: &authv3.AttributeContext_HttpRequest{ + Method: tc.method, + Path: "/mcp/github", + Body: tc.body, + Headers: map[string]string{ + "authorization": "Bearer " + narrowedB64, + }, }, }, }, - }, - }) - if err != nil { - t.Fatalf("Check: %v", err) + }) + if err != nil { + t.Fatalf("%s: Check: %v", tc.name, err) + } + if got := codes.Code(grpcResp.GetStatus().GetCode()); got != tc.wantCode { + t.Fatalf("%s: gRPC CheckResponse status code %v, want %v", tc.name, got, tc.wantCode) + } + } +} + +// An application on the same host can reach the ext_authz routes. Only a +// caller that the transport authenticates as the gateway gets the upstream +// credential of an egress destination (GHSA-2g97-3v45-p9f4). +func TestExtAuthzUpstreamCredentialNeedsTrustedTransport(t *testing.T) { + const secret = "ghp_secret_of_the_node" + secrets := t.TempDir() + if err := os.WriteFile(filepath.Join(secrets, "github-ro"), []byte(secret+"\n"), 0o600); err != nil { + t.Fatalf("write the credential file: %v", err) } - if grpcResp.GetStatus().GetCode() != int32(codes.OK) || grpcResp.GetOkResponse() == nil { - t.Fatalf("expected gRPC CheckResponse status.code == OK, got %+v", grpcResp) + + plainTCP := func(r *http.Request) *http.Request { return r } + unixSocket := func(r *http.Request) *http.Request { + return r.WithContext(context.WithValue(r.Context(), localSocketContextKey{}, true)) + } + tlsWith := func(state tls.ConnectionState) func(*http.Request) *http.Request { + return func(r *http.Request) *http.Request { + r.TLS = &state + return r + } + } + tlsNoClientCert := tlsWith(tls.ConnectionState{}) + verifiedClientCert := tlsWith(tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}}) + + tests := []struct { + name string + credential string + target string + tool string + transport func(*http.Request) *http.Request + wantStatus int + wantAuth string + }{ + {name: "plain TCP", credential: "github-ro", target: "egress://api.github.com", transport: plainTCP, wantStatus: http.StatusForbidden}, + {name: "TLS without a client certificate", credential: "github-ro", target: "egress://api.github.com", transport: tlsNoClientCert, wantStatus: http.StatusForbidden}, + {name: "Unix socket", credential: "github-ro", target: "egress://api.github.com", transport: unixSocket, wantStatus: http.StatusOK, wantAuth: "Bearer " + secret}, + {name: "verified client certificate", credential: "github-ro", target: "egress://api.github.com", transport: verifiedClientCert, wantStatus: http.StatusOK, wantAuth: "Bearer " + secret}, + {name: "plain TCP, destination without a credential", target: "egress://api.github.com", transport: plainTCP, wantStatus: http.StatusOK}, + {name: "plain TCP, MCP service", credential: "github-ro", target: "mcp://github", tool: "get_pr", transport: plainTCP, wantStatus: http.StatusOK}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + h := newSTSNodeHarness(t) + h.node.services = NewServiceRegistry(&fakeDHT{}, 0) + svc, err := newEgressServiceForNode(h.node, &api.EgressDestination{ + Name: "api.github.com", + TargetUrl: "https://api.github.com", + Credential: tc.credential, + }, secrets) + if err != nil { + t.Fatalf("newEgressServiceForNode: %v", err) + } + t.Cleanup(func() { _ = svc.Teardown() }) + if err := h.node.services.Register(context.Background(), svc); err != nil { + t.Fatalf("Register egress: %v", err) + } + task, err := identity.AttenuateBiscuit(h.nodeBiscuit, &api.TaskAuthorizationRule{ + Name: "read-acme-repos", + Rules: []*api.TaskRule{ + { + AllowedServices: []string{"egress://api.github.com"}, + Operation: &api.TaskOperation{AllowedMethods: []string{"GET"}, AllowedPaths: []string{"/repos/acme/*"}}, + }, + { + AllowedServices: []string{"mcp://github"}, + Operation: &api.TaskOperation{AllowedTools: []string{"get_pr"}}, + }, + }, + }) + if err != nil { + t.Fatalf("AttenuateBiscuit: %v", err) + } + + req := httptest.NewRequest(http.MethodGet, "/ext_authz/repos/acme/x", nil) + if tc.tool != "" { + // The body names the tool of an MCP call. + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tc.tool + `"}}` + req = httptest.NewRequest(http.MethodPost, "/ext_authz/repos/acme/x", strings.NewReader(body)) + } + req.Header.Set(api.HeaderMeshTargetService, tc.target) + req.Header.Set(api.HeaderMeshBiscuit, base64.StdEncoding.EncodeToString(task)) + rec := httptest.NewRecorder() + handleExtAuthzHTTP(h.node, rec, tc.transport(req)) + + if rec.Code != tc.wantStatus { + t.Errorf("status = %d, want %d (body %q)", rec.Code, tc.wantStatus, rec.Body.String()) + } + if got := rec.Header().Get("Authorization"); got != tc.wantAuth { + t.Errorf("Authorization in the answer = %q, want %q", got, tc.wantAuth) + } + if strings.Contains(rec.Body.String(), secret) { + t.Errorf("body %q carries the upstream credential", rec.Body.String()) + } + if tc.wantStatus == http.StatusForbidden && !strings.Contains(rec.Body.String(), "Unix socket") { + t.Errorf("body = %q, want it to name the Unix socket and the client certificate", rec.Body.String()) + } + }) } } @@ -915,6 +1027,58 @@ func TestCrossNodeBiscuitAndBannedPeerRejection(t *testing.T) { } } +// Datalog reads an expiration before 1970 as a far future date, so the Datalog +// expiration check passes. The enforcement point must also check the +// expiration in Go, or the Biscuit does not lapse (GHSA-qg99-6frq-2h5m). +func TestVerifyBiscuitTokenRefusesExpirationBeforeEpoch(t *testing.T) { + h := newSTSNodeHarness(t) + reqCtx := RequestContext{PeerID: h.peerID, Protocol: string(api.MCPProtocolID), Target: "mcp://github", MCPTool: "get_pr", Local: true} + + // A delegated Biscuit as the control plane mints it. The builder is used + // directly because the mint refuses an expiration before 1970. + build := func(t *testing.T, expiry time.Time) []byte { + t.Helper() + facts := []biscuit.Fact{ + {Predicate: biscuit.Predicate{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Date(expiry)}}}, + {Predicate: biscuit.Predicate{Name: api.FactActorNode, IDs: []biscuit.Term{biscuit.String(h.peerID.String())}}}, + {Predicate: biscuit.Predicate{Name: api.FactClientPeerID, IDs: []biscuit.Term{biscuit.String(h.peerID.String())}}}, + {Predicate: biscuit.Predicate{Name: api.FactUser, IDs: []biscuit.Term{biscuit.String("alice")}}}, + } + facts = append(facts, api.BuildServiceDatalogFacts([]string{"mcp://github"})...) + builder := biscuit.NewBuilder(h.cpPriv) + for _, f := range facts { + if err := builder.AddAuthorityFact(f); err != nil { + t.Fatalf("AddAuthorityFact(%s): %v", f, err) + } + } + token, err := builder.Build() + if err != nil { + t.Fatalf("Build: %v", err) + } + raw, err := token.Serialize() + if err != nil { + t.Fatalf("Serialize: %v", err) + } + return raw + } + + for _, tc := range []struct { + name string + expiry time.Time + wantAdmit bool + }{ + {name: "valid for five minutes", expiry: time.Now().Add(5 * time.Minute), wantAdmit: true}, + {name: "before 1970", expiry: time.Date(1734, time.August, 16, 0, 0, 0, 0, time.UTC)}, + } { + t.Run(tc.name, func(t *testing.T) { + err := h.node.VerifyBiscuitToken(build(t, tc.expiry), reqCtx) + if (err == nil) != tc.wantAdmit { + t.Errorf("VerifyBiscuitToken(expiration %s) error = %v, want admitted = %v", tc.expiry.UTC().Format(time.RFC3339), err, tc.wantAdmit) + } + }) + } +} + func TestExtAuthzMCPBodyInspection(t *testing.T) { h := newSTSNodeHarness(t) tar := &api.TaskAuthorizationRule{ @@ -930,7 +1094,7 @@ func TestExtAuthzMCPBodyInspection(t *testing.T) { } b64Biscuit := base64.StdEncoding.EncodeToString(taskBiscuit) - // 1. HTTP ext_authz with tools/call for disallowed tool "merge_pr" in JSON-RPC body (without X-Mesh-Mcp-Tool header) -> 403. + // 1. HTTP ext_authz with tools/call for disallowed tool "merge_pr" in JSON-RPC body -> 403. disallowedBody := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"merge_pr"}}` httpReq := httptest.NewRequest(http.MethodPost, "/ext_authz/mesh/mcp/github", strings.NewReader(disallowedBody)) httpReq.Header.Set("Authorization", "Bearer "+b64Biscuit) @@ -949,4 +1113,112 @@ func TestExtAuthzMCPBodyInspection(t *testing.T) { if httpRecOK.Code != http.StatusOK { t.Fatalf("expected HTTP ext_authz to allow get_pr tool in body, got %d", httpRecOK.Code) } + + // 3. A client can set any request header. An X-Mesh-Mcp-Tool header that names the allowed tool + // does not replace the tool that the body calls ("merge_pr") -> 403. + httpReqHeader := httptest.NewRequest(http.MethodPost, "/ext_authz/mesh/mcp/github", strings.NewReader(disallowedBody)) + httpReqHeader.Header.Set("Authorization", "Bearer "+b64Biscuit) + httpReqHeader.Header.Set("X-Mesh-Mcp-Tool", "get_pr") + httpRecHeader := httptest.NewRecorder() + handleExtAuthzHTTP(h.node, httpRecHeader, httpReqHeader) + if httpRecHeader.Code != http.StatusForbidden { + t.Fatalf("HTTP ext_authz with a body that calls merge_pr and a client header that names get_pr: got status %d, want 403", httpRecHeader.Code) + } +} + +// A border JWT is a bearer credential for an egress destination: its holder +// can exchange it at the cloud provider. The node returns it only on a +// transport that authenticates the caller as the gateway. On any other +// transport it does not ask the control plane for one. +func TestNodeOAuthTokenBorderJWTNeedsTrustedTransport(t *testing.T) { + h := newSTSNodeHarness(t) + const borderJWT = "header.payload.signature" + + var mints atomic.Int32 + controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/sts/token" { + http.NotFound(w, r) + return + } + mints.Add(1) + payload, err := proto.Marshal(&api.STSTokenResponse{Jwt: borderJWT, ExpireTime: timestamppb.New(time.Now().Add(5 * time.Minute))}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/x-protobuf") + _, _ = w.Write(payload) + })) + t.Cleanup(controlPlane.Close) + if err := h.node.Store.SaveControlPlaneURL(controlPlane.URL); err != nil { + t.Fatalf("SaveControlPlaneURL: %v", err) + } + + plainTCP := func(r *http.Request) *http.Request { return r } + unixSocket := func(r *http.Request) *http.Request { + return r.WithContext(context.WithValue(r.Context(), localSocketContextKey{}, true)) + } + tlsWith := func(state tls.ConnectionState) func(*http.Request) *http.Request { + return func(r *http.Request) *http.Request { + r.TLS = &state + return r + } + } + + tests := []struct { + name string + transport func(*http.Request) *http.Request + requestedTokenType string + wantStatus int + wantIssued string + }{ + {name: "plain TCP", transport: plainTCP, requestedTokenType: api.TokenTypeJWT, wantStatus: http.StatusForbidden}, + {name: "TLS without a client certificate", transport: tlsWith(tls.ConnectionState{}), requestedTokenType: api.TokenTypeJWT, wantStatus: http.StatusForbidden}, + {name: "Unix socket", transport: unixSocket, requestedTokenType: api.TokenTypeJWT, wantStatus: http.StatusOK, wantIssued: api.TokenTypeJWT}, + {name: "verified client certificate", transport: tlsWith(tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}}), requestedTokenType: api.TokenTypeJWT, wantStatus: http.StatusOK, wantIssued: api.TokenTypeJWT}, + {name: "plain TCP, the caller asks for a Biscuit", transport: plainTCP, wantStatus: http.StatusOK, wantIssued: api.TokenTypeBiscuit}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + mintsBefore := mints.Load() + form := url.Values{} + form.Set("grant_type", api.GrantTypeTokenExchange) + form.Set("subject_token", base64.StdEncoding.EncodeToString(h.nodeBiscuit)) + form.Set("subject_token_type", api.TokenTypeBiscuit) + form.Add("resource", "egress://api.github.com") + if tc.requestedTokenType != "" { + form.Set("requested_token_type", tc.requestedTokenType) + } + req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rec := httptest.NewRecorder() + handleNodeOAuthToken(h.node, "secret-sidecar-token", rec, tc.transport(req)) + + if rec.Code != tc.wantStatus { + t.Fatalf("status %d, want %d: %s", rec.Code, tc.wantStatus, rec.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("response is not JSON: %s", rec.Body.String()) + } + if tc.wantStatus != http.StatusOK { + if body["error"] != "access_denied" { + t.Errorf("error %v, want access_denied", body["error"]) + } + if strings.Contains(rec.Body.String(), borderJWT) { + t.Errorf("the refusal carries the border JWT: %s", rec.Body.String()) + } + if got := mints.Load() - mintsBefore; got != 0 { + t.Errorf("the node asked the control plane for %d border JWT(s), want 0", got) + } + return + } + if body["issued_token_type"] != tc.wantIssued { + t.Errorf("issued_token_type %v, want %s", body["issued_token_type"], tc.wantIssued) + } + if tc.wantIssued == api.TokenTypeJWT && body["access_token"] != borderJWT { + t.Errorf("access_token %v, want the border JWT of the control plane", body["access_token"]) + } + }) + } } diff --git a/internal/router/directory.go b/internal/router/directory.go index d50307c6..c7f098a2 100644 --- a/internal/router/directory.go +++ b/internal/router/directory.go @@ -16,9 +16,11 @@ package router import ( "bytes" + "cmp" "context" "errors" "fmt" + "slices" "sync" "time" @@ -99,6 +101,11 @@ var directoryLookupsTotal = promauto.NewCounterVec( []string{"result"}, ) +var directoryRecordsOmittedTotal = promauto.NewCounter(prometheus.CounterOpts{ + Name: "agentmesh_router_directory_records_omitted_total", + Help: "Provider records left out of a directory answer because the answer did not fit the frame; the largest records are left out first", +}) + func init() { for _, op := range []string{directoryOpProvide, directoryOpWithdraw, directoryOpFindProviders, directoryOpFindPeer, directoryOpPlace, directoryOpLookup} { for _, result := range []string{directoryResultOK, directoryResultEmpty, directoryResultInvalid, directoryResultDenied, directoryResultError} { @@ -402,12 +409,14 @@ func (r *Router) directoryWithdraw(ctx context.Context, remote peer.ID, q *api.D } // recordAddrs parses a record's addresses: at most DirectoryMaxAddrs, each -// with no peer suffix or the provider's own, stored without it as the -// peerstore keeps them. +// at most DirectoryMaxAddrBytes with the provider's peer suffix, each with +// no peer suffix or the provider's own, stored without it as the peerstore +// keeps them. func recordAddrs(provider peer.ID, raw []string) ([]multiaddr.Multiaddr, error) { if len(raw) > api.DirectoryMaxAddrs { return nil, fmt.Errorf("%d addresses, at most %d", len(raw), api.DirectoryMaxAddrs) } + suffixBytes := len("/p2p/") + len(provider.String()) addrs := make([]multiaddr.Multiaddr, 0, len(raw)) for _, a := range raw { ma, err := multiaddr.NewMultiaddr(a) @@ -421,6 +430,10 @@ func recordAddrs(provider peer.ID, raw []string) ([]multiaddr.Multiaddr, error) if transport == nil { return nil, fmt.Errorf("address %q has no transport", a) } + // The error does not quote the address: it is long. + if n := len(transport.String()) + suffixBytes; n > api.DirectoryMaxAddrBytes { + return nil, fmt.Errorf("an address of %d bytes with its peer suffix, at most %d", n, api.DirectoryMaxAddrBytes) + } addrs = append(addrs, transport) } return addrs, nil @@ -597,10 +610,10 @@ func (r *Router) findProviders(ctx context.Context, key []byte, limit int) []pro merged = append(merged, entry) continue } - for _, a := range entry.info.Addrs { - if !containsAddr(merged[i].info.Addrs, a) { - merged[i].info.Addrs = append(merged[i].info.Addrs, a) - } + addrs, omitted := mergeAddrs(merged[i].info.Addrs, entry.info.Addrs) + merged[i].info.Addrs = addrs + if omitted > 0 { + logger.Warnf("[Directory] Provider %s has more than %d addresses on the routers asked: left out %d", entry.info.ID, api.DirectoryMaxAddrs, omitted) } if merged[i].ingress == nil && entry.ingress != nil { merged[i].ingress = entry.ingress @@ -610,9 +623,28 @@ func (r *Router) findProviders(ctx context.Context, key []byte, limit int) []pro return merged } +// mergeAddrs adds to have the addresses of more that it lacks, up to +// DirectoryMaxAddrs in all, so a merged record is no larger than one that +// a provide accepts. It returns how many addresses it left out. +func mergeAddrs(have, more []multiaddr.Multiaddr) ([]multiaddr.Multiaddr, int) { + omitted := 0 + for _, a := range more { + if containsAddr(have, a) { + continue + } + if len(have) >= api.DirectoryMaxAddrs { + omitted++ + continue + } + have = append(have, a) + } + return have, omitted +} + // freshRecords renders up to limit providers, each at the addresses this // router sees for it when it holds the provider, which are ahead of the -// record, and at the record's otherwise. +// record, and at the record's otherwise. The records it returns fit one +// frame. func (r *Router) freshRecords(entries []providerEntry, limit int) []*api.PeerRecord { records := make([]*api.PeerRecord, 0, min(limit, len(entries))) for _, entry := range entries { @@ -628,7 +660,70 @@ func (r *Router) freshRecords(entries []providerEntry, limit int) []*api.PeerRec rec.Ingress = cloneServiceIngress(entry.ingress) records = append(records, rec) } - return records + return frameRecords(records) +} + +// frameRecords returns the records that fit one frame of the directory +// protocol, in their order. It logs and counts the records it leaves out. +func frameRecords(records []*api.PeerRecord) []*api.PeerRecord { + kept, omitted := fitRecords(records, directoryMaxMessage) + if len(omitted) == 0 { + return kept + } + directoryRecordsOmittedTotal.Add(float64(len(omitted))) + providers := make([]string, len(omitted)) + for i, rec := range omitted { + providers[i] = rec.GetPeerId() + } + logger.Warnw("[Directory] Records left out of an answer that did not fit the frame", "frame_bytes", directoryMaxMessage, "kept", len(kept), "omitted", len(omitted), "providers", providers) + return kept +} + +// fitRecords splits records into those whose encoded DirectoryResponse is +// at most budget bytes and those it leaves out. Both keep the order of +// records. A record that is at most an even share of the budget is always +// kept, so a large record cannot take the room of a small one. The room +// that is left goes to the larger records, the smallest first. +func fitRecords(records []*api.PeerRecord, budget int) (kept, omitted []*api.PeerRecord) { + if len(records) == 0 { + return nil, nil + } + share := budget / len(records) + sizes := make([]int, len(records)) + fits := make([]bool, len(records)) + var larger []int + used := 0 + for i, rec := range records { + sizes[i] = answerBytes(rec) + if sizes[i] > share { + larger = append(larger, i) + continue + } + fits[i] = true + used += sizes[i] + } + slices.SortStableFunc(larger, func(a, b int) int { return cmp.Compare(sizes[a], sizes[b]) }) + for _, i := range larger { + if used+sizes[i] > budget { + break + } + fits[i] = true + used += sizes[i] + } + for i, rec := range records { + if fits[i] { + kept = append(kept, rec) + } else { + omitted = append(omitted, rec) + } + } + return kept, omitted +} + +// answerBytes is what one record adds to an encoded DirectoryResponse. The +// sizes of the records add up to the size of the answer. +func answerBytes(rec *api.PeerRecord) int { + return proto.Size(&api.DirectoryResponse{Providers: []*api.PeerRecord{rec}}) } // providerEntryOfRecord parses a record another router answered with. @@ -661,7 +756,8 @@ func containsAddr(addrs []multiaddr.Multiaddr, a multiaddr.Multiaddr) bool { // directoryFindPeer answers where a peer is reached: from this router's // own peerstore for a member attached here, from the record the member -// announced under its peer key otherwise. +// announced under its peer key otherwise. A peer whose addresses do not +// fit one frame is not found. func (r *Router) directoryFindPeer(ctx context.Context, remote peer.ID, q *api.DirectoryFindPeer) (*api.DirectoryResponse, error) { p, err := peer.Decode(q.GetPeerId()) if err != nil { @@ -669,7 +765,11 @@ func (r *Router) directoryFindPeer(ctx context.Context, remote peer.ID, q *api.D } if r.isPeerAuthenticated(p) && r.Host.Network().Connectedness(p) == network.Connected { if addrs := r.Host.Peerstore().Addrs(p); len(addrs) > 0 { - return &api.DirectoryResponse{Peer: peerRecord(peer.AddrInfo{ID: p, Addrs: addrs})}, nil + records := frameRecords([]*api.PeerRecord{peerRecord(peer.AddrInfo{ID: p, Addrs: addrs})}) + if len(records) == 0 { + return &api.DirectoryResponse{}, nil + } + return &api.DirectoryResponse{Peer: records[0]}, nil } } records, err := r.lookupProviders(ctx, remote, api.PeerKey(p), 1) diff --git a/internal/router/directory_test.go b/internal/router/directory_test.go index 8e3ec8df..bd15e57f 100644 --- a/internal/router/directory_test.go +++ b/internal/router/directory_test.go @@ -17,7 +17,10 @@ package router import ( "context" "crypto/ed25519" + "crypto/rand" + "fmt" "slices" + "strings" "testing" "time" @@ -25,9 +28,11 @@ import ( "github.com/golang-jwt/jwt/v5" dht "github.com/libp2p/go-libp2p-kad-dht" kb "github.com/libp2p/go-libp2p-kbucket" + "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-msgio" + "github.com/multiformats/go-multiaddr" dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" @@ -260,6 +265,7 @@ func TestDirectoryRefusesWhatAMemberMayNotAnnounce(t *testing.T) { "a service key naming no service": provide(key, ""), "a peer key naming a service": provide(api.PeerKey(member.ID()), "mcp://calculator"), "another peer's key": provide(api.PeerKey(stranger.ID()), ""), + "an address longer than the bound": provide(key, "mcp://calculator", "/ip4/10.0.0.1/tcp/4001/tls/http/http-path/"+strings.Repeat("a", api.DirectoryMaxAddrBytes)), "a lookup of such a key": findProviders([]byte("calculator")), "a peer id that is not one": findPeer(peer.ID("nobody")), } { @@ -314,6 +320,275 @@ func withdraw(key []byte) *api.DirectoryRequest { return &api.DirectoryRequest{Request: &api.DirectoryRequest_Withdraw{Withdraw: &api.DirectoryWithdraw{Key: key}}} } +// newPeerID is the ID of a new Ed25519 key, the kind a member has. +func newPeerID(t *testing.T) peer.ID { + t.Helper() + _, pub, err := crypto.GenerateEd25519Key(rand.Reader) + if err != nil { + t.Fatalf("GenerateEd25519Key: %v", err) + } + id, err := peer.IDFromPublicKey(pub) + if err != nil { + t.Fatalf("IDFromPublicKey: %v", err) + } + return id +} + +// recordAddrBase starts an address that a test makes as long as it needs. +const recordAddrBase = "/ip4/203.0.113.7/tcp/443/tls/http/http-path/" + +// addrOfBytes is address i of a record: n bytes, with no peer suffix. +func addrOfBytes(i, n int) string { + return fmt.Sprintf("%s%02d%s", recordAddrBase, i, strings.Repeat("a", n-len(recordAddrBase)-2)) +} + +// An address of a record is at most api.DirectoryMaxAddrBytes with the +// provider's peer suffix, whether the member sent the suffix or not. An +// address at the bound is still accepted in the form an answer carries, +// which is the form a peer router reads. +func TestRecordAddrsBoundsAnAddress(t *testing.T) { + provider := newPeerID(t) + suffix := "/p2p/" + provider.String() + atBound := addrOfBytes(0, api.DirectoryMaxAddrBytes-len(suffix)) + aboveBound := addrOfBytes(0, api.DirectoryMaxAddrBytes-len(suffix)+1) + for name, tc := range map[string]struct { + addr string + wantErr bool + }{ + "at the bound, sent without the suffix": {addr: atBound}, + "at the bound, sent with the suffix": {addr: atBound + suffix}, + "one byte above, sent without the suffix": {addr: aboveBound, wantErr: true}, + "one byte above, sent with the suffix": {addr: aboveBound + suffix, wantErr: true}, + } { + t.Run(name, func(t *testing.T) { + addrs, err := recordAddrs(provider, []string{tc.addr}) + if tc.wantErr { + if err == nil { + t.Fatalf("recordAddrs accepted an address of %d bytes with its suffix, want a refusal above %d", len(aboveBound+suffix), api.DirectoryMaxAddrBytes) + } + if strings.Contains(err.Error(), recordAddrBase) { + t.Errorf("the refusal repeats the address, want its length only: %v", err) + } + return + } + if err != nil { + t.Fatalf("recordAddrs refused an address of %d bytes with its suffix, want it accepted up to %d: %v", len(atBound+suffix), api.DirectoryMaxAddrBytes, err) + } + rendered := peerRecord(peer.AddrInfo{ID: provider, Addrs: addrs}).GetAddrs() + if _, err := recordAddrs(provider, rendered); err != nil { + t.Errorf("recordAddrs refused the address as an answer carries it, %d bytes: %v", len(rendered[0]), err) + } + }) + } +} + +// providerWith is a new provider with n addresses. Each address has +// addrBytes with the peer suffix that an answer adds. +func providerWith(t *testing.T, n, addrBytes int) peer.AddrInfo { + t.Helper() + info := peer.AddrInfo{ID: newPeerID(t)} + for i := range n { + addr, err := multiaddr.NewMultiaddr(addrOfBytes(i, addrBytes-len("/p2p/"+info.ID.String()))) + if err != nil { + t.Fatalf("NewMultiaddr: %v", err) + } + info.Addrs = append(info.Addrs, addr) + } + return info +} + +// oversizeAddrBytes makes a record of api.DirectoryMaxAddrs addresses +// larger than the frame, as the record of GHSA-gw5v-gc33-3wg6 was. +const oversizeAddrBytes = 2100 + +func recordsOmitted(t *testing.T) float64 { + t.Helper() + var m dto.Metric + if err := directoryRecordsOmittedTotal.Write(&m); err != nil { + t.Fatal(err) + } + return m.GetCounter().GetValue() +} + +// fitRecords gives each record an even share of the frame, then gives the +// room that is left to the larger records, the smallest first. The answer +// fits the frame, a large record does not take the room of a small one, +// and the records keep their order. +func TestFitRecordsSharesTheFrame(t *testing.T) { + type shape struct{ addrs, addrBytes, allowBytes int } + small := shape{addrs: 2, addrBytes: 128} + quarter := shape{addrs: api.DirectoryMaxAddrs / 4, addrBytes: api.DirectoryMaxAddrBytes} + half := shape{addrs: api.DirectoryMaxAddrs / 2, addrBytes: api.DirectoryMaxAddrBytes} + threeQuarters := shape{addrs: 3 * api.DirectoryMaxAddrs / 4, addrBytes: api.DirectoryMaxAddrBytes} + full := shape{addrs: api.DirectoryMaxAddrs, addrBytes: api.DirectoryMaxAddrBytes} + oversize := shape{addrs: api.DirectoryMaxAddrs, addrBytes: oversizeAddrBytes} + // The ingress of a record counts as its addresses do. + oversizeIngress := shape{addrs: 2, addrBytes: 128, allowBytes: directoryMaxMessage} + for name, tc := range map[string]struct { + shapes []shape + want []int // the positions of the records kept + }{ + "every record fits": {shapes: []shape{small, full, small}, want: []int{0, 1, 2}}, + "a record larger than the frame": {shapes: []shape{oversize, small, small}, want: []int{1, 2}}, + "an ingress larger than the frame": {shapes: []shape{small, oversizeIngress, small}, want: []int{0, 2}}, + "full records ahead of small ones": {shapes: []shape{full, full, small, small}, want: []int{0, 2, 3}}, + "the room left goes to the smallest records": {shapes: []shape{full, half, threeQuarters, quarter, small, small, small, small}, want: []int{1, 2, 3, 4, 5, 6, 7}}, + } { + t.Run(name, func(t *testing.T) { + records := make([]*api.PeerRecord, len(tc.shapes)) + var wantOmitted []int + for i, s := range tc.shapes { + records[i] = peerRecord(providerWith(t, s.addrs, s.addrBytes)) + if s.allowBytes > 0 { + records[i].Ingress = &api.ServiceIngress{Allow: []string{"email:" + strings.Repeat("a", s.allowBytes)}} + } + if !slices.Contains(tc.want, i) { + wantOmitted = append(wantOmitted, i) + } + } + positions := func(recs []*api.PeerRecord) []int { + var out []int + for _, rec := range recs { + out = append(out, slices.Index(records, rec)) + } + return out + } + + kept, omitted := fitRecords(records, directoryMaxMessage) + if got := positions(kept); !slices.Equal(got, tc.want) { + t.Errorf("fitRecords kept the records at %v, want %v", got, tc.want) + } + if got := positions(omitted); !slices.Equal(got, wantOmitted) { + t.Errorf("fitRecords left out the records at %v, want %v", got, wantOmitted) + } + data, err := proto.Marshal(&api.DirectoryResponse{Providers: kept}) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if len(data) > directoryMaxMessage { + t.Errorf("the answer is %d bytes, want at most %d", len(data), directoryMaxMessage) + } + }) + } +} + +// A router answers a lookup in a frame that the reader accepts, whatever +// records it holds. It leaves out and counts a record that does not fit, +// and the other providers are found. In GHSA-gw5v-gc33-3wg6 one record +// under a service type key made every lookup of that type fail. +func TestDirectoryAnswerFitsTheFrame(t *testing.T) { + a := newDirectoryRouter(t) + asker := attach(t, a) + put := func(key []byte, info peer.AddrInfo) { + a.records.put(key, info.ID, info.Addrs, time.Now()) + } + + t.Run("a record larger than the frame among small ones", func(t *testing.T) { + key, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_MCP, "") + if err != nil { + t.Fatal(err) + } + large := providerWith(t, api.DirectoryMaxAddrs, oversizeAddrBytes) + put(key, large) + for range 5 { + put(key, providerWith(t, 2, 128)) + } + var want []string + for _, info := range held(a, key) { + if info.ID != large.ID { + want = append(want, info.ID.String()) + } + } + + before := recordsOmitted(t) + resp := ask(t, asker, a.Host.ID(), findProviders(key)) + if resp.GetError() != "" { + t.Fatalf("find_providers failed: %s", resp.GetError()) + } + var got []string + for _, rec := range resp.GetProviders() { + got = append(got, rec.GetPeerId()) + } + if !slices.Equal(got, want) { + t.Errorf("providers = %v, want the small records in the order the router holds them: %v", got, want) + } + if got := recordsOmitted(t); got != before+1 { + t.Errorf("records left out counted = %v, want %v", got, before+1) + } + }) + + t.Run("as many records of the maximum size as a lookup returns", func(t *testing.T) { + key, err := api.ServiceKey(api.ServiceType_SERVICE_TYPE_INFERENCE, "") + if err != nil { + t.Fatal(err) + } + for range directoryMaxLimit { + put(key, providerWith(t, api.DirectoryMaxAddrs, api.DirectoryMaxAddrBytes)) + } + req := findProviders(key) + req.GetFindProviders().Limit = directoryMaxLimit + + before := recordsOmitted(t) + resp := ask(t, asker, a.Host.ID(), req) + found := len(resp.GetProviders()) + if resp.GetError() != "" || found == 0 { + t.Fatalf("find_providers found %d providers with error %q, want at least one", found, resp.GetError()) + } + if got, want := recordsOmitted(t), before+float64(directoryMaxLimit-found); got != want { + t.Errorf("records left out counted = %v, want %v: %d of %d were found", got, want, found, directoryMaxLimit) + } + }) + + t.Run("find_peer of a held member whose addresses do not fit", func(t *testing.T) { + member := attach(t, a) + a.Host.Peerstore().AddAddrs(member.ID(), providerWith(t, api.DirectoryMaxAddrs, oversizeAddrBytes).Addrs, time.Hour) + + before := recordsOmitted(t) + resp := ask(t, asker, a.Host.ID(), findPeer(member.ID())) + if resp.GetError() != "" || resp.GetPeer() != nil { + t.Fatalf("find_peer answered peer %s with error %q, want no peer: its record is larger than the frame", resp.GetPeer().GetPeerId(), resp.GetError()) + } + if got := recordsOmitted(t); got != before+1 { + t.Errorf("records left out counted = %v, want %v", got, before+1) + } + }) +} + +// A lookup merges the addresses that several routers hold for one +// provider. The merge stops at api.DirectoryMaxAddrs, the most a provide +// accepts, and reports how many addresses it left out. +func TestMergeAddrsStopsAtTheRecordBound(t *testing.T) { + addrs := func(from, to int) []multiaddr.Multiaddr { + var out []multiaddr.Multiaddr + for i := from; i < to; i++ { + a, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/10.0.0.%d/tcp/4001", i)) + if err != nil { + t.Fatalf("NewMultiaddr: %v", err) + } + out = append(out, a) + } + return out + } + for name, tc := range map[string]struct { + have, more []multiaddr.Multiaddr + want []multiaddr.Multiaddr + wantOmitted int + }{ + "the addresses the record lacks are added": {have: addrs(0, 2), more: addrs(1, 4), want: addrs(0, 4)}, + "a full record takes no more": {have: addrs(0, api.DirectoryMaxAddrs-2), more: addrs(api.DirectoryMaxAddrs-4, api.DirectoryMaxAddrs+3), want: addrs(0, api.DirectoryMaxAddrs), wantOmitted: 3}, + } { + t.Run(name, func(t *testing.T) { + got, omitted := mergeAddrs(tc.have, tc.more) + if !slices.EqualFunc(got, tc.want, func(a, b multiaddr.Multiaddr) bool { return a.Equal(b) }) { + t.Errorf("mergeAddrs = %v, want %v", got, tc.want) + } + if omitted != tc.wantOmitted { + t.Errorf("mergeAddrs left out %d addresses, want %d", omitted, tc.wantOmitted) + } + }) + } +} + // A member that stops a service withdraws its record: it is gone from the // router it announced to and from the routers the record was placed on, // and a lookup from any router no longer names the member. Announcing a diff --git a/sdk/js/src/sync.test.ts b/sdk/js/src/sync.test.ts index 467fae44..01d905b7 100644 --- a/sdk/js/src/sync.test.ts +++ b/sdk/js/src/sync.test.ts @@ -196,6 +196,27 @@ test("a ban learned after the answer was requested survives an answer that omits assert.ok(!bans.add("A", 1), "an existing ban is not re-added"); }); +test("a ban repeated after the answer was requested survives an answer that omits it", () => { + const bans = new BanSet(); + const t0 = new Date("2026-09-24T10:00:00Z"); + const t1 = new Date(t0.getTime() + 1000); + assert.ok(bans.add("X", t0.getTime())); + // The ban was lifted, which publishes no event, and set again after t1's request went out. + assert.ok(!bans.add("X", t1.getTime() + 500), "a repeated ban is not a new ban"); + assert.deepEqual(bans.reconcile([], t1), { banned: [], unbanned: [] }); + assert.deepEqual(bans.peers(), ["X"]); +}); + +test("a repeated ban with an earlier time does not move the ban time back", () => { + const bans = new BanSet(); + const t0 = new Date("2026-09-24T10:00:00Z"); + const t1 = new Date(t0.getTime() + 1000); + assert.ok(bans.add("X", t1.getTime() + 500)); + assert.ok(!bans.add("X", t0.getTime()), "a repeated ban is not a new ban"); + assert.deepEqual(bans.reconcile([], t1), { banned: [], unbanned: [] }); + assert.deepEqual(bans.peers(), ["X"]); +}); + test("a mesh event verifies only under a trusted key and only when fresh", () => { const key = new SigningKey(); const sign = (event: ReturnType>) => { diff --git a/sdk/js/src/sync.ts b/sdk/js/src/sync.ts index 33d98767..ed7d5d20 100644 --- a/sdk/js/src/sync.ts +++ b/sdk/js/src/sync.ts @@ -48,13 +48,18 @@ export class BanSet { return [...this.#bannedAt.keys()].sort(); } - /** Records a ban; returns false when the ban was already known. */ + /** + * Records a ban; returns false when the peer was already in the set. The + * set then keeps the later of the stored time and atMs: a ban time never + * moves back. A second event for a peer can be a new ban, because the + * control plane publishes no event when it lifts one. + */ add(peerId: string, atMs: number): boolean { - if (this.#bannedAt.has(peerId)) { - return false; + const known = this.#bannedAt.get(peerId); + if (known === undefined || atMs > known) { + this.#bannedAt.set(peerId, atMs); } - this.#bannedAt.set(peerId, atMs); - return true; + return known === undefined; } /** diff --git a/sdk/python/src/agent_mesh/sync.py b/sdk/python/src/agent_mesh/sync.py index 0e9e32b7..406dbc85 100644 --- a/sdk/python/src/agent_mesh/sync.py +++ b/sdk/python/src/agent_mesh/sync.py @@ -50,11 +50,14 @@ def peers(self) -> list[str]: return sorted(self._banned_at) def add(self, peer_id: str, at_ms: int) -> bool: - """Records a ban; returns False when the ban was already known.""" - if peer_id in self._banned_at: - return False - self._banned_at[peer_id] = at_ms - return True + """Records a ban; returns False when the peer was already in the set. + The set then keeps the later of the stored time and at_ms: a ban time + never moves back. A second event for a peer can be a new ban, because + the control plane publishes no event when it lifts one.""" + known = self._banned_at.get(peer_id) + if known is None or at_ms > known: + self._banned_at[peer_id] = at_ms + return known is None def reconcile(self, banned_peer_ids: Sequence[str], fetched_at: float) -> tuple[list[str], list[str]]: """Makes the set match the control plane's ban set as of fetched_at diff --git a/sdk/python/tests/test_sync.py b/sdk/python/tests/test_sync.py index f5745875..354c98ab 100644 --- a/sdk/python/tests/test_sync.py +++ b/sdk/python/tests/test_sync.py @@ -160,6 +160,27 @@ def test_ban_learned_after_the_answer_was_requested_survives_an_answer_that_omit assert not bans.add("A", 1) +def test_ban_repeated_after_the_answer_was_requested_survives_an_answer_that_omits_it(): + bans = BanSet() + t0 = 1_800_000_000.0 + t1 = t0 + 1 + assert bans.add("X", int(t0 * 1000)) + # The ban was lifted, which publishes no event, and set again after t1's request went out. + assert not bans.add("X", int(t1 * 1000) + 500) + assert bans.reconcile([], t1) == ([], []) + assert bans.peers() == ["X"] + + +def test_repeated_ban_with_an_earlier_time_does_not_move_the_ban_time_back(): + bans = BanSet() + t0 = 1_800_000_000.0 + t1 = t0 + 1 + assert bans.add("X", int(t1 * 1000) + 500) + assert not bans.add("X", int(t0 * 1000)) + assert bans.reconcile([], t1) == ([], []) + assert bans.peers() == ["X"] + + def test_mesh_event_verifies_only_under_a_trusted_key_and_only_when_fresh(): key = SigningKey() diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md index 02949c1b..e6f0cc97 100644 --- a/site/content/docs/contributing/security-architecture.md +++ b/site/content/docs/contributing/security-architecture.md @@ -286,6 +286,22 @@ match at least one `TaskRule` in every appended block. | **`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. | +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 +`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 +the request on HTTP. On a `/mesh/mcp` stream, the node answers such a +`tools/call` under a task-scoped credential with JSON-RPC `-32602` (invalid +params) and does not send it to the backend. Under such a credential, the +node sends a message with no `id` on that stream to the backend only when its +method starts with `notifications/`; it drops any other and logs a warning, +because JSON-RPC allows no answer to a message with no `id`. A command-backed +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. + #### One authorizer assembly for every PEP Every enforcement point builds its Datalog authorizer through @@ -300,7 +316,10 @@ or control-plane caller); `MeshPolicy` says what the PEP adds (its own `target_fact()`s, local attenuation, the synced mesh rules). The assembly always adds `BaselineTargetCheck`, the baseline policies and rules, and `expiration()`, so a PEP cannot leave one out, and an absent field means "not -present" (fails closed), never "unrestricted". `MeshRequest.TaskRequest()` +present" (fails closed), never "unrestricted". After the authorizer passes, +the assembly also compares `expiration()` with the current time in Go, +because Datalog stores a date as unsigned seconds and reads an expiration +before 1970 as a far future date. `MeshRequest.TaskRequest()` derives the `TaskAuthorizationRule` context from the same value. A rule added to one path therefore reaches every path; the only intended differences are the inputs a path does not have (no connection peer on an @@ -373,6 +392,7 @@ as a standard OIDC issuer: | **Discovery & JWKS** | `GET /.well-known/openid-configuration` and `GET /jwks` on the control plane. For air-gapped or private control planes, the JWKS can be uploaded directly to the cloud workload identity pool. | | **Mint endpoint** | `POST /sts/token` (protobuf over HTTP): accepts the caller's Biscuit and `destination` name, verifies the Biscuit and the full `tar_block` chain against `egress://`, writes a `Border Crossing` audit log, and returns a short-lived ES256 JWT. In the `/sts/token` lines, `actor_node` is the egress node that called it and `client_peer_id` is the origin peer the caller's Biscuit is bound to, on allow and on deny once the Biscuit has verified. The `served_by` and audience refusals, which happen after the node's PoP challenge but before the Biscuit is checked, also write a deny line, with the requested `audience` and `client_peer_id` empty; in the `/token/exchange` lines, `actor_node` is the exchanging node, which becomes that Biscuit's `client_peer_id`. | | **JWT claims** | `iss` = control plane URL; `sub` = caller principal (`email` or `issuer#subject`); `act` = `{"sub": ""}`; `aud` = destination audience from `EgressDestination` (one audience per destination); `mesh_roles` = authority-block roles (mapped to `google.groups` for `principalSet` bindings); `mesh_task` = innermost `TaskAuthorizationRule.name` (audit-only). | +| **Audience from policy only** | `aud` is the audience that the broker of the destination pins (`oidc_federation.audience`, or `sts.amazonaws.com` for `aws_assume_role`), and otherwise `https://`. The calling node cannot select it: the control plane refuses with 403 a request that names a different `audience`, and a request for a destination whose default audience the policy pins for another destination. If the control plane cannot read the egress policy, it refuses the request with 500 and mints no JWT. All `aws_assume_role` destinations share the audience `sts.amazonaws.com`, so `aud` does not separate one AWS destination from another. | | **TAR narrows, never selects** | Nothing in a holder-appended `tar_block` can select a broker, role ARN, service account, or audience; every claim that cloud IAM binds on (`sub`, `mesh_roles`, `act.sub`, `aud`) comes from Block 0 or the control plane's `EgressDestination` policy. | | **Caching** | The egress node caches minted border JWTs and upstream cloud tokens by Biscuit SHA-256 digest, keeping the control plane off the per-request hot path. | @@ -393,8 +413,8 @@ as a standard OIDC issuer: #### Gateway integration (`agentmesh-node`) -`agentmesh-node` exposes three standard gateway interfaces on its HTTP listener -(`--bind-addr`): +`agentmesh-node` exposes three standard gateway interfaces on its local API +listeners (`--bind-addr` and `--socket-path`): 1. Envoy `ext_authz` (`/ext_authz` and `/envoy.service.auth.v3.Authorization/Check`) evaluates standing Datalog @@ -404,10 +424,18 @@ as a standard OIDC issuer: `agentmesh-node` exchanges at the control plane into a delegated Biscuit. On `OK` it returns `X-Mesh-Biscuit`, `X-Mesh-Principal`, `X-Mesh-Roles`, `X-Mesh-Task-Id` and, for `egress://` targets with a credential broker, the - brokered upstream `Authorization` header. + brokered upstream `Authorization` header. An application on the same host + can send the same check, so the node returns the upstream credential only + when the transport authenticates the caller as the gateway: the Unix + socket, or TLS with a verified client certificate (`--tls-ca`). On any + other transport the node refuses the check with `403` and logs a warning. + The API token is not sufficient, because applications hold it. 2. Envoy `ext_proc` (`/envoy.service.ext_proc.v3.ExternalProcessor/Process`) inspects buffered JSON-RPC request bodies so `operation.allowed_tools` on - MCP `tools/call` is enforced before injecting the upstream credential. + MCP `tools/call` is enforced before injecting the upstream credential. The + tool comes from the body only: a client can set any request header, so no + header names the tool on `ext_authz` or `ext_proc`. The transport rule of + `ext_authz` applies to the header mutations of `ext_proc` too. 3. RFC 8693 Token Exchange (`POST /oauth/token`) and MCP OAuth 2.1 accept `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with a JWT or Biscuit `subject_token` and optional `TaskAuthorizationRule` (in `options`, diff --git a/site/content/docs/guides/scalability.md b/site/content/docs/guides/scalability.md index 43b125fe..a8eb9717 100644 --- a/site/content/docs/guides/scalability.md +++ b/site/content/docs/guides/scalability.md @@ -222,7 +222,9 @@ its own members and r copies of records whose keys land on it, and asks r routers per lookup. A key that every member publishes, such as a service type, lands on the same r routers for all of them; those r routers hold a record per publisher and answer every lookup of it, and -a lookup of it returns at most 100 providers. +a lookup of it returns at most 100 providers in an answer of at most +64 KiB; `agentmesh_router_directory_records_omitted_total` counts the +records that did not fit. What bounds the total is the router's libp2p connection cap. The cap is twice the larger of `--high-watermark` and `--conns-per-source-ip`, and diff --git a/site/content/docs/preview/agent-architecture.md b/site/content/docs/preview/agent-architecture.md index 27380487..8e645d8e 100644 --- a/site/content/docs/preview/agent-architecture.md +++ b/site/content/docs/preview/agent-architecture.md @@ -163,12 +163,19 @@ interfaces: presents a Biscuit, or a platform JWT that `agentmesh-node` exchanges at the control plane into a delegated Biscuit. On `OK` it returns `X-Mesh-Biscuit`, `X-Mesh-Principal`, `X-Mesh-Roles`, `X-Mesh-Task-Id` and, for `egress://` - targets with a credential broker, the brokered `Authorization` header. + targets with a credential broker, the brokered `Authorization` header. The + node returns that header only to a gateway that reaches it over the Unix + socket or with a verified client certificate. The MCP tool name is in the + request body, so `ext_authz` enforces `operation.allowed_tools` only when + its filter sends the body (`with_request_body`); without it, the node + refuses a `POST` to an MCP service from a credential that has + `operation.allowed_tools`. 2. **Envoy `ext_proc` (`envoy.service.ext_proc.v3.ExternalProcessor`):** the body-aware counterpart to `ext_authz`. Because MCP tool names travel inside the JSON-RPC request body (`params.name`), `ext_proc` inspects the buffered body to enforce `operation.allowed_tools` and injects the brokered - credential only after the payload passes inspection. + credential only after the payload passes inspection, on the same + transport condition. 3. **RFC 8693 Token Exchange (`POST /oauth/token`) & OAuth 2.1:** accepts `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with a JWT or Biscuit `subject_token` and optional `TaskAuthorizationRule` (in `options`, diff --git a/site/content/docs/preview/sandboxed-agents.md b/site/content/docs/preview/sandboxed-agents.md index 18967307..594dda2c 100644 --- a/site/content/docs/preview/sandboxed-agents.md +++ b/site/content/docs/preview/sandboxed-agents.md @@ -161,6 +161,8 @@ Decision Point and Token Service: `TaskAuthorizationRule` chain (including MCP tool names in JSON-RPC bodies via `ext_proc`), and for `egress://` targets injects the brokered upstream credential into `Authorization` before the gateway forwards the request. + The node returns that credential only to a gateway that reaches it over the + Unix socket or with a verified client certificate. - **RFC 8693 backend token exchange (`POST /oauth/token`):** `agentgateway`'s built-in RFC 8693 token exchange policy can point directly at `http://agentmesh-node:8080/oauth/token` to exchange workload JWTs or narrow diff --git a/site/content/docs/reference/control-plane.md b/site/content/docs/reference/control-plane.md index a79adde0..c6f89bae 100644 --- a/site/content/docs/reference/control-plane.md +++ b/site/content/docs/reference/control-plane.md @@ -112,7 +112,7 @@ arithmetic. A client of your own should retry the same way. | `GET /enroll/status?peer_id=` | headers `X-Mesh-Challenge-Ts`, `X-Mesh-Challenge-Sig` | Poll a pending enrollment. Any authentication failure answers `401`, so the credential is released only to the enrollee. | | `POST /refresh` | `TokenRefreshRequest` (optional `jwt`), current credential as `Authorization: Bearer ` | Exchange a credential for a new one. When `jwt` is present and its `iss|sub` matches the enrolled node record, re-attests the node in place, updates stored claims and extends the session. Refuses a replayed (superseded) credential, a banned node, an expired session without a matching `jwt`, and a credential signed by a retired key unless the node has `autonomous_recovery`. | | `POST /token/exchange` | `TokenExchangeRequest` (`subject_token`, optional `task_rule` and `seal`, challenge signature), node credential as bearer | Stateless JWT-to-Biscuit exchange. Mints a Delegated Session Biscuit bound to the calling node (`actor_node`, `client_peer_id`) with zero database writes. | -| `POST /sts/token` | `STSTokenRequest` (`biscuit`, `destination`, optional `audience`, challenge signature), node credential as bearer | Stateless Biscuit-to-JWT minting. Verifies the Biscuit and `tar_block` chain against `egress://` and mints a short-lived ES256 border JWT (`sub`, `act.sub`, `aud`, `mesh_roles`, `mesh_claims`, `mesh_labels`, `mesh_task`). | +| `POST /sts/token` | `STSTokenRequest` (`biscuit`, `destination`, optional `audience`, challenge signature), node credential as bearer | Stateless Biscuit-to-JWT minting. Verifies the Biscuit and `tar_block` chain against `egress://` and mints a short-lived ES256 border JWT (`sub`, `act.sub`, `aud`, `mesh_roles`, `mesh_claims`, `mesh_labels`, `mesh_task`). `aud` comes from the egress policy: a request that names a different `audience` is refused with 403. | | `GET /revocations` | credential as `Authorization: Bearer `, headers `X-Mesh-Challenge-Ts`, `X-Mesh-Challenge-Sig` | `RevocationsResponse`: revoked root Biscuit revocation IDs (`revocation_ids`) and banned peer IDs (`banned_peer_ids`). | | `POST /routers/lease` | `RouterLeaseRequest` (credential, addresses, telemetry: connected peers, DHT size, open connections against the connection limit) | Register or renew a router lease. Requires `role("mesh:role:router")`. Announced addresses must end in the router's own peer ID. The load is what `/info` lists for the router. | | `GET /policies` | credential as `Authorization: Bearer `, headers `X-Mesh-Challenge-Ts`, `X-Mesh-Challenge-Sig` | The mesh policy as `PolicyConfigGetResponse`: the Datalog rules a member adds to its authorizer, one per entry. Operators read the document at `GET /admin/policy`. | diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.md index a624c6f1..fac8e91a 100644 --- a/site/content/docs/reference/node-api.md +++ b/site/content/docs/reference/node-api.md @@ -93,6 +93,7 @@ the control plane's `POST /token/exchange`, a Biscuit is attenuated locally. | `assertion` | The JWT authorization grant for `jwt-bearer`. | | `options` (or `scope` / `resource`) | Optional `TaskAuthorizationRule` as protojson (or space-separated service patterns in `scope`) to append as a `tar_block`. | | `seal` | Optional (`true` / `1`): seal the returned Biscuit so downstream holders cannot append further blocks. | +| `requested_token_type` | Optional. `urn:ietf:params:oauth:token-type:jwt` with an `egress://` in `resource` returns a border JWT for that destination in place of a Biscuit. Its holder can exchange it at the cloud provider, so the node returns it only over the Unix socket or to a verified client certificate, as for the upstream credential of `ext_authz` (see the gateway integration below). On any other transport it answers `403`. | Returns standard RFC 8693 JSON (`access_token`, `issued_token_type: "urn:agentmesh:params:oauth:token-type:biscuit"`, @@ -139,13 +140,14 @@ On the local API listeners, `agentmesh-node` serves: `X-Mesh-Labels`, `X-Mesh-Actor-Node`, `X-Mesh-Origin: mesh-gateway`, and, when the token is task-attenuated, `X-Mesh-Task` (the last `TaskAuthorizationRule` as protojson) and `X-Mesh-Task-Id`. For an `egress://` target with a configured credential - broker it also carries the brokered `Authorization` header for the upstream. + broker it also carries the brokered `Authorization` header for the upstream, + but only to a gateway on a trusted transport (see below). - **Envoy gRPC `envoy.service.ext_proc.v3.ExternalProcessor/Process`**: the body-aware gateway processor. It inspects JSON-RPC bodies on MCP `tools/call` requests to enforce `operation.allowed_tools` in `TaskAuthorizationRule` blocks, strips spoofed inbound `X-Mesh-*` and `X-Peer-Id` headers via `remove_headers`, stamps the verified provenance headers above, and injects - the upstream credential. + the upstream credential on the same condition. Inbound mesh streams (`/libp2p-http`) and external router ingress (`/mesh/ingress/1.0.0`) stamp the same verified `X-Mesh-Principal`, @@ -153,6 +155,34 @@ Inbound mesh streams (`/libp2p-http`) and external router ingress (`mesh-remote` or `mesh-external-ingress`) headers after stripping inbound caller values. +The node reads the tool of an MCP `tools/call` from the request body, and from +nothing else. No request header names the tool, because a client can set a +header; the node ignores an `X-Mesh-Mcp-Tool` header. To enforce +`operation.allowed_tools` at the gateway, Envoy must send the body to the node: + +- `ext_proc` asks Envoy for the body of a `POST` to an MCP service with a mode + override. Set `allow_mode_override: true` on the filter. +- `ext_authz` receives the body only when its filter sets `with_request_body`. + Without a body the node cannot see the tool, so it refuses a `POST` to an + MCP service from a credential that has `operation.allowed_tools`. A `GET` + or a `DELETE` carries no call and is decided for the service alone. + +These endpoints do not require the node's API token, so an application on the +same host can call them too. The node returns the upstream credential only +when the transport authenticates the caller as the gateway: + +- the Unix socket (`--socket-path`), or +- the TCP listener with TLS and a verified client certificate (`--tls-cert`, + `--tls-key` and `--tls-ca`). + +On any other transport the node refuses a check that would return the +upstream credential. It answers `403` and logs a warning with the target. It +does not allow the request without the credential. The API token does not +change this, because applications hold it. Checks that return no upstream +credential (`mcp://`, `inference://`, `a2a://`, or an `egress://` destination +with no credential) work on every transport. The same rule applies to a border +JWT from `POST /oauth/token` (`requested_token_type`). + ## MCP tools The `/mcp` endpoint speaks Streamable HTTP and takes `POST` only. The diff --git a/site/content/docs/reference/router.md b/site/content/docs/reference/router.md index db0066e0..d2227afa 100644 --- a/site/content/docs/reference/router.md +++ b/site/content/docs/reference/router.md @@ -88,13 +88,20 @@ replica count. (the role's `allowed_publish`), checked against the credential the handshake presented and the mesh policy the router synced, so a grant added to a role reaches the directory at the next pass; a record for - anything else is refused. A record + anything else is refused. A record carries at most 32 addresses, and an + address is at most 1024 bytes with its peer ID; the router refuses a + record above either bound. A record lives for the mesh's record TTL after its last announcement, and an announcement replaces the addresses of the one before; a member that stops a service or leaves withdraws its records, and the router withdraws them from the same routers. A member asks for providers of a key or for a peer; the router answers from its own records and from - the routers closest to the key, asked at once. A member keeps no DHT + the routers closest to the key, asked at once. An answer carries at + most 100 providers in at most 64 KiB, the frame that every reader of + the protocol accepts. When the records do not fit, the router keeps + each record that is at most an even share of the frame, gives the room + that is left to the larger records, the smallest first, and logs and + counts the records it leaves out. A member keeps no DHT and asks only the routers it holds. It connects to another router only to reach a peer behind that router. 6. Refreshes its own credential before it expires, like a node, at the @@ -155,6 +162,7 @@ The metrics address exposes, next to the Go runtime metrics: | `agentmesh_router_directory_requests_total{op,result}`, `agentmesh_router_directory_request_seconds{op}` | Directory requests served, by operation (`provide`, `withdraw`, `find_providers`, `find_peer`; `place` is a record or withdrawal another router put here, `lookup` a find another router ran here) and result (`ok`, `empty`, `invalid`, `denied` for a record naming a service the member's credential does not grant serving, `error`), with the time each took. | | `agentmesh_router_directory_records` | Directory records this router holds: its own members' and the copies placed on it. | | `agentmesh_router_directory_records_expired_total` | Records dropped because their provider stopped announcing them for the mesh's record TTL. | +| `agentmesh_router_directory_records_omitted_total` | Provider records left out of an answer that did not fit the 64 KiB frame, the largest first. The router logs their peer IDs. A steady rate is a key with more providers than one answer carries, or a provider with very large records. | | `agentmesh_router_directory_placements_total{result}` | Copies of a member's record, or of its withdrawal, this router placed on the routers closest to the key. | | `agentmesh_router_directory_lookups_total{result}` | Peer routers asked during a lookup; `error` is one that did not answer in time and was left out of the answer. | | `agentmesh_router_auth_handshakes_total{result}`, `agentmesh_router_lease_renewals_total{result}` | Handshakes and lease renewals by outcome. | diff --git a/tests/e2e/standalone.bats b/tests/e2e/standalone.bats index 9e4b4f4d..5d32c475 100644 --- a/tests/e2e/standalone.bats +++ b/tests/e2e/standalone.bats @@ -311,6 +311,9 @@ static_resources: typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz transport_api_version: V3 + with_request_body: + max_request_bytes: 1048576 + allow_partial_message: false grpc_service: envoy_grpc: cluster_name: agentmesh_node_b_h2c diff --git a/tests/integration/sts_cuj_test.go b/tests/integration/sts_cuj_test.go index cedaaa9f..90cda2d2 100644 --- a/tests/integration/sts_cuj_test.go +++ b/tests/integration/sts_cuj_test.go @@ -237,9 +237,19 @@ egress: } pepCfg := writeNodeConfig(t, pepDir, nil, svcDecl{Type: "mcp", Name: "github", TargetURL: mcpBackend.URL}) pepToken := "test-token" + // The ext_proc gateway below reaches the pep node over its Unix socket: + // the node returns the upstream credential only there or to a verified + // client certificate. t.TempDir is too long for a socket path. + socketDir, err := os.MkdirTemp("", "agentmesh-sts-") + if err != nil { + t.Fatalf("create short socket directory: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(socketDir) }) + pepSocket := filepath.Join(socketDir, "pep.sock") pep := launchNode(t, nodeBin, os.Environ(), pepDir, "run", "--control-plane", controlPlane, "--data-dir", pepDir, + "--socket-path", pepSocket, "--api-token-path", tokenPath(t, pepToken), "--jwt", mintToken(map[string]any{"sub": "pep-user", "roles": []string{api.RoleNode}}), "--listen", "/ip4/127.0.0.1/udp/0/quic-v1", @@ -609,14 +619,14 @@ egress: t.Fatalf("GET /repos/acme/private/secret with taskBiscuit: %d, want 403", got) } - // 5. Outbound Border STS JWT Minting at the PEP node for egress://api.github.com: + // 5. Outbound Border STS JWT Minting at the PEP node for egress://api.github.com. + // The request names no audience: the control plane takes it from the egress policy. stsForm := url.Values{} stsForm.Set("grant_type", api.GrantTypeTokenExchange) stsForm.Set("subject_token", taskBiscuit) stsForm.Set("subject_token_type", api.TokenTypeBiscuit) stsForm.Set("requested_token_type", api.TokenTypeJWT) stsForm.Add("resource", "egress://api.github.com") - stsForm.Set("audience", "https://sts.googleapis.com") stsResp, err := client.PostForm("http://"+pepAPI+"/oauth/token", stsForm) if err != nil { t.Fatalf("POST /oauth/token (border JWT): %v", err) @@ -624,8 +634,21 @@ egress: var stsData map[string]any _ = json.NewDecoder(stsResp.Body).Decode(&stsData) _ = stsResp.Body.Close() + // The TCP listener does not authenticate the caller as the gateway, + // and a border JWT is a bearer credential for the destination. + if stsResp.StatusCode != http.StatusForbidden { + t.Fatalf("border JWT over plain TCP: status = %d, want 403: %v", stsResp.StatusCode, stsData) + } + // The same request over the Unix socket of the PEP node returns it. + stsResp, err = identityEvidenceSocketClient(pepSocket).PostForm("http://localhost/oauth/token", stsForm) + if err != nil { + t.Fatalf("POST /oauth/token over the Unix socket (border JWT): %v", err) + } + stsData = nil + _ = json.NewDecoder(stsResp.Body).Decode(&stsData) + _ = stsResp.Body.Close() if stsResp.StatusCode != http.StatusOK { - t.Fatalf("border JWT status = %d, want 200: %v", stsResp.StatusCode, stsData) + t.Fatalf("border JWT over the Unix socket: status = %d, want 200: %v", stsResp.StatusCode, stsData) } borderJWT, _ := stsData["access_token"].(string) if strings.Count(borderJWT, ".") != 2 { @@ -656,7 +679,7 @@ egress: }) t.Run("Gateway ext_proc over h2c datapath on live agentmesh-node (egress credential injection and MCP tools/call across mesh)", func(t *testing.T) { - cc, err := grpc.NewClient("passthrough:///"+pepAPI, grpc.WithTransportCredentials(insecure.NewCredentials())) + cc, err := grpc.NewClient("unix:"+pepSocket, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { t.Fatalf("grpc.NewClient: %v", err) } @@ -665,7 +688,7 @@ egress: mcpBackendCalls.Store(0) // Envoy-compatible Gateway proxy that runs the ExternalProcessor/Process gRPC stream - // against pepAPI (including ModeOverride BUFFERED body inspection and HeaderMutation) + // against the pep node's Unix socket (including ModeOverride BUFFERED body inspection and HeaderMutation) // before forwarding to the target backend or mesh dataplane. gatewayProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var bodyBytes []byte