Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(egress): address T2b review — endpoint validators, port null, cache bound
高然97d6d5e7f6f5
diff --git a/components/egress/fastsandbox_resolve_test.go b/components/egress/fastsandbox_resolve_test.goindex c3e1b20a6..0db277e05 100644--- a/components/egress/fastsandbox_resolve_test.go+++ b/components/egress/fastsandbox_resolve_test.go@@ -393,7 +393,7 @@ func TestSidecarResolveVaultAccessEnvSubject(t *testing.T) {_, accessErr := s.resolveVaultAccess(nil)require.NotNil(t, accessErr)require.Equal(t, http.StatusServiceUnavailable, accessErr.Status)- require.Equal(t, "sandbox identity not configured", accessErr.Reason)+ require.Equal(t, "sandbox identity unavailable", accessErr.Reason)t.Setenv(constants.EnvSandboxID, " sbx-sidecar-7 ")access, accessErr := s.resolveVaultAccess(nil)diff --git a/components/egress/pkg/credentialvault/resolve_handler.go b/components/egress/pkg/credentialvault/resolve_handler.goindex dd6ebf4bf..9eb3f1fe6 100644--- a/components/egress/pkg/credentialvault/resolve_handler.go+++ b/components/egress/pkg/credentialvault/resolve_handler.go@@ -212,8 +212,14 @@ func (h *ResolveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {writeResolveSuccess(w, capture.Revision, document.Binding, decision)}-// clientFor caches one ResolverClient per captured endpoint; clients are-// stateless beyond their transport and the env never changes at runtime.+// maxCachedResolverClients bounds the per-endpoint client cache: entries are+// never evicted (the handler lives for the process lifetime), so a churning+// endpoint set must not grow it without limit. Past the cap, clients are+// rebuilt per request — construction is parse-only, no I/O.+const maxCachedResolverClients = 64++// clientFor caches one ResolverClient per captured endpoint (hot resolvers+// are few); the env never changes at runtime.func (h *ResolveHandler) clientFor(endpoint string) (ResolverClient, error) {h.mu.Lock()defer h.mu.Unlock()@@ -224,7 +230,9 @@ func (h *ResolveHandler) clientFor(endpoint string) (ResolverClient, error) {if err != nil {return nil, err}- h.clients[endpoint] = client+ if len(h.clients) < maxCachedResolverClients {+ h.clients[endpoint] = client+ }return client, nil}@@ -312,7 +320,13 @@ func decodeResolveRequest(data []byte) (resolveEndpointRequest, error) {return resolveEndpointRequest{}, err}if portRaw, ok := requestFields["port"]; ok {- if err := json.Unmarshal(bytes.TrimSpace(portRaw), &document.Request.Port); err != nil {+ trimmed := bytes.TrimSpace(portRaw)+ // JSON null unmarshals into an int as a no-op success; reject it+ // explicitly like every other scalar (no null scalars).+ if bytes.Equal(trimmed, []byte("null")) {+ return resolveEndpointRequest{}, errors.New("port must be an integer")+ }+ if err := json.Unmarshal(trimmed, &document.Request.Port); err != nil {return resolveEndpointRequest{}, errors.New("port must be an integer")}}@@ -469,12 +483,13 @@ func writeResolveJSON(w http.ResponseWriter, status int, document resolveEndpoin// object, so a same-name replacement — including a delete/recreate whose// revision wraps back — with different content is always detectable, while an// unrelated mutation that did not touch the captured binding does not-// invalidate (OSEP-0012 immutable-snapshot semantics).+// invalidate (OSEP-0012 immutable-snapshot semantics). The active-snapshot+// tag is deliberately NOT captured: it flips on unrelated mutations and must+// not gate invalidation.type ResolveCapture struct {Credential stringEndpoint stringRevision int64- ActiveTag stringFingerprint [sha256.Size]byte}@@ -504,7 +519,6 @@ func (v *Store) CaptureResolve(bindingName string) (ResolveCapture, error) {Credential: credential.Name,Endpoint: exchange.endpoint,Revision: v.revision,- ActiveTag: v.activeTag,Fingerprint: resolveFingerprint(binding, credential.raw),}, nil}diff --git a/components/egress/pkg/credentialvault/resolve_handler_test.go b/components/egress/pkg/credentialvault/resolve_handler_test.goindex a11843bac..4a44dd8a5 100644--- a/components/egress/pkg/credentialvault/resolve_handler_test.go+++ b/components/egress/pkg/credentialvault/resolve_handler_test.go@@ -228,6 +228,9 @@ func TestResolveHandlerRequestDiscipline(t *testing.T) {{"float port", http.MethodPost, "application/json",`{"binding":"internal-api","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","port":443.5,"method":"GET","path":"/"}}`,http.StatusBadRequest, "malformed request"},+ {"null port", http.MethodPost, "application/json",+ `{"binding":"internal-api","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","port":null,"method":"GET","path":"/"}}`,+ http.StatusBadRequest, "malformed request"},{"out-of-range port", http.MethodPost, "application/json",`{"binding":"internal-api","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","port":65536,"method":"GET","path":"/"}}`,http.StatusBadRequest, "malformed request"},@@ -316,11 +319,11 @@ func TestResolveHandlerUnknownSubjectsAndBindings(t *testing.T) {// Access failures propagate their own fixed status.h.handler = NewResolveHandler(func(*http.Request) (ResolveAccess, *ResolveAccessError) {- return ResolveAccess{}, &ResolveAccessError{Status: http.StatusServiceUnavailable, Reason: "sandbox identity not configured"}+ return ResolveAccess{}, &ResolveAccessError{Status: http.StatusServiceUnavailable, Reason: "sandbox identity unavailable"}})rec = h.postResolve(validResolveBody())require.Equal(t, http.StatusServiceUnavailable, rec.Code)- require.Equal(t, "sandbox identity not configured", strings.TrimSpace(rec.Body.String()))+ require.Equal(t, "sandbox identity unavailable", strings.TrimSpace(rec.Body.String()))// A vault that does not exist is a binding-level 404.empty := testResolverReadyStore()@@ -562,6 +565,33 @@ func TestResolveHandlerClientCachedPerEndpoint(t *testing.T) {require.Len(t, h.client.recorded(), 2)}+func TestResolveHandlerClientCacheBounded(t *testing.T) {+ // The cache is never evicted; past the cap, clients are rebuilt per+ // request instead of growing the map without bound.+ h := newResolveHarness(t)+ h.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}+ h.client.unblock()+ // Rotate the captured endpoint past the cap by swapping the credential.+ for i := 0; i <= maxCachedResolverClients; i++ {+ _, err := h.store.Patch(MutationRequest{Credentials: &CredentialMutationSet{Replace: []Credential{{+ Name: "spi-signer",+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": fmt.Sprintf("unix:///run/spi/%d.sock", i)}),+ }}}}, testExchangePolicy(t))+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, h.postResolve(validResolveBody()).Code)+ }+ require.Len(t, h.handler.clients, maxCachedResolverClients, "cache must not exceed the cap")+ require.Equal(t, maxCachedResolverClients+1, h.newCalls)+ // An endpoint still inside the cache keeps reusing its client.+ _, err := h.store.Patch(MutationRequest{Credentials: &CredentialMutationSet{Replace: []Credential{{+ Name: "spi-signer",+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": "unix:///run/spi/0.sock"}),+ }}}}, testExchangePolicy(t))+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, h.postResolve(validResolveBody()).Code)+ require.Equal(t, maxCachedResolverClients+1, h.newCalls, "cached endpoint must not rebuild")+}+func TestResolverConfigFromEnvWiring(t *testing.T) {t.Setenv(constants.EnvCredentialResolverTimeout, "5")t.Setenv(constants.EnvCredentialResolverAuth, "https://resolver.internal:8443=token-1")diff --git a/components/egress/pkg/credentialvault/source_exchange.go b/components/egress/pkg/credentialvault/source_exchange.goindex 7b98c7045..eaa42048b 100644--- a/components/egress/pkg/credentialvault/source_exchange.go+++ b/components/egress/pkg/credentialvault/source_exchange.go@@ -83,6 +83,13 @@ func validateResolverEndpoint(endpoint string) (string, error) {if parsed.RawQuery != "" || parsed.Fragment != "" || parsed.RawFragment != "" {return "", fmt.Errorf("exchange credential endpoint %q must not carry a query or fragment", endpoint)}+ // Align with the transport-side endpoint validator+ // (parseResolverEndpoint): a path prefix the resolver client can+ // never construct from must fail at vault admission, not surface as+ // per-request 503s. A bare "/" is the empty prefix and stays valid.+ if path := parsed.EscapedPath(); path != "/" && strings.HasSuffix(path, "/") {+ return "", fmt.Errorf("exchange credential endpoint %q path prefix must not end with /", endpoint)+ }return endpoint, nildefault:return "", fmt.Errorf("exchange credential endpoint %q must use the unix:/// or https:// scheme", endpoint)diff --git a/components/egress/pkg/credentialvault/source_exchange_test.go b/components/egress/pkg/credentialvault/source_exchange_test.goindex 4ecdb3ced..082f38084 100644--- a/components/egress/pkg/credentialvault/source_exchange_test.go+++ b/components/egress/pkg/credentialvault/source_exchange_test.go@@ -28,6 +28,7 @@ func TestExchangeSourceFactoryAcceptsSupportedEndpoints(t *testing.T) {"https://header-resolver.internal","https://resolver.internal:8443","https://resolver.internal/prefix",+ "https://resolver.internal/", // bare "/" is the empty prefix on the wire} {t.Run(endpoint, func(t *testing.T) {source, err := NewSourceRegistry().Create(mustMarshal(map[string]string{"type": "exchange", "endpoint": endpoint}))@@ -50,6 +51,11 @@ func TestExchangeSourceFactoryRejects(t *testing.T) {{"port zero", `{"type":"exchange","endpoint":"https://resolver.internal:0"}`},{"query string", `{"type":"exchange","endpoint":"https://resolver.internal/prefix?debug=1"}`},{"fragment", `{"type":"exchange","endpoint":"https://resolver.internal/prefix#section"}`},+ // The transport-side validator (parseResolverEndpoint) rejects a+ // trailing-slash prefix; admission must agree so the vault write+ // fails instead of every resolve turning into a 503.+ {"https trailing slash prefix", `{"type":"exchange","endpoint":"https://resolver.corp/api/"}`},+ {"https trailing slash only path", `{"type":"exchange","endpoint":"https://resolver.corp/api//"}`},{"unix relative path", `{"type":"exchange","endpoint":"unix://spi.sock"}`},{"unix empty path", `{"type":"exchange","endpoint":"unix:///"}`},{"unknown field", `{"type":"exchange","endpoint":"unix:///run/spi.sock","value":"secret"}`},diff --git a/components/egress/policy_server.go b/components/egress/policy_server.goindex 07e3d81e4..df8088ff8 100644--- a/components/egress/policy_server.go+++ b/components/egress/policy_server.go@@ -657,7 +657,7 @@ func (s *policyServer) resolveVaultAccess(_ *http.Request) (credentialvault.Resoif sandboxID == "" {return credentialvault.ResolveAccess{}, &credentialvault.ResolveAccessError{Status: http.StatusServiceUnavailable,- Reason: "sandbox identity not configured",+ Reason: "sandbox identity unavailable",}}return credentialvault.ResolveAccess{SandboxID: sandboxID, Store: s.credentialVault}, nil