Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: classify sandbox destinations and enforce egress policy
Antonio Ojea09ad9bfa356f
diff --git a/internal/sambox/route.go b/internal/sambox/route.gonew file mode 100644index 00000000..3e1caaac--- /dev/null+++ b/internal/sambox/route.go@@ -0,0 +1,160 @@+// 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"+ "strings"++ "github.com/google/sam/api"+)++// Routing decides where a flow leaving a sandbox belongs, from the destination+// name alone. It is deliberately free of I/O so the decision can be tested+// exhaustively and read in one sitting: opening the connection is a separate+// concern.++// RouteKind is the destination class a flow was resolved to.+type RouteKind int++const (+ // RouteLocalNode is the sam-node sidecar this sandbox is attached to.+ RouteLocalNode RouteKind = iota++ // RouteMeshService is a service provided by some peer in the mesh. Which+ // peer is a discovery decision, deliberately not encoded in the name.+ RouteMeshService++ // RouteExternal is a destination outside the mesh, permitted by policy.+ RouteExternal+)++func (k RouteKind) String() string {+ switch k {+ case RouteLocalNode:+ return "local-node"+ case RouteMeshService:+ return "mesh-service"+ case RouteExternal:+ return "external"+ default:+ return fmt.Sprintf("RouteKind(%d)", int(k))+ }+}++// Route is the outcome of classifying a destination.+type Route struct {+ Kind RouteKind++ // ServiceURI is the canonical mesh identity for RouteMeshService, e.g.+ // "inference://openrouter". It is the same string policy is written+ // against, so a routing decision and an authorization decision can never+ // disagree about what was asked for.+ ServiceURI string++ Destination Destination+}++// EgressPolicy is the allowlist for destinations outside the mesh. A nil+// policy allows nothing: a sandbox with no configured egress must reach+// nothing, so the zero value has to be the safe one.+type EgressPolicy struct {+ exact map[string]struct{}+ suffixes []string+}++// NewEgressPolicy compiles an allowlist. Entries are either an exact host+// ("api.github.com") or a leading-label wildcard ("*.pypi.org"). Any other use+// of "*" is rejected rather than quietly treated as a literal, because an+// allowlist entry that silently means something other than what it looks like+// is how allowlists leak.+func NewEgressPolicy(allow []string) (*EgressPolicy, error) {+ p := &EgressPolicy{exact: make(map[string]struct{}, len(allow))}+ for _, raw := range allow {+ entry := api.NormalizeMeshHost(raw)+ if entry == "" {+ return nil, fmt.Errorf("empty egress allow entry")+ }+ if suffix, found := strings.CutPrefix(entry, "*."); found {+ if suffix == "" || strings.Contains(suffix, "*") {+ return nil, fmt.Errorf("invalid egress allow entry %q", raw)+ }+ // Stored with the dot so matching is anchored on a label boundary.+ p.suffixes = append(p.suffixes, "."+suffix)+ continue+ }+ if strings.Contains(entry, "*") {+ return nil, fmt.Errorf("invalid egress allow entry %q: a wildcard is only allowed as a leading %q label", raw, "*.")+ }+ p.exact[entry] = struct{}{}+ }+ return p, nil+}++// Allows reports whether host may be reached. A wildcard covers subdomains+// only, never the parent, matching how every other wildcard in this system and+// in TLS behaves.+func (p *EgressPolicy) Allows(host string) bool {+ if p == nil {+ return false+ }+ h := api.NormalizeMeshHost(host)+ if h == "" {+ return false+ }+ if _, ok := p.exact[h]; ok {+ return true+ }+ for _, suffix := range p.suffixes {+ if strings.HasSuffix(h, suffix) && len(h) > len(suffix) {+ return true+ }+ }+ return false+}++// Router classifies destinations arriving on the sandbox boundary.+type Router struct {+ // Egress is the allowlist for destinations outside the mesh. Nil denies+ // every external destination.+ Egress *EgressPolicy+}++// Route classifies a destination, or returns ErrNotAllowed. Mesh names that do+// not name a service are denied rather than reported as unreachable: to a+// sandbox, "not permitted" and "does not exist" must look the same, or the+// boundary becomes a discovery oracle for the mesh's contents.+func (r *Router) Route(dst Destination) (Route, error) {+ if api.IsLocalNodeHost(dst.Name) {+ return Route{Kind: RouteLocalNode, Destination: dst}, nil+ }++ if api.IsMeshHost(dst.Name) {+ serviceURI, err := api.ParseMeshHost(dst.Name)+ if err != nil {+ return Route{}, fmt.Errorf("%w: %s names no mesh service", ErrNotAllowed, dst.Name)+ }+ return Route{Kind: RouteMeshService, ServiceURI: serviceURI, Destination: dst}, nil+ }++ // Literal addresses are not special-cased: they carry no name, so they are+ // allowed only by an exact entry. CIDR ranges are deliberately not+ // supported yet; adding them is a policy-language decision, not a routing+ // one.+ if !r.Egress.Allows(dst.Name) {+ return Route{}, fmt.Errorf("%w: %s", ErrNotAllowed, dst.Name)+ }+ return Route{Kind: RouteExternal, Destination: dst}, nil+}diff --git a/internal/sambox/route_test.go b/internal/sambox/route_test.gonew file mode 100644index 00000000..bd207353--- /dev/null+++ b/internal/sambox/route_test.go@@ -0,0 +1,150 @@+// 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 (+ "errors"+ "testing"+)++// TestZeroRouterDeniesEverythingExternal pins the fail-closed default: a+// sam-box configured with no egress policy must not be an open proxy.+func TestZeroRouterDeniesEverythingExternal(t *testing.T) {+ var r Router+ for _, host := range []string{"api.github.com", "127.0.0.1", "localhost", "example.com"} {+ if _, err := r.Route(Destination{Name: host, Port: 443, IsName: true}); !errors.Is(err, ErrNotAllowed) {+ t.Errorf("Route(%q) with no policy = %v, want ErrNotAllowed", host, err)+ }+ }+}++func TestRouteClassification(t *testing.T) {+ policy, err := NewEgressPolicy([]string{"api.github.com", "*.pypi.org", "192.0.2.10"})+ if err != nil {+ t.Fatalf("NewEgressPolicy: %v", err)+ }+ r := &Router{Egress: policy}++ tests := []struct {+ name string+ host string+ wantKind RouteKind+ wantURI string+ wantDenied bool+ }{+ {"local sidecar", "node.sam.alt", RouteLocalNode, "", false},+ {"local sidecar is case-insensitive", "NODE.SAM.ALT", RouteLocalNode, "", false},+ {"mesh inference service", "openrouter.inference.sam.alt", RouteMeshService, "inference://openrouter", false},+ {"mesh mcp service", "code-reviewer.mcp.sam.alt", RouteMeshService, "mcp://code-reviewer", false},+ {"allowlisted host", "api.github.com", RouteExternal, "", false},+ {"allowlisted wildcard subdomain", "files.pypi.org", RouteExternal, "", false},+ {"allowlisted literal address", "192.0.2.10", RouteExternal, "", false},++ {"unknown external host", "evil.example", 0, "", true},+ {"mesh zone but no service type", "whatever.sam.alt", 0, "", true},+ {"mesh zone with unknown service type", "thing.storage.sam.alt", 0, "", true},+ {"bare mesh zone", "sam.alt", 0, "", true},+ {"lookalike of the mesh zone", "evil-sam.alt", 0, "", true},+ {"lookalike of an allowlisted host", "evil-api.github.com", 0, "", true},+ {"wildcard parent is not covered", "pypi.org", 0, "", true},+ {"lookalike of a wildcard parent", "evilpypi.org", 0, "", true},+ {"unlisted literal address", "192.0.2.11", 0, "", true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got, err := r.Route(Destination{Name: tc.host, Port: 443, IsName: true})+ if tc.wantDenied {+ if !errors.Is(err, ErrNotAllowed) {+ t.Fatalf("Route(%q) = %+v, %v; want ErrNotAllowed", tc.host, got, err)+ }+ return+ }+ if err != nil {+ t.Fatalf("Route(%q) returned error: %v", tc.host, err)+ }+ if got.Kind != tc.wantKind {+ t.Errorf("Route(%q) kind = %v, want %v", tc.host, got.Kind, tc.wantKind)+ }+ if got.ServiceURI != tc.wantURI {+ t.Errorf("Route(%q) service = %q, want %q", tc.host, got.ServiceURI, tc.wantURI)+ }+ if got.Destination.Name != tc.host {+ t.Errorf("Route(%q) lost the destination: %+v", tc.host, got.Destination)+ }+ })+ }+}++// TestMeshNamesIgnoreEgressPolicy pins that mesh routing is not reachable+// through the allowlist: a mesh name is authorized by mesh policy, and an+// operator listing it under egress must not change how it is routed.+func TestMeshNamesIgnoreEgressPolicy(t *testing.T) {+ policy, err := NewEgressPolicy([]string{"*.sam.alt"})+ if err != nil {+ t.Fatalf("NewEgressPolicy: %v", err)+ }+ r := &Router{Egress: policy}++ got, err := r.Route(Destination{Name: "openrouter.inference.sam.alt", Port: 80, IsName: true})+ if err != nil {+ t.Fatalf("Route returned error: %v", err)+ }+ if got.Kind != RouteMeshService {+ t.Errorf("kind = %v, want %v", got.Kind, RouteMeshService)+ }++ if _, err := r.Route(Destination{Name: "nothing.sam.alt", Port: 80, IsName: true}); !errors.Is(err, ErrNotAllowed) {+ t.Errorf("a non-service mesh name was allowed by the egress list: %v", err)+ }+}++func TestNewEgressPolicyRejectsAmbiguousEntries(t *testing.T) {+ tests := []struct {+ name string+ entry string+ }{+ {"empty", ""},+ {"bare wildcard", "*"},+ {"trailing wildcard", "github.*"},+ {"infix wildcard", "api.*.com"},+ {"partial label wildcard", "*api.github.com"},+ {"double wildcard", "*.*.github.com"},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := NewEgressPolicy([]string{tc.entry}); err == nil {+ t.Fatalf("NewEgressPolicy(%q) = nil error, want a rejection", tc.entry)+ }+ })+ }+}++func TestEgressPolicyNormalizesEntriesAndHosts(t *testing.T) {+ policy, err := NewEgressPolicy([]string{"API.GitHub.com.", "*.PyPI.org"})+ if err != nil {+ t.Fatalf("NewEgressPolicy: %v", err)+ }++ for _, host := range []string{"api.github.com", "API.GITHUB.COM", "api.github.com.", "files.PyPI.org."} {+ if !policy.Allows(host) {+ t.Errorf("Allows(%q) = false, want true", host)+ }+ }+ if policy.Allows("") {+ t.Error("Allows(\"\") = true, want false")+ }+}