diff --git a/api/ingress.go b/api/ingress.go index 84bb4451..71a0fc64 100644 --- a/api/ingress.go +++ b/api/ingress.go @@ -155,6 +155,21 @@ func ValidatePeerRecordIngress(ing *ServiceIngress) error { return nil } +// HasDotSegment reports whether a URL path carries a "." or ".." segment. +// Policy is decided on the // prefix of a path, so a dot segment +// in what follows could resolve to a sibling service or file on the backend. +// A backslash counts as a separator too: it reaches the backend +// percent-encoded, and a backend on a platform that treats "\" as "/" would +// otherwise see a traversal this check did not. +func HasDotSegment(p string) bool { + for _, seg := range strings.Split(strings.ReplaceAll(p, "\\", "/"), "/") { + if seg == "." || seg == ".." { + return true + } + } + return false +} + // SanitizeExternalIngressHeaders removes ambient cookies, spoofable X-Mesh-* // and X-Peer-Id attribution headers, and (when stripAuthorization is true) the // external caller's Authorization header before forwarding an external ingress diff --git a/api/ingress_test.go b/api/ingress_test.go index 14472b38..f7a904bd 100644 --- a/api/ingress_test.go +++ b/api/ingress_test.go @@ -61,7 +61,7 @@ func TestValidateServiceIngress(t *testing.T) { svcType: ServiceType_SERVICE_TYPE_MCP, ing: &ServiceIngress{ AuthMode: IngressAuthMode_INGRESS_AUTH_MODE_EDGE, - Allow: []string{"email:alice@example.com", "email:*@google.com", "node:" + pid.String()}, + Allow: []string{"email:alice@example.com", "email:*@example.com", "node:" + pid.String()}, }, }, { @@ -119,7 +119,7 @@ func TestServiceIngressFromConfig(t *testing.T) { } got, err = ServiceIngressFromConfig(ServiceType_SERVICE_TYPE_A2A, &IngressConfig{ - Allow: []string{"email:yaroslav@google.com"}, + Allow: []string{"email:carol@example.com"}, }) if err != nil { t.Fatalf("ServiceIngressFromConfig default mode: %v", err) @@ -237,7 +237,7 @@ func TestValidateIngressURL(t *testing.T) { func TestMatchIngressAllow(t *testing.T) { pid := testPeerID(t) claims := map[string][]string{ - FactEmail: {"yaroslav@google.com"}, + FactEmail: {"carol@example.com"}, FactGroup: {"a2a-team"}, FactNode: {pid.String()}, } @@ -251,8 +251,8 @@ func TestMatchIngressAllow(t *testing.T) { if !MatchIngressAllow([]string{SystemAuthenticated}, claims) { t.Fatal("SystemAuthenticated must match non-empty identity claims") } - if !MatchIngressAllow([]string{"email:*@google.com"}, claims) { - t.Fatal("wildcard domain should match yaroslav@google.com") + if !MatchIngressAllow([]string{"email:*@example.com"}, claims) { + t.Fatal("wildcard domain should match carol@example.com") } if !MatchIngressAllow([]string{"node:" + pid.String()}, claims) { t.Fatal("exact node peer ID should match") diff --git a/internal/controlplane/sts.go b/internal/controlplane/sts.go index 35fe26d3..6895fc02 100644 --- a/internal/controlplane/sts.go +++ b/internal/controlplane/sts.go @@ -1206,39 +1206,6 @@ func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byt if err != nil { return claims, http.StatusForbidden, err } - authorizer.AddFact(biscuit.Fact{ - Predicate: biscuit.Predicate{ - Name: api.FactService, - IDs: []biscuit.Term{biscuit.String("egress"), biscuit.String(destination)}, - }, - }) - authorizer.AddFact(biscuit.Fact{ - Predicate: biscuit.Predicate{ - Name: api.FactConnectionPeerID, - IDs: []biscuit.Term{biscuit.String(clientPeer.String())}, - }, - }) - authorizer.AddCheck(api.BaselineReplayCheck) - authorizer.AddFact(api.MarkerFact(api.FactTargetUnrestricted)) - authorizer.AddCheck(api.BaselineTargetCheck) - identity.EnforceExpiration(authorizer) - - for _, p := range api.BaselinePolicies { - authorizer.AddPolicy(p) - } - for _, r := range api.BaselineRules { - authorizer.AddRule(r) - } - for _, r := range api.BaselineHTTPRules { - authorizer.AddRule(r) - } - // Destination-level STS minting checks whether the role grants egress:// - // at all (plain or HTTP-narrowed); per-request method/path restrictions are - // enforced by the egress agentmesh-node PEP on the wire HTTP request. - for _, r := range stsDestinationRules { - authorizer.AddRule(r) - } - roles, bindings, err := s.store.GetMeshPolicy(ctx) if err != nil && err != storage.ErrNotFound { return claims, http.StatusInternalServerError, fmt.Errorf("failed to load mesh policy: %w", err) @@ -1249,11 +1216,27 @@ func (s *Server) authorizeBiscuitForEgress(ctx context.Context, rawBiscuit []byt } policyRules, _ := api.BuildPolicyRules(roles, bindings) policyRules = append(policyRules, api.BuildEgressServingRules(egressDests)...) + meshRules := make([]biscuit.Rule, 0, len(policyRules)) for _, pr := range policyRules { - authorizer.AddRule(pr.Rule) - } - - if err := authorizer.Authorize(); err != nil { + meshRules = append(meshRules, pr.Rule) + } + + // The same assembly every node PEP runs. The control plane has no + // provider credential of its own to match target grants against, so the + // request is unrestricted on targets; it is bound to the client peer the + // Biscuit names, as a stream to that node would be. Destination-level + // minting asks whether the role grants egress:// at all + // (plain or HTTP-narrowed, stsDestinationRules); per-request method and + // path restrictions are enforced by the egress agentmesh-node on the + // wire HTTP request. + meshReq := identity.MeshRequest{ + ServiceType: api.ServiceTypeStringEgress, + ServiceName: destination, + Unrestricted: true, + ConnectionPeer: clientPeer, + } + pol := identity.MeshPolicy{LocalRules: stsDestinationRules, MeshRules: meshRules} + if err := identity.AuthorizeMeshRequest(authorizer, meshReq, pol); err != nil { return claims, http.StatusForbidden, fmt.Errorf("standing policy denied egress://%s: %w", destination, err) } diff --git a/internal/identity/authorize.go b/internal/identity/authorize.go new file mode 100644 index 00000000..ab044f62 --- /dev/null +++ b/internal/identity/authorize.go @@ -0,0 +1,175 @@ +// 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 identity + +import ( + "github.com/eclipse-biscuit/biscuit-go/v2" + "github.com/google/agentmesh/api" + "github.com/libp2p/go-libp2p/core/peer" +) + +// MeshRequest is what a policy enforcement point knows about one request, +// whichever path it arrived on: a mesh stream from another member, the +// node's own sidecar, router external ingress, or the control plane's +// /sts/token. Every PEP turns its request into one of these and hands it to +// AuthorizeMeshRequest, so the facts and checks a credential is evaluated +// against are decided in one place and a rule added for one path reaches +// the others. The fields a path does not have stay at their zero value, and +// the zero value always means "not present", never "unrestricted". +type MeshRequest struct { + // ServiceType and ServiceName are the service() fact: the service the + // request targets, or (api.SystemNamespace, ) for a bare stream + // that names no service. + ServiceType string + ServiceName string + + // HasHTTP reports whether Method and Path were carried on the wire. They + // become method() and path() only then, so a grant narrowed to methods + // and paths (PolicyRole.http) has nothing to match on a bare stream and + // fails closed. + HasHTTP bool + Method string + Path string + + // HasEgress reports whether the request is an egress call to + // EgressHost:EgressPort, which become host() and port(). + HasEgress bool + EgressHost string + EgressPort int64 + + // Unrestricted adds target_unrestricted: the caller is this node's own + // sidecar, or the verifier has no provider identity to match target + // grants against (the control plane minting a border JWT). + Unrestricted bool + + // ConnectionPeer, when set, is the libp2p peer the credential arrived + // from: connection_peer_id() and BaselineReplayCheck then bind + // client_peer_id to it, so an exfiltrated token cannot be replayed from + // another peer. It stays empty for a bearer presented over HTTPS at the + // border, where there is no libp2p connection to bind to + // (security-architecture, section 5.2). + ConnectionPeer peer.ID + + // MCPTool and AllowMCPStreamInit describe the MCP call for + // TaskAuthorizationRule evaluation (TaskRequest). + MCPTool string + AllowMCPStreamInit bool +} + +// MeshPolicy is what the enforcement point adds to every evaluation on top +// of the credential: the provider's own target facts, its local attenuation, +// and the rules the control plane rendered from the mesh policy. +type MeshPolicy struct { + // TargetFacts are target_fact(type, value) facts from the provider's own + // credential (TargetFactsFromBiscuit); BaselineTargetCheck is always + // added, so a caller whose grant names a target the provider does not + // carry is refused, and so is every caller when the provider has none. + TargetFacts []biscuit.Fact + // LocalPolicies, LocalChecks and LocalRules are the enforcement point's + // own attenuation (agentmesh-node.yaml, or a PEP's static rules). + LocalPolicies []biscuit.Policy + LocalChecks []biscuit.Check + LocalRules []biscuit.Rule + // MeshRules are PolicyConfigGetResponse.datalog_rules as parsed. + MeshRules []biscuit.Rule +} + +// AuthorizeMeshRequest loads req and pol into authorizer in the one order +// 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. +func AuthorizeMeshRequest(authorizer biscuit.Authorizer, req MeshRequest, pol MeshPolicy) error { + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactService, + IDs: []biscuit.Term{biscuit.String(req.ServiceType), biscuit.String(req.ServiceName)}, + }}) + if req.HasHTTP { + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactMethod, + IDs: []biscuit.Term{biscuit.String(req.Method)}, + }}) + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactPath, + IDs: []biscuit.Term{biscuit.String(req.Path)}, + }}) + } + if req.HasEgress { + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactHost, + IDs: []biscuit.Term{biscuit.String(req.EgressHost)}, + }}) + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactPort, + IDs: []biscuit.Term{biscuit.Integer(req.EgressPort)}, + }}) + } + if req.Unrestricted { + authorizer.AddFact(api.MarkerFact(api.FactTargetUnrestricted)) + } + if req.ConnectionPeer != "" { + authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ + Name: api.FactConnectionPeerID, + IDs: []biscuit.Term{biscuit.String(req.ConnectionPeer.String())}, + }}) + authorizer.AddCheck(api.BaselineReplayCheck) + } + + EnforceExpiration(authorizer) + + for _, f := range pol.TargetFacts { + authorizer.AddFact(f) + } + authorizer.AddCheck(api.BaselineTargetCheck) + + for _, p := range pol.LocalPolicies { + authorizer.AddPolicy(p) + } + for _, c := range pol.LocalChecks { + authorizer.AddCheck(c) + } + for _, r := range pol.LocalRules { + authorizer.AddRule(r) + } + + for _, p := range api.BaselinePolicies { + authorizer.AddPolicy(p) + } + for _, r := range api.BaselineRules { + authorizer.AddRule(r) + } + for _, r := range api.BaselineHTTPRules { + authorizer.AddRule(r) + } + for _, r := range pol.MeshRules { + authorizer.AddRule(r) + } + + return authorizer.Authorize() +} + +// TaskRequest is req as TaskAuthorizationRule evaluation sees it, so the +// TAR intersection is computed from the same request on every path. +func (req MeshRequest) TaskRequest() api.TaskRequestContext { + return api.TaskRequestContext{ + ServiceType: req.ServiceType, + ServiceName: req.ServiceName, + HasHTTP: req.HasHTTP, + Method: req.Method, + Path: req.Path, + MCPTool: req.MCPTool, + AllowMCPStreamInit: req.AllowMCPStreamInit, + } +} diff --git a/internal/identity/authorize_test.go b/internal/identity/authorize_test.go new file mode 100644 index 00000000..579c0318 --- /dev/null +++ b/internal/identity/authorize_test.go @@ -0,0 +1,241 @@ +// 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 identity + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + "time" + + "github.com/eclipse-biscuit/biscuit-go/v2" + "github.com/eclipse-biscuit/biscuit-go/v2/parser" + "github.com/golang-jwt/jwt/v5" + "github.com/google/agentmesh/api" + "github.com/libp2p/go-libp2p/core/peer" +) + +// meshAuthzFixture is one mesh for the authorizer tests: a control plane key, +// a provider whose credential carries a target fact, a policy that grants +// callers bound by email, and the rules the control plane would render. +type meshAuthzFixture struct { + pub ed25519.PublicKey + priv ed25519.PrivateKey + providerPeer peer.ID + otherPeer peer.ID + targetFacts []biscuit.Fact + meshRules []biscuit.Rule +} + +func newMeshAuthzFixture(t *testing.T) *meshAuthzFixture { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("GenerateKey: %v", err) + } + f := &meshAuthzFixture{pub: pub, priv: priv, providerPeer: testGenPeerID(t), otherPeer: testGenPeerID(t)} + + roles := []*api.PolicyRole{ + { + Name: "caller", + AllowedServices: []string{"a2a://assistant", "mcp://calc"}, + AllowedTargets: []string{"node:" + f.providerPeer.String()}, + Http: []*api.HTTPGrant{{Service: "a2a://assistant", Methods: []string{"POST"}, Paths: []string{"/invoke"}}}, + }, + { + Name: "anywhere", + AllowedServices: []string{"a2a://assistant"}, + AllowedTargets: []string{"*"}, + }, + } + bindings := []*api.PolicyBinding{ + {Role: "caller", Members: []string{"email:alice@example.com"}}, + {Role: "anywhere", Members: []string{"email:bob@example.com"}}, + } + compiled, warnings := api.BuildPolicyRules(roles, bindings) + if len(warnings) != 0 { + t.Fatalf("BuildPolicyRules warnings: %v", warnings) + } + f.meshRules, err = api.ParseDatalogRules(api.PolicyRuleTexts(compiled)) + if err != nil { + t.Fatalf("ParseDatalogRules: %v", err) + } + + provRaw, err := MintBootstrapBiscuitToken(priv, f.providerPeer, "agent-host", time.Now().Add(time.Hour), nil, nil) + if err != nil { + t.Fatalf("MintBootstrapBiscuitToken: %v", err) + } + provB, err := biscuit.Unmarshal(provRaw) + if err != nil { + t.Fatalf("Unmarshal provider biscuit: %v", err) + } + f.targetFacts, err = TargetFactsFromBiscuit(provB, []ed25519.PublicKey{pub}, time.Second) + if err != nil { + t.Fatalf("TargetFactsFromBiscuit: %v", err) + } + return f +} + +// delegated mints a Delegated Session Biscuit for email, bound to actor, and +// returns an authorizer on it under the fixture's key. +func (f *meshAuthzFixture) delegated(t *testing.T, email string, actor peer.ID) biscuit.Authorizer { + t.Helper() + raw, err := MintDelegatedBiscuitToken(f.priv, jwt.MapClaims{"email": email}, actor, time.Now().Add(time.Hour), nil, nil, nil, false) + if err != nil { + t.Fatalf("MintDelegatedBiscuitToken: %v", err) + } + b, _, err := UnmarshalInbound(raw) + if err != nil { + t.Fatalf("UnmarshalInbound: %v", err) + } + a, err := b.Authorizer(f.pub, AuthorizerOptions(time.Second)...) + if err != nil { + t.Fatalf("Authorizer: %v", err) + } + return a +} + +func (f *meshAuthzFixture) policy() MeshPolicy { + return MeshPolicy{TargetFacts: f.targetFacts, MeshRules: f.meshRules} +} + +// The one assembly behind every enforcement point: which facts and checks a +// request contributes is decided by MeshRequest alone, and each absent field +// fails closed rather than open. +func TestAuthorizeMeshRequest(t *testing.T) { + f := newMeshAuthzFixture(t) + invoke := MeshRequest{ServiceType: "a2a", ServiceName: "assistant", HasHTTP: true, Method: "POST", Path: "/invoke"} + + tests := []struct { + name string + email string + actor peer.ID + req MeshRequest + pol MeshPolicy + wantErr bool + }{ + { + name: "granted service, matching target, HTTP grant satisfied", + email: "alice@example.com", actor: f.otherPeer, req: invoke, pol: f.policy(), + }, + { + name: "service outside the grant is denied", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "other", HasHTTP: true, Method: "POST", Path: "/invoke"}, pol: f.policy(), + wantErr: true, + }, + { + name: "HTTP-narrowed grant has nothing to match on a bare stream and fails closed", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant"}, pol: f.policy(), + wantErr: true, + }, + { + name: "HTTP-narrowed grant denies another method", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant", HasHTTP: true, Method: "DELETE", Path: "/invoke"}, pol: f.policy(), + wantErr: true, + }, + { + name: "target check is always on: a provider without target facts admits no node-scoped grant", + email: "alice@example.com", actor: f.otherPeer, req: invoke, pol: MeshPolicy{MeshRules: f.meshRules}, + wantErr: true, + }, + { + name: "target check is always on: an unrestricted grant still passes without target facts", + email: "bob@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant"}, pol: MeshPolicy{MeshRules: f.meshRules}, + }, + { + name: "Unrestricted request admits a node-scoped grant without provider facts", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant", HasHTTP: true, Method: "POST", Path: "/invoke", Unrestricted: true}, + pol: MeshPolicy{MeshRules: f.meshRules}, + }, + { + name: "connection peer matching client_peer_id passes the replay check", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant", HasHTTP: true, Method: "POST", Path: "/invoke", ConnectionPeer: f.otherPeer}, + pol: f.policy(), + }, + { + name: "connection peer other than client_peer_id is a replay and is denied", + email: "alice@example.com", actor: f.otherPeer, + req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant", HasHTTP: true, Method: "POST", Path: "/invoke", ConnectionPeer: f.providerPeer}, + pol: f.policy(), + wantErr: true, + }, + { + name: "no connection peer adds no replay check: a border bearer is evaluated on policy alone", + email: "alice@example.com", actor: f.providerPeer, req: invoke, pol: f.policy(), + }, + { + name: "local deny policy of the enforcement point applies", + email: "alice@example.com", actor: f.otherPeer, req: invoke, + pol: MeshPolicy{TargetFacts: f.targetFacts, MeshRules: f.meshRules, LocalPolicies: []biscuit.Policy{mustPolicy(t, `deny if path("/invoke")`)}}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := AuthorizeMeshRequest(f.delegated(t, tt.email, tt.actor), tt.req, tt.pol) + if (err != nil) != tt.wantErr { + t.Fatalf("AuthorizeMeshRequest() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// The ingress evaluator is the shared assembly and nothing more: for the same +// credential, service and policy it reaches the decision AuthorizeMeshRequest +// reaches for a border bearer. A difference here is a rule one path has and +// the other lacks. +func TestIngressEvalParamsMatchMeshRequest(t *testing.T) { + f := newMeshAuthzFixture(t) + + cases := []struct { + name string + email string + params IngressEvalParams + }{ + {"granted POST", "alice@example.com", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/invoke", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}}, + {"method outside the HTTP grant", "alice@example.com", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "GET", Path: "/invoke", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}}, + {"service outside the grant", "alice@example.com", IngressEvalParams{ServiceType: "mcp", ServiceName: "other", Method: "POST", Path: "/", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}}, + {"no provider target facts", "alice@example.com", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/invoke", MeshPolicyRules: f.meshRules}}, + {"unrestricted grant without target facts", "bob@example.com", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/", MeshPolicyRules: f.meshRules}}, + {"local deny", "alice@example.com", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/invoke", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules, LocalPolicies: []biscuit.Policy{mustPolicy(t, `deny if path("/invoke")`)}}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, viaIngress := runIngressAuthorizer(f.delegated(t, tc.email, f.otherPeer), tc.params) + viaMesh := AuthorizeMeshRequest(f.delegated(t, tc.email, f.otherPeer), tc.params.meshRequest(), tc.params.meshPolicy()) + if (viaIngress == nil) != (viaMesh == nil) { + t.Fatalf("ingress evaluator and mesh authorizer disagree: ingress err = %v, mesh err = %v", viaIngress, viaMesh) + } + if tr := tc.params.meshRequest().TaskRequest(); tr.ServiceType != tc.params.ServiceType || tr.ServiceName != tc.params.ServiceName || !tr.HasHTTP || tr.Method != tc.params.Method || tr.Path != tc.params.Path { + t.Fatalf("TaskRequest() = %+v does not describe %+v", tr, tc.params) + } + }) + } +} + +func mustPolicy(t *testing.T, src string) biscuit.Policy { + t.Helper() + pol, err := parser.FromStringPolicy(src) + if err != nil { + t.Fatalf("parse policy %q: %v", src, err) + } + return pol +} diff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.go index 18354b1d..f8267c88 100644 --- a/internal/identity/biscuit_test.go +++ b/internal/identity/biscuit_test.go @@ -115,7 +115,7 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) { claims := jwt.MapClaims{ "sub": "user-12345", - "email": "agent@google.com", + "email": "agent@example.com", "groups": []any{"beta-testers", "engineering"}, } @@ -144,11 +144,11 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) { }} authorizer.AddCheck(checkUser) - // Verify email("agent@google.com") fact is present + // Verify email("agent@example.com") fact is present checkEmail := biscuit.Check{Queries: []biscuit.Rule{ { Body: []biscuit.Predicate{ - {Name: "email", IDs: []biscuit.Term{biscuit.String("agent@google.com")}}, + {Name: "email", IDs: []biscuit.Term{biscuit.String("agent@example.com")}}, }, }, }} diff --git a/internal/identity/ingress.go b/internal/identity/ingress.go index f3e939af..5fd768d9 100644 --- a/internal/identity/ingress.go +++ b/internal/identity/ingress.go @@ -74,7 +74,9 @@ func TargetFactsFromBiscuit(b *biscuit.Biscuit, trustedKeys []ed25519.PublicKey, } // IngressEvalParams configures Datalog + TAR + ServiceIngress.allow evaluation -// for an external HTTP ingress request in INGRESS_AUTH_MODE_EDGE. +// for an external HTTP ingress request in INGRESS_AUTH_MODE_EDGE. Method and +// Path are present on every ingress request (it is HTTP); the credential is a +// bearer over HTTPS, so there is no connection peer to bind it to. type IngressEvalParams struct { ServiceType string ServiceName string @@ -83,7 +85,6 @@ type IngressEvalParams struct { MCPTool string AllowMCPStreamInit bool TargetFacts []biscuit.Fact - EnforceTargetCheck bool MeshPolicyRules []biscuit.Rule LocalPolicies []biscuit.Policy LocalChecks []biscuit.Check @@ -92,6 +93,28 @@ type IngressEvalParams struct { Timeout time.Duration } +func (p IngressEvalParams) meshRequest() MeshRequest { + return MeshRequest{ + ServiceType: p.ServiceType, + ServiceName: p.ServiceName, + HasHTTP: p.Method != "", + Method: p.Method, + Path: p.Path, + MCPTool: p.MCPTool, + AllowMCPStreamInit: p.AllowMCPStreamInit, + } +} + +func (p IngressEvalParams) meshPolicy() MeshPolicy { + return MeshPolicy{ + TargetFacts: p.TargetFacts, + LocalPolicies: p.LocalPolicies, + LocalChecks: p.LocalChecks, + LocalRules: p.LocalRules, + MeshRules: p.MeshPolicyRules, + } +} + // IngressCallerResult describes an authorized external ingress caller. type IngressCallerResult struct { Principal string @@ -102,49 +125,7 @@ type IngressCallerResult struct { } func runIngressAuthorizer(authorizer biscuit.Authorizer, p IngressEvalParams) ([]string, error) { - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactService, - IDs: []biscuit.Term{biscuit.String(p.ServiceType), biscuit.String(p.ServiceName)}, - }}) - if p.Method != "" { - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactMethod, - IDs: []biscuit.Term{biscuit.String(p.Method)}, - }}) - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactPath, - IDs: []biscuit.Term{biscuit.String(p.Path)}, - }}) - } - EnforceExpiration(authorizer) - for _, tf := range p.TargetFacts { - authorizer.AddFact(tf) - } - if p.EnforceTargetCheck { - authorizer.AddCheck(api.BaselineTargetCheck) - } - for _, pol := range p.LocalPolicies { - authorizer.AddPolicy(pol) - } - for _, chk := range p.LocalChecks { - authorizer.AddCheck(chk) - } - for _, r := range p.LocalRules { - authorizer.AddRule(r) - } - for _, pol := range api.BaselinePolicies { - authorizer.AddPolicy(pol) - } - for _, r := range api.BaselineRules { - authorizer.AddRule(r) - } - for _, r := range api.BaselineHTTPRules { - authorizer.AddRule(r) - } - for _, r := range p.MeshPolicyRules { - authorizer.AddRule(r) - } - if err := authorizer.Authorize(); err != nil { + if err := AuthorizeMeshRequest(authorizer, p.meshRequest(), p.meshPolicy()); err != nil { return nil, err } @@ -179,16 +160,7 @@ func ValidateIngressCallerPreDial(claims *VerifiedBiscuitClaims, p IngressEvalPa return nil, fmt.Errorf("unattenuated transport member biscuits cannot be used as HTTP edge bearer tokens; exchange at /oauth/token") } if len(claims.TaskRules) > 0 { - taskReq := api.TaskRequestContext{ - ServiceType: p.ServiceType, - ServiceName: p.ServiceName, - HasHTTP: p.Method != "", - Method: p.Method, - Path: p.Path, - MCPTool: p.MCPTool, - AllowMCPStreamInit: p.AllowMCPStreamInit, - } - if err := api.EvaluateTaskRules(claims.TaskRules, taskReq, time.Now()); err != nil { + if err := api.EvaluateTaskRules(claims.TaskRules, p.meshRequest().TaskRequest(), time.Now()); err != nil { return nil, err } } diff --git a/internal/identity/ingress_test.go b/internal/identity/ingress_test.go index 058b922e..3cfe8cf8 100644 --- a/internal/identity/ingress_test.go +++ b/internal/identity/ingress_test.go @@ -111,7 +111,7 @@ func TestAuthorizeIngressCallers(t *testing.T) { }, } bindings := []*api.PolicyBinding{ - {Role: "caller-role", Members: []string{"email:*@google.com"}}, + {Role: "caller-role", Members: []string{"email:*@example.com"}}, } compiled, warnings := api.BuildPolicyRules(roles, bindings) if len(warnings) != 0 { @@ -145,14 +145,13 @@ func TestAuthorizeIngressCallers(t *testing.T) { t.Fatalf("InspectVerifiedBiscuit: %v", err) } if _, err := AuthorizeIngressDelegatedBiscuit(memberClaims, IngressEvalParams{ - ServiceType: "a2a", - ServiceName: "assistant", - Method: "POST", - Path: "/message:send", - TargetFacts: targetFacts, - EnforceTargetCheck: true, - MeshPolicyRules: meshRules, - Timeout: time.Second, + ServiceType: "a2a", + ServiceName: "assistant", + Method: "POST", + Path: "/message:send", + TargetFacts: targetFacts, + MeshPolicyRules: meshRules, + Timeout: time.Second, }); err == nil { t.Fatal("expected unattenuated member transport biscuit to be rejected at HTTP edge") } @@ -173,14 +172,13 @@ func TestAuthorizeIngressCallers(t *testing.T) { t.Fatalf("InspectVerifiedBiscuit attenuated member: %v", err) } attRes, err := AuthorizeIngressDelegatedBiscuit(attMemberClaims, IngressEvalParams{ - ServiceType: "a2a", - ServiceName: "assistant", - Method: "POST", - Path: "/message:send", - TargetFacts: targetFacts, - EnforceTargetCheck: true, - MeshPolicyRules: meshRules, - Timeout: time.Second, + ServiceType: "a2a", + ServiceName: "assistant", + Method: "POST", + Path: "/message:send", + TargetFacts: targetFacts, + MeshPolicyRules: meshRules, + Timeout: time.Second, }) if err != nil { t.Fatalf("expected task-attenuated member biscuit to be accepted: %v", err) @@ -195,7 +193,6 @@ func TestAuthorizeIngressCallers(t *testing.T) { Path: "/", AllowMCPStreamInit: true, TargetFacts: targetFacts, - EnforceTargetCheck: true, MeshPolicyRules: meshRules, Timeout: time.Second, }); err == nil { @@ -211,7 +208,7 @@ func TestAuthorizeIngressCallers(t *testing.T) { } delRaw, err := MintDelegatedBiscuitToken(priv, jwt.MapClaims{ "sub": "uid-1", - "email": "yaroslav@google.com", + "email": "carol@example.com", }, actorPeer, time.Now().Add(time.Hour), []string{"caller-role"}, roles, tarRule, true) if err != nil { t.Fatalf("MintDelegatedBiscuitToken: %v", err) @@ -227,48 +224,45 @@ func TestAuthorizeIngressCallers(t *testing.T) { } res, err := AuthorizeIngressDelegatedBiscuit(delClaims, IngressEvalParams{ - ServiceType: "a2a", - ServiceName: "assistant", - Method: "POST", - Path: "/message:send", - TargetFacts: targetFacts, - EnforceTargetCheck: true, - MeshPolicyRules: meshRules, - Allow: []string{"email:yaroslav@google.com"}, - Timeout: time.Second, + ServiceType: "a2a", + ServiceName: "assistant", + Method: "POST", + Path: "/message:send", + TargetFacts: targetFacts, + MeshPolicyRules: meshRules, + Allow: []string{"email:carol@example.com"}, + Timeout: time.Second, }) if err != nil { t.Fatalf("AuthorizeIngressDelegatedBiscuit: %v", err) } - if res.Principal != "yaroslav@google.com" || res.TaskName != "assist-only" { - t.Fatalf("got principal=%q task=%q, want yaroslav@google.com / assist-only", res.Principal, res.TaskName) + if res.Principal != "carol@example.com" || res.TaskName != "assist-only" { + t.Fatalf("got principal=%q task=%q, want carol@example.com / assist-only", res.Principal, res.TaskName) } // TAR blocks mcp://calc even though role grants it. if _, err := AuthorizeIngressDelegatedBiscuit(delClaims, IngressEvalParams{ - ServiceType: "mcp", - ServiceName: "calc", - Method: "POST", - Path: "/mcp", - TargetFacts: targetFacts, - EnforceTargetCheck: true, - MeshPolicyRules: meshRules, - Timeout: time.Second, + ServiceType: "mcp", + ServiceName: "calc", + Method: "POST", + Path: "/mcp", + TargetFacts: targetFacts, + MeshPolicyRules: meshRules, + Timeout: time.Second, }); err == nil { t.Fatal("expected TAR to deny mcp://calc") } // Allow list blocks non-matching email. if _, err := AuthorizeIngressDelegatedBiscuit(delClaims, IngressEvalParams{ - ServiceType: "a2a", - ServiceName: "assistant", - Method: "POST", - Path: "/message:send", - TargetFacts: targetFacts, - EnforceTargetCheck: true, - MeshPolicyRules: meshRules, - Allow: []string{"email:someone-else@google.com"}, - Timeout: time.Second, + ServiceType: "a2a", + ServiceName: "assistant", + Method: "POST", + Path: "/message:send", + TargetFacts: targetFacts, + MeshPolicyRules: meshRules, + Allow: []string{"email:someone-else@example.com"}, + Timeout: time.Second, }); err == nil { t.Fatal("expected allow list mismatch to deny") } diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.go index 14c1101a..359a7ebd 100644 --- a/internal/node/a2a_service.go +++ b/internal/node/a2a_service.go @@ -289,7 +289,7 @@ func regenerateAgentCardForMesh(card *a2a.AgentCard, base string) error { func meshInterfaceURL(base, raw string) string { ref, err := url.Parse(raw) if err != nil || ref.Scheme != "" || ref.Host != "" || ref.User != nil || ref.Opaque != "" || - strings.HasPrefix(ref.Path, "/") || hasDotSegment(ref.Path) { + strings.HasPrefix(ref.Path, "/") || api.HasDotSegment(ref.Path) { return base } out := base @@ -411,7 +411,7 @@ func relativeToRoot(raw, root string) (string, bool) { default: return "", false } - if hasDotSegment(rest) { + if api.HasDotSegment(rest) { return "", false } if u.RawQuery != "" { diff --git a/internal/node/egress.go b/internal/node/egress.go index 4a437986..bfa7460b 100644 --- a/internal/node/egress.go +++ b/internal/node/egress.go @@ -474,7 +474,7 @@ func (n *AgentMeshNode) applyPendingEgress(ctx context.Context) { // path and the destination's host and port, as on the mesh datapath. The // client's Authorization was for the node and does not travel further. func handleLocalEgress(node *AgentMeshNode, w http.ResponseWriter, r *http.Request) { - if hasDotSegment(r.URL.Path) { + if api.HasDotSegment(r.URL.Path) { http.Error(w, "Invalid path", http.StatusBadRequest) return } diff --git a/internal/node/ingress.go b/internal/node/ingress.go index c0bdab10..0fcc59a7 100644 --- a/internal/node/ingress.go +++ b/internal/node/ingress.go @@ -16,14 +16,12 @@ package node import ( "context" - "fmt" "net/http" "slices" "sort" "strings" "time" - "github.com/eclipse-biscuit/biscuit-go/v2" "github.com/google/agentmesh/api" "github.com/google/agentmesh/internal/identity" gostream "github.com/libp2p/go-libp2p-gostream" @@ -179,7 +177,7 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler { }() path := r.URL.Path - if hasDotSegment(path) { + if api.HasDotSegment(path) { externalIngressRequestsTotal.WithLabelValues(modeMetric, externalIngressOutcomeInvalid).Inc() http.Error(w, "Invalid path", http.StatusBadRequest) return @@ -444,42 +442,23 @@ func (n *AgentMeshNode) externalIngressHandler() http.Handler { } func (n *AgentMeshNode) buildExternalIngressEvalParams(serviceType, serviceName, method, path string, allow []string) (identity.IngressEvalParams, error) { - var targetFacts []biscuit.Fact - enforceTarget := false - if ourIdentity := n.GetIdentity(); len(ourIdentity) > 0 { - ourB, err := biscuit.Unmarshal(ourIdentity) - if err != nil { - return identity.IngressEvalParams{}, fmt.Errorf("failed to unmarshal node identity: %w", err) - } - tf, err := identity.TargetFactsFromBiscuit(ourB, n.trustedPublicKeys(), n.BiscuitTimeout) - if err != nil { - return identity.IngressEvalParams{}, fmt.Errorf("failed to extract node target facts: %w", err) - } - targetFacts = tf - enforceTarget = true - } - - n.MeshPolicyMu.RLock() - meshRules := n.MeshPolicyRules - n.MeshPolicyMu.RUnlock() - - p := identity.IngressEvalParams{ - ServiceType: serviceType, - ServiceName: serviceName, - Method: method, - Path: path, - TargetFacts: targetFacts, - EnforceTargetCheck: enforceTarget, - MeshPolicyRules: meshRules, - Allow: allow, - Timeout: n.BiscuitTimeout, - } - if n.nodeConfig != nil { - p.LocalPolicies = n.nodeConfig.Policies - p.LocalChecks = n.nodeConfig.Checks - p.LocalRules = n.nodeConfig.Rules + pol, err := n.meshPolicy() + if err != nil { + return identity.IngressEvalParams{}, err } - return p, nil + return identity.IngressEvalParams{ + ServiceType: serviceType, + ServiceName: serviceName, + Method: method, + Path: path, + TargetFacts: pol.TargetFacts, + MeshPolicyRules: pol.MeshRules, + LocalPolicies: pol.LocalPolicies, + LocalChecks: pol.LocalChecks, + LocalRules: pol.LocalRules, + Allow: allow, + Timeout: n.BiscuitTimeout, + }, nil } func rewriteExternalIngressRequestPath(r *http.Request, parts []string, upstreamPath string) { diff --git a/internal/node/middleware.go b/internal/node/middleware.go index 62445efd..dbc13993 100644 --- a/internal/node/middleware.go +++ b/internal/node/middleware.go @@ -278,103 +278,38 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, return nil, err } - // Inject the current action context (Standard Vocabulary) - var opType, opName string + // The request as every enforcement point describes it: the service it + // names, or the connection protocol in the system namespace when it + // names none; the HTTP line and egress destination when present; and + // the connection peer, which binds client_peer_id to this stream. + meshReq := identity.MeshRequest{ + ConnectionPeer: req.PeerID, + Unrestricted: req.Local, + MCPTool: req.MCPTool, + AllowMCPStreamInit: req.AllowMCPStreamInit || (req.HTTP == nil && req.MCPTool == "" && req.Protocol == string(api.MCPProtocolID)), + } if req.Target == "" { - // When no explicit target is requested, the operation is scoped to the connection protocol itself, - // which resides in the "system" namespace. - opType = api.SystemNamespace - opName = req.Protocol + meshReq.ServiceType = api.SystemNamespace + meshReq.ServiceName = req.Protocol } else { - opType, opName = api.ParseServiceTarget(req.Target) - } - authorizer.AddFact(biscuit.Fact{ - Predicate: biscuit.Predicate{ - Name: api.FactService, - IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)}, - }, - }) - - // Inject connection_peer_id fact for replay defense - authorizer.AddFact(biscuit.Fact{ - Predicate: biscuit.Predicate{ - Name: api.FactConnectionPeerID, - IDs: []biscuit.Term{biscuit.String(req.PeerID.String())}, - }, - }) - - // Enforce client_peer_id matches connection_peer_id - authorizer.AddCheck(api.BaselineReplayCheck) - - // The request as the wire carried it. Present only when there is an HTTP - // request, so a grant narrowed to methods and paths (PolicyRole.http) has - // nothing to match on a bare stream and fails closed. + meshReq.ServiceType, meshReq.ServiceName = api.ParseServiceTarget(req.Target) + } if req.HTTP != nil { - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactMethod, - IDs: []biscuit.Term{biscuit.String(req.HTTP.Method)}, - }}) - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactPath, - IDs: []biscuit.Term{biscuit.String(req.HTTP.Path)}, - }}) + meshReq.HasHTTP = true + meshReq.Method = req.HTTP.Method + meshReq.Path = req.HTTP.Path } if req.Egress != nil { - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactHost, - IDs: []biscuit.Term{biscuit.String(req.Egress.Host)}, - }}) - authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{ - Name: api.FactPort, - IDs: []biscuit.Term{biscuit.Integer(req.Egress.Port)}, - }}) - } - if req.Local { - authorizer.AddFact(api.MarkerFact(api.FactTargetUnrestricted)) - } - - identity.EnforceExpiration(authorizer) - - // Inject facts from our own identity token to support target matching - if err := n.injectIdentityFacts(authorizer, pubKey); err != nil { - return nil, fmt.Errorf("failed to inject target facts: %w", err) - } - - if n.nodeConfig != nil { - for _, p := range n.nodeConfig.Policies { - authorizer.AddPolicy(p) - } - for _, c := range n.nodeConfig.Checks { - authorizer.AddCheck(c) - } - for _, r := range n.nodeConfig.Rules { - authorizer.AddRule(r) - } + meshReq.HasEgress = true + meshReq.EgressHost = req.Egress.Host + meshReq.EgressPort = int64(req.Egress.Port) } - // Apply Baseline Policies and Rules - authorizer.AddCheck(api.BaselineTargetCheck) - for _, p := range api.BaselinePolicies { - authorizer.AddPolicy(p) - } - for _, r := range api.BaselineRules { - authorizer.AddRule(r) - } - for _, r := range api.BaselineHTTPRules { - authorizer.AddRule(r) - } - - // Apply Dynamic Mesh Policy Rules - n.MeshPolicyMu.RLock() - meshRules := n.MeshPolicyRules - n.MeshPolicyMu.RUnlock() - - for _, r := range meshRules { - authorizer.AddRule(r) - } - - err = authorizer.Authorize() + pol, err := n.meshPolicy() if err != nil { + return nil, err + } + if err := identity.AuthorizeMeshRequest(authorizer, meshReq, pol); err != nil { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...) logger.Debugf("Authorizer failure: %v, token: %s", err, b.String()) logger.Debugf("Authorizer state: %s", authorizer.PrintWorld()) @@ -382,18 +317,7 @@ func (n *AgentMeshNode) authorizeWithRules(rawToken []byte, req RequestContext, } if len(taskRules) > 0 { - taskReq := api.TaskRequestContext{ - ServiceType: opType, - ServiceName: opName, - MCPTool: req.MCPTool, - AllowMCPStreamInit: req.AllowMCPStreamInit || (req.HTTP == nil && req.MCPTool == "" && req.Protocol == string(api.MCPProtocolID)), - } - if req.HTTP != nil { - taskReq.HasHTTP = true - taskReq.Method = req.HTTP.Method - taskReq.Path = req.HTTP.Path - } - if err := api.EvaluateTaskRules(taskRules, taskReq, time.Now()); err != nil { + if err := api.EvaluateTaskRules(taskRules, meshReq.TaskRequest(), time.Now()); err != nil { logger.Infow("Audit Traceability", append(req.auditFields(), "decision", "deny", "reason", err.Error())...) return nil, err } @@ -483,52 +407,47 @@ func (req RequestContext) auditFields() []any { return fields } -func (n *AgentMeshNode) injectIdentityFacts(authorizer biscuit.Authorizer, pubKey ed25519.PublicKey) error { - ourIdentity := n.GetIdentity() - if ourIdentity == nil { - logger.Debugf("[Auth] Node identity is missing, skipping target fact injection") - return nil - } - - ourB, err := biscuit.Unmarshal(ourIdentity) +// meshPolicy is what this node adds to every authorization it performs, +// on whichever path the request arrived: the target facts of its own +// credential, its local attenuation from agentmesh-node.yaml, and the mesh +// policy rules it last synced. Both the in-mesh verifier +// (verifyBiscuitTokenWithRules) and the external ingress handler build their +// authorizer from this one value, so neither can drift from the other. +func (n *AgentMeshNode) meshPolicy() (identity.MeshPolicy, error) { + targetFacts, err := n.ownTargetFacts() if err != nil { - return fmt.Errorf("failed to unmarshal node identity: %w", err) + return identity.MeshPolicy{}, err } + n.MeshPolicyMu.RLock() + meshRules := n.MeshPolicyRules + n.MeshPolicyMu.RUnlock() - n.keysMu.RLock() - keys := make([]TrustedKey, len(n.trustedKeys)) - copy(keys, n.trustedKeys) - n.keysMu.RUnlock() - - authOpts := identity.AuthorizerOptions(n.BiscuitTimeout) - - var auth biscuit.Authorizer - var authErr error - for _, tk := range keys { - if a, err := ourB.Authorizer(tk.Key, authOpts...); err == nil { - auth = a - break - } else { - authErr = err - } + pol := identity.MeshPolicy{TargetFacts: targetFacts, MeshRules: meshRules} + if n.nodeConfig != nil { + pol.LocalPolicies = n.nodeConfig.Policies + pol.LocalChecks = n.nodeConfig.Checks + pol.LocalRules = n.nodeConfig.Rules } + return pol, nil +} - if auth == nil { - return fmt.Errorf("failed to create authorizer for node identity (signature verification mismatch): %w", authErr) +// ownTargetFacts queries this node's own credential for the target_fact() +// facts a caller's target grants are matched against. A node without an +// identity yet contributes none: BaselineTargetCheck then admits only a +// caller whose grant is unrestricted. +func (n *AgentMeshNode) ownTargetFacts() ([]biscuit.Fact, error) { + ourIdentity := n.GetIdentity() + if len(ourIdentity) == 0 { + logger.Debugf("[Auth] Node identity is missing, no target facts to match against") + return nil, nil } - - // We must Authorize() to evaluate the token's facts into the world - auth.AddPolicy(api.AllowIfTruePolicy) - if err := auth.Authorize(); err != nil { - return fmt.Errorf("failed to validate node identity token (e.g. expired): %w", err) + ourB, err := biscuit.Unmarshal(ourIdentity) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal node identity: %w", err) } - - for _, rule := range api.TargetFactRules { - if factSet, err := auth.Query(rule); err == nil { - for _, fact := range factSet { - authorizer.AddFact(fact) - } - } + facts, err := identity.TargetFactsFromBiscuit(ourB, n.trustedPublicKeys(), n.BiscuitTimeout) + if err != nil { + return nil, fmt.Errorf("failed to inject target facts: %w", err) } - return nil + return facts, nil } diff --git a/internal/node/node.go b/internal/node/node.go index d1e1a61c..918f4d2a 100644 --- a/internal/node/node.go +++ b/internal/node/node.go @@ -2530,7 +2530,7 @@ func (n *AgentMeshNode) StartIngressServer(ctx context.Context) error { path := r.URL.Path // Policy is decided on the /{type}/{name} prefix; a ".." segment in // what follows could resolve to a sibling service on a shared backend. - if hasDotSegment(path) { + if api.HasDotSegment(path) { http.Error(w, "Invalid path", http.StatusBadRequest) return } diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go index 00ba4b40..0bca8f55 100644 --- a/internal/node/sidecar.go +++ b/internal/node/sidecar.go @@ -490,19 +490,6 @@ func stripSidecarTokenFromAuthorization(r *http.Request, token string) { } } -// hasDotSegment reports whether any path segment is "." or "..". Go's -// ServeMux canonicalizes these with a redirect, but the mesh proxies pass -// paths through to backends that may resolve them against a different -// service prefix than the one authorization was decided on. -func hasDotSegment(p string) bool { - for _, seg := range strings.Split(p, "/") { - if seg == "." || seg == ".." { - return true - } - } - return false -} - // constantTimeEqual compares two secrets without leaking their contents through // timing. Hashing first keeps the comparison length-independent, so a mismatched // length is no more distinguishable than a mismatched byte. This mirrors how the @@ -776,7 +763,7 @@ func createEgressProxy(node *AgentMeshNode) http.Handler { } // The remote's policy is decided on the /{type}/{name} prefix this // proxy forwards verbatim; a ".." in the rest is not ours to send. - if hasDotSegment(r.URL.Path) { + if api.HasDotSegment(r.URL.Path) { http.Error(w, "Bad Request: path must not contain dot segments", http.StatusBadRequest) return } diff --git a/internal/node/sidecar_hygiene_test.go b/internal/node/sidecar_hygiene_test.go index 155df0d3..47467225 100644 --- a/internal/node/sidecar_hygiene_test.go +++ b/internal/node/sidecar_hygiene_test.go @@ -34,9 +34,14 @@ func TestHasDotSegment(t *testing.T) { "/mcp/a/x..y/tools": false, // ".." inside a segment is just a name "/mcp/a/tools/...": false, "/mesh/p/mcp/a/../b/x": true, + // A backslash reaches the backend percent-encoded; a backend that + // treats it as a separator would see a traversal, so it is one here. + "/mcp/a/..\\b/tools": true, + "/mcp/a\\..\\b/tools": true, + "/mcp/a/x\\y/tools": false, } { - if got := hasDotSegment(path); got != want { - t.Errorf("hasDotSegment(%q) = %v, want %v", path, got, want) + if got := api.HasDotSegment(path); got != want { + t.Errorf("HasDotSegment(%q) = %v, want %v", path, got, want) } } } diff --git a/internal/router/ingress.go b/internal/router/ingress.go index d4f369d8..3c46d9b4 100644 --- a/internal/router/ingress.go +++ b/internal/router/ingress.go @@ -146,7 +146,13 @@ func (r *Router) IngressHandler() http.Handler { if r.gated == nil { return nil, errors.New("router host is not initialized") } - return gostream.Dial(network.WithAllowLimitedConn(ctx, "ingress"), r.gated, pid, api.IngressProtocolID) + // The inbound request carries no deadline, so an unresponsive + // provider or a hung stream negotiation would hold this + // goroutine for as long as the client waits. The stream, once + // open, outlives dialCtx. + dialCtx, cancel := context.WithTimeout(ctx, ingressDialTimeout) + defer cancel() + return gostream.Dial(network.WithAllowLimitedConn(dialCtx, "ingress"), r.gated, pid, api.IngressProtocolID) }, MaxIdleConnsPerHost: 16, IdleConnTimeout: 60 * time.Second, @@ -299,7 +305,7 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, clientIP := clientIPFromRemoteAddr(req.RemoteAddr) req.Body = http.MaxBytesReader(w, req.Body, maxIngressBodyBytes) - if hasDotSegment(req.URL.Path) { + if api.HasDotSegment(req.URL.Path) { routerIngressRequestsTotal.WithLabelValues(ingressModeUnknown, ingressOutcomeInvalid).Inc() logger.Debugf("[Ingress] Rejecting dot-segment path from %s", clientIP) http.Error(w, "Invalid path", http.StatusBadRequest) @@ -497,14 +503,13 @@ func (r *Router) handleIngressRequest(w http.ResponseWriter, req *http.Request, } evalParams = identity.IngressEvalParams{ - ServiceType: serviceTypeStr, - ServiceName: serviceName, - Method: req.Method, - Path: backendPath, - EnforceTargetCheck: true, - MeshPolicyRules: r.meshPolicyRules(), - Allow: ing.GetAllow(), - Timeout: r.config.BiscuitTimeout, + ServiceType: serviceTypeStr, + ServiceName: serviceName, + Method: req.Method, + Path: backendPath, + MeshPolicyRules: r.meshPolicyRules(), + Allow: ing.GetAllow(), + Timeout: r.config.BiscuitTimeout, } if svcType == api.ServiceType_SERVICE_TYPE_MCP { mcpTool, allowInit, bodyErr := api.InspectMCPHTTPRequestBody(req, api.DefaultMaxMCPBodyInspectBytes) @@ -950,15 +955,6 @@ func clientIPFromRemoteAddr(remoteAddr string) string { return "unknown" } -func hasDotSegment(p string) bool { - for _, seg := range strings.Split(p, "/") { - if seg == "." || seg == ".." { - return true - } - } - return false -} - func isHTTPTransportBinding(binding a2a.TransportProtocol) bool { switch strings.ToUpper(string(binding)) { case string(a2a.TransportProtocolJSONRPC), string(a2a.TransportProtocolHTTPJSON): @@ -970,7 +966,7 @@ func isHTTPTransportBinding(binding a2a.TransportProtocol) bool { func resolveIngressInterfaceURL(base, raw string) string { ref, err := url.Parse(raw) if err != nil || ref.Scheme != "" || ref.Host != "" || ref.User != nil || ref.Opaque != "" || - strings.HasPrefix(ref.Path, "/") || hasDotSegment(ref.Path) { + strings.HasPrefix(ref.Path, "/") || api.HasDotSegment(ref.Path) { return base } out := base diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.md index 7409c011..ff6a7af8 100644 --- a/site/content/docs/contributing/security-architecture.md +++ b/site/content/docs/contributing/security-architecture.md @@ -286,6 +286,27 @@ 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. | +#### One authorizer assembly for every PEP + +Every enforcement point builds its Datalog authorizer through +`identity.AuthorizeMeshRequest(authorizer, MeshRequest, MeshPolicy)`: the +node's in-mesh verifier (`/libp2p-http`, `/mesh/mcp`, the local sidecar), the +node's external ingress handler (`/mesh/ingress/1.0.0`), the router's edge +check on `/ingress/*`, and the control plane's `/sts/token`. `MeshRequest` +says what the request is (`service()`, `method()`/`path()` when it is HTTP, +`host()`/`port()` when it is egress, the connection peer when there is a +libp2p stream to bind `client_peer_id` to, `target_unrestricted` for a local +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()` +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 +HTTPS bearer) and the checks a path adds on top (`allowed_ingress`, +`ServiceIngress.allow`, `stsDestinationRules`). + --- ### 4.3 Subject vs. actor (`actor_node`), stateless exchange, and revocation diff --git a/site/content/docs/guides/external-ingress.md b/site/content/docs/guides/external-ingress.md index 81385402..efd08920 100644 --- a/site/content/docs/guides/external-ingress.md +++ b/site/content/docs/guides/external-ingress.md @@ -26,6 +26,33 @@ For example: https://bananas.sam-mesh.dev/ingress/12D3KooW.../a2a/coder ``` +## Ingress is for callers without a sidecar + +An agent that is already on the mesh does not use `/ingress/`. It calls a peer +through its own `agentmesh-node` sidecar +(`http://127.0.0.1:/mesh//a2a/coder`), which dials the +serving node directly over libp2p and only crosses a router's relay when NAT +forces it. The sidecar never advertises the ingress URL, and an A2A agent card +fetched through the sidecar points back at the sidecar, so a client that +starts inside the mesh stays inside it. + +The ingress URL is not a second route for that agent, and it will not accept +the agent's node credential: a standing member Biscuit is refused at +`/ingress/`, which takes only a Delegated Session or task Biscuit. Choosing +the ingress URL from inside the mesh would mean minting a task Biscuit first +and then hairpinning through a router to reach a peer the sidecar could have +dialed directly. + +Both paths evaluate the same policy on the serving node. The in-mesh verifier +and the ingress handler build their Datalog authorizer from one shared +assembly (`identity.AuthorizeMeshRequest`), so a service grant, HTTP +narrowing, target grant, `TaskAuthorizationRule`, or local attenuation that +denies a request on one path denies it on the other. Ingress adds two +constraints on top (the admin's `allowed_ingress` ceiling and the service's +`allow` list) and drops one that only a libp2p stream can satisfy (the +`client_peer_id` connection binding; see the security architecture, section +5.2). A caller can never gain access by picking the path. + ## Two-layer opt-in Nothing on the mesh is reachable from `/ingress/` unless **both** the mesh diff --git a/tests/integration/ingress_test.go b/tests/integration/ingress_test.go index faf22f17..4dbcb03f 100644 --- a/tests/integration/ingress_test.go +++ b/tests/integration/ingress_test.go @@ -273,7 +273,7 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) { Bindings: []*api.PolicyBinding{ { Role: "external-caller", - Members: []string{"email:yaroslav@example.com", "email:other@example.com"}, + Members: []string{"email:carol@example.com", "email:other@example.com"}, }, }, }) @@ -379,7 +379,7 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) { Type: "a2a", Name: "coder", TargetURL: coderBackend.URL, - Ingress: &api.IngressConfig{AuthMode: "edge", Allow: []string{"email:yaroslav@example.com"}}, + Ingress: &api.IngressConfig{AuthMode: "edge", Allow: []string{"email:carol@example.com"}}, }, { Type: "a2a", @@ -476,10 +476,10 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) { // Raw OIDC JWT presented directly to /ingress/ is rejected with 401 + RFC 9728 WWW-Authenticate // (external callers exchange JWTs at POST /oauth/token into Delegated Session Biscuits). - yaroslavJWT := mintJWT(map[string]any{"sub": "yaroslav-sub", "email": "yaroslav@example.com"}) + carolJWT := mintJWT(map[string]any{"sub": "carol-sub", "email": "carol@example.com"}) rawJWTReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, wantInvokeURL, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"message/send"}`)) rawJWTReq.Header.Set("Content-Type", "application/json") - rawJWTReq.Header.Set("Authorization", "Bearer "+yaroslavJWT) + rawJWTReq.Header.Set("Authorization", "Bearer "+carolJWT) rawJWTResp, err := httpClient.Do(rawJWTReq) if err != nil { t.Fatalf("raw JWT POST: %v", err) @@ -501,22 +501,22 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) { } // Authorized Delegated Session Biscuit succeeds on both SendMessage and SSE SendStreamingMessage. - yaroslavBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), yaroslavJWT, "", false) - allowedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(yaroslavBiscuit, nil))) + carolBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), carolJWT, "", false) + allowedClient, err := a2aclient.NewFromCard(ctx, publicCoderCard, a2aclient.WithJSONRPCTransport(bearerClient(carolBiscuit, nil))) if err != nil { - t.Fatalf("NewFromCard(yaroslav): %v", err) + t.Fatalf("NewFromCard(carol): %v", err) } sendRes, err := allowedClient.SendMessage(ctx, &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("hi"))}) if err != nil { - t.Fatalf("SendMessage(yaroslav): %v", err) + t.Fatalf("SendMessage(carol): %v", err) } replyMsg, ok := sendRes.(*a2a.Message) if !ok || len(replyMsg.Parts) == 0 || replyMsg.Parts[0].Text() != "hello from laptop" { t.Fatalf("SendMessage reply = %#v, want 'hello from laptop'", sendRes) } evPrincipal, _ := lastPrincipal.Load().(string) - if !strings.Contains(evPrincipal, "yaroslav") { - t.Fatalf("backend X-Mesh-Principal = %q, want yaroslav identity", evPrincipal) + if !strings.Contains(evPrincipal, "carol") { + t.Fatalf("backend X-Mesh-Principal = %q, want carol identity", evPrincipal) } var streamed []a2a.Event @@ -536,7 +536,7 @@ func TestStandaloneExternalIngressCUJ(t *testing.T) { // Exchange OIDC JWT at POST /oauth/token into a TAR-attenuated, sealed Session Biscuit // scoped exclusively to mcp://tools tool "read_file". tarJSON := `{"name":"read-only","rules":[{"allowed_services":["mcp://tools"],"operation":{"allowed_tools":["read_file"]}}]}` - tarBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), yaroslavJWT, tarJSON, true) + tarBiscuit := exchangeJWTForBiscuit(t, srv.PublicURL(), carolJWT, tarJSON, true) mcpURL := fmt.Sprintf("%s/%s/mcp/tools", srv.IngressURL(), peerID) mcpCli := mcp.NewClient(&mcp.Implementation{Name: "external-mcp-caller", Version: "1.0.0"}, nil) @@ -677,7 +677,7 @@ func TestFederatedMultiRouterIngressRoleCeilingAndBan(t *testing.T) { Bindings: []*api.PolicyBinding{ {Role: api.RoleRouter, Members: []string{"group:routers"}}, {Role: api.RoleNode, Members: []string{"email:node-owner@example.com"}}, - {Role: "external-caller", Members: []string{"email:alan@example.com"}}, + {Role: "external-caller", Members: []string{"email:dave@example.com"}}, }, }) @@ -840,11 +840,11 @@ func TestFederatedMultiRouterIngressRoleCeilingAndBan(t *testing.T) { } // External caller exchanges OIDC JWT at POST /oauth/token and invokes a2a://coder through Router B -> Router A circuit relay -> private node. - alanJWT := mintJWT(map[string]any{"sub": "alan-sub", "email": "alan@example.com"}) - alanBiscuit := exchangeJWTForBiscuit(t, cpURL, alanJWT, "", false) - a2aCli, err := a2aclient.NewFromCard(ctx, resolvedCard, a2aclient.WithJSONRPCTransport(bearerClient(alanBiscuit, nil))) + daveJWT := mintJWT(map[string]any{"sub": "dave-sub", "email": "dave@example.com"}) + daveBiscuit := exchangeJWTForBiscuit(t, cpURL, daveJWT, "", false) + a2aCli, err := a2aclient.NewFromCard(ctx, resolvedCard, a2aclient.WithJSONRPCTransport(bearerClient(daveBiscuit, nil))) if err != nil { - t.Fatalf("NewFromCard(alan): %v", err) + t.Fatalf("NewFromCard(dave): %v", err) } res, err := a2aCli.SendMessage(ctx, &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("ping"))}) if err != nil {