Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: make the agent bundle answer to a credential
Antonio Ojea09e286e65c08
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex 343c9e7f..05d06277 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -44,6 +44,9 @@ func main() {sidecarSocket stringbundlePath stringegressAllow []string+ issuer string+ audience string+ insecure boollogLevel string)@@ -69,6 +72,9 @@ func main() {if err != nil {return err}+ if err := verifyBundleCredential(cmd.Context(), bundlePath, issuer, audience, insecure); err != nil {+ return err+ }listener, err := sambox.ListenSandboxSocket(sandboxSocket)if err != nil {@@ -107,6 +113,9 @@ func main() {runCmd.Flags().StringVar(&sidecarSocket, "sidecar-socket", "", "Path to the local sam-node API Unix socket (required)")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(&issuer, "credential-issuer", "", "Issuer whose credentials attest an agent's identity, e.g. a cluster's service-account issuer; required with --bundle")+ runCmd.Flags().StringVar(&audience, "credential-audience", "", "Audience an agent's credential must be scoped to; required with --bundle")+ runCmd.Flags().BoolVar(&insecure, "insecure-unverified-bundle", false, "Trust the bundle's declared identity without a credential to back it, letting whoever can write the file decide which agent this sandbox is")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 {@@ -143,3 +152,50 @@ func resolveAgent(bundlePath string, egressAllow []string, egressSet bool) (stri}return bundle.Agent.ID, bundle.EgressPolicy(), nil}++// verifyBundleCredential checks that the bundle is backed by a credential the+// platform issued to this workload.+//+// A bundle that is not verified is self-asserting: whoever can write the file+// picks the agent, and the identity the whole mesh reasons about rests on a+// YAML field. That is a real choice an operator may need to make, so it is+// available -- but it has to be made explicitly, in a flag that is visible in a+// process listing and a pod spec, rather than by leaving something unset.+//+// The issuer is an operator flag and never a bundle field, because the bundle+// travels with the agent: an issuer named there could be one the attacker+// controls, and their self-signed credential would verify perfectly.+func verifyBundleCredential(ctx context.Context, bundlePath, issuer, audience string, insecure bool) error {+ if bundlePath == "" {+ // No bundle is not a weak claim, it is no claim: the sandbox is+ // unidentified and mesh policy sees only the node it came through.+ return nil+ }++ if insecure {+ if issuer != "" || audience != "" {+ return fmt.Errorf("--insecure-unverified-bundle contradicts --credential-issuer; pick one")+ }+ logger.Warn("--insecure-unverified-bundle: this bundle is taken at its word, so whoever can write it decides which agent this sandbox is")+ return nil+ }++ if issuer == "" || audience == "" {+ return fmt.Errorf("--bundle needs --credential-issuer and --credential-audience so the agent it names can be checked" ++ " against the credential the platform issued; pass --insecure-unverified-bundle to run without that check")+ }++ verifier, err := sambox.NewWorkloadVerifier(ctx, issuer, audience)+ if err != nil {+ return err+ }+ bundle, err := sambox.LoadAgentBundle(bundlePath)+ if err != nil {+ return err+ }+ if err := verifier.Verify(ctx, bundle); err != nil {+ return err+ }+ logger.Infof("Credential verified: %s is %s", bundle.Agent.ID, bundle.Agent.ExternalID)+ return nil+}diff --git a/internal/sambox/bundle.go b/internal/sambox/bundle.goindex 8b355b27..ea5253bc 100644--- a/internal/sambox/bundle.go+++ b/internal/sambox/bundle.go@@ -52,8 +52,14 @@ type AgentIdentity struct {// 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.+ // value the platform actually issued. When credentials are verified, it is+ // also the subject the credential has to attest.ExternalID string `yaml:"external_id"`++ // Credential is the path to the credential the platform issued this+ // workload, such as a projected Kubernetes service-account token. It backs+ // the claim the rest of this file makes; see credential.go.+ Credential string `yaml:"credential"`}// BundleEgress is the agent's allowance outside the mesh. Absent means none.diff --git a/internal/sambox/bundle_test.go b/internal/sambox/bundle_test.goindex 13209934..3f428a0d 100644--- a/internal/sambox/bundle_test.go+++ b/internal/sambox/bundle_test.go@@ -119,9 +119,9 @@ func TestLoadAgentBundleRejects(t *testing.T) {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: "a plausible misspelling of a real field",+ content: "version: v1\nagent:\n id: reviewer.acme.example\n credentials: /var/run/secrets/token\n",+ wantErr: "credentials",},{name: "an ambiguous egress entry",diff --git a/internal/sambox/credential.go b/internal/sambox/credential.gonew file mode 100644index 00000000..8014cd09--- /dev/null+++ b/internal/sambox/credential.go@@ -0,0 +1,97 @@+// 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 (+ "context"+ "fmt"+ "os"+ "strings"++ "github.com/coreos/go-oidc/v3/oidc"++ "github.com/google/sam/internal/identity"+)++// Without this, a bundle is self-asserting: whoever can write the file decides+// which agent the sandbox is, and the identity the whole mesh then reasons+// about rests on a YAML field. Verification makes the bundle a claim that has+// to be backed by a credential the platform issued to that workload — a+// projected Kubernetes service-account token today.+//+// The issuer is deliberately not read from the bundle. The bundle travels with+// the agent and is therefore exactly as trustworthy as the agent; an issuer+// named there could be one the attacker controls, and self-signed credentials+// would verify perfectly. It comes from the operator instead, on the command+// line beside the socket paths.++// WorkloadVerifier checks the credential a platform issued to a sandbox.+type WorkloadVerifier struct {+ providers map[string]*oidc.Provider+ audiences []string+}++// NewWorkloadVerifier resolves the issuer, which requires reaching its+// discovery endpoint, so a misconfigured issuer fails at startup rather than+// on the first agent.+func NewWorkloadVerifier(ctx context.Context, issuer, audience string) (*WorkloadVerifier, error) {+ if issuer == "" || audience == "" {+ return nil, fmt.Errorf("both a credential issuer and an audience are required")+ }+ provider, err := oidc.NewProvider(ctx, issuer)+ if err != nil {+ return nil, fmt.Errorf("resolving the credential issuer %s: %w", issuer, err)+ }+ return &WorkloadVerifier{+ providers: map[string]*oidc.Provider{issuer: provider},+ audiences: []string{audience},+ }, nil+}++// Verify reports whether the bundle's credential attests the identity the+// bundle claims.+//+// The check that matters is the last one: the credential's subject must be the+// external identity the bundle declares. Verifying the signature alone would+// only prove the sandbox holds *a* valid credential, which every sandbox on the+// platform does, and any of them could then claim to be any other.+func (v *WorkloadVerifier) Verify(ctx context.Context, bundle *AgentBundle) error {+ if bundle.Agent.Credential == "" {+ return fmt.Errorf("agent %s declares no credential, and this gateway verifies them", bundle.Agent.ID)+ }+ if bundle.Agent.ExternalID == "" {+ return fmt.Errorf("agent %s declares no external_id, so there is nothing for its credential to attest", bundle.Agent.ID)+ }++ raw, err := os.ReadFile(bundle.Agent.Credential)+ if err != nil {+ return fmt.Errorf("reading the credential for agent %s: %w", bundle.Agent.ID, err)+ }++ claims, _, err := identity.VerifyJWT(ctx, strings.TrimSpace(string(raw)), v.audiences, v.providers)+ if err != nil {+ return fmt.Errorf("verifying the credential for agent %s: %w", bundle.Agent.ID, err)+ }++ subject, _ := claims["sub"].(string)+ if subject == "" {+ return fmt.Errorf("the credential for agent %s attests no subject", bundle.Agent.ID)+ }+ if subject != bundle.Agent.ExternalID {+ return fmt.Errorf("agent %s claims to be %q, but its credential attests %q",+ bundle.Agent.ID, bundle.Agent.ExternalID, subject)+ }+ return nil+}diff --git a/internal/sambox/credential_test.go b/internal/sambox/credential_test.gonew file mode 100644index 00000000..bdaa72fd--- /dev/null+++ b/internal/sambox/credential_test.go@@ -0,0 +1,247 @@+// 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 (+ "context"+ "crypto/rand"+ "crypto/rsa"+ "encoding/base64"+ "encoding/json"+ "math/big"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/golang-jwt/jwt/v5"+)++const testKID = "test-key"++// newMockPlatformIssuer stands in for a Kubernetes API server issuing projected+// service-account tokens.+func newMockPlatformIssuer(t *testing.T) (issuer string, key *rsa.PrivateKey) {+ t.Helper()++ privKey, err := rsa.GenerateKey(rand.Reader, 2048)+ if err != nil {+ t.Fatalf("GenerateKey: %v", err)+ }++ mux := http.NewServeMux()+ srv := httptest.NewServer(mux)+ t.Cleanup(srv.Close)+ issuer = srv.URL++ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "issuer": issuer,+ "jwks_uri": issuer + "/keys",+ })+ })+ mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "keys": []map[string]any{{+ "kty": "RSA",+ "alg": "RS256",+ "use": "sig",+ "kid": testKID,+ "n": base64.RawURLEncoding.EncodeToString(privKey.N.Bytes()),+ "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(privKey.E)).Bytes()),+ }},+ })+ })++ return issuer, privKey+}++func signCredential(t *testing.T, key *rsa.PrivateKey, claims jwt.MapClaims) string {+ t.Helper()+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)+ token.Header["kid"] = testKID+ signed, err := token.SignedString(key)+ if err != nil {+ t.Fatalf("SignedString: %v", err)+ }+ return signed+}++// bundleWithCredential writes a bundle and its credential file, returning the+// loaded bundle.+func bundleWithCredential(t *testing.T, externalID, credential string) *AgentBundle {+ t.Helper()++ dir := t.TempDir()+ credentialPath := filepath.Join(dir, "token")+ if credential != "" {+ if err := os.WriteFile(credentialPath, []byte(credential), 0600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }+ }++ content := "version: v1\nagent:\n id: reviewer-7.prod.acme.example\n"+ if externalID != "" {+ content += " external_id: " + externalID + "\n"+ }+ if credential != "" {+ content += " credential: " + credentialPath + "\n"+ }++ bundle, err := LoadAgentBundle(writeBundle(t, content))+ if err != nil {+ t.Fatalf("LoadAgentBundle: %v", err)+ }+ return bundle+}++func TestWorkloadVerifier(t *testing.T) {+ issuer, key := newMockPlatformIssuer(t)+ ctx := context.Background()++ verifier, err := NewWorkloadVerifier(ctx, issuer, "sam-mesh")+ if err != nil {+ t.Fatalf("NewWorkloadVerifier: %v", err)+ }++ subject := "system:serviceaccount:prod:reviewer"+ valid := jwt.MapClaims{+ "iss": issuer,+ "aud": "sam-mesh",+ "sub": subject,+ "exp": time.Now().Add(time.Hour).Unix(),+ }++ t.Run("a credential attesting the declared identity", func(t *testing.T) {+ bundle := bundleWithCredential(t, subject, signCredential(t, key, valid))+ if err := verifier.Verify(ctx, bundle); err != nil {+ t.Fatalf("Verify: %v", err)+ }+ })++ // The one that matters. Every sandbox on a platform holds a valid+ // credential, so a signature check alone would let any of them claim to be+ // any other.+ t.Run("a valid credential for somebody else", func(t *testing.T) {+ other := signCredential(t, key, jwt.MapClaims{+ "iss": issuer,+ "aud": "sam-mesh",+ "sub": "system:serviceaccount:prod:some-other-workload",+ "exp": time.Now().Add(time.Hour).Unix(),+ })+ bundle := bundleWithCredential(t, subject, other)++ err := verifier.Verify(ctx, bundle)+ if err == nil {+ t.Fatal("Verify accepted a credential attesting a different workload")+ }+ if !strings.Contains(err.Error(), "some-other-workload") {+ t.Errorf("error = %v, want it to name the subject actually attested", err)+ }+ })++ t.Run("rejections", func(t *testing.T) {+ otherIssuer, otherKey := newMockPlatformIssuer(t)++ tests := []struct {+ name string+ externalID string+ credential string+ }{+ {+ name: "expired",+ externalID: subject,+ credential: signCredential(t, key, jwt.MapClaims{+ "iss": issuer, "aud": "sam-mesh", "sub": subject,+ "exp": time.Now().Add(-time.Minute).Unix(),+ }),+ },+ {+ name: "for a different audience",+ externalID: subject,+ credential: signCredential(t, key, jwt.MapClaims{+ "iss": issuer, "aud": "somebody-else", "sub": subject,+ "exp": time.Now().Add(time.Hour).Unix(),+ }),+ },+ {+ // An issuer the operator did not name. This is why the issuer+ // cannot come from the bundle: an attacker who chose it would+ // simply sign their own.+ name: "from an issuer this gateway does not trust",+ externalID: subject,+ credential: signCredential(t, otherKey, jwt.MapClaims{+ "iss": otherIssuer, "aud": "sam-mesh", "sub": subject,+ "exp": time.Now().Add(time.Hour).Unix(),+ }),+ },+ {+ name: "signed by the wrong key for the right issuer",+ externalID: subject,+ credential: signCredential(t, otherKey, valid),+ },+ {+ name: "not a token at all",+ externalID: subject,+ credential: "not-a-jwt",+ },+ {+ name: "attesting no subject",+ externalID: subject,+ credential: signCredential(t, key, jwt.MapClaims{+ "iss": issuer, "aud": "sam-mesh",+ "exp": time.Now().Add(time.Hour).Unix(),+ }),+ },+ {+ name: "declared without an external identity to attest",+ credential: signCredential(t, key, valid),+ },+ {+ name: "no credential at all",+ externalID: subject,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ bundle := bundleWithCredential(t, tc.externalID, tc.credential)+ if err := verifier.Verify(ctx, bundle); err == nil {+ t.Fatal("Verify accepted it, want an error")+ }+ })+ }+ })+}++func TestNewWorkloadVerifierRequiresIssuerAndAudience(t *testing.T) {+ ctx := context.Background()+ issuer, _ := newMockPlatformIssuer(t)++ if _, err := NewWorkloadVerifier(ctx, "", "sam-mesh"); err == nil {+ t.Error("NewWorkloadVerifier accepted an empty issuer")+ }+ if _, err := NewWorkloadVerifier(ctx, issuer, ""); err == nil {+ t.Error("NewWorkloadVerifier accepted an empty audience")+ }+ if _, err := NewWorkloadVerifier(ctx, "http://127.0.0.1:1/not-an-issuer", "sam-mesh"); err == nil {+ t.Error("NewWorkloadVerifier accepted an unreachable issuer, want it to fail at startup")+ }+}diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 97abe752..1ba9dcb3 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -624,7 +624,18 @@ the rules in §10.8. **The scheduler needs no mesh enrollment and no meshcredential of its own.** It keeps doing exactly what it already does for everyworkload: project an identity document. This is the OIDC relationship, not amerger of the two domains.-+The check that carries the weight is not the signature but the subject: the+credential must attest the `external_id` the bundle declares. Every sandbox on a+platform holds a valid credential, so verifying the signature alone would let+any of them claim to be any other. And the issuer is operator configuration+(`--credential-issuer`), never a bundle field — the bundle travels with the+agent, so an issuer named there could be one an attacker controls, and their+self-signed credential would verify perfectly.++Verification is the default: a bundle without an issuer to check it against is+refused. Deployments with no platform issuer can still run, but by saying so+(`--insecure-unverified-bundle`), because a name the whole mesh authorizes+against should not become trustworthy through a field being left unset.`sam-box` then binds that identity to the channel, so nothing has to be assertedin-band afterwards:diff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.mdindex 1c79b5b9..092351a3 100644--- a/site/content/docs/user/secure-gateway.md+++ b/site/content/docs/user/secure-gateway.md@@ -55,12 +55,25 @@ sam-box run \|---|---|| `--socket` | The sandbox-facing socket. Created 0600: its permissions are the credential. || `--sidecar-socket` | The local `sam-node`'s API socket (`sam-node run --socket-path`). |+| `--bundle` | The agent's identity and egress allowance, declared by the platform. || `--egress-allow` | A destination outside the mesh the agent may reach. Repeatable. **Empty means nothing is reachable.** |+| `--credential-issuer`, `--credential-audience` | The issuer whose credentials attest an agent's identity. **Required with `--bundle`.** |+| `--insecure-unverified-bundle` | Trust the bundle without a credential behind it. An explicit choice, not a default. |Egress entries are matched on the name the agent asked for, never on a resolvedaddress. A wildcard covers subdomains only: `*.pypi.org` matches`files.pypi.org` but not `pypi.org`, and never `evilpypi.org`.+A bundle names an agent, and that name is what the whole mesh then authorizes+against — so by default it has to be backed by the credential the platform+issued to that workload. Running without that check is available, because some+deployments have no platform issuer, but it takes a flag that is visible in a+process listing and a pod spec rather than something quietly left unset.++The issuer is a flag rather than a bundle field on purpose: the bundle travels+with the agent, so an issuer named there could be one an attacker controls, and+their self-signed credential would verify perfectly.+---## 3. What the agent sees@@ -112,5 +125,6 @@ Deliberately absent, and tracked in the architecture document:* **Secret injection** for external destinations. The ephemeral CA and theinjection machinery exist, but are not wired into this datapath.* **Ingress**: an agent serving a mesh service of its own.-* **Per-agent identity** on the wire. Today flows carry the node's identity;- the agent's own identity is the next piece of work.+* **Credential rotation.** A bundle's credential is verified when the gateway+ starts. Platforms rotate projected tokens, and re-verifying on rotation is+ the connector interface's `Refresh` operation, which is not built yet.