Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
identity: one authorizer assembly for every policy enforcement point
Antonio Ojea5d2a94b7b3d4
diff --git a/internal/controlplane/sts.go b/internal/controlplane/sts.goindex 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 []bytif 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://<destination>- // 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://<destination> 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.gonew file mode 100644index 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, <protocol>) 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.gonew file mode 100644index 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:[email protected]"}},+ {Role: "anywhere", Members: []string{"email:[email protected]"}},+ }+ 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: "[email protected]", actor: f.otherPeer, req: invoke, pol: f.policy(),+ },+ {+ name: "service outside the grant is denied",+ email: "[email protected]", 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: "[email protected]", actor: f.otherPeer,+ req: MeshRequest{ServiceType: "a2a", ServiceName: "assistant"}, pol: f.policy(),+ wantErr: true,+ },+ {+ name: "HTTP-narrowed grant denies another method",+ email: "[email protected]", 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: "[email protected]", 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: "[email protected]", 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: "[email protected]", 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: "[email protected]", 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: "[email protected]", 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: "[email protected]", actor: f.providerPeer, req: invoke, pol: f.policy(),+ },+ {+ name: "local deny policy of the enforcement point applies",+ email: "[email protected]", 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", "[email protected]", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/invoke", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}},+ {"method outside the HTTP grant", "[email protected]", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "GET", Path: "/invoke", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}},+ {"service outside the grant", "[email protected]", IngressEvalParams{ServiceType: "mcp", ServiceName: "other", Method: "POST", Path: "/", TargetFacts: f.targetFacts, MeshPolicyRules: f.meshRules}},+ {"no provider target facts", "[email protected]", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/invoke", MeshPolicyRules: f.meshRules}},+ {"unrestricted grant without target facts", "[email protected]", IngressEvalParams{ServiceType: "a2a", ServiceName: "assistant", Method: "POST", Path: "/", MeshPolicyRules: f.meshRules}},+ {"local deny", "[email protected]", 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/ingress.go b/internal/identity/ingress.goindex 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 stringServiceName string@@ -83,7 +85,6 @@ type IngressEvalParams struct {MCPTool stringAllowMCPStreamInit boolTargetFacts []biscuit.Fact- EnforceTargetCheck boolMeshPolicyRules []biscuit.RuleLocalPolicies []biscuit.PolicyLocalChecks []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 IngressEvalPareturn 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.goindex 058b922e..3eeeb2b1 100644--- a/internal/identity/ingress_test.go+++ b/internal/identity/ingress_test.go@@ -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 {@@ -227,15 +224,14 @@ 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:[email protected]"},- Timeout: time.Second,+ ServiceType: "a2a",+ ServiceName: "assistant",+ Method: "POST",+ Path: "/message:send",+ TargetFacts: targetFacts,+ MeshPolicyRules: meshRules,+ Allow: []string{"email:[email protected]"},+ Timeout: time.Second,})if err != nil {t.Fatalf("AuthorizeIngressDelegatedBiscuit: %v", err)@@ -246,29 +242,27 @@ func TestAuthorizeIngressCallers(t *testing.T) {// 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:[email protected]"},- Timeout: time.Second,+ ServiceType: "a2a",+ ServiceName: "assistant",+ Method: "POST",+ Path: "/message:send",+ TargetFacts: targetFacts,+ MeshPolicyRules: meshRules,+ Allow: []string{"email:[email protected]"},+ Timeout: time.Second,}); err == nil {t.Fatal("expected allow list mismatch to deny")}diff --git a/internal/node/ingress.go b/internal/node/ingress.goindex c0bdab10..bdeb9946 100644--- a/internal/node/ingress.go+++ b/internal/node/ingress.go@@ -16,14 +16,12 @@ package nodeimport ("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"@@ -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.goindex 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/router/ingress.go b/internal/router/ingress.goindex d4f369d8..4a551138 100644--- a/internal/router/ingress.go+++ b/internal/router/ingress.go@@ -497,14 +497,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)diff --git a/site/content/docs/contributing/security-architecture.md b/site/content/docs/contributing/security-architecture.mdindex 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://<name>`** | 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://<name>`** | 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 revocationdiff --git a/site/content/docs/guides/external-ingress.md b/site/content/docs/guides/external-ingress.mdindex 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:<sidecar>/mesh/<peer_id>/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-inNothing on the mesh is reachable from `/ingress/` unless **both** the mesh