Skip to content

Agent Mesh

node: carry the agent claim to the peer that authorizes it

Antonio Ojea51bc72352daf
diff --git a/internal/node/agent.go b/internal/node/agent.go
new file mode 100644
index 00000000..b0201293
--- /dev/null
+++ b/internal/node/agent.go
@@ -0,0 +1,81 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "net/http"
+
+ "github.com/google/sam/api"
+)
+
+// An agent has no key and no enrolment: it is a sandbox, and giving every
+// sandbox a mesh identity is the cost this design exists to avoid. So the node
+// it runs behind speaks for it, naming the agent alongside its own token.
+//
+// What this covers: attribution and policy on the HTTP datapath. A peer can
+// authorize and audit "agent reviewer-7 called me", not merely "some node did",
+// and it can do so with the existing vocabulary because the claim is injected
+// as an ordinary agent() fact.
+//
+// What it does not cover, and cannot:
+//
+// - Proof. The claim is the calling node's word. A node that lies can name
+// any agent, so a mesh that cares must also constrain which peers may speak
+// for which agent namespaces. This is not a weakness of carrying the claim
+// in a header: an appended Biscuit block would be exactly as forgeable by
+// the same party, and is invisible to the authorizer besides (see
+// internal/identity's TestAttenuationBlockFactsAreInvisibleToTheAuthorizer).
+// Only a block signed by the agent's own key would be proof, which needs
+// third-party blocks that biscuit-go does not implement.
+// - The stream datapath. MCP tool calls authenticate over a libp2p stream
+// with an AuthFrame rather than HTTP headers, and carry no agent yet.
+// - Anything an agent does that never leaves its node.
+//
+// One consequence worth knowing before writing such a policy: a node's own
+// housekeeping carries no agent, because no agent asked for it. A provider
+// whose policy demands an agent therefore also refuses that node's model
+// catalog probe, and its models stop appearing in peers' /v1/models listings
+// even though agents can still call them. Policies that mean to gate agent
+// traffic should say so, rather than demanding an agent unconditionally.
+
+// agentFromLocalGateway returns the agent a local gateway is speaking for.
+//
+// Only the node's Unix socket can name an agent: its permissions are the
+// credential, so a caller that reached it is the gateway that admitted the
+// sandbox. A claim arriving over TCP is from something that is not the gateway
+// and is dropped.
+//
+// An invalid identifier is dropped rather than rejected. The request continues
+// unattributed, which is the same position the mesh was in before agents
+// existed, and refusing outright would turn a malformed bundle into an outage.
+func agentFromLocalGateway(r *http.Request) string {
+ if !fromLocalSocket(r) {
+ return ""
+ }
+ return agentClaim(r.Header.Get(api.HeaderSamAgent))
+}
+
+// agentClaim validates an agent identifier arriving from elsewhere, returning
+// "" for anything malformed so a bad claim is worth no more than no claim.
+func agentClaim(agentID string) string {
+ if agentID == "" {
+ return ""
+ }
+ if err := api.ValidateAgentID(agentID); err != nil {
+ logger.Warnf("[Auth] Ignoring malformed agent claim %q: %v", agentID, err)
+ return ""
+ }
+ return agentID
+}
diff --git a/internal/node/agent_test.go b/internal/node/agent_test.go
new file mode 100644
index 00000000..8cf3ac1d
--- /dev/null
+++ b/internal/node/agent_test.go
@@ -0,0 +1,96 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/sam/api"
+)
+
+// localSocketConn looks like a connection accepted on the node's Unix socket,
+// which is what markLocalSocketConn keys off.
+type localSocketConn struct{ net.Conn }
+
+func (localSocketConn) LocalAddr() net.Addr {
+ return &net.UnixAddr{Name: "/run/sam/node.sock", Net: "unix"}
+}
+
+func requestWithAgent(agentID string, overSocket bool) *http.Request {
+ req := httptest.NewRequest(http.MethodGet, "/sam/12D3KooWpeer/mcp/svc", nil)
+ if agentID != "" {
+ req.Header.Set(api.HeaderSamAgent, agentID)
+ }
+ if overSocket {
+ req = req.WithContext(markLocalSocketConn(req.Context(), localSocketConn{}))
+ }
+ return req
+}
+
+func TestAgentFromLocalGateway(t *testing.T) {
+ tests := []struct {
+ name string
+ agentID string
+ overSocket bool
+ want string
+ }{
+ {
+ name: "named by the local gateway",
+ agentID: "reviewer-7.prod.acme.example",
+ overSocket: true,
+ want: "reviewer-7.prod.acme.example",
+ },
+ {
+ // The socket is what identifies the gateway, so a claim from
+ // anywhere else is from something that is not the gateway. Honouring
+ // it would let any local process with the API token speak for any
+ // agent.
+ name: "claimed over TCP",
+ agentID: "privileged.prod.acme.example",
+ overSocket: false,
+ want: "",
+ },
+ {name: "no claim", overSocket: true, want: ""},
+ {name: "malformed identifier", agentID: "not a valid id", overSocket: true, want: ""},
+ {name: "a pattern rather than an identity", agentID: "*.prod.acme.example", overSocket: true, want: ""},
+ {name: "an identifier with no authority", agentID: "reviewer", overSocket: true, want: ""},
+ {name: "uppercase, which DNS cannot distinguish", agentID: "Reviewer.acme.example", overSocket: true, want: ""},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := agentFromLocalGateway(requestWithAgent(tc.agentID, tc.overSocket)); got != tc.want {
+ t.Errorf("agentFromLocalGateway = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestAgentClaimDropsRatherThanRejects: an unattributed request is the position
+// the mesh was in before agents existed, whereas refusing would turn one
+// malformed bundle into an outage for that sandbox.
+func TestAgentClaimDropsRatherThanRejects(t *testing.T) {
+ for _, claim := range []string{"", "not a valid id", "*.acme.example", "UPPER.acme.example"} {
+ if got := agentClaim(claim); got != "" {
+ t.Errorf("agentClaim(%q) = %q, want it dropped", claim, got)
+ }
+ }
+ if got := agentClaim("reviewer.acme.example"); got != "reviewer.acme.example" {
+ t.Errorf("agentClaim dropped a valid identifier: %q", got)
+ }
+}
diff --git a/internal/node/middleware.go b/internal/node/middleware.go
index c9c6ac85..ba49c3fc 100644
--- a/internal/node/middleware.go
+++ b/internal/node/middleware.go
@@ -36,6 +36,19 @@ type RequestContext struct {
Group string
Protocol string
Target string
+
+ // Agent is the principal the calling node says the request is for, and it
+ // is exactly that: the calling node's word. It arrives beside the token
+ // rather than inside it, because Biscuit deliberately hides an appended
+ // block's facts from the authorizer (see internal/identity's
+ // TestAttenuationBlockFactsAreInvisibleToTheAuthorizer). Nothing is lost by
+ // that: whoever can append a block can append any block, so a claim in a
+ // block would be worth no more than a claim in a header on the same
+ // authenticated connection.
+ //
+ // So it is attribution, not proof. Policy that cares should also constrain
+ // which peers may speak for which agent namespaces.
+ Agent string
}
// recoverStreamHandler isolates a panic while processing untrusted peer bytes
@@ -233,6 +246,18 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
},
})
+ // The calling node's claim about which agent it speaks for. Injected here
+ // rather than trusted from the token, so it is visible to policy while
+ // staying plainly what it is: an assertion by the peer at the other end.
+ if req.Agent != "" {
+ authorizer.AddFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: api.FactAgent,
+ IDs: []biscuit.Term{biscuit.String(req.Agent)},
+ },
+ })
+ }
+
// Enforce client_peer_id matches connection_peer_id
authorizer.AddCheck(api.BaselineReplayCheck)
diff --git a/internal/node/node.go b/internal/node/node.go
index 5340c39c..b9b558f1 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -1866,6 +1866,7 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
User: "", // Extracted implicitly if needed, or left empty
Protocol: "/libp2p-http",
Target: target,
+ Agent: agentClaim(r.Header.Get(api.HeaderSamAgent)),
}
// Verify authorization
@@ -1877,6 +1878,9 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {
// Strip the biscuit header so it doesn't leak to the backend service
r.Header.Del(api.HeaderSamBiscuit)
+ // The agent is for policy, not for the backend, which has no way to
+ // judge it.
+ r.Header.Del(api.HeaderSamAgent)
svc, ok := n.services.Get(serviceName)
if !ok {
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index ca67e5b4..39e6b2c5 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -680,6 +680,16 @@ func createEgressProxy(node *SamNode) http.Handler {
r.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuitBytes))
+ // Forwarded, not stripped: the agent claim is what lets the peer at the
+ // other end authorize and audit the agent rather than just this node.
+ // Replacing it with what the local gateway said also drops any value a
+ // caller that is not the gateway tried to set.
+ if agentID := agentFromLocalGateway(r); agentID != "" {
+ r.Header.Set(api.HeaderSamAgent, agentID)
+ } else {
+ r.Header.Del(api.HeaderSamAgent)
+ }
+
// Strip the local sidecar gate header before forwarding off-node; a caller-supplied
// "Authorization" header passes straight through untouched as the destination's own credential.
r.Header.Del(api.HeaderSamAuthentication)
diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.md
index 8a5164b0..95503870 100644
--- a/site/content/docs/agent-architecture.md
+++ b/site/content/docs/agent-architecture.md
@@ -526,6 +526,36 @@ and non-repudiation arrives without a wire break.
> 3. **Wait for third-party blocks**, which would make the agent's own signature
> the thing being verified, and is the only option that adds real
> non-repudiation.
+>
+> **Decided: option 1**, implemented in `internal/node/agent.go`.
+
+### 10.2.1 What the agent claim covers, and what it does not
+
+**Covers.** Attribution and policy on the HTTP datapath. A peer can authorize
+and audit "agent `reviewer-7` called me" rather than only "some node did", using
+the existing vocabulary, because the claim is injected as an ordinary `agent()`
+fact. `TestAgentPolicyCUJ` shows two agents behind two gateways on one node
+being told apart by the provider's policy, including a lookalike authority being
+refused and an unidentified sandbox being refused.
+
+**Does not cover.**
+
+* **Proof.** The claim is the calling node's word. A node that lies can name any
+ agent, so a mesh that cares must also constrain which peers may speak for
+ which agent namespaces. Carrying it in a header rather than a block costs
+ nothing here: an appended block is exactly as forgeable by the same party.
+* **The stream datapath.** MCP tool calls authenticate over a libp2p stream with
+ an `AuthFrame`, not HTTP headers, and carry no agent yet. Inference does;
+ tools do not.
+* **Anything that never leaves the node**, which the boundary already gates
+ locally.
+
+**A consequence to design around.** A node's own housekeeping carries no agent,
+because no agent asked for it. A provider whose policy demands an agent
+unconditionally therefore also refuses that node's model-catalog probe, and its
+models stop appearing in peers' `/v1/models` listings even though agents can
+still call them. This was found by the test, not by reasoning. Policy that means
+to gate agent traffic should say so rather than demanding an agent everywhere.
### 10.3 Why it scales: delegation, not enumeration
diff --git a/tests/integration/agent_policy_test.go b/tests/integration/agent_policy_test.go
new file mode 100644
index 00000000..1a4b5175
--- /dev/null
+++ b/tests/integration/agent_policy_test.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 integration_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+)
+
+// TestAgentPolicyCUJ is the selling point end to end: two agents behind two
+// gateways on the same node, reaching the same service, told apart by mesh
+// policy on the far side.
+//
+// The provider decides. Node A's local attenuation demands that the caller be
+// named, and named within a namespace it accepts. Neither gateway can influence
+// that: the agent each one asserts is the identity its bundle gave it.
+func TestAgentPolicyCUJ(t *testing.T) {
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ _, hubAddr := startMockRouter(t)
+
+ homeA := t.TempDir()
+ homeB := t.TempDir()
+ apiToken := "test-token"
+
+ // Only agents under prod.acme.example may reach this node's services. The
+ // suffix is matched with a leading dot so a lookalike authority such as
+ // "evil-prod.acme.example" cannot satisfy it.
+ configA := filepath.Join(homeA, "sam-node.yaml")
+ if err := os.WriteFile(configA, []byte(`version: "v1alpha1"
+attenuation:
+ checks:
+ - 'check if agent($a), $a.ends_with(".prod.acme.example")'
+`), 0600); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ sockDir, err := os.MkdirTemp("", "agentpolicy")
+ if err != nil {
+ t.Fatalf("MkdirTemp: %v", err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(sockDir) })
+ nodeSocket := filepath.Join(sockDir, "node.sock")
+
+ _ = startBackgroundNode(t, nodeBin, hubAddr, homeA,
+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "--listen", "/ip4/127.0.0.1/tcp/0",
+ "--discovery-interval", "100ms",
+ "--config", configA,
+ )
+ _ = startBackgroundNode(t, nodeBin, hubAddr, homeB,
+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",
+ "--listen", "/ip4/127.0.0.1/tcp/0",
+ "--discovery-interval", "100ms",
+ "--socket-path", nodeSocket,
+ )
+
+ apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))
+ apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))
+ waitForAPI(t, apiAddrA)
+ waitForAPI(t, apiAddrB)
+
+ addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))
+ callMCP(t, apiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})
+ waitForDHTPeers(t, apiAddrA)
+
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{"object":"list","data":[{"id":"test-model"}]}`))
+ }))
+ defer backend.Close()
+
+ registerInferenceService(t, apiAddrA, apiToken, "test-llm", backend.URL)
+
+ // Not waitForFacadeModel: node A's own catalog probe carries no agent, so a
+ // provider demanding one refuses it and its models never appear in a peer's
+ // /v1/models listing. That is a real consequence of this policy shape, not a
+ // test artefact -- see internal/node/agent.go.
+ waitForDiscoverableService(t, apiAddrB, apiToken, "inference", "test-llm")
+
+ tests := []struct {
+ name string
+ agentID string
+ wantStatus int
+ }{
+ {
+ name: "an agent in the namespace the provider accepts",
+ agentID: "reviewer-7.prod.acme.example",
+ wantStatus: http.StatusOK,
+ },
+ {
+ name: "an agent outside it, on the same node and the same gateway build",
+ agentID: "auditor-1.staging.acme.example",
+ wantStatus: http.StatusForbidden,
+ },
+ {
+ // A lookalike authority must not satisfy a suffix match, which is
+ // the whole reason agent identifiers are dot-anchored.
+ name: "an agent whose authority merely looks similar",
+ agentID: "intruder.evil-prod.acme.example",
+ wantStatus: http.StatusForbidden,
+ },
+ {
+ // Without a bundle the gateway asserts nothing, so a provider that
+ // demands an agent refuses the request rather than falling back to
+ // trusting the node.
+ name: "an unidentified sandbox",
+ agentID: "",
+ wantStatus: http.StatusForbidden,
+ },
+ }
+
+ for i, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ agentSocket := filepath.Join(sockDir, string(rune('a'+i))+".sock")
+ startBoundaryForAgent(t, agentSocket, nodeSocket, tc.agentID)
+
+ resp, err := boundaryClient(t, agentSocket).Get(
+ "http://test-llm.inference." + api.MeshZone + "/v1/models")
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != tc.wantStatus {
+ t.Errorf("status = %s, want %d", resp.Status, tc.wantStatus)
+ }
+ })
+ }
+}
+
+// waitForDiscoverableService polls until a peer offering the service is visible,
+// which unlike a model listing needs no call the provider's policy might refuse.
+func waitForDiscoverableService(t *testing.T, apiAddr, token, svcType, svcName string) {
+ t.Helper()
+
+ deadline := time.Now().Add(15 * time.Second)
+ for time.Now().Before(deadline) {
+ req, err := http.NewRequest(http.MethodGet,
+ "http://"+apiAddr+"/sam/service/discover?type="+svcType+"&name="+svcName, nil)
+ if err != nil {
+ t.Fatalf("NewRequest: %v", err)
+ }
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)
+
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ var providers []*api.DiscoveredProvider
+ decodeErr := json.NewDecoder(resp.Body).Decode(&providers)
+ _ = resp.Body.Close()
+ if decodeErr == nil && len(providers) > 0 {
+ return
+ }
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ t.Fatalf("timeout waiting for %s://%s to be discoverable", svcType, svcName)
+}
diff --git a/tests/integration/sandbox_boundary_test.go b/tests/integration/sandbox_boundary_test.go
index 8c42d208..4da9506b 100644
--- a/tests/integration/sandbox_boundary_test.go
+++ b/tests/integration/sandbox_boundary_test.go
@@ -248,6 +248,17 @@ func TestSandboxBoundaryCUJ(t *testing.T) {
// does: it holds no identity and no mesh connection of its own.
func startBoundary(t *testing.T, agentSocket, nodeSocket string, egressAllow ...string) {
t.Helper()
+ startBoundaryWith(t, agentSocket, nodeSocket, "", egressAllow)
+}
+
+// startBoundaryForAgent serves one named agent, as an admitted sandbox does.
+func startBoundaryForAgent(t *testing.T, agentSocket, nodeSocket, agentID string) {
+ t.Helper()
+ startBoundaryWith(t, agentSocket, nodeSocket, agentID, nil)
+}
+
+func startBoundaryWith(t *testing.T, agentSocket, nodeSocket, agentID string, egressAllow []string) {
+ t.Helper()
egress, err := sambox.NewEgressPolicy(egressAllow)
if err != nil {
@@ -262,6 +273,7 @@ func startBoundary(t *testing.T, agentSocket, nodeSocket string, egressAllow ...
Dialer: &sambox.AgentDialer{
Router: &sambox.Router{Egress: egress},
SidecarSocket: nodeSocket,
+ AgentID: agentID,
},
}