Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: admit an agent from its bundle and name it to the node
Antonio Ojea467e93720bf4
diff --git a/api/network.go b/api/network.goindex e6f3a128..7fabf454 100644--- a/api/network.go+++ b/api/network.go@@ -87,6 +87,17 @@ const (// are forwarded to backend services.HeaderSamBiscuit = "X-Sam-Biscuit"+ // HeaderSamAgent names the agent a request is made on behalf of, as a+ // canonical agent identifier (see api/agent.go). It is set by the sandbox+ // gateway on the node's local API socket, and honoured by the node only+ // there: arriving on that socket is proof the caller is the gateway, which+ // is the only party that knows which agent a flow belongs to.+ //+ // A sandboxed agent can never set it. The gateway overwrites the header on+ // every request it forwards, so a value an agent supplies is replaced by+ // the identity the platform bound to its channel, never merged with it.+ HeaderSamAgent = "X-Sam-Agent"+// HeaderSamAuthentication is the custom HTTP header used to authenticate a local// process to this node's sidecar API (the shared secret configured via// "--api-token-path" or the SAM_API_TOKEN environment variable). Using adiff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex de04cb92..343c9e7f 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -24,6 +24,7 @@ package mainimport ("context"+ "fmt""os""os/signal""syscall"@@ -41,6 +42,7 @@ func main() {var (sandboxSocket stringsidecarSocket string+ bundlePath stringegressAllow []stringlogLevel string)@@ -63,7 +65,7 @@ func main() {golog.SetAllLoggers(lvl)}- egress, err := sambox.NewEgressPolicy(egressAllow)+ agentID, egress, err := resolveAgent(bundlePath, egressAllow, cmd.Flags().Changed("egress-allow"))if err != nil {return err}@@ -81,11 +83,17 @@ func main() {Dialer: &sambox.AgentDialer{Router: &sambox.Router{Egress: egress},SidecarSocket: sidecarSocket,+ AgentID: agentID,},}logger.Infof("Sandbox boundary listening on %s, node at %s", sandboxSocket, sidecarSocket)- logger.Infof("Agents reach the mesh at http://%s; %d egress destination(s) allowed", api.MeshEntrypointHost, len(egressAllow))+ if agentID == "" {+ logger.Warn("No agent bundle: this sandbox is unidentified, and mesh policy will see only the node it came through")+ } else {+ logger.Infof("Serving agent %s", agentID)+ }+ logger.Infof("Agents reach the mesh at http://%s", api.MeshEntrypointHost)if err := server.Serve(cmd.Context(), listener); err != nil {return err@@ -97,7 +105,8 @@ func main() {runCmd.Flags().StringVar(&sandboxSocket, "socket", "", "Path to the sandbox-facing Unix socket to serve SOCKS5 on (required)")runCmd.Flags().StringVar(&sidecarSocket, "sidecar-socket", "", "Path to the local sam-node API Unix socket (required)")- runCmd.Flags().StringSliceVar(&egressAllow, "egress-allow", nil, "Destinations outside the mesh an agent may reach, e.g. api.github.com or *.pypi.org (default: none)")+ runCmd.Flags().StringVar(&bundlePath, "bundle", "", "Path to the agent bundle declaring the agent's identity and its egress allowance")+ runCmd.Flags().StringSliceVar(&egressAllow, "egress-allow", nil, "Destinations an unidentified sandbox may reach, e.g. api.github.com or *.pypi.org; use --bundle instead where an agent has an identity")runCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")for _, required := range []string{"socket", "sidecar-socket"} {if err := runCmd.MarkFlagRequired(required); err != nil {@@ -114,3 +123,23 @@ func main() {logger.Fatalf("%v", err)}}++// resolveAgent settles who this boundary serves. A bundle is the real answer;+// --egress-allow covers a sandbox with no identity yet, which mesh policy can+// only attribute to the node it came through. Accepting both would leave the+// egress allowance ambiguous, so it is refused rather than silently resolved.+func resolveAgent(bundlePath string, egressAllow []string, egressSet bool) (string, *sambox.EgressPolicy, error) {+ if bundlePath == "" {+ policy, err := sambox.NewEgressPolicy(egressAllow)+ return "", policy, err+ }+ if egressSet {+ return "", nil, fmt.Errorf("--bundle already declares the egress allowance; drop --egress-allow")+ }++ bundle, err := sambox.LoadAgentBundle(bundlePath)+ if err != nil {+ return "", nil, err+ }+ return bundle.Agent.ID, bundle.EgressPolicy(), nil+}diff --git a/internal/sambox/bundle.go b/internal/sambox/bundle.gonew file mode 100644index 00000000..8b355b27--- /dev/null+++ b/internal/sambox/bundle.go@@ -0,0 +1,98 @@+// 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 sambox++import (+ "fmt"+ "os"++ "gopkg.in/yaml.v2"++ "github.com/google/sam/api"+)++// An agent bundle is what the platform declares about one agent. Its canonical+// home is a file in the agent's own state directory, so that suspending an+// agent on one host and resuming it on another carries it along with no extra+// machinery: the gateway on the new host reads the same bundle and asserts the+// same identity.+//+// Parsing is strict. A bundle is a security document, and a typo in a field+// name that silently parsed as "absent" would hand an agent broader access than+// intended, or an identity nobody granted it.++// AgentBundle is the parsed form of that file.+type AgentBundle struct {+ Version string `yaml:"version"`+ Agent AgentIdentity `yaml:"agent"`+ Egress BundleEgress `yaml:"egress"`++ // egress is the compiled form of Egress.Allow, built during loading so a+ // malformed allowlist fails at startup rather than on an agent's first+ // request.+ egress *EgressPolicy+}++// AgentIdentity names the principal the gateway asserts for this sandbox.+type AgentIdentity struct {+ // ID is the canonical mesh identifier, without the "agent:" prefix.+ ID string `yaml:"id"`++ // ExternalID is the platform's own identifier, kept verbatim: the+ // translation into ID is not always reversible, and an auditor needs the+ // value the platform actually issued.+ ExternalID string `yaml:"external_id"`+}++// BundleEgress is the agent's allowance outside the mesh. Absent means none.+type BundleEgress struct {+ Allow []string `yaml:"allow"`+}++// LoadAgentBundle reads and validates a bundle.+func LoadAgentBundle(path string) (*AgentBundle, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("reading the agent bundle: %w", err)+ }++ var bundle AgentBundle+ // Strict: an unrecognised field is a mistake worth failing on, and it is+ // also how a bundle written for a later version announces itself.+ if err := yaml.UnmarshalStrict(data, &bundle); err != nil {+ return nil, fmt.Errorf("parsing the agent bundle %s: %w", path, err)+ }++ if bundle.Version != BundleVersion {+ return nil, fmt.Errorf("agent bundle %s has version %q, want %q", path, bundle.Version, BundleVersion)+ }+ if err := api.ValidateAgentID(bundle.Agent.ID); err != nil {+ return nil, fmt.Errorf("agent bundle %s: %w", path, err)+ }++ policy, err := NewEgressPolicy(bundle.Egress.Allow)+ if err != nil {+ return nil, fmt.Errorf("agent bundle %s: %w", path, err)+ }+ bundle.egress = policy++ return &bundle, nil+}++// BundleVersion is the only bundle version this gateway understands.+const BundleVersion = "v1"++// EgressPolicy returns the compiled allowlist.+func (b *AgentBundle) EgressPolicy() *EgressPolicy { return b.egress }diff --git a/internal/sambox/bundle_test.go b/internal/sambox/bundle_test.gonew file mode 100644index 00000000..13209934--- /dev/null+++ b/internal/sambox/bundle_test.go@@ -0,0 +1,155 @@+// 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 sambox++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func writeBundle(t *testing.T, content string) string {+ t.Helper()+ dir := t.TempDir()+ path := filepath.Join(dir, "agent.yaml")+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }+ return path+}++func TestLoadAgentBundle(t *testing.T) {+ path := writeBundle(t, `+version: v1+agent:+ id: reviewer-7.prod.acme.example+ external_id: spiffe://acme.example/prod/reviewer-7+egress:+ allow:+ - api.github.com+ - "*.pypi.org"+`)++ bundle, err := LoadAgentBundle(path)+ if err != nil {+ t.Fatalf("LoadAgentBundle: %v", err)+ }+ if bundle.Agent.ID != "reviewer-7.prod.acme.example" {+ t.Errorf("agent id = %q", bundle.Agent.ID)+ }+ if bundle.Agent.ExternalID != "spiffe://acme.example/prod/reviewer-7" {+ t.Errorf("external id = %q, want it kept verbatim", bundle.Agent.ExternalID)+ }+ if !bundle.EgressPolicy().Allows("files.pypi.org") {+ t.Error("compiled egress policy does not allow files.pypi.org")+ }+ if bundle.EgressPolicy().Allows("pypi.org") {+ t.Error("a wildcard covered its parent domain")+ }+}++func TestLoadAgentBundleWithNoEgressAllowsNothing(t *testing.T) {+ path := writeBundle(t, `+version: v1+agent:+ id: reviewer.acme.example+`)++ bundle, err := LoadAgentBundle(path)+ if err != nil {+ t.Fatalf("LoadAgentBundle: %v", err)+ }+ for _, host := range []string{"api.github.com", "example.com", "127.0.0.1"} {+ if bundle.EgressPolicy().Allows(host) {+ t.Errorf("a bundle declaring no egress allowed %s", host)+ }+ }+}++// TestLoadAgentBundleRejects covers the reason parsing is strict: a bundle is a+// security document, and a field that silently reads as absent grants either+// more access than intended or an identity nobody issued.+func TestLoadAgentBundleRejects(t *testing.T) {+ tests := []struct {+ name string+ content string+ wantErr string+ }{+ {+ name: "no version",+ content: "agent:\n id: reviewer.acme.example\n",+ wantErr: "version",+ },+ {+ name: "a version this gateway does not understand",+ content: "version: v2\nagent:\n id: reviewer.acme.example\n",+ wantErr: "version",+ },+ {+ name: "no agent id",+ content: "version: v1\nagent:\n external_id: spiffe://acme.example/x\n",+ wantErr: "empty",+ },+ {+ name: "an agent id with no authority",+ content: "version: v1\nagent:\n id: reviewer\n",+ wantErr: "authority",+ },+ {+ name: "an agent id that is a pattern",+ content: "version: v1\nagent:\n id: \"*.acme.example\"\n",+ wantErr: "wildcard",+ },+ {+ name: "a misspelled field",+ content: "version: v1\nagent:\n id: reviewer.acme.example\negres:\n allow: [api.github.com]\n",+ wantErr: "egres",+ },+ {+ name: "a field from a future version",+ content: "version: v1\nagent:\n id: reviewer.acme.example\n credential: /var/run/secrets/token\n",+ wantErr: "credential",+ },+ {+ name: "an ambiguous egress entry",+ content: "version: v1\nagent:\n id: reviewer.acme.example\negress:\n allow: [\"api.*.com\"]\n",+ wantErr: "wildcard",+ },+ {+ name: "not yaml at all",+ content: "\tthis is not yaml\n",+ wantErr: "parsing",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ _, err := LoadAgentBundle(writeBundle(t, tc.content))+ if err == nil {+ t.Fatalf("LoadAgentBundle accepted %q, want an error", tc.content)+ }+ if !strings.Contains(err.Error(), tc.wantErr) {+ t.Errorf("error = %v, want it to mention %q", err, tc.wantErr)+ }+ })+ }+}++func TestLoadAgentBundleMissingFile(t *testing.T) {+ if _, err := LoadAgentBundle(filepath.Join(t.TempDir(), "absent.yaml")); err == nil {+ t.Fatal("LoadAgentBundle accepted a missing file, want an error")+ }+}diff --git a/internal/sambox/dial.go b/internal/sambox/dial.goindex 77fb4af3..feaadaab 100644--- a/internal/sambox/dial.go+++ b/internal/sambox/dial.go@@ -40,6 +40,11 @@ type AgentDialer struct {// socket, only the curated surface built on top of it (entrypoint.go).SidecarSocket string+ // AgentID is the principal this boundary serves, asserted to the node on+ // every request (api.HeaderSamAgent). Empty means the sandbox is+ // unidentified, and mesh policy sees only the node it came through.+ AgentID string+// DialContext opens external destinations. Nil uses a plain net.Dialer;// tests and future egress interception replace it.DialContext func(ctx context.Context, network, address string) (net.Conn, error)diff --git a/internal/sambox/entrypoint.go b/internal/sambox/entrypoint.goindex f055f7a8..93699a00 100644--- a/internal/sambox/entrypoint.go+++ b/internal/sambox/entrypoint.go@@ -70,14 +70,7 @@ func (d *AgentDialer) entrypointHandler() http.Handler {r.Out.URL.Scheme = "http"r.Out.URL.Host = sidecarHostr.Out.Host = sidecarHost-- // Headers that assert an identity the agent does not have. The- // sidecar would honour them: X-Sam-Biscuit is the mesh datapath- // credential, and X-Sam-Authentication is the node's local gate.- // Authorization is left alone, because there it means the- // destination service's own credential and is the agent's to send.- r.Out.Header.Del(api.HeaderSamBiscuit)- r.Out.Header.Del(api.HeaderSamAuthentication)+ d.assertAgent(r)},Transport: d.sidecarTransport(),}@@ -90,3 +83,23 @@ func (d *AgentDialer) entrypointHandler() http.Handler {proxy.ServeHTTP(w, r)})}++// assertAgent replaces every identity-bearing header with what the gateway+// knows, so an agent cannot claim to be anything by setting them itself.+//+// X-Sam-Biscuit is the mesh datapath credential and X-Sam-Authentication is the+// node's local gate; both are the node's business, not the agent's. X-Sam-Agent+// is the one the gateway does set, and it is always overwritten rather than+// merged: an agent's own value must never survive.+//+// Authorization is deliberately untouched. There it means the destination+// service's credential, which is the agent's to send.+func (d *AgentDialer) assertAgent(r *httputil.ProxyRequest) {+ r.Out.Header.Del(api.HeaderSamBiscuit)+ r.Out.Header.Del(api.HeaderSamAuthentication)++ r.Out.Header.Del(api.HeaderSamAgent)+ if d.AgentID != "" {+ r.Out.Header.Set(api.HeaderSamAgent, d.AgentID)+ }+}diff --git a/internal/sambox/entrypoint_test.go b/internal/sambox/entrypoint_test.goindex 57cf5f05..a6663ba8 100644--- a/internal/sambox/entrypoint_test.go+++ b/internal/sambox/entrypoint_test.go@@ -46,9 +46,14 @@ func recordingSidecar(t *testing.T) (socket string, calls chan sidecarCall) {}func entrypointClient(t *testing.T, socket string) *http.Client {+ t.Helper()+ return entrypointClientForAgent(t, socket, "")+}++func entrypointClientForAgent(t *testing.T, socket, agentID string) *http.Client {t.Helper()boundary := startSOCKS5(t, &SOCKS5Server{- Dialer: &AgentDialer{Router: &Router{}, SidecarSocket: socket},+ Dialer: &AgentDialer{Router: &Router{}, SidecarSocket: socket, AgentID: agentID},})dialer, err := proxy.SOCKS5("unix", boundary, nil, proxy.Direct)if err != nil {@@ -61,6 +66,71 @@ func entrypointClient(t *testing.T, socket string) *http.Client {return &http.Client{Transport: &http.Transport{DialContext: contextDialer.DialContext}}}+// TestAgentIdentityIsAssertedToTheNode covers the half of admission that makes+// an agent visible to mesh policy: the gateway names the principal, because it+// is the only party that knows which agent a flow belongs to.+func TestAgentIdentityIsAssertedToTheNode(t *testing.T) {+ socket, calls := recordingSidecar(t)+ client := entrypointClientForAgent(t, socket, "reviewer-7.prod.acme.example")++ resp, err := client.Get("http://" + api.MeshEntrypointHost + "/v1/models")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ _ = resp.Body.Close()++ if got := (<-calls).headers.Get(api.HeaderSamAgent); got != "reviewer-7.prod.acme.example" {+ t.Errorf("%s = %q, want the agent the gateway serves", api.HeaderSamAgent, got)+ }+}++// TestAgentCannotForgeItsIdentity is the other half. An agent that could set+// the header would be able to borrow any other agent's authority, so the+// gateway overwrites it rather than merging with it.+func TestAgentCannotForgeItsIdentity(t *testing.T) {+ t.Run("a different agent", func(t *testing.T) {+ socket, calls := recordingSidecar(t)+ client := entrypointClientForAgent(t, socket, "reviewer-7.prod.acme.example")++ req, err := http.NewRequest(http.MethodGet, "http://"+api.MeshEntrypointHost+"/v1/models", nil)+ if err != nil {+ t.Fatalf("NewRequest: %v", err)+ }+ req.Header.Set(api.HeaderSamAgent, "privileged.prod.acme.example")++ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("Do: %v", err)+ }+ _ = resp.Body.Close()++ if got := (<-calls).headers.Get(api.HeaderSamAgent); got != "reviewer-7.prod.acme.example" {+ t.Errorf("%s = %q, want the forged value replaced", api.HeaderSamAgent, got)+ }+ })++ t.Run("any agent at all when the boundary has none", func(t *testing.T) {+ socket, calls := recordingSidecar(t)+ client := entrypointClient(t, socket)++ req, err := http.NewRequest(http.MethodGet, "http://"+api.MeshEntrypointHost+"/v1/models", nil)+ if err != nil {+ t.Fatalf("NewRequest: %v", err)+ }+ req.Header.Set(api.HeaderSamAgent, "privileged.prod.acme.example")++ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("Do: %v", err)+ }+ _ = resp.Body.Close()++ if got := (<-calls).headers.Get(api.HeaderSamAgent); got != "" {+ t.Errorf("%s = %q, want it stripped entirely", api.HeaderSamAgent, got)+ }+ })+}+// TestAgentReachesInferenceAndTools covers what an agent is supposed to have:// the mesh's inference and tool endpoints, reached by name, over SOCKS5.func TestAgentReachesInferenceAndTools(t *testing.T) {diff --git a/internal/sambox/mesh.go b/internal/sambox/mesh.goindex ea8049ad..5252af8d 100644--- a/internal/sambox/mesh.go+++ b/internal/sambox/mesh.go@@ -69,11 +69,7 @@ func (d *AgentDialer) dialMeshService(ctx context.Context, route Route) (net.Conr.Out.Host = sidecarHostr.Out.URL.Path = prefix + r.In.URL.Pathr.Out.URL.RawPath = ""-- // Same reasoning as the entrypoint: an agent must not be able to- // assert an identity by setting the headers the sidecar honours.- r.Out.Header.Del(api.HeaderSamBiscuit)- r.Out.Header.Del(api.HeaderSamAuthentication)+ d.assertAgent(r)},Transport: transport,}