Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

feat(egress): OSEP-0025 T2b credential-vault _resolve endpoint

高然1f545b9323ea
diff --git a/components/egress/credential_vault_handler_test.go b/components/egress/credential_vault_handler_test.go
index 4b9f817e9..cacaeac74 100644
--- a/components/egress/credential_vault_handler_test.go
+++ b/components/egress/credential_vault_handler_test.go
@@ -105,7 +105,7 @@ func TestCredentialVaultActiveUnixSocketReturnsSnapshot(t *testing.T) {
require.NoError(t, os.RemoveAll(tmpDir))
})
socketPath := filepath.Join(tmpDir, "credential-proxy", "active.sock")
- _, cleanup, err := credentialvault.StartActiveSocketServerRequestAware(srv.handleCredentialVaultActive, socketPath, -1)
+ _, cleanup, err := credentialvault.StartActiveSocketServerRequestAware(srv.handleCredentialVaultActive, nil, socketPath, -1)
require.NoError(t, err)
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
diff --git a/components/egress/fastsandbox_actions.go b/components/egress/fastsandbox_actions.go
index 5c0f9b1a8..b4f9a1d2d 100644
--- a/components/egress/fastsandbox_actions.go
+++ b/components/egress/fastsandbox_actions.go
@@ -601,7 +601,7 @@ func (s *fastSandboxPolicyServer) applySetBinding(ctx context.Context, env *acti
installStarted := time.Now()
// Record even failed first installs: partial kernel effects otherwise have
// no network identity for a later same-fence retry or changed-fence rebind.
- s.recordBindingState(subj, att)
+ s.recordBindingState(subj, att, env.Sandbox.Name)
var victims []subject.Subject
state, err := s.reg.RegisterAndEnforce(subj, subject.SubjectKey{SourceIP: att.IP}, fence, func() error {
return s.OnRegistered(subj, att)
diff --git a/components/egress/fastsandbox_mitm.go b/components/egress/fastsandbox_mitm.go
index 90844f875..4f8ca6998 100644
--- a/components/egress/fastsandbox_mitm.go
+++ b/components/egress/fastsandbox_mitm.go
@@ -126,7 +126,10 @@ func startFastSandboxActiveSocket(ctx context.Context, srv *fastSandboxPolicySer
log.Fatalf("lookup credential proxy user %q: %v (ensure this user exists in the image)", mitmproxy.RunAsUser, err)
}
socketPath := fastSandboxActiveSocketPath()
- activeSrv, cleanup, err := credentialvault.StartActiveSocketServerRequestAware(srv.handleCredentialVaultActive, socketPath, int(mitmGID))
+ activeSrv, cleanup, err := credentialvault.StartActiveSocketServerRequestAware(
+ srv.handleCredentialVaultActive,
+ credentialvault.NewResolveHandler(srv.resolveVaultAccess),
+ socketPath, int(mitmGID))
if err != nil {
log.Fatalf("credential vault active socket: %v", err)
}
diff --git a/components/egress/fastsandbox_resolve_test.go b/components/egress/fastsandbox_resolve_test.go
new file mode 100644
index 000000000..c3e1b20a6
--- /dev/null
+++ b/components/egress/fastsandbox_resolve_test.go
@@ -0,0 +1,418 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// 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 main
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/alibaba/opensandbox/egress/pkg/actionhandler"
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+ "github.com/alibaba/opensandbox/egress/pkg/credentialvault"
+ "github.com/alibaba/opensandbox/egress/pkg/subject"
+)
+
+// bindBodyWithName builds a SET_BINDING envelope whose SandboxRef.Name is the
+// wire sandboxId recorded for the resolve path.
+func bindBodyWithName(t *testing.T, uid, name, ip, runtimeID, attID string, specGen uint64, input *string) string {
+ t.Helper()
+ body := bindBody(t, uid, ip, runtimeID, attID, specGen, input)
+ var env actionhandler.Envelope
+ require.NoError(t, json.Unmarshal([]byte(body), &env))
+ env.Sandbox.Name = name
+ raw, err := json.Marshal(env)
+ require.NoError(t, err)
+ return string(raw)
+}
+
+const resolveTestPolicy = `{"defaultAction":"deny","egress":[{"action":"allow","target":"api.internal.example.com"}]}`
+
+// bindNamedAndReady drives a subject to active with a SET_BINDING whose
+// SandboxRef.Name is the wire sandboxId the resolve path must use.
+func bindNamedAndReady(t *testing.T, srv *fastSandboxPolicyServer, uid, name, ip, runtimeID, attID string, specGen uint64) subject.Subject {
+ t.Helper()
+ rec := doAction(t, srv, bindBodyWithName(t, uid, name, ip, runtimeID, attID, specGen, strPtr(resolveTestPolicy)))
+ require.Equal(t, http.StatusOK, rec.Code)
+ rec = doAction(t, srv, hookBody(t, uid, runtimeID, attID, constants.HookDataPlaneReady))
+ require.Equal(t, http.StatusOK, rec.Code)
+ return subject.FromSandboxUID(uid)
+}
+
+// fakeResolverServer serves the egress→resolver contract over a real unix
+// socket: deterministic headers keyed on the request parts (mirroring the
+// tests/resolver stub) plus optional per-request delay.
+type fakeResolverServer struct {
+ listener net.Listener
+ server *httptest.Server
+ requests chan resolveServerRequest
+ delay time.Duration
+}
+
+type resolveServerRequest struct {
+ Subject string
+ Credential string
+ Binding string
+ Authority string
+ Path string
+}
+
+func startFakeResolverServer(t *testing.T, delay time.Duration) *fakeResolverServer {
+ t.Helper()
+ // Short temp dir: AF_UNIX sun_path is capped near 104 bytes and the
+ // default testing temp dirs exceed that on macOS.
+ dir, err := os.MkdirTemp("", "osbr-resolver-*")
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ listener, err := net.Listen("unix", dir+"/resolver.sock")
+ require.NoError(t, err)
+ fake := &fakeResolverServer{listener: listener, requests: make(chan resolveServerRequest, 64), delay: delay}
+ mux := http.NewServeMux()
+ mux.HandleFunc("/resolve", func(w http.ResponseWriter, r *http.Request) {
+ var document struct {
+ Subject string `json:"subject"`
+ Credential string `json:"credential"`
+ Binding string `json:"binding"`
+ Destination struct {
+ Scheme string `json:"scheme"`
+ Authority string `json:"authority"`
+ SNI string `json:"sni"`
+ } `json:"destination"`
+ Request struct {
+ Method string `json:"method"`
+ Host string `json:"host"`
+ Path string `json:"path"`
+ } `json:"request"`
+ }
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&document))
+ fake.requests <- resolveServerRequest{
+ Subject: document.Subject,
+ Credential: document.Credential,
+ Binding: document.Binding,
+ Authority: document.Destination.Authority,
+ Path: document.Request.Path,
+ }
+ if fake.delay > 0 {
+ time.Sleep(fake.delay)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(fmt.Sprintf(
+ `{"headers":{"x-test-subject":%q,"authorization":"Bearer test-%s"},"redactions":{"authorization":["Bearer test-%s"]}}`,
+ document.Subject, document.Credential, document.Credential)))
+ })
+ server := &httptest.Server{Listener: listener, Config: &http.Server{Handler: mux}}
+ server.Start()
+ t.Cleanup(server.Close)
+ fake.server = server
+ return fake
+}
+
+func (f *fakeResolverServer) endpoint() string {
+ return "unix://" + f.listener.Addr().String()
+}
+
+// seedExchangeVault installs an exchange binding on the subject's vault.
+func seedExchangeVault(t *testing.T, srv *fastSandboxPolicyServer, s subject.Subject, reg *subject.MemoryRegistry, endpoint string) {
+ t.Helper()
+ vault := srv.vaultFor(s)
+ require.NotNil(t, vault)
+ _, err := vault.Create(credentialvault.CreateRequest{
+ Credentials: []credentialvault.Credential{{
+ Name: "spi-signer",
+ Source: json.RawMessage(`{"type":"exchange","endpoint":"` + endpoint + `"}`),
+ }},
+ Bindings: []credentialvault.Binding{{
+ Name: "internal-api",
+ Match: credentialvault.Match{Hosts: []string{"api.internal.example.com"}, Methods: []string{"GET"}, Paths: []string{"/*"}},
+ Auth: credentialvault.Auth{Credential: "spi-signer"},
+ }},
+ }, reg.EffectivePolicy(s))
+ require.NoError(t, err)
+}
+
+func fastSandboxResolveRequest(ip string) *http.Request {
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve?clientIp="+ip, strings.NewReader(
+ `{"binding":"internal-api","sni":"api.internal.example.com",`+
+ `"request":{"scheme":"https","host":"api.internal.example.com","port":443,"method":"GET","path":"/v1/foo"}}`))
+ req.Header.Set("Content-Type", "application/json")
+ return req
+}
+
+// resolveHandlerFor builds the production resolve endpoint around the server.
+func resolveHandlerFor(srv *fastSandboxPolicyServer) http.Handler {
+ return credentialvault.NewResolveHandler(srv.resolveVaultAccess)
+}
+
+func TestFastSandboxResolveSubjectDerivation(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ fake := startFakeResolverServer(t, 0)
+
+ // Wire subject = SandboxRef.Name (sandboxId), not the internal UID.
+ const sandboxName = "fsb-wire-42"
+ s := bindNamedAndReady(t, srv, "uid-1", sandboxName, testIP, testFenceR, testFenceA, 1)
+
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest(testIP))
+ require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
+
+ served := <-fake.requests
+ require.Equal(t, sandboxName, served.Subject, "wire subject must be the sandboxId, never the internal UID")
+ require.Equal(t, "spi-signer", served.Credential)
+ require.Equal(t, "internal-api", served.Binding)
+ require.Equal(t, "api.internal.example.com:443", served.Authority)
+ require.Equal(t, "/v1/foo", served.Path)
+
+ var document struct {
+ Headers []struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ } `json:"headers"`
+ }
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &document))
+ values := map[string]string{}
+ for _, header := range document.Headers {
+ values[header.Name] = header.Value
+ }
+ require.Equal(t, sandboxName, values["x-test-subject"])
+}
+
+func TestFastSandboxResolveSubjectUnknownIPs(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ fake := startFakeResolverServer(t, 0)
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-a", testIP, testFenceR, testFenceA, 1)
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ cases := []struct {
+ name string
+ target string
+ status int
+ message string
+ }{
+ {"unknown ip", "10.0.0.99", http.StatusNotFound, "no subject for clientIp"},
+ {"missing clientIp", "", http.StatusBadRequest, "clientIp query parameter required"},
+ {"malformed clientIp", "not-an-ip", http.StatusBadRequest, "invalid clientIp"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ request := fastSandboxResolveRequest(tc.target)
+ if tc.target == "" {
+ request = httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", strings.NewReader(
+ `{"binding":"internal-api","sni":"api.internal.example.com",`+
+ `"request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`))
+ request.Header.Set("Content-Type", "application/json")
+ }
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, request)
+ require.Equal(t, tc.status, recorder.Code)
+ require.Contains(t, recorder.Body.String(), tc.message)
+ })
+ }
+}
+
+func TestFastSandboxResolveAttachmentIPMismatch(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ fake := startFakeResolverServer(t, 0)
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-a", testIP, testFenceR, testFenceA, 1)
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ // A second subject registered at another IP: dispatch by IP must not
+ // cross the two subjects' vaults.
+ s2 := bindNamedAndReady(t, srv, "uid-2", "fsb-b", "10.0.0.9", "r-2", "a-2", 1)
+ seedExchangeVault(t, srv, s2, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest("10.0.0.9"))
+ require.Equal(t, http.StatusOK, recorder.Code)
+ served := <-fake.requests
+ require.Equal(t, "fsb-b", served.Subject)
+}
+
+func TestFastSandboxResolveTakeoverInvalidatesInFlight(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ fake := startFakeResolverServer(t, 1500*time.Millisecond)
+
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-original", testIP, testFenceR, testFenceA, 1)
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ completed := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest(testIP))
+ completed <- recorder
+ }()
+
+ // Wait until the resolver call is in flight, then rebind the slot: a
+ // successor SET_BINDING (new fence, new sandboxId) takes the subject over
+ // while the old identity's resolution is still running.
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) && len(fake.requests) == 0 {
+ time.Sleep(10 * time.Millisecond)
+ }
+ require.Len(t, fake.requests, 1)
+ <-fake.requests
+ takeover := doAction(t, srv, bindBodyWithName(t, "uid-1", "fsb-successor", testIP, "runtime-2", "attachment-2", 2, strPtr(resolveTestPolicy)))
+ require.Equal(t, http.StatusOK, takeover.Code)
+
+ select {
+ case recorder := <-completed:
+ require.Equal(t, http.StatusConflict, recorder.Code)
+ require.Equal(t, "resolution invalidated", strings.TrimSpace(recorder.Body.String()))
+ case <-time.After(10 * time.Second):
+ t.Fatal("resolve did not complete")
+ }
+}
+
+func TestFastSandboxResolveFailureLeavesPersistentStateUntouched(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ // A resolver endpoint that accepts nothing: every call is unavailable.
+ deadDir, deadErr := os.MkdirTemp("", "osbr-dead-*")
+ require.NoError(t, deadErr)
+ t.Cleanup(func() { _ = os.RemoveAll(deadDir) })
+ deadSocket := deadDir + "/dead.sock"
+ listener, err := net.Listen("unix", deadSocket)
+ require.NoError(t, err)
+ dead := &httptest.Server{Listener: listener, Config: &http.Server{Handler: http.NotFoundHandler()}}
+ dead.Start()
+ t.Cleanup(dead.Close)
+
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-x", testIP, testFenceR, testFenceA, 1)
+ seedExchangeVault(t, srv, s, reg, "unix://"+deadSocket)
+
+ handler := resolveHandlerFor(srv)
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest(testIP))
+ require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
+
+ // Red line: resolve failures never touch degraded / unknown / the sticky
+ // recovery latch — that is disk-indeterminate semantics only.
+ srv.mu.Lock()
+ entry, hasEntry := srv.vaults[s]
+ rebind := srv.rebinds[s]
+ srv.mu.Unlock()
+ require.True(t, hasEntry)
+ require.Empty(t, entry.degraded)
+ require.False(t, entry.vaultStateUnknown)
+ require.Nil(t, rebind)
+ require.Nil(t, srv.vaultRecovery.Load(), "recovery latch must stay unset")
+ health := httptest.NewRecorder()
+ srv.handleHealthz(health, httptest.NewRequest(http.MethodGet, "/healthz", nil))
+ require.Equal(t, http.StatusOK, health.Code)
+
+ // The vault itself keeps serving snapshots (state is not poisoned).
+ recorder = httptest.NewRecorder()
+ srv.handleCredentialVaultActive(recorder, httptest.NewRequest(http.MethodGet, "/credential-vault/_active?clientIp="+testIP, nil))
+ require.Equal(t, http.StatusOK, recorder.Code)
+}
+
+func TestFastSandboxResolveSemaphoreSaturationDoesNotBlockActive(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ t.Setenv(constants.EnvCredentialResolverMaxConcurrency, "2")
+ fake := startFakeResolverServer(t, 1200*time.Millisecond)
+
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-sat", testIP, testFenceR, testFenceA, 1)
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ var inFlight atomic.Int32
+ for i := 0; i < 6; i++ {
+ go func() {
+ inFlight.Add(1)
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest(testIP))
+ }()
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) && inFlight.Load() < 6 {
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ // While resolves saturate the semaphore, the non-exchange surface answers
+ // promptly (no shared lock is held across the resolver call).
+ started := time.Now()
+ recorder := httptest.NewRecorder()
+ srv.handleCredentialVaultActive(recorder, httptest.NewRequest(http.MethodGet, "/credential-vault/_active?clientIp="+testIP, nil))
+ require.Equal(t, http.StatusOK, recorder.Code)
+ require.Less(t, time.Since(started), 500*time.Millisecond, "active snapshot must not wait on the resolver semaphore")
+}
+
+func TestFastSandboxResolveWireSubjectRefreshesWithFence(t *testing.T) {
+ srv, reg, _ := fastSandboxTestServer(t)
+ fake := startFakeResolverServer(t, 0)
+
+ bindNamedAndReady(t, srv, "uid-1", "fsb-first", testIP, testFenceR, testFenceA, 1)
+ // Same subject, new fence: SET_BINDING replays with a new sandboxId and
+ // the mirror must refresh (the old name never goes back on the wire).
+ s := bindNamedAndReady(t, srv, "uid-1", "fsb-second", testIP, "runtime-2", "attachment-2", 2)
+ seedExchangeVault(t, srv, s, reg, fake.endpoint())
+
+ handler := resolveHandlerFor(srv)
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, fastSandboxResolveRequest(testIP))
+ require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
+ served := <-fake.requests
+ require.Equal(t, "fsb-second", served.Subject)
+}
+
+// ---------------------------------------------------------------------------
+// Sidecar profile
+// ---------------------------------------------------------------------------
+
+func TestSidecarResolveVaultAccessEnvSubject(t *testing.T) {
+ s := &policyServer{credentialVault: credentialvault.NewStore(nil, nil)}
+
+ // Without the injected identity the endpoint fails closed before any
+ // resolver interaction.
+ t.Setenv(constants.EnvSandboxID, "")
+ _, accessErr := s.resolveVaultAccess(nil)
+ require.NotNil(t, accessErr)
+ require.Equal(t, http.StatusServiceUnavailable, accessErr.Status)
+ require.Equal(t, "sandbox identity not configured", accessErr.Reason)
+
+ t.Setenv(constants.EnvSandboxID, " sbx-sidecar-7 ")
+ access, accessErr := s.resolveVaultAccess(nil)
+ require.Nil(t, accessErr)
+ require.Equal(t, "sbx-sidecar-7", access.SandboxID)
+ require.Same(t, s.credentialVault, access.Store)
+}
+
+func TestPolicyServerResolveSubresourceForbiddenOnTCP(t *testing.T) {
+ s := &policyServer{}
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", nil)
+ rec := httptest.NewRecorder()
+ s.handleCredentialVaultSubresource(rec, req)
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Equal(t, "forbidden", strings.TrimSpace(rec.Body.String()))
+
+ req = httptest.NewRequest(http.MethodGet, "/credential-vault/_resolve", nil)
+ rec = httptest.NewRecorder()
+ s.handleCredentialVaultSubresource(rec, req)
+ require.Equal(t, http.StatusMethodNotAllowed, rec.Code)
+ require.Equal(t, "POST", rec.Header().Get("Allow"))
+}
diff --git a/components/egress/fastsandbox_server.go b/components/egress/fastsandbox_server.go
index 31dee10bd..23d2a41ae 100644
--- a/components/egress/fastsandbox_server.go
+++ b/components/egress/fastsandbox_server.go
@@ -77,6 +77,11 @@ type fastSandboxPolicyServer struct {
// subjAtt records the latest validated registration attempt, including
// failed enforcement, for same-fence comparison and old-IP cleanup.
subjAtt map[subject.Subject]actionhandler.NetworkAttachment
+ // subjSandbox mirrors the SandboxRef.Name (the wire sandboxId, D11) of
+ // the latest SET_BINDING attempt per subject. The resolve path puts this
+ // value on the resolver wire; it is refreshed with the fence and purged
+ // with every other subject mirror.
+ subjSandbox map[subject.Subject]string
// subjFence mirrors the registered fence per subject: the relay paths
// finish registry pre-reads before taking s.mu; no registry lock spans mu.
// The mirror is published after successful registration, and
@@ -155,6 +160,7 @@ func newFastSandboxPolicyServer(ctx context.Context, reg *subject.MemoryRegistry
pendingPolicies: make(map[subject.Subject]*policy.NetworkPolicy),
policies: make(map[subject.Subject]*policyEntry),
subjAtt: make(map[subject.Subject]actionhandler.NetworkAttachment),
+ subjSandbox: make(map[subject.Subject]string),
subjFence: make(map[subject.Subject]subject.Fencing),
gatewayDNSRefs: make(map[subject.Subject]netip.Addr),
dnsRedirectApply: iptables.ReplaceGatewayDNSRedirects,
@@ -389,32 +395,103 @@ func (s *fastSandboxPolicyServer) handleCredentialVaultActive(w http.ResponseWri
http.Error(w, fmt.Sprintf("invalid clientIp %q", raw), http.StatusBadRequest)
return
}
+ result := s.withVaultAccess(ip, func(store *credentialvault.Store, _ string) vaultAccessResult {
+ return vaultAccessResult{respond: captureActiveVaultSnapshot(r, store)}
+ })
+ if result.err != nil {
+ result.err.write(w)
+ return
+ }
+ result.respond(w)
+}
+
+// vaultAccessError is a fixed-vocabulary HTTP failure of the shared
+// clientIp -> subject -> vault derivation.
+type vaultAccessError struct {
+ status int
+ reason string
+}
+
+func (e *vaultAccessError) write(w http.ResponseWriter) {
+ http.Error(w, e.reason, e.status)
+}
+
+// vaultAccessResult carries the outcome of the locked derivation: the
+// subject's store and wire sandboxId, or a failure. respond, when set, was
+// produced under the same s.mu hold (the active-snapshot capture).
+type vaultAccessResult struct {
+ store *credentialvault.Store
+ sandboxID string
+ respond func(http.ResponseWriter)
+ err *vaultAccessError
+}
+
+// withVaultAccess applies the active-vault identity discipline for one client
+// IP — registry pre-read outside the lock, then validation and store
+// derivation under s.mu (lock order registry → s.mu unchanged) — and runs
+// derive under the same hold. It is shared by the _active snapshot path and
+// the _resolve path; the resolve path additionally requires the recorded
+// sandboxId.
+func (s *fastSandboxPolicyServer) withVaultAccess(
+ ip netip.Addr,
+ derive func(store *credentialvault.Store, sandboxID string) vaultAccessResult,
+) vaultAccessResult {
subj, resolved := s.reg.Resolve(subject.SubjectKey{SourceIP: ip})
fence, registered := s.reg.Fence(subj)
- respond := func() func(http.ResponseWriter) {
- s.mu.Lock()
- defer s.mu.Unlock()
- if !resolved {
- return func(w http.ResponseWriter) { http.Error(w, "no subject for clientIp", http.StatusNotFound) }
- }
- if s.subjectRebindingLocked(subj) {
- return func(w http.ResponseWriter) {
- http.Error(w, "subject rebind in progress", http.StatusServiceUnavailable)
- }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !resolved {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusNotFound, "no subject for clientIp"}}
+ }
+ if s.subjectRebindingLocked(subj) {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusServiceUnavailable, "subject rebind in progress"}}
+ }
+ if !registered || !s.fenceMatchesLocked(subj, fence) || s.subjAtt[subj].IP != ip {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusNotFound, "no subject for clientIp"}}
+ }
+ store := s.vaultForLocked(subj, fence)
+ if s.vaultSealedLocked(subj) {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusConflict, "subject vault is sealed"}}
+ }
+ if entry := s.vaults[subj]; entry.vaultStateUnknown {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusServiceUnavailable, "vault state is unknown"}}
+ }
+ return derive(store, s.subjSandbox[subj])
+}
+
+// resolveVaultAccess derives the fast-sandbox resolve access for one request:
+// clientIp -> subject -> fence/IP-validated store plus the wire subject — the
+// sandboxId recorded by the subject's SET_BINDING, never a protocol value.
+// The same derivation runs at recheck; any failure there is a scoped
+// invalidation of the in-flight resolution.
+func (s *fastSandboxPolicyServer) resolveVaultAccess(r *http.Request) (credentialvault.ResolveAccess, *credentialvault.ResolveAccessError) {
+ raw := strings.TrimSpace(r.URL.Query().Get("clientIp"))
+ if raw == "" {
+ return credentialvault.ResolveAccess{}, &credentialvault.ResolveAccessError{
+ Status: http.StatusBadRequest,
+ Reason: "clientIp query parameter required",
}
- if !registered || !s.fenceMatchesLocked(subj, fence) || s.subjAtt[subj].IP != ip {
- return func(w http.ResponseWriter) { http.Error(w, "no subject for clientIp", http.StatusNotFound) }
+ }
+ ip, err := netip.ParseAddr(raw)
+ if err != nil {
+ return credentialvault.ResolveAccess{}, &credentialvault.ResolveAccessError{
+ Status: http.StatusBadRequest,
+ Reason: "invalid clientIp",
}
- store := s.vaultForLocked(subj, fence)
- if s.vaultSealedLocked(subj) {
- return func(w http.ResponseWriter) { http.Error(w, "subject vault is sealed", http.StatusConflict) }
+ }
+ result := s.withVaultAccess(ip, func(store *credentialvault.Store, sandboxID string) vaultAccessResult {
+ if sandboxID == "" {
+ return vaultAccessResult{err: &vaultAccessError{http.StatusServiceUnavailable, "sandbox identity unavailable"}}
}
- if entry := s.vaults[subj]; entry.vaultStateUnknown {
- return func(w http.ResponseWriter) { http.Error(w, "vault state is unknown", http.StatusServiceUnavailable) }
+ return vaultAccessResult{store: store, sandboxID: sandboxID}
+ })
+ if result.err != nil {
+ return credentialvault.ResolveAccess{}, &credentialvault.ResolveAccessError{
+ Status: result.err.status,
+ Reason: result.err.reason,
}
- return captureActiveVaultSnapshot(r, store)
- }()
- respond(w)
+ }
+ return credentialvault.ResolveAccess{SandboxID: result.sandboxID, Store: result.store}, nil
}
// applyPolicy applies a policy to a subject. Ordering: nft FIRST, registry
@@ -520,7 +597,7 @@ func (s *fastSandboxPolicyServer) vaultForLocked(subj subject.Subject, fence sub
}
delete(s.vaults, subj)
}
- v := credentialvault.NewStore(nil, func() bool { return true })
+ v := credentialvault.NewSubjectStore()
e := vaultEntry{store: v, fence: fence, lazyVaultProbe: true}
s.inspectLazyVaultStateLocked(subj, &e)
if s.vaultFiles != nil && s.vaultFiles.isSealed(subj) {
@@ -692,16 +769,20 @@ func (s *fastSandboxPolicyServer) dropSubjectStateLocked(subj subject.Subject) e
delete(s.subjFence, subj)
delete(s.pendingPolicies, subj)
delete(s.subjAtt, subj)
+ delete(s.subjSandbox, subj)
return nil
}
// recordBindingState records a validated network attempt before enforcement.
// A failed initial deny-first may already have kernel effects; retries must
// still compare its network rather than treat missing success metadata as
-// evidence that no rules exist. Called outside the registry lock.
-func (s *fastSandboxPolicyServer) recordBindingState(subj subject.Subject, att actionhandler.NetworkAttachment) {
+// evidence that no rules exist. sandboxName is the envelope's SandboxRef.Name
+// (the wire sandboxId); it refreshes with the attempt. Called outside the
+// registry lock.
+func (s *fastSandboxPolicyServer) recordBindingState(subj subject.Subject, att actionhandler.NetworkAttachment, sandboxName string) {
s.mu.Lock()
s.subjAtt[subj] = att
+ s.subjSandbox[subj] = strings.TrimSpace(sandboxName)
s.mu.Unlock()
}
diff --git a/components/egress/fastsandbox_vault_persist.go b/components/egress/fastsandbox_vault_persist.go
index 0913a8068..88223b78c 100644
--- a/components/egress/fastsandbox_vault_persist.go
+++ b/components/egress/fastsandbox_vault_persist.go
@@ -583,7 +583,7 @@ func (s *fastSandboxPolicyServer) rehydrateVaultReload(subj subject.Subject, fen
delete(s.vaults, subj)
}
entry := vaultEntry{
- store: credentialvault.NewStore(nil, func() bool { return true }), fence: fence,
+ store: credentialvault.NewSubjectStore(), fence: fence,
fileMeta: previousMeta, vaultStateProtected: protectedBefore,
}
fs, err := s.vaultFiles.storeFor(subj)
diff --git a/components/egress/fastsandbox_vault_snapshot.go b/components/egress/fastsandbox_vault_snapshot.go
index 6dc618f24..4a50f6608 100644
--- a/components/egress/fastsandbox_vault_snapshot.go
+++ b/components/egress/fastsandbox_vault_snapshot.go
@@ -402,7 +402,7 @@ func (s *fastSandboxPolicyServer) installImportedVaultLocked(subj subject.Subjec
pol := validation
entry, ok := s.vaults[subj]
if !ok || entry.fence != fence {
- entry = vaultEntry{store: credentialvault.NewStore(nil, func() bool { return true }), fence: fence}
+ entry = vaultEntry{store: credentialvault.NewSubjectStore(), fence: fence}
}
if err := entry.store.Reload(vf.Revision, credentialvault.CreateRequest(body), pol); err != nil {
return err
@@ -420,7 +420,7 @@ func (s *fastSandboxPolicyServer) installImportedVaultLocked(subj subject.Subjec
// validateImportedVault runs the imported revision through the exact Reload
// the live install will use, on a scratch store.
func validateImportedVault(vf credentialvault.VaultFile, body credentialvault.VaultFileBody, pol *policy.NetworkPolicy) error {
- scratch := credentialvault.NewStore(nil, func() bool { return true })
+ scratch := credentialvault.NewSubjectStore()
return scratch.Reload(vf.Revision, credentialvault.CreateRequest(body), pol)
}
diff --git a/components/egress/pkg/credentialvault/active_socket.go b/components/egress/pkg/credentialvault/active_socket.go
index 72e0fdfda..62d5bdc85 100644
--- a/components/egress/pkg/credentialvault/active_socket.go
+++ b/components/egress/pkg/credentialvault/active_socket.go
@@ -32,25 +32,29 @@ func StartActiveSocketServer(
if activeHandler == nil {
return nil, nil, fmt.Errorf("active credential vault handler is required")
}
- return startActiveSocketServer(func(w http.ResponseWriter, _ *http.Request) { activeHandler(w) }, socketPath, socketGID)
+ return startActiveSocketServer(func(w http.ResponseWriter, _ *http.Request) { activeHandler(w) }, nil, socketPath, socketGID)
}
// StartActiveSocketServerRequestAware passes the request to active-vault
// handlers. Sidecar handlers inspect conditional snapshot headers; fast-sandbox
// handlers additionally dispatch clientIp (source IP -> subject -> snapshot).
+// resolveHandler (an http.Handler) serves POST /credential-vault/_resolve;
+// nil keeps the route mounted but forbidden.
func StartActiveSocketServerRequestAware(
activeHandler func(http.ResponseWriter, *http.Request),
+ resolveHandler http.Handler,
socketPath string,
socketGID int,
) (*http.Server, func(context.Context) error, error) {
if activeHandler == nil {
return nil, nil, fmt.Errorf("active credential vault handler is required")
}
- return startActiveSocketServer(activeHandler, socketPath, socketGID)
+ return startActiveSocketServer(activeHandler, resolveHandler, socketPath, socketGID)
}
func startActiveSocketServer(
activeHandler func(http.ResponseWriter, *http.Request),
+ resolveHandler http.Handler,
socketPath string,
socketGID int,
) (*http.Server, func(context.Context) error, error) {
@@ -106,6 +110,18 @@ func startActiveSocketServer(
}
activeHandler(w, r)
})
+ mux.HandleFunc("/credential-vault/_resolve", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", "POST")
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if resolveHandler == nil {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ resolveHandler.ServeHTTP(w, r)
+ })
srv := &http.Server{Handler: mux}
errCh := make(chan error, 1)
diff --git a/components/egress/pkg/credentialvault/active_socket_test.go b/components/egress/pkg/credentialvault/active_socket_test.go
index d4a588b36..2346292d0 100644
--- a/components/egress/pkg/credentialvault/active_socket_test.go
+++ b/components/egress/pkg/credentialvault/active_socket_test.go
@@ -22,6 +22,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -106,7 +107,10 @@ func TestStartActiveSocketServerRequestAwareDispatch(t *testing.T) {
return
}
http.Error(w, "no subject for clientIp", http.StatusNotFound)
- }, socketPath, -1)
+ }, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"headers":[]}`))
+ }), socketPath, -1)
require.NoError(t, err)
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
@@ -125,3 +129,62 @@ func TestStartActiveSocketServerRequestAwareDispatch(t *testing.T) {
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.NotEmpty(t, resp.Status)
}
+
+func TestStartActiveSocketServerResolveRoute(t *testing.T) {
+ socketPath := shortSocketPath(t)
+ t.Cleanup(func() { _ = os.Remove(socketPath) })
+ _, cleanup, err := StartActiveSocketServerRequestAware(
+ func(http.ResponseWriter, *http.Request) {},
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"revision":1}`))
+ }), socketPath, -1)
+ require.NoError(t, err)
+ defer func() {
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ require.NoError(t, cleanup(shutdownCtx))
+ }()
+
+ resp, body := httpPostUnix(t, socketPath, "/credential-vault/_resolve", "application/json", `{}`)
+ require.Equal(t, http.StatusOK, resp.StatusCode)
+ require.Equal(t, `{"revision":1}`, body)
+
+ // Non-POST on the same path is 405 with an Allow header.
+ resp, _ = httpGetUnix(t, socketPath, "/credential-vault/_resolve")
+ require.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode)
+ require.Equal(t, "POST", resp.Header.Get("Allow"))
+}
+
+func TestStartActiveSocketServerResolveHandlerNilForbidden(t *testing.T) {
+ socketPath := shortSocketPath(t)
+ t.Cleanup(func() { _ = os.Remove(socketPath) })
+ _, cleanup, err := StartActiveSocketServerRequestAware(
+ func(http.ResponseWriter, *http.Request) {}, nil, socketPath, -1)
+ require.NoError(t, err)
+ defer func() {
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ require.NoError(t, cleanup(shutdownCtx))
+ }()
+
+ resp, _ := httpPostUnix(t, socketPath, "/credential-vault/_resolve", "application/json", `{}`)
+ require.Equal(t, http.StatusForbidden, resp.StatusCode)
+}
+
+// httpPostUnix performs a POST over a unix socket (the addon's transport).
+func httpPostUnix(t *testing.T, socketPath, target, contentType, body string) (*http.Response, string) {
+ t.Helper()
+ tr := &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return net.Dial("unix", socketPath)
+ },
+ }
+ client := &http.Client{Transport: tr, Timeout: 2 * time.Second}
+ resp, err := client.Post("http://credential-proxy"+target, contentType, strings.NewReader(body))
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ return resp, string(raw)
+}
diff --git a/components/egress/pkg/credentialvault/resolve_handler.go b/components/egress/pkg/credentialvault/resolve_handler.go
new file mode 100644
index 000000000..dd6ebf4bf
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolve_handler.go
@@ -0,0 +1,569 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// 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 credentialvault
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+ "github.com/alibaba/opensandbox/egress/pkg/log"
+ "github.com/alibaba/opensandbox/egress/pkg/telemetry"
+)
+
+// Addon → egress resolve RPC (OSEP-0025 T2b). The addon owns binding
+// evaluation on the active snapshot; this endpoint owns the per-request
+// resolver call. Discipline: capture under the Store read lock, release
+// before the resolver call (a slow resolver must never pin a Store lock),
+// recheck by binding content fingerprint afterwards (D12) — a bare revision
+// cannot detect a same-name replacement or a delete/recreate revision
+// wraparound, and an unrelated mutation must not invalidate.
+
+const maxResolveRequestBytes = 64 << 10
+
+// ResolveAccess is the requesting sandbox's resolve authorization: the wire
+// subject (the egress-authoritative sandboxId, D11) and its vault Store.
+type ResolveAccess struct {
+ SandboxID string
+ Store *Store
+}
+
+// ResolveAccessError is a fixed-vocabulary access failure.
+type ResolveAccessError struct {
+ Status int
+ Reason string
+}
+
+func (e *ResolveAccessError) Error() string { return e.Reason }
+
+// ResolveAccessFunc derives resolve access from the request. It runs once
+// before the resolver call (capture) and once after it (recheck); the subject
+// never comes from the protocol surface and the client IP never crosses the
+// resolver boundary.
+type ResolveAccessFunc func(r *http.Request) (ResolveAccess, *ResolveAccessError)
+
+// ResolveHandler serves POST /credential-vault/_resolve.
+type ResolveHandler struct {
+ access ResolveAccessFunc
+ newClient func(endpoint string) (ResolverClient, error)
+ audit func(event ResolveAuditEvent)
+
+ mu sync.Mutex
+ clients map[string]ResolverClient
+}
+
+// NewResolveHandler builds the resolve endpoint around one access derivation.
+func NewResolveHandler(access ResolveAccessFunc) *ResolveHandler {
+ return &ResolveHandler{
+ access: access,
+ newClient: NewResolverClientFromEnv,
+ audit: defaultResolveAudit,
+ clients: make(map[string]ResolverClient),
+ }
+}
+
+// ResolveAuditEvent is the R10 audit record: names, decision, and target host
+// only — credential values never appear.
+type ResolveAuditEvent struct {
+ Resolution string // resolved | denied | timeout
+ Credential string
+ Binding string
+ TargetHost string
+ Subject string
+ Duration time.Duration
+}
+
+func defaultResolveAudit(event ResolveAuditEvent) {
+ log.Infof("credential_resolve_audit resolution=%s credential=%s binding=%s target_host=%s subject=%s duration_ms=%d",
+ event.Resolution, event.Credential, event.Binding, event.TargetHost, event.Subject, event.Duration.Milliseconds())
+ telemetry.RecordCredentialResolution(event.Resolution, event.Duration.Seconds())
+}
+
+// ServeHTTP implements the §2 contract: strict JSON (no duplicate keys, exact
+// field sets), exact Content-Type, bounded body, fixed error vocabulary, and
+// the capture-release-recheck flow around the resolver call.
+func (h *ResolveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ drainResolveBody(r)
+ w.Header().Set("Allow", http.MethodPost)
+ writeResolveError(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ if contentType := strings.TrimSpace(r.Header.Get("Content-Type")); contentType != "application/json" {
+ drainResolveBody(r)
+ writeResolveError(w, http.StatusBadRequest, "malformed request")
+ return
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, maxResolveRequestBytes+1))
+ if err != nil {
+ writeResolveError(w, http.StatusBadRequest, "malformed request")
+ return
+ }
+ if len(body) > maxResolveRequestBytes {
+ drainResolveBody(r)
+ writeResolveError(w, http.StatusBadRequest, "request too large")
+ return
+ }
+ document, err := decodeResolveRequest(body)
+ if err != nil {
+ writeResolveError(w, http.StatusBadRequest, "malformed request")
+ return
+ }
+ destination, frame, targetErr := buildResolveTarget(document)
+ if targetErr != nil {
+ writeResolveError(w, targetErr.status, targetErr.reason)
+ return
+ }
+
+ started := time.Now()
+ event := ResolveAuditEvent{Binding: document.Binding, TargetHost: frame.Host}
+ outcome := telemetry.ResolutionOutcomeDenied
+ defer func() {
+ event.Resolution = outcome
+ event.Duration = time.Since(started)
+ h.audit(event)
+ }()
+
+ access, accessErr := h.access(r)
+ if accessErr != nil {
+ writeResolveError(w, accessErr.Status, accessErr.Reason)
+ return
+ }
+ event.Subject = access.SandboxID
+ if access.Store == nil {
+ writeResolveError(w, http.StatusNotFound, "binding not found")
+ return
+ }
+ capture, err := access.Store.CaptureResolve(document.Binding)
+ if err != nil {
+ writeResolveError(w, http.StatusNotFound, "binding not found")
+ return
+ }
+ event.Credential = capture.Credential
+
+ client, err := h.clientFor(capture.Endpoint)
+ if err != nil {
+ log.Warnf("credential resolver client unavailable: %v", err)
+ writeResolveError(w, http.StatusServiceUnavailable, "resolver unavailable")
+ return
+ }
+ decision, err := client.Resolve(r.Context(), ResolveInput{
+ Subject: access.SandboxID,
+ Credential: capture.Credential,
+ Binding: document.Binding,
+ Destination: destination,
+ Request: frame,
+ })
+ if err != nil || decision == nil {
+ if err == nil {
+ err = resolverErrorf(ResolverUnavailable, "empty decision")
+ }
+ status, reason, timedOut := resolveFailureResponse(err)
+ if timedOut {
+ outcome = telemetry.ResolutionOutcomeTimeout
+ }
+ writeResolveError(w, status, reason)
+ return
+ }
+
+ // Recheck (D12): the resolver call ran without any lock held. Any
+ // identity change (subject replaced, store replaced) or captured-state
+ // change (binding or credential content, vault deleted) discards the
+ // resolved headers — never serve credentials resolved under state the
+ // caller no longer owns.
+ recheckAccess, accessErr := h.access(r)
+ if accessErr != nil ||
+ recheckAccess.SandboxID != access.SandboxID ||
+ recheckAccess.Store != access.Store {
+ writeResolveError(w, http.StatusConflict, "resolution invalidated")
+ return
+ }
+ recheck, err := recheckAccess.Store.CaptureResolve(document.Binding)
+ if err != nil || recheck.Fingerprint != capture.Fingerprint {
+ writeResolveError(w, http.StatusConflict, "resolution invalidated")
+ return
+ }
+
+ outcome = telemetry.ResolutionOutcomeResolved
+ 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.
+func (h *ResolveHandler) clientFor(endpoint string) (ResolverClient, error) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if client, ok := h.clients[endpoint]; ok {
+ return client, nil
+ }
+ client, err := h.newClient(endpoint)
+ if err != nil {
+ return nil, err
+ }
+ h.clients[endpoint] = client
+ return client, nil
+}
+
+// resolveFailureResponse maps T2a error classes to the §2 status table.
+func resolveFailureResponse(err error) (status int, reason string, timedOut bool) {
+ var resolverErr *ResolverError
+ if !errors.As(err, &resolverErr) {
+ return http.StatusServiceUnavailable, "resolver unavailable", false
+ }
+ switch resolverErr.Kind {
+ case ResolverTimeout:
+ return http.StatusGatewayTimeout, "resolver timeout", true
+ case ResolverDenied:
+ return http.StatusForbidden, "forbidden", false
+ case ResolverInvalidResponse:
+ return http.StatusBadRequest, "invalid resolver response", false
+ case ResolverInvalidRequest:
+ return http.StatusBadRequest, "malformed request", false
+ default:
+ return http.StatusServiceUnavailable, "resolver unavailable", false
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Request decoding and target construction
+// ---------------------------------------------------------------------------
+
+type resolveEndpointRequest struct {
+ Binding string
+ SNI string
+ Request resolveEndpointHTTPRequest
+}
+
+type resolveEndpointHTTPRequest struct {
+ Scheme string
+ Host string
+ Port int
+ Method string
+ Path string
+}
+
+// decodeResolveRequest strictly decodes the addon request: exact field sets,
+// unique keys, no trailing data, no null scalars.
+func decodeResolveRequest(data []byte) (resolveEndpointRequest, error) {
+ fields, err := strictJSONObject(data)
+ if err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if len(fields) != 3 {
+ return resolveEndpointRequest{}, errors.New("resolve request requires exactly binding, sni, request")
+ }
+ document := resolveEndpointRequest{}
+ if document.Binding, err = decodeStrictStringField(fields, "binding"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if document.SNI, err = decodeStrictStringField(fields, "sni"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ requestRaw, ok := fields["request"]
+ if !ok {
+ return resolveEndpointRequest{}, errors.New("request field required")
+ }
+ requestFields, err := strictJSONObject(requestRaw)
+ if err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ for name := range requestFields {
+ if name != "scheme" && name != "host" && name != "port" && name != "method" && name != "path" {
+ return resolveEndpointRequest{}, errors.New("request carries an unknown field")
+ }
+ }
+ if len(requestFields) < 4 {
+ return resolveEndpointRequest{}, errors.New("request requires scheme, host, method, path and optional port")
+ }
+ if document.Request.Scheme, err = decodeStrictStringField(requestFields, "scheme"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if document.Request.Host, err = decodeStrictStringField(requestFields, "host"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if document.Request.Method, err = decodeStrictStringField(requestFields, "method"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if document.Request.Path, err = decodeStrictStringField(requestFields, "path"); err != nil {
+ return resolveEndpointRequest{}, err
+ }
+ if portRaw, ok := requestFields["port"]; ok {
+ if err := json.Unmarshal(bytes.TrimSpace(portRaw), &document.Request.Port); err != nil {
+ return resolveEndpointRequest{}, errors.New("port must be an integer")
+ }
+ }
+ return document, nil
+}
+
+func decodeStrictStringField(fields map[string]json.RawMessage, name string) (string, error) {
+ raw, ok := fields[name]
+ if !ok {
+ return "", fmt.Errorf("%s field required", name)
+ }
+ trimmed := bytes.TrimSpace(raw)
+ if len(trimmed) == 0 || trimmed[0] != '"' {
+ return "", fmt.Errorf("%s must be a string", name)
+ }
+ var value string
+ if err := json.Unmarshal(trimmed, &value); err != nil {
+ return "", fmt.Errorf("%s must be a string", name)
+ }
+ return value, nil
+}
+
+// buildResolveTarget validates and normalizes the outbound frame and applies
+// the SNI gate: the resolver's proof binds to the destination, so the
+// client-visible host must equal the connection's SNI (403 otherwise).
+func buildResolveTarget(document resolveEndpointRequest) (ResolveDestination, ResolveRequestFrame, *resolveRequestError) {
+ badRequest := &resolveRequestError{status: http.StatusBadRequest, reason: "malformed request"}
+ forbidden := &resolveRequestError{status: http.StatusForbidden, reason: "forbidden"}
+
+ binding := strings.TrimSpace(document.Binding)
+ scheme := strings.ToLower(strings.TrimSpace(document.Request.Scheme))
+ if scheme != "http" && scheme != "https" {
+ return ResolveDestination{}, ResolveRequestFrame{}, badRequest
+ }
+ port := document.Request.Port
+ if port == 0 {
+ if scheme == "https" {
+ port = 443
+ } else {
+ port = 80
+ }
+ }
+ if port < 1 || port > 65535 {
+ return ResolveDestination{}, ResolveRequestFrame{}, badRequest
+ }
+ host, err := normalizeCredentialHost(strings.TrimSpace(document.Request.Host))
+ if err != nil {
+ return ResolveDestination{}, ResolveRequestFrame{}, badRequest
+ }
+ sni, err := normalizeCredentialHost(strings.TrimSpace(document.SNI))
+ if err != nil {
+ return ResolveDestination{}, ResolveRequestFrame{}, badRequest
+ }
+ if host != sni {
+ return ResolveDestination{}, ResolveRequestFrame{}, forbidden
+ }
+ method := strings.ToUpper(strings.TrimSpace(document.Request.Method))
+ path := strings.TrimSpace(document.Request.Path)
+ if binding == "" || method == "" || !strings.HasPrefix(path, "/") {
+ return ResolveDestination{}, ResolveRequestFrame{}, badRequest
+ }
+ return ResolveDestination{
+ Scheme: scheme,
+ Authority: host + ":" + strconv.Itoa(port),
+ SNI: sni,
+ }, ResolveRequestFrame{
+ Method: method,
+ Host: host,
+ Path: path,
+ Headers: map[string]string{},
+ }, nil
+}
+
+// resolveRequestError is a fixed-vocabulary request-shape failure.
+type resolveRequestError struct {
+ status int
+ reason string
+}
+
+func drainResolveBody(r *http.Request) {
+ if r.Body == nil {
+ return
+ }
+ _, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxResolveRequestBytes+1))
+}
+
+// ---------------------------------------------------------------------------
+// Response encoding
+// ---------------------------------------------------------------------------
+
+type resolveResponseHeader struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+}
+
+type resolveEndpointResponse struct {
+ Revision int64 `json:"revision"`
+ Binding string `json:"binding"`
+ Headers []resolveResponseHeader `json:"headers"`
+ Redactions []string `json:"redactions"`
+ SuppressHeaders []string `json:"suppressHeaders"`
+}
+
+func writeResolveSuccess(w http.ResponseWriter, revision int64, binding string, decision *ResolverDecision) {
+ names := make([]string, 0, len(decision.Headers))
+ for name := range decision.Headers {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ headers := make([]resolveResponseHeader, 0, len(names))
+ suppress := make([]string, 0, len(decision.Suppress))
+ for name := range decision.Suppress {
+ suppress = append(suppress, name)
+ }
+ sort.Strings(suppress)
+ for _, name := range names {
+ headers = append(headers, resolveResponseHeader{Name: name, Value: decision.Headers[name]})
+ }
+ redactions := decision.Redactions
+ if redactions == nil {
+ redactions = []string{}
+ }
+ writeResolveJSON(w, http.StatusOK, resolveEndpointResponse{
+ Revision: revision,
+ Binding: binding,
+ Headers: headers,
+ Redactions: redactions,
+ SuppressHeaders: suppress,
+ })
+}
+
+func writeResolveError(w http.ResponseWriter, status int, reason string) {
+ http.Error(w, reason, status)
+}
+
+func writeResolveJSON(w http.ResponseWriter, status int, document resolveEndpointResponse) {
+ encoded, err := json.Marshal(document)
+ if err != nil {
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write(encoded)
+}
+
+// ---------------------------------------------------------------------------
+// Store capture (D12)
+// ---------------------------------------------------------------------------
+
+// ResolveCapture is the immutable per-binding resolve state captured under
+// the Store read lock and released before the resolver call. Fingerprint is
+// over the binding content and the referenced credential's exact source
+// 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).
+type ResolveCapture struct {
+ Credential string
+ Endpoint string
+ Revision int64
+ ActiveTag string
+ Fingerprint [sha256.Size]byte
+}
+
+// CaptureResolve captures the exchange binding's resolve inputs: the
+// referenced exchange credential's resolver endpoint plus the content
+// fingerprint. Non-exchange bindings, unknown names, and missing vaults are
+// not resolvable (ErrNotFound).
+func (v *Store) CaptureResolve(bindingName string) (ResolveCapture, error) {
+ v.mu.RLock()
+ defer v.mu.RUnlock()
+ if !v.exists {
+ return ResolveCapture{}, ErrNotFound
+ }
+ binding, ok := v.bindings[bindingName]
+ if !ok || binding.Auth.Type != "" {
+ return ResolveCapture{}, ErrNotFound
+ }
+ credential, ok := v.credentials[binding.Auth.Credential]
+ if !ok || credential.SourceType != "exchange" {
+ return ResolveCapture{}, ErrNotFound
+ }
+ exchange, ok := credential.Source.(*exchangeSource)
+ if !ok {
+ return ResolveCapture{}, ErrNotFound
+ }
+ return ResolveCapture{
+ Credential: credential.Name,
+ Endpoint: exchange.endpoint,
+ Revision: v.revision,
+ ActiveTag: v.activeTag,
+ Fingerprint: resolveFingerprint(binding, credential.raw),
+ }, nil
+}
+
+// resolveFingerprint digests the binding and credential source content. The
+// comparison happens outside any lock; the digest itself is computed under
+// the capturing read lock so it names the exact captured state.
+func resolveFingerprint(binding Binding, credentialRaw json.RawMessage) [sha256.Size]byte {
+ bindingBytes, _ := json.Marshal(binding)
+ h := sha256.New()
+ writeField := func(label string, value []byte) {
+ var length [8]byte
+ binary.BigEndian.PutUint64(length[:], uint64(len(value)))
+ _, _ = h.Write([]byte(label))
+ _, _ = h.Write(length[:])
+ _, _ = h.Write(value)
+ }
+ writeField("binding", bindingBytes)
+ writeField("credential", credentialRaw)
+ return [sha256.Size]byte(h.Sum(nil))
+}
+
+// ---------------------------------------------------------------------------
+// Resolver capability gate wiring (D13)
+// ---------------------------------------------------------------------------
+
+// ResolverConfigFromEnv derives the exchange capability gate from the
+// operator env. A malformed timeout or auth-table value fails its flag closed
+// (exchange vaults are then rejected at admission); absent values keep the
+// documented defaults and count as ready. The returned error is diagnostic
+// only — the config itself is authoritative.
+func ResolverConfigFromEnv() (ResolverConfig, error) {
+ config := ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true}
+ var diag error
+ if raw := strings.TrimSpace(os.Getenv(constants.EnvCredentialResolverTimeout)); raw != "" {
+ seconds, err := strconv.Atoi(raw)
+ if err != nil || seconds < 1 || seconds > 120 {
+ config.TimeoutConfigured = false
+ diag = fmt.Errorf("%s value is not an integer in [1,120]", constants.EnvCredentialResolverTimeout)
+ }
+ }
+ if _, err := ParseResolverAuthEnv(os.Getenv(constants.EnvCredentialResolverAuth)); err != nil {
+ config.AuthTableParsed = false
+ if diag == nil {
+ diag = err
+ }
+ }
+ return config, diag
+}
+
+// NewSubjectStore creates a per-subject store (fast-sandbox profile) with
+// the resolver capability gate derived from the operator env, so a reloaded
+// exchange vault is admitted under the same D13 gate as a fresh write.
+func NewSubjectStore() *Store {
+ store := NewStore(nil, func() bool { return true })
+ config, err := ResolverConfigFromEnv()
+ if err != nil {
+ log.Warnf("credential resolver operator configuration not ready: %v", err)
+ }
+ store.SetResolverConfig(config)
+ return store
+}
diff --git a/components/egress/pkg/credentialvault/resolve_handler_test.go b/components/egress/pkg/credentialvault/resolve_handler_test.go
new file mode 100644
index 000000000..a11843bac
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolve_handler_test.go
@@ -0,0 +1,674 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// 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 credentialvault
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+)
+
+// fakeResolveClient is an in-process ResolverClient: records inputs, blocks
+// each call until release (or returns immediately), and answers with a fixed
+// decision or error.
+type fakeResolveClient struct {
+ mu sync.Mutex
+ inputs []ResolveInput
+ decision *ResolverDecision
+ err error
+ release chan struct{}
+}
+
+func newFakeResolveClient() *fakeResolveClient {
+ return &fakeResolveClient{release: make(chan struct{})}
+}
+
+func (f *fakeResolveClient) Resolve(_ context.Context, input ResolveInput) (*ResolverDecision, error) {
+ f.mu.Lock()
+ f.inputs = append(f.inputs, input)
+ f.mu.Unlock()
+ <-f.release
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.decision, f.err
+}
+
+func (f *fakeResolveClient) recorded() []ResolveInput {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]ResolveInput(nil), f.inputs...)
+}
+
+func (f *fakeResolveClient) unblock() { close(f.release) }
+
+// resolveHarness wires a handler around one store and one fake client.
+type resolveHarness struct {
+ store *Store
+ client *fakeResolveClient
+ handler *ResolveHandler
+ access ResolveAccess
+ audits []ResolveAuditEvent
+ newCalls int
+}
+
+func newResolveHarness(t *testing.T) *resolveHarness {
+ t.Helper()
+ store := testResolverReadyStore()
+ _, createErr := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, createErr)
+ harness := &resolveHarness{
+ store: store,
+ client: newFakeResolveClient(),
+ access: ResolveAccess{SandboxID: "sbx_01HZYEXAMPLE", Store: store},
+ audits: nil,
+ handler: nil,
+ }
+ harness.handler = NewResolveHandler(func(*http.Request) (ResolveAccess, *ResolveAccessError) {
+ return harness.access, nil
+ })
+ harness.handler.newClient = func(string) (ResolverClient, error) {
+ harness.newCalls++
+ return harness.client, nil
+ }
+ harness.handler.audit = func(event ResolveAuditEvent) { harness.audits = append(harness.audits, event) }
+ return harness
+}
+
+// postResolve issues one resolve RPC against the harness handler.
+func (h *resolveHarness) postResolve(body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ h.handler.ServeHTTP(rec, req)
+ return rec
+}
+
+func validResolveBody() string {
+ return `{"binding":"internal-api","sni":"api.internal.example.com",` +
+ `"request":{"scheme":"https","host":"api.internal.example.com","port":443,"method":"GET","path":"/v1/foo"}}`
+}
+
+func TestResolveHandlerHappyPath(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.decision = &ResolverDecision{
+ Headers: map[string]string{"authorization": "Bearer secret-value", "x-signature": "sig"},
+ Suppress: map[string]struct{}{"authorization": {}, "x-signature": {}},
+ Redactions: []string{
+ "Bearer secret-value",
+ "secret-value",
+ "sig",
+ },
+ }
+
+ h.client.unblock()
+ rec := h.postResolve(validResolveBody())
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
+
+ var document resolveEndpointResponse
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &document))
+ require.Equal(t, int64(1), document.Revision)
+ require.Equal(t, "internal-api", document.Binding)
+ require.Equal(t, []resolveResponseHeader{
+ {Name: "authorization", Value: "Bearer secret-value"},
+ {Name: "x-signature", Value: "sig"},
+ }, document.Headers)
+ require.Equal(t, []string{"authorization", "x-signature"}, document.SuppressHeaders)
+ require.Equal(t, []string{"Bearer secret-value", "secret-value", "sig"}, document.Redactions)
+
+ // The wire subject is the resolved sandboxId, the destination carries the
+ // normalized authority (default port), and the frame headers serialize as
+ // an empty object.
+ recorded := h.client.recorded()
+ require.Len(t, recorded, 1)
+ require.Equal(t, "sbx_01HZYEXAMPLE", recorded[0].Subject)
+ require.Equal(t, "spi-signer", recorded[0].Credential)
+ require.Equal(t, "internal-api", recorded[0].Binding)
+ require.Equal(t, ResolveDestination{
+ Scheme: "https",
+ Authority: "api.internal.example.com:443",
+ SNI: "api.internal.example.com",
+ }, recorded[0].Destination)
+ require.Equal(t, ResolveRequestFrame{
+ Method: "GET",
+ Host: "api.internal.example.com",
+ Path: "/v1/foo",
+ Headers: map[string]string{},
+ }, recorded[0].Request)
+
+ require.Equal(t, 1, h.newCalls)
+ require.Len(t, h.audits, 1)
+ require.Equal(t, "resolved", h.audits[0].Resolution)
+ require.Equal(t, "spi-signer", h.audits[0].Credential)
+ require.Equal(t, "internal-api", h.audits[0].Binding)
+ require.Equal(t, "api.internal.example.com", h.audits[0].TargetHost)
+ require.Equal(t, "sbx_01HZYEXAMPLE", h.audits[0].Subject)
+}
+
+func TestResolveHandlerPortAuthorityNormalization(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}
+ h.client.unblock()
+
+ body := `{"binding":"internal-api","sni":"api.internal.example.com",` +
+ `"request":{"scheme":"http","host":"api.internal.example.com","method":"get","path":"/x"}}`
+ rec := h.postResolve(body)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "api.internal.example.com:80", h.client.recorded()[0].Destination.Authority)
+ require.Equal(t, "GET", h.client.recorded()[0].Request.Method)
+
+ body = `{"binding":"internal-api","sni":"api.internal.example.com",` +
+ `"request":{"scheme":"https","host":"API.internal.example.com.","port":8443,"method":"GET","path":"/x"}}`
+ rec = h.postResolve(body)
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Equal(t, "api.internal.example.com:8443", h.client.recorded()[1].Destination.Authority)
+ require.Equal(t, "api.internal.example.com", h.client.recorded()[1].Destination.SNI)
+}
+
+func TestResolveHandlerRequestDiscipline(t *testing.T) {
+ h := newResolveHarness(t)
+ cases := []struct {
+ name string
+ method string
+ typeCT string
+ body string
+ status int
+ message string
+ }{
+ {"wrong method", http.MethodGet, "application/json", validResolveBody(), http.StatusMethodNotAllowed, "method not allowed"},
+ {"wrong content type", http.MethodPost, "text/plain", validResolveBody(), http.StatusBadRequest, "malformed request"},
+ {"charset content type", http.MethodPost, "application/json; charset=utf-8", validResolveBody(), http.StatusBadRequest, "malformed request"},
+ {"missing content type", http.MethodPost, "", validResolveBody(), http.StatusBadRequest, "malformed request"},
+ {"not json", http.MethodPost, "application/json", `nope`, http.StatusBadRequest, "malformed request"},
+ {"duplicate key", http.MethodPost, "application/json",
+ `{"binding":"a","binding":"a","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"duplicate request key", http.MethodPost, "application/json",
+ `{"binding":"a","sni":"api.internal.example.com","request":{"scheme":"https","scheme":"http","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"unknown field", http.MethodPost, "application/json",
+ `{"binding":"a","sni":"api.internal.example.com","extra":1,"request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"unknown request field", http.MethodPost, "application/json",
+ `{"binding":"a","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/","headers":{}}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"missing request", http.MethodPost, "application/json", `{"binding":"a","sni":"api.internal.example.com"}`, http.StatusBadRequest, "malformed request"},
+ {"null binding", http.MethodPost, "application/json",
+ `{"binding":null,"sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"blank binding", http.MethodPost, "application/json",
+ `{"binding":" ","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"bad scheme", http.MethodPost, "application/json",
+ `{"binding":"internal-api","sni":"api.internal.example.com","request":{"scheme":"ftp","host":"api.internal.example.com","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"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"},
+ {"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"},
+ {"ip host", http.MethodPost, "application/json",
+ `{"binding":"internal-api","sni":"10.0.0.5","request":{"scheme":"https","host":"10.0.0.5","method":"GET","path":"/"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"path without slash", http.MethodPost, "application/json",
+ `{"binding":"internal-api","sni":"api.internal.example.com","request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"v1"}}`,
+ http.StatusBadRequest, "malformed request"},
+ {"trailing data", http.MethodPost, "application/json", validResolveBody() + " {}", http.StatusBadRequest, "malformed request"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(tc.method, "/credential-vault/_resolve", strings.NewReader(tc.body))
+ if tc.typeCT != "" {
+ req.Header.Set("Content-Type", tc.typeCT)
+ }
+ rec := httptest.NewRecorder()
+ h.handler.ServeHTTP(rec, req)
+ require.Equal(t, tc.status, rec.Code)
+ require.Equal(t, tc.message, strings.TrimSpace(rec.Body.String()))
+ })
+ }
+
+ // Over-limit bodies stay within the closed status table (400).
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve",
+ strings.NewReader(`{"binding":"`+strings.Repeat("x", maxResolveRequestBytes)+`"}`))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ h.handler.ServeHTTP(rec, req)
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ require.Equal(t, "request too large", strings.TrimSpace(rec.Body.String()))
+
+ // Nothing reached the resolver.
+ require.Empty(t, h.client.recorded())
+}
+
+func TestResolveHandlerSNIGate(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}
+ h.client.unblock()
+
+ body := `{"binding":"internal-api","sni":"other.internal.example.com",` +
+ `"request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/v1/foo"}}`
+ rec := h.postResolve(body)
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Equal(t, "forbidden", strings.TrimSpace(rec.Body.String()))
+ require.Empty(t, h.client.recorded())
+
+ // Case and trailing-dot differences normalize to equality.
+ body = `{"binding":"internal-api","sni":"API.internal.example.com.",` +
+ `"request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/v1/foo"}}`
+ rec = h.postResolve(body)
+ require.Equal(t, http.StatusOK, rec.Code)
+}
+
+func TestResolveHandlerUnknownSubjectsAndBindings(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.unblock()
+
+ rec := h.postResolve(`{"binding":"missing","sni":"api.internal.example.com",` +
+ `"request":{"scheme":"https","host":"api.internal.example.com","method":"GET","path":"/"}}`)
+ require.Equal(t, http.StatusNotFound, rec.Code)
+ require.Equal(t, "binding not found", strings.TrimSpace(rec.Body.String()))
+
+ // A static (non-exchange) binding is not resolvable through the RPC.
+ staticStore := testResolverReadyStore()
+ _, err := staticStore.Create(CreateRequest{
+ Credentials: []Credential{{
+ Name: "inline-cred",
+ Source: mustMarshal(map[string]string{"type": "inline", "value": "v"}),
+ }},
+ Bindings: []Binding{{
+ Name: "static-api",
+ Match: Match{Hosts: []string{"api.internal.example.com"}, Methods: []string{"GET"}, Paths: []string{"/*"}},
+ Auth: Auth{Type: "bearer", Credential: "inline-cred"},
+ }},
+ }, testExchangePolicy(t))
+ require.NoError(t, err)
+ hStatic := newResolveHarness(t)
+ hStatic.access = ResolveAccess{SandboxID: "sbx-static", Store: staticStore}
+ hStatic.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}
+ hStatic.client.unblock()
+ rec = hStatic.postResolve(validResolveBody())
+ require.Equal(t, http.StatusNotFound, rec.Code)
+
+ // 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"}
+ })
+ rec = h.postResolve(validResolveBody())
+ require.Equal(t, http.StatusServiceUnavailable, rec.Code)
+ require.Equal(t, "sandbox identity not configured", strings.TrimSpace(rec.Body.String()))
+
+ // A vault that does not exist is a binding-level 404.
+ empty := testResolverReadyStore()
+ h2 := newResolveHarness(t)
+ h2.access = ResolveAccess{SandboxID: "sbx-x", Store: empty}
+ h2.client.unblock()
+ rec = h2.postResolve(validResolveBody())
+ require.Equal(t, http.StatusNotFound, rec.Code)
+}
+
+// startDelayedResolve launches one resolve RPC whose resolver call blocks
+// until the returned release func, then returns the recorded input snapshot.
+func startDelayedResolve(t *testing.T, h *resolveHarness) (release func(), recorded func() []ResolveInput, done <-chan *httptest.ResponseRecorder) {
+ t.Helper()
+ h.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}
+ completed := make(chan *httptest.ResponseRecorder, 1)
+ go func() { completed <- h.postResolve(validResolveBody()) }()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if len(h.client.recorded()) == 1 {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ require.Len(t, h.client.recorded(), 1, "resolver call must start before mutations")
+ return h.client.unblock, func() []ResolveInput { return h.client.recorded() }, completed
+}
+
+func TestResolveHandlerScopedInvalidationUnrelatedMutationSucceeds(t *testing.T) {
+ h := newResolveHarness(t)
+ release, _, done := startDelayedResolve(t, h)
+
+ // Revision advances (new unrelated credential+binding) while the captured
+ // binding is untouched: the in-flight resolution must still succeed.
+ _, err := h.store.Patch(MutationRequest{
+ Credentials: &CredentialMutationSet{Add: []Credential{{
+ Name: "inline-2",
+ Source: mustMarshal(map[string]string{"type": "inline", "value": "v2"}),
+ }}},
+ Bindings: &BindingMutationSet{Add: []Binding{{
+ Name: "other-api",
+ Match: Match{Hosts: []string{"other.internal.example.com"}, Methods: []string{"GET"}, Paths: []string{"/*"}},
+ Auth: Auth{Type: "bearer", Credential: "inline-2"},
+ }}},
+ }, testCredentialPolicy(t, `{"defaultAction":"deny","egress":[
+ {"action":"allow","target":"api.internal.example.com"},
+ {"action":"allow","target":"other.internal.example.com"}]}`))
+ require.NoError(t, err)
+
+ release()
+ select {
+ case rec := <-done:
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Contains(t, rec.Body.String(), `"revision":1`, "captured revision is reported")
+ case <-time.After(5 * time.Second):
+ t.Fatal("resolve did not complete")
+ }
+}
+
+func TestResolveHandlerScopedInvalidationBindingTouchedFails(t *testing.T) {
+ original := testExchangeVaultRequest()
+ cases := []struct {
+ name string
+ // mutate runs while the resolve call is in flight.
+ mutate func(t *testing.T, store *Store)
+ }{
+ {"binding replaced", func(t *testing.T, store *Store) {
+ replaced := original.Bindings[0]
+ replaced.Match.Paths = []string{"/v2/*"}
+ _, err := store.Patch(MutationRequest{Bindings: &BindingMutationSet{Replace: []Binding{replaced}}}, testExchangePolicy(t))
+ require.NoError(t, err)
+ }},
+ {"binding replaced same revision content identical", func(t *testing.T, store *Store) {
+ // A content-identical replacement does not invalidate.
+ replaced := original.Bindings[0]
+ _, err := store.Patch(MutationRequest{Bindings: &BindingMutationSet{Replace: []Binding{replaced}}}, testExchangePolicy(t))
+ require.NoError(t, err)
+ }},
+ {"binding deleted then recreated different content", func(t *testing.T, store *Store) {
+ _, err := store.Patch(MutationRequest{Bindings: &BindingMutationSet{Delete: []string{"internal-api"}}}, testExchangePolicy(t))
+ require.NoError(t, err)
+ recreated := original.Bindings[0]
+ recreated.Match.Methods = []string{"GET", "POST"}
+ _, err = store.Patch(MutationRequest{Bindings: &BindingMutationSet{Add: []Binding{recreated}}}, testExchangePolicy(t))
+ require.NoError(t, err)
+ }},
+ {"credential replaced", func(t *testing.T, store *Store) {
+ _, err := store.Patch(MutationRequest{Credentials: &CredentialMutationSet{Replace: []Credential{{
+ Name: "spi-signer",
+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": "unix:///run/spi/other.sock"}),
+ }}}}, testExchangePolicy(t))
+ require.NoError(t, err)
+ }},
+ {"vault deleted", func(t *testing.T, store *Store) {
+ require.NoError(t, store.Delete())
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newResolveHarness(t)
+ release, _, done := startDelayedResolve(t, h)
+ tc.mutate(t, h.store)
+ release()
+ select {
+ case rec := <-done:
+ switch tc.name {
+ case "binding replaced same revision content identical":
+ require.Equal(t, http.StatusOK, rec.Code, "identical content is not a replacement")
+ default:
+ require.Equal(t, http.StatusConflict, rec.Code)
+ require.Equal(t, "resolution invalidated", strings.TrimSpace(rec.Body.String()))
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("resolve did not complete")
+ }
+ })
+ }
+}
+
+func TestResolveHandlerSubjectReplacementInvalidates(t *testing.T) {
+ storeA := testResolverReadyStore()
+ _, createErrA := storeA.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, createErrA)
+ storeB := testResolverReadyStore()
+ _, createErrB := storeB.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, createErrB)
+
+ mu := sync.Mutex{}
+ current := ResolveAccess{SandboxID: "sbx-original", Store: storeA}
+ handler := NewResolveHandler(func(*http.Request) (ResolveAccess, *ResolveAccessError) {
+ mu.Lock()
+ defer mu.Unlock()
+ return current, nil
+ })
+ client := newFakeResolveClient()
+ handler.newClient = func(string) (ResolverClient, error) { return client, nil }
+ client.decision = &ResolverDecision{Headers: map[string]string{}, Redactions: []string{}}
+
+ completed := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", strings.NewReader(validResolveBody()))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+ completed <- rec
+ }()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) && len(client.recorded()) == 0 {
+ time.Sleep(5 * time.Millisecond)
+ }
+ require.Len(t, client.recorded(), 1)
+
+ // Takeover: the identity re-derivation now yields a different sandbox /
+ // store — the resolved headers must be discarded.
+ mu.Lock()
+ current = ResolveAccess{SandboxID: "sbx-successor", Store: storeB}
+ mu.Unlock()
+ client.unblock()
+
+ select {
+ case rec := <-completed:
+ require.Equal(t, http.StatusConflict, rec.Code)
+ case <-time.After(5 * time.Second):
+ t.Fatal("resolve did not complete")
+ }
+}
+
+func TestResolveHandlerFailureMapping(t *testing.T) {
+ cases := []struct {
+ kind ResolverErrorKind
+ status int
+ message string
+ outcome string
+ }{
+ {ResolverTimeout, http.StatusGatewayTimeout, "resolver timeout", "timeout"},
+ {ResolverDenied, http.StatusForbidden, "forbidden", "denied"},
+ {ResolverInvalidResponse, http.StatusBadRequest, "invalid resolver response", "denied"},
+ {ResolverRejected, http.StatusServiceUnavailable, "resolver unavailable", "denied"},
+ {ResolverUnavailable, http.StatusServiceUnavailable, "resolver unavailable", "denied"},
+ }
+ for _, tc := range cases {
+ t.Run(string(tc.kind), func(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.err = &ResolverError{Kind: tc.kind}
+ h.client.unblock()
+ rec := h.postResolve(validResolveBody())
+ require.Equal(t, tc.status, rec.Code)
+ require.Equal(t, tc.message, strings.TrimSpace(rec.Body.String()))
+ require.Len(t, h.audits, 1)
+ require.Equal(t, tc.outcome, h.audits[0].Resolution)
+ })
+ }
+
+ // A non-typed error is an operational 503.
+ h := newResolveHarness(t)
+ h.client.err = errors.New("boom")
+ h.client.unblock()
+ rec := h.postResolve(validResolveBody())
+ require.Equal(t, http.StatusServiceUnavailable, rec.Code)
+}
+
+func TestResolveHandlerAuditNeverCarriesValues(t *testing.T) {
+ secret := "super-secret-bearer-value"
+ h := newResolveHarness(t)
+ h.client.decision = &ResolverDecision{
+ Headers: map[string]string{"authorization": "Bearer " + secret},
+ Suppress: map[string]struct{}{"authorization": {}},
+ Redactions: []string{secret},
+ }
+ h.client.unblock()
+
+ rec := h.postResolve(validResolveBody())
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Len(t, h.audits, 1)
+ event := h.audits[0]
+ require.Equal(t, "resolved", event.Resolution)
+ encoded, err := json.Marshal(event)
+ require.NoError(t, err)
+ require.NotContains(t, string(encoded), secret)
+ require.NotContains(t, string(encoded), "Bearer")
+
+ // Denied outcomes carry no values either.
+ h2 := newResolveHarness(t)
+ h2.client.err = &ResolverError{Kind: ResolverTimeout}
+ h2.client.unblock()
+ rec = h2.postResolve(validResolveBody())
+ require.Equal(t, http.StatusGatewayTimeout, rec.Code)
+ encoded, _ = json.Marshal(h2.audits[0])
+ require.NotContains(t, string(encoded), "Bearer")
+}
+
+func TestResolveHandlerClientCachedPerEndpoint(t *testing.T) {
+ h := newResolveHarness(t)
+ h.client.decision = &ResolverDecision{Headers: map[string]string{}, Suppress: map[string]struct{}{}, Redactions: []string{}}
+ h.client.unblock()
+ require.Equal(t, http.StatusOK, h.postResolve(validResolveBody()).Code)
+ require.Equal(t, http.StatusOK, h.postResolve(validResolveBody()).Code)
+ require.Equal(t, 1, h.newCalls, "one endpoint must produce one client")
+ require.Len(t, h.client.recorded(), 2)
+}
+
+func TestResolverConfigFromEnvWiring(t *testing.T) {
+ t.Setenv(constants.EnvCredentialResolverTimeout, "5")
+ t.Setenv(constants.EnvCredentialResolverAuth, "https://resolver.internal:8443=token-1")
+ config, diag := ResolverConfigFromEnv()
+ require.NoError(t, diag)
+ require.True(t, config.Ready())
+
+ t.Setenv(constants.EnvCredentialResolverTimeout, "nope")
+ config, diag = ResolverConfigFromEnv()
+ require.Error(t, diag)
+ require.False(t, config.TimeoutConfigured)
+ require.True(t, config.AuthTableParsed)
+
+ t.Setenv(constants.EnvCredentialResolverTimeout, "5")
+ t.Setenv(constants.EnvCredentialResolverAuth, "https://resolver.internal:8443")
+ config, diag = ResolverConfigFromEnv()
+ require.Error(t, diag)
+ require.False(t, config.AuthTableParsed)
+ require.True(t, config.TimeoutConfigured)
+
+ // Absent values keep defaults and count as ready.
+ t.Setenv(constants.EnvCredentialResolverTimeout, "")
+ t.Setenv(constants.EnvCredentialResolverAuth, "")
+ config, diag = ResolverConfigFromEnv()
+ require.NoError(t, diag)
+ require.True(t, config.Ready())
+}
+
+func TestNewSubjectStoreAdmitsExchangeOnlyWithReadyEnv(t *testing.T) {
+ t.Setenv(constants.EnvCredentialResolverAuth, "https://r=,broken") // malformed table
+ store := NewSubjectStore()
+ _, err := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.ErrorContains(t, err, "exchange credentials are not supported until the credential resolver operator configuration is ready")
+
+ t.Setenv(constants.EnvCredentialResolverAuth, "")
+ store = NewSubjectStore()
+ _, err = store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, err)
+}
+
+// ---------------------------------------------------------------------------
+// Stub-backed end-to-end (tests/resolver/resolver.py): asserts the wire
+// subject, the deterministic signature, timeout and fail-once classes.
+// ---------------------------------------------------------------------------
+
+func TestResolveHandlerStubEndToEnd(t *testing.T) {
+ socketPath := fmt.Sprintf("%s/r.sock", shortTempDir(t))
+ stub := startStubResolver(t, nil, "--uds", socketPath)
+
+ store := testResolverReadyStore()
+ request := testExchangeVaultRequest()
+ request.Credentials = []Credential{{
+ Name: "spi-signer",
+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": strings.Replace(stub.endpoint, "uds://", "unix://", 1)}),
+ }}
+ _, createErr := store.Create(request, testExchangePolicy(t))
+ require.NoError(t, createErr)
+
+ handler := NewResolveHandler(func(*http.Request) (ResolveAccess, *ResolveAccessError) {
+ return ResolveAccess{SandboxID: "sbx_01HZYEXAMPLE", Store: store}, nil
+ })
+ body := validResolveBody()
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+
+ var document resolveEndpointResponse
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &document))
+ headers := map[string]string{}
+ for _, header := range document.Headers {
+ headers[header.Name] = header.Value
+ }
+ expected := stubSignature("sbx_01HZYEXAMPLE", "spi-signer", "internal-api", "api.internal.example.com:443", "/v1/foo")
+ require.Equal(t, expected, headers["x-test-signature"])
+ require.Equal(t, "sbx_01HZYEXAMPLE", headers["x-test-subject"], "wire subject must be the sandboxId (D11)")
+ require.Contains(t, headers, "authorization")
+ require.Contains(t, document.Redactions, headers["authorization"])
+ require.Contains(t, document.SuppressHeaders, "authorization")
+}
+
+func TestResolveHandlerStubTimeout(t *testing.T) {
+ t.Setenv(constants.EnvCredentialResolverTimeout, "1")
+ socketPath := fmt.Sprintf("%s/r.sock", shortTempDir(t))
+ stub := startStubResolver(t, nil, "--uds", socketPath, "--delay", "2000")
+
+ store := testResolverReadyStore()
+ request := testExchangeVaultRequest()
+ request.Credentials = []Credential{{
+ Name: "spi-signer",
+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": strings.Replace(stub.endpoint, "uds://", "unix://", 1)}),
+ }}
+ _, createErr := store.Create(request, testExchangePolicy(t))
+ require.NoError(t, createErr)
+ handler := NewResolveHandler(func(*http.Request) (ResolveAccess, *ResolveAccessError) {
+ return ResolveAccess{SandboxID: "sbx_01HZYEXAMPLE", Store: store}, nil
+ })
+
+ started := time.Now()
+ rec := func() *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/credential-vault/_resolve", strings.NewReader(validResolveBody()))
+ req.Header.Set("Content-Type", "application/json")
+ r := httptest.NewRecorder()
+ handler.ServeHTTP(r, req)
+ return r
+ }()
+ require.Equal(t, http.StatusGatewayTimeout, rec.Code)
+ require.Less(t, time.Since(started), 2*time.Second)
+}
diff --git a/components/egress/pkg/telemetry/metrics.go b/components/egress/pkg/telemetry/metrics.go
index b13cc6d8e..08437e5da 100644
--- a/components/egress/pkg/telemetry/metrics.go
+++ b/components/egress/pkg/telemetry/metrics.go
@@ -40,6 +40,8 @@ var (
nftUpdateFailed metric.Int64Counter
tlsShadowRequests metric.Int64Counter
tlsAdmissionConnections metric.Int64Counter
+ credentialResolutions metric.Int64Counter
+ credentialResolutionDur metric.Float64Histogram
lastNftRuleCount atomic.Int64
)
@@ -189,6 +191,26 @@ func registerEgressMetrics() error {
if err != nil {
return err
}
+ credentialResolutions, err = meter.Int64Counter(
+ "egress.credential.resolutions_total",
+ metric.WithDescription("Credential header resolutions by closed-set outcome (resolved|denied|timeout). "+
+ "Credential and binding names are tenant-provided and are never attached (OSEP-0025 R10/OSEP-0010)."),
+ )
+ if err != nil {
+ return err
+ }
+ credentialResolutionDur, err = meter.Float64Histogram(
+ "egress.credential.resolution.duration",
+ metric.WithDescription("Credential header resolution wall-clock latency, outcome-tagged; "+
+ "bounded by the resolver timeout (max 120s)."),
+ metric.WithUnit("s"),
+ metric.WithExplicitBucketBoundaries(
+ 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120,
+ ),
+ )
+ if err != nil {
+ return err
+ }
_, err = meter.Int64ObservableGauge(
"egress.nftables.rules.count",
@@ -348,3 +370,22 @@ func RecordNftablesUpdateFailed(operation string) {
}
nftUpdateFailed.Add(context.Background(), 1, egressMetricOptWith(attribute.String("operation", operation)))
}
+
+// Closed-set credential resolution outcomes (OSEP-0025 R10). Tenant-provided
+// names are audit-log fields only, never metric dimensions.
+const (
+ ResolutionOutcomeResolved = "resolved"
+ ResolutionOutcomeDenied = "denied"
+ ResolutionOutcomeTimeout = "timeout"
+)
+
+// RecordCredentialResolution records one resolve RPC outcome. outcome must be
+// one of the closed-set constants above.
+func RecordCredentialResolution(outcome string, seconds float64) {
+ if credentialResolutions == nil || credentialResolutionDur == nil {
+ return
+ }
+ opt := egressMetricOptWith(attribute.String("resolution", outcome))
+ credentialResolutions.Add(context.Background(), 1, opt)
+ credentialResolutionDur.Record(context.Background(), seconds, opt)
+}
diff --git a/components/egress/policy_server.go b/components/egress/policy_server.go
index a8898aed9..07e3d81e4 100644
--- a/components/egress/policy_server.go
+++ b/components/egress/policy_server.go
@@ -120,6 +120,13 @@ func startPolicyServer(
} else {
handler.credentialVault = credentialvault.NewStore(mitmGate, func() bool { return strings.TrimSpace(token) != "" })
}
+ // D13 capability gate: derived from the operator env once at assembly;
+ // malformed resolver config fails exchange admission closed.
+ resolverConfig, resolverConfigErr := credentialvault.ResolverConfigFromEnv()
+ if resolverConfigErr != nil {
+ log.Warnf("credential resolver operator configuration not ready: %v", resolverConfigErr)
+ }
+ handler.credentialVault.SetResolverConfig(resolverConfig)
handler.credentialVaultRequireTLS = constants.IsTruthy(os.Getenv(constants.EnvCredentialVaultRequireTLS))
handler.setAlwaysRules(alwaysDeny, alwaysAllow)
if liveRevision {
@@ -149,7 +156,10 @@ func startPolicyServer(
if err != nil {
return nil, nil, fmt.Errorf("lookup credential proxy user %q: %w", mitmproxy.RunAsUser, err)
}
- activeSrv, cleanupActiveSocket, err = credentialvault.StartActiveSocketServerRequestAware(handler.handleCredentialVaultActive, socketPath, int(mitmGID))
+ activeSrv, cleanupActiveSocket, err = credentialvault.StartActiveSocketServerRequestAware(
+ handler.handleCredentialVaultActive,
+ credentialvault.NewResolveHandler(handler.resolveVaultAccess),
+ socketPath, int(mitmGID))
if err != nil {
return nil, nil, fmt.Errorf("credential vault active socket: %w", err)
}
@@ -314,6 +324,16 @@ func (s *policyServer) handleCredentialVaultSubresource(w http.ResponseWriter, r
}
http.Error(w, "forbidden", http.StatusForbidden)
return
+ case path == "_resolve":
+ // Same permission model as _active: the resolve RPC is served only on
+ // the active socket to the mitm addon, never on the TCP surface.
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", "POST")
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
}
if !s.authorize(r) {
@@ -628,6 +648,21 @@ func (s *policyServer) handleCredentialVaultActive(w http.ResponseWriter, r *htt
handleActiveVaultSnapshot(w, r, s.credentialVault)
}
+// resolveVaultAccess derives the sidecar resolve subject: the sandbox
+// identity this egress serves, injected as env at pod creation — never a
+// protocol-supplied value. The store is the sidecar's single vault; the
+// same derivation runs at recheck and is byte-identical.
+func (s *policyServer) resolveVaultAccess(_ *http.Request) (credentialvault.ResolveAccess, *credentialvault.ResolveAccessError) {
+ sandboxID := strings.TrimSpace(os.Getenv(constants.EnvSandboxID))
+ if sandboxID == "" {
+ return credentialvault.ResolveAccess{}, &credentialvault.ResolveAccessError{
+ Status: http.StatusServiceUnavailable,
+ Reason: "sandbox identity not configured",
+ }
+ }
+ return credentialvault.ResolveAccess{SandboxID: sandboxID, Store: s.credentialVault}, nil
+}
+
func (s *policyServer) handleGet(w http.ResponseWriter) {
current := s.proxy.CurrentPolicy()
mode := modeFromPolicy(current)