Skip to content

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

chore(egress): trim T2b resolve comments to match repo terseness

高然519f82eff3f3
diff --git a/components/egress/fastsandbox_server.go b/components/egress/fastsandbox_server.go
index 23d2a41ae..b15eb4abf 100644
--- a/components/egress/fastsandbox_server.go
+++ b/components/egress/fastsandbox_server.go
@@ -77,10 +77,9 @@ 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 mirrors the SET_BINDING SandboxRef.Name (wire sandboxId,
+ // D11); the resolve path puts it on the resolver wire. Refreshed and
+ // purged with subjAtt.
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.
@@ -405,8 +404,8 @@ func (s *fastSandboxPolicyServer) handleCredentialVaultActive(w http.ResponseWri
result.respond(w)
}
-// vaultAccessError is a fixed-vocabulary HTTP failure of the shared
-// clientIp -> subject -> vault derivation.
+// vaultAccessError is a fixed-vocabulary failure of the clientIp → subject →
+// vault derivation.
type vaultAccessError struct {
status int
reason string
@@ -416,9 +415,9 @@ 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).
+// vaultAccessResult is the locked derivation outcome: 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
@@ -426,12 +425,10 @@ type vaultAccessResult struct {
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.
+// withVaultAccess applies the active-vault identity discipline (registry
+// pre-read, then s.mu; lock order registry → s.mu unchanged) and runs derive
+// under the same hold. Shared by the _active and _resolve paths; the resolve
+// path additionally requires the recorded sandboxId.
func (s *fastSandboxPolicyServer) withVaultAccess(
ip netip.Addr,
derive func(store *credentialvault.Store, sandboxID string) vaultAccessResult,
@@ -459,10 +456,9 @@ func (s *fastSandboxPolicyServer) withVaultAccess(
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
+// resolveVaultAccess derives the fast-sandbox resolve access: clientIp →
+// subject → store plus the wire subject (the SET_BINDING-recorded sandboxId,
+// never a protocol value). Runs again at recheck; 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"))
@@ -773,12 +769,10 @@ func (s *fastSandboxPolicyServer) dropSubjectStateLocked(subj subject.Subject) e
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. sandboxName is the envelope's SandboxRef.Name
-// (the wire sandboxId); it refreshes with the attempt. Called outside the
-// registry lock.
+// recordBindingState records a validated network attempt before enforcement
+// (a failed deny-first may already have kernel effects; retries must compare
+// its network). sandboxName is the envelope's SandboxRef.Name — the wire
+// sandboxId. Called outside the registry lock.
func (s *fastSandboxPolicyServer) recordBindingState(subj subject.Subject, att actionhandler.NetworkAttachment, sandboxName string) {
s.mu.Lock()
s.subjAtt[subj] = att
diff --git a/components/egress/pkg/credentialvault/active_socket.go b/components/egress/pkg/credentialvault/active_socket.go
index 62d5bdc85..9a6bd611e 100644
--- a/components/egress/pkg/credentialvault/active_socket.go
+++ b/components/egress/pkg/credentialvault/active_socket.go
@@ -38,8 +38,8 @@ func StartActiveSocketServer(
// 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.
+// resolveHandler serves POST /credential-vault/_resolve; nil mounts the route
+// forbidden.
func StartActiveSocketServerRequestAware(
activeHandler func(http.ResponseWriter, *http.Request),
resolveHandler http.Handler,
diff --git a/components/egress/pkg/credentialvault/resolve_handler.go b/components/egress/pkg/credentialvault/resolve_handler.go
index 9eb3f1fe6..006e907a0 100644
--- a/components/egress/pkg/credentialvault/resolve_handler.go
+++ b/components/egress/pkg/credentialvault/resolve_handler.go
@@ -35,18 +35,16 @@ import (
"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.
+// Addon → egress resolve RPC (OSEP-0025): the addon owns binding evaluation,
+// this endpoint owns the per-request resolver call. Capture under the Store
+// read lock, release before the resolver call, recheck by binding content
+// fingerprint (D12) — a bare revision misses same-name replacement and
+// delete/recreate wraparound, and unrelated mutations 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.
+// ResolveAccess is the requesting sandbox's resolve access: the wire subject
+// (sandboxId, D11) and its vault Store.
type ResolveAccess struct {
SandboxID string
Store *Store
@@ -60,10 +58,9 @@ type ResolveAccessError struct {
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.
+// ResolveAccessFunc derives resolve access from the request; it runs at
+// capture and again at recheck. The subject never comes from the protocol;
+// the client IP never crosses the resolver boundary.
type ResolveAccessFunc func(r *http.Request) (ResolveAccess, *ResolveAccessError)
// ResolveHandler serves POST /credential-vault/_resolve.
@@ -86,7 +83,7 @@ func NewResolveHandler(access ResolveAccessFunc) *ResolveHandler {
}
}
-// ResolveAuditEvent is the R10 audit record: names, decision, and target host
+// ResolveAuditEvent is the R10 audit record: names, decision and target host
// only — credential values never appear.
type ResolveAuditEvent struct {
Resolution string // resolved | denied | timeout
@@ -103,9 +100,9 @@ func defaultResolveAudit(event ResolveAuditEvent) {
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.
+// ServeHTTP serves the OSEP-0025 resolve contract: strict JSON, exact
+// Content-Type, bounded body, fixed error vocabulary, capture-release-
+// recheck.
func (h *ResolveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
drainResolveBody(r)
@@ -190,11 +187,9 @@ func (h *ResolveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
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.
+ // Recheck (D12): discard on any identity change (subject or store
+ // replaced) or captured-state change — never serve credentials resolved
+ // under state the caller no longer owns.
recheckAccess, accessErr := h.access(r)
if accessErr != nil ||
recheckAccess.SandboxID != access.SandboxID ||
@@ -212,14 +207,11 @@ func (h *ResolveHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeResolveSuccess(w, capture.Revision, document.Binding, decision)
}
-// 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.
+// maxCachedResolverClients bounds the never-evicted per-endpoint cache; past
+// the cap, clients are rebuilt per request (construction is parse-only).
const maxCachedResolverClients = 64
-// clientFor caches one ResolverClient per captured endpoint (hot resolvers
-// are few); the env never changes at runtime.
+// clientFor caches one ResolverClient per endpoint; the env never changes.
func (h *ResolveHandler) clientFor(endpoint string) (ResolverClient, error) {
h.mu.Lock()
defer h.mu.Unlock()
@@ -236,7 +228,7 @@ func (h *ResolveHandler) clientFor(endpoint string) (ResolverClient, error) {
return client, nil
}
-// resolveFailureResponse maps T2a error classes to the §2 status table.
+// resolveFailureResponse maps resolver error classes to contract statuses.
func resolveFailureResponse(err error) (status int, reason string, timedOut bool) {
var resolverErr *ResolverError
if !errors.As(err, &resolverErr) {
@@ -256,10 +248,6 @@ func resolveFailureResponse(err error) (status int, reason string, timedOut bool
}
}
-// ---------------------------------------------------------------------------
-// Request decoding and target construction
-// ---------------------------------------------------------------------------
-
type resolveEndpointRequest struct {
Binding string
SNI string
@@ -321,8 +309,7 @@ func decodeResolveRequest(data []byte) (resolveEndpointRequest, error) {
}
if portRaw, ok := requestFields["port"]; ok {
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).
+ // JSON null into an int is a no-op success; reject like the rest.
if bytes.Equal(trimmed, []byte("null")) {
return resolveEndpointRequest{}, errors.New("port must be an integer")
}
@@ -349,9 +336,8 @@ func decodeStrictStringField(fields map[string]json.RawMessage, name string) (st
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).
+// buildResolveTarget normalizes the outbound frame and applies the SNI gate
+// (host != sni → 403): the resolver proof binds to the destination.
func buildResolveTarget(document resolveEndpointRequest) (ResolveDestination, ResolveRequestFrame, *resolveRequestError) {
badRequest := &resolveRequestError{status: http.StatusBadRequest, reason: "malformed request"}
forbidden := &resolveRequestError{status: http.StatusForbidden, reason: "forbidden"}
@@ -413,10 +399,6 @@ func drainResolveBody(r *http.Request) {
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxResolveRequestBytes+1))
}
-// ---------------------------------------------------------------------------
-// Response encoding
-// ---------------------------------------------------------------------------
-
type resolveResponseHeader struct {
Name string `json:"name"`
Value string `json:"value"`
@@ -473,19 +455,11 @@ func writeResolveJSON(w http.ResponseWriter, status int, document resolveEndpoin
_, _ = 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). The active-snapshot
-// tag is deliberately NOT captured: it flips on unrelated mutations and must
-// not gate invalidation.
+// ResolveCapture is the per-binding resolve state captured under the Store
+// read lock and released before the resolver call. Fingerprint digests the
+// binding plus the referenced credential's source: same-name replacement and
+// delete/recreate wraparound are detectable, unrelated mutations do not
+// invalidate (D12). No active-snapshot tag — it flips on unrelated mutations.
type ResolveCapture struct {
Credential string
Endpoint string
@@ -493,10 +467,8 @@ type ResolveCapture struct {
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).
+// CaptureResolve captures an exchange binding's resolve inputs; static
+// 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()
@@ -523,9 +495,8 @@ func (v *Store) CaptureResolve(bindingName string) (ResolveCapture, error) {
}, 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.
+// resolveFingerprint names the exact captured state; the recheck comparison
+// happens outside any lock.
func resolveFingerprint(binding Binding, credentialRaw json.RawMessage) [sha256.Size]byte {
bindingBytes, _ := json.Marshal(binding)
h := sha256.New()
@@ -541,15 +512,9 @@ func resolveFingerprint(binding Binding, credentialRaw json.RawMessage) [sha256.
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.
+// ResolverConfigFromEnv derives the D13 capability gate from the operator
+// env: malformed timeout/auth values fail their flag closed, absent values
+// keep the defaults. The returned error is diagnostic only.
func ResolverConfigFromEnv() (ResolverConfig, error) {
config := ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true}
var diag error
@@ -569,9 +534,8 @@ func ResolverConfigFromEnv() (ResolverConfig, error) {
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.
+// NewSubjectStore creates a per-subject store (fast-sandbox) with the D13
+// gate derived from env, so reloaded exchange vaults face the same gate.
func NewSubjectStore() *Store {
store := NewStore(nil, func() bool { return true })
config, err := ResolverConfigFromEnv()
diff --git a/components/egress/pkg/credentialvault/resolve_handler_test.go b/components/egress/pkg/credentialvault/resolve_handler_test.go
index 4a44dd8a5..235c0fc9c 100644
--- a/components/egress/pkg/credentialvault/resolve_handler_test.go
+++ b/components/egress/pkg/credentialvault/resolve_handler_test.go
@@ -32,8 +32,7 @@ import (
)
// fakeResolveClient is an in-process ResolverClient: records inputs, blocks
-// each call until release (or returns immediately), and answers with a fixed
-// decision or error.
+// each call until release, answers with a fixed decision or error.
type fakeResolveClient struct {
mu sync.Mutex
inputs []ResolveInput
@@ -139,9 +138,8 @@ func TestResolveHandlerHappyPath(t *testing.T) {
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.
+ // Wire subject is the resolved sandboxId; authority carries the default
+ // port; frame headers serialize as an empty object.
recorded := h.client.recorded()
require.Len(t, recorded, 1)
require.Equal(t, "sbx_01HZYEXAMPLE", recorded[0].Subject)
@@ -632,10 +630,8 @@ func TestNewSubjectStoreAdmitsExchangeOnlyWithReadyEnv(t *testing.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.
-// ---------------------------------------------------------------------------
+// Stub-backed end-to-end (tests/resolver/resolver.py): the wire subject, the
+// deterministic signature, and timeout classification.
func TestResolveHandlerStubEndToEnd(t *testing.T) {
socketPath := fmt.Sprintf("%s/r.sock", shortTempDir(t))
diff --git a/components/egress/pkg/credentialvault/source_exchange.go b/components/egress/pkg/credentialvault/source_exchange.go
index eaa42048b..4aef8a80d 100644
--- a/components/egress/pkg/credentialvault/source_exchange.go
+++ b/components/egress/pkg/credentialvault/source_exchange.go
@@ -83,10 +83,9 @@ 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.
+ // Aligned with parseResolverEndpoint: a prefix the transport rejects
+ // must fail at 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)
}
diff --git a/components/egress/pkg/telemetry/metrics.go b/components/egress/pkg/telemetry/metrics.go
index 08437e5da..c3078a414 100644
--- a/components/egress/pkg/telemetry/metrics.go
+++ b/components/egress/pkg/telemetry/metrics.go
@@ -193,16 +193,15 @@ func registerEgressMetrics() error {
}
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)."),
+ metric.WithDescription("Credential header resolutions by closed-set outcome (resolved|denied|timeout); "+
+ "credential and binding names are never attached (OSEP-0025 R10)."),
)
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.WithDescription("Credential header resolution latency, outcome-tagged; bounded by the resolver timeout."),
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,
@@ -371,8 +370,8 @@ 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.
+// Closed-set credential resolution outcomes (OSEP-0025 R10); tenant-provided
+// names stay in audit logs, never metric dimensions.
const (
ResolutionOutcomeResolved = "resolved"
ResolutionOutcomeDenied = "denied"
diff --git a/components/egress/policy_server.go b/components/egress/policy_server.go
index df8088ff8..f5afbf634 100644
--- a/components/egress/policy_server.go
+++ b/components/egress/policy_server.go
@@ -120,8 +120,7 @@ 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.
+ // D13 capability gate from env; malformed config fails exchange admission.
resolverConfig, resolverConfigErr := credentialvault.ResolverConfigFromEnv()
if resolverConfigErr != nil {
log.Warnf("credential resolver operator configuration not ready: %v", resolverConfigErr)
@@ -325,8 +324,7 @@ 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.
+ // Socket-only like _active: never served on the TCP surface.
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
@@ -648,10 +646,9 @@ 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.
+// resolveVaultAccess derives the sidecar resolve subject: the pod-injected
+// sandbox identity, never a protocol value. The store is the single vault;
+// the recheck derivation is byte-identical.
func (s *policyServer) resolveVaultAccess(_ *http.Request) (credentialvault.ResolveAccess, *credentialvault.ResolveAccessError) {
sandboxID := strings.TrimSpace(os.Getenv(constants.EnvSandboxID))
if sandboxID == "" {