Skip to content

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

feat(egress): OSEP-0025 T2a — resolver client transport (UDS/HTTPS + envelope enforcement)

高然4840c3450123
diff --git a/components/egress/pkg/constants/configuration.go b/components/egress/pkg/constants/configuration.go
index 2ce9d3f5d..4c6aa0fdf 100644
--- a/components/egress/pkg/constants/configuration.go
+++ b/components/egress/pkg/constants/configuration.go
@@ -39,6 +39,23 @@ const (
EnvCredentialVaultRequireScopedMatch = "OPENSANDBOX_EGRESS_CREDENTIAL_VAULT_REQUIRE_SCOPED_MATCH"
)
+// Credential header resolver client (OSEP-0025): egress → resolver transport
+// configuration. Ownership of this surface lives with the resolver client
+// (pkg/credentialvault/resolver_client.go); interception consumers only
+// consume the client interface.
+//
+// EnvCredentialResolverTimeout: per-resolve deadline in seconds (1..120).
+// EnvCredentialResolverMaxConcurrency: in-flight resolve cap (1..1024).
+// EnvCredentialResolverAuth: origin-scoped bearer tokens
+// "scheme://host:port=token[,...]" (D5). An endpoint whose normalized origin
+// has no entry resolves WITHOUT an Authorization header — there is no global
+// token. Never logged.
+const (
+ EnvCredentialResolverTimeout = "OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_TIMEOUT"
+ EnvCredentialResolverMaxConcurrency = "OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_MAX_CONCURRENCY"
+ EnvCredentialResolverAuth = "OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH"
+)
+
// Fast Sandbox profile: the egress control plane serves N sandboxes
// sharing one host/network domain; sidecar remains the default profile.
const (
@@ -197,6 +214,9 @@ const (
DefaultMaxEgressRules = 4096
DefaultDNSUpstreamTimeoutSec = 2
OpenSandboxRootDir = "/opt/opensandbox"
+ // Credential header resolver client defaults (OSEP-0025).
+ DefaultCredentialResolverTimeoutSeconds = 2
+ DefaultCredentialResolverMaxConcurrency = 32
// OSEP-0023 live admission defaults (experimental sidecar only).
DefaultRevisionTLSCapacity = 1024
DefaultRevisionRequestCapacity = 4096
diff --git a/components/egress/pkg/credentialvault/resolver_client.go b/components/egress/pkg/credentialvault/resolver_client.go
new file mode 100644
index 000000000..3c2844fee
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolver_client.go
@@ -0,0 +1,745 @@
+// 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"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+)
+
+// Egress → credential header resolver client (OSEP-0025, frozen contract
+// §3.3): one POSTed JSON request document answered with a header map plus
+// optional incremental redactions. The envelope is untrusted input (D14):
+// every response over a limit is a per-request denial, never a global fault.
+
+const (
+ // maxResolverResponseBytes (D14): total response body byte cap.
+ maxResolverResponseBytes = 64 << 10
+ // maxResolverHeaderCount (D14): header entries per response.
+ maxResolverHeaderCount = 16
+ // maxResolverValueBytes (D14): single header name/value or redaction value cap.
+ maxResolverValueBytes = 8 << 10
+ // maxResolverRedactionCount (D14): total resolver-provided redaction values.
+ maxResolverRedactionCount = 64
+ // maxResolverResponseHeaderBytes caps the HTTP response header block itself.
+ maxResolverResponseHeaderBytes = 8 << 10
+)
+
+// ResolverErrorKind classifies a failed resolve for the interception path.
+// Denied/invalid/rejected/timeout/unavailable are all per-request outcomes:
+// the request proceeds without resolver headers (fail closed), the client
+// itself stays healthy.
+type ResolverErrorKind string
+
+const (
+ // ResolverInvalidRequest: caller-supplied input violates the request contract.
+ ResolverInvalidRequest ResolverErrorKind = "invalid_request"
+ // ResolverUnavailable: transport failure (dial/write/read error).
+ ResolverUnavailable ResolverErrorKind = "unavailable"
+ // ResolverTimeout: per-call deadline exceeded.
+ ResolverTimeout ResolverErrorKind = "timeout"
+ // ResolverRejected: resolver answered with a non-200 status.
+ ResolverRejected ResolverErrorKind = "rejected"
+ // ResolverInvalidResponse: 200 but the body is not the contracted JSON envelope.
+ ResolverInvalidResponse ResolverErrorKind = "invalid_response"
+ // ResolverDenied (D14/R14): envelope limit exceeded or header name denied —
+ // per-request denial.
+ ResolverDenied ResolverErrorKind = "denied"
+)
+
+// ResolverError is the typed failure of one resolve call.
+type ResolverError struct {
+ Kind ResolverErrorKind
+ Reason string
+ Status int
+ err error
+}
+
+func (e *ResolverError) Error() string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "resolver %s", e.Kind)
+ if e.Reason != "" {
+ fmt.Fprintf(&b, " (%s)", e.Reason)
+ }
+ if e.Status != 0 {
+ fmt.Fprintf(&b, " status=%d", e.Status)
+ }
+ return b.String()
+}
+
+func (e *ResolverError) Unwrap() error { return e.err }
+
+func resolverErrorf(kind ResolverErrorKind, reason string) *ResolverError {
+ return &ResolverError{Kind: kind, Reason: reason}
+}
+
+// ResolverClient resolves one HTTP exchange's credential headers against the
+// credential header resolver.
+type ResolverClient interface {
+ Resolve(ctx context.Context, input ResolveInput) (*ResolverDecision, error)
+}
+
+// ResolveInput is one resolution request (frozen contract request document).
+type ResolveInput struct {
+ // Subject is the egress-authoritative sandboxId.
+ Subject string
+ // Credential and Binding name the vault credential and binding whose
+ // headers the resolver renders.
+ Credential string
+ Binding string
+ // Destination is the target origin of the intercepted exchange.
+ Destination ResolveDestination
+ // Request describes the outbound request frame the headers apply to.
+ Request ResolveRequestFrame
+}
+
+// ResolveDestination identifies the intercepted origin.
+type ResolveDestination struct {
+ Scheme string // "http" or "https"
+ Authority string // host:port of the origin
+ SNI string // TLS server name (authority host for https)
+}
+
+// ResolveRequestFrame describes the outbound request.
+type ResolveRequestFrame struct {
+ Method string
+ Host string
+ Path string // starts with "/"
+ Headers map[string]string
+}
+
+// ResolverDecision is the validated per-request outcome: headers to inject,
+// the header names to suppress from passthrough, and the merged redaction
+// set (derived variants are authoritative; resolver-provided redactions are
+// incremental only, R9).
+type ResolverDecision struct {
+ Headers map[string]string
+ Suppress map[string]struct{} // lowercase header names
+ Redactions []string // canonically ordered, deduped, non-empty
+}
+
+// ResolverClientOptions constructs one client.
+type ResolverClientOptions struct {
+ // Endpoint is the resolver URI: "uds:///absolute/socket/path" or
+ // "unix://..." (alias) or "https://host[:port][/prefix]".
+ Endpoint string
+ // Timeout bounds every resolve call; 0 selects the configured default.
+ Timeout time.Duration
+ // MaxConcurrency bounds in-flight resolves; 0 selects the configured default.
+ MaxConcurrency int
+ // Auth maps normalized origins ("https://host:port") to the bearer token
+ // presented for that origin only (D5). Endpoints without a matching
+ // origin resolve without an Authorization header.
+ Auth map[string]string
+ // TLSClientConfig overrides the HTTPS transport TLS configuration (test
+ // and deployment seam). Nil selects system verification.
+ TLSClientConfig *tls.Config
+}
+
+// NewResolverClient validates the endpoint and constructs the transport
+// without dialing.
+func NewResolverClient(options ResolverClientOptions) (ResolverClient, error) {
+ if options.Timeout <= 0 {
+ options.Timeout = ResolverTimeoutFromEnv()
+ }
+ if options.Timeout <= 0 {
+ return nil, resolverErrorf(ResolverInvalidRequest, "timeout_must_be_positive")
+ }
+ if options.MaxConcurrency <= 0 {
+ options.MaxConcurrency = ResolverMaxConcurrencyFromEnv()
+ }
+ if options.MaxConcurrency <= 0 {
+ return nil, resolverErrorf(ResolverInvalidRequest, "max_concurrency_must_be_positive")
+ }
+ parsed, err := parseResolverEndpoint(options.Endpoint)
+ if err != nil {
+ return nil, err
+ }
+
+ client := &resolverClient{
+ timeout: options.Timeout,
+ concurrency: make(chan struct{}, options.MaxConcurrency),
+ }
+ httpClient := &http.Client{
+ CheckRedirect: func(*http.Request, []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
+
+ var transport *http.Transport
+ if parsed.network == "unix" {
+ socketPath := parsed.socketPath
+ dialer := &net.Dialer{}
+ transport = &http.Transport{
+ DisableKeepAlives: true,
+ MaxResponseHeaderBytes: maxResolverResponseHeaderBytes,
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, "unix", socketPath)
+ },
+ }
+ client.requestURL = (&url.URL{Scheme: "http", Host: "localhost", Path: parsed.resolvePath}).String()
+ } else {
+ if parsed.origin == "" {
+ return nil, resolverErrorf(ResolverInvalidRequest, "missing_https_origin")
+ }
+ // Proxy stays nil: the resolver hop is direct TLS and must never
+ // chain through an outbound proxy (the bearer token must not leak
+ // to one).
+ transport = &http.Transport{
+ DisableKeepAlives: true,
+ ForceAttemptHTTP2: false,
+ MaxResponseHeaderBytes: maxResolverResponseHeaderBytes,
+ TLSClientConfig: options.TLSClientConfig,
+ }
+ client.requestURL = (&url.URL{Scheme: "https", Host: parsed.authority, Path: parsed.resolvePath}).String()
+ client.hostHeader = parsed.authority
+ // D5: origin-scoped bearer token; an unmatched origin sends no header.
+ if token, ok := options.Auth[parsed.origin]; ok {
+ client.authorization = "Bearer " + token
+ }
+ }
+ httpClient.Transport = transport
+ client.http = httpClient
+ return client, nil
+}
+
+type parsedResolverEndpoint struct {
+ network string // "unix" or "tcp"
+ socketPath string // unix only
+ authority string // https host[:port] as configured
+ origin string // normalized "https://host:port" (D5 lookup key)
+ resolvePath string // request target: prefix + "/resolve"
+}
+
+// parseResolverEndpoint validates the resolver URI and derives the framing
+// (D15): https endpoints may carry a path prefix; the resolve target is
+// prefix + "/resolve". Unix endpoints carry no prefix.
+func parseResolverEndpoint(endpoint string) (*parsedResolverEndpoint, error) {
+ raw, err := url.Parse(strings.TrimSpace(endpoint))
+ if err != nil {
+ return nil, fmt.Errorf("invalid resolver endpoint %q: %w", endpoint, err)
+ }
+ switch strings.ToLower(raw.Scheme) {
+ case "uds", "unix":
+ if raw.Host != "" {
+ return nil, resolverErrorf(ResolverInvalidRequest, "uds_endpoint_requires_empty_authority")
+ }
+ if !filepath.IsAbs(raw.Path) {
+ return nil, resolverErrorf(ResolverInvalidRequest, "uds_endpoint_requires_absolute_path")
+ }
+ return &parsedResolverEndpoint{
+ network: "unix",
+ socketPath: filepath.Clean(raw.Path),
+ resolvePath: "/resolve",
+ }, nil
+ case "https":
+ if raw.Host == "" {
+ return nil, resolverErrorf(ResolverInvalidRequest, "https_endpoint_requires_authority")
+ }
+ if raw.RawQuery != "" || raw.Fragment != "" || raw.User != nil {
+ return nil, resolverErrorf(ResolverInvalidRequest, "https_endpoint_rejects_query_fragment_userinfo")
+ }
+ origin, err := normalizeResolverOrigin(raw)
+ if err != nil {
+ return nil, err
+ }
+ prefix := raw.Path
+ if prefix == "/" {
+ prefix = ""
+ }
+ if prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasSuffix(prefix, "/")) {
+ return nil, resolverErrorf(ResolverInvalidRequest, "https_endpoint_prefix_must_be_a_non_trailing_slash_path")
+ }
+ return &parsedResolverEndpoint{
+ network: "tcp",
+ authority: raw.Host,
+ origin: origin,
+ resolvePath: prefix + "/resolve",
+ }, nil
+ default:
+ return nil, resolverErrorf(ResolverInvalidRequest, "unsupported_endpoint_scheme")
+ }
+}
+
+// normalizeResolverOrigin canonicalizes an https URL to "https://host:port"
+// (D5): lowercase scheme and host, explicit port (443 added when absent).
+func normalizeResolverOrigin(u *url.URL) (string, error) {
+ if strings.ToLower(u.Scheme) != "https" {
+ return "", resolverErrorf(ResolverInvalidRequest, "origin_requires_https_scheme")
+ }
+ host := strings.ToLower(u.Hostname())
+ if host == "" {
+ return "", resolverErrorf(ResolverInvalidRequest, "origin_requires_host")
+ }
+ port := u.Port()
+ if port == "" {
+ port = "443"
+ }
+ if net.ParseIP(host) != nil && strings.Contains(host, ":") {
+ host = "[" + host + "]"
+ }
+ return "https://" + host + ":" + port, nil
+}
+
+// ParseResolverAuthEnv parses OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH
+// (D5): comma-separated "origin=token" entries. Origins are normalized; a
+// malformed entry is a configuration error (fail closed), and an empty token
+// is rejected rather than treated as "no auth".
+func ParseResolverAuthEnv(raw string) (map[string]string, error) {
+ tokens := make(map[string]string)
+ for _, entry := range strings.Split(raw, ",") {
+ entry = strings.TrimSpace(entry)
+ if entry == "" {
+ continue
+ }
+ origin, token, found := strings.Cut(entry, "=")
+ origin = strings.TrimSpace(origin)
+ token = strings.TrimSpace(token)
+ if !found || origin == "" || token == "" {
+ return nil, fmt.Errorf("invalid resolver auth entry (want origin=token)")
+ }
+ normalized, err := normalizeResolverOriginString(origin)
+ if err != nil {
+ return nil, fmt.Errorf("invalid resolver auth origin %q: %w", origin, err)
+ }
+ if _, duplicate := tokens[normalized]; duplicate {
+ return nil, fmt.Errorf("duplicate resolver auth origin %q", origin)
+ }
+ tokens[normalized] = token
+ }
+ return tokens, nil
+}
+
+func normalizeResolverOriginString(origin string) (string, error) {
+ parsed, err := url.Parse(strings.TrimSpace(origin))
+ if err != nil {
+ return "", err
+ }
+ return normalizeResolverOrigin(parsed)
+}
+
+// ResolverTimeoutFromEnv reads OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_TIMEOUT
+// (seconds); unparseable or out-of-range values keep the default.
+func ResolverTimeoutFromEnv() time.Duration {
+ seconds := constants.EnvIntRange(
+ constants.EnvCredentialResolverTimeout,
+ constants.DefaultCredentialResolverTimeoutSeconds,
+ 1, 120,
+ )
+ return time.Duration(seconds) * time.Second
+}
+
+// ResolverMaxConcurrencyFromEnv reads
+// OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_MAX_CONCURRENCY; unparseable or
+// out-of-range values keep the default.
+func ResolverMaxConcurrencyFromEnv() int {
+ return constants.EnvIntRange(
+ constants.EnvCredentialResolverMaxConcurrency,
+ constants.DefaultCredentialResolverMaxConcurrency,
+ 1, 1024,
+ )
+}
+
+// NewResolverClientFromEnv constructs a client from the three resolver
+// environment variables (endpoint supplied by the caller — there is no
+// endpoint env; wiring owns it).
+func NewResolverClientFromEnv(endpoint string) (ResolverClient, error) {
+ auth, err := authTokensFromEnv()
+ if err != nil {
+ return nil, err
+ }
+ return NewResolverClient(ResolverClientOptions{
+ Endpoint: endpoint,
+ Auth: auth,
+ })
+}
+
+func authTokensFromEnv() (map[string]string, error) {
+ raw := strings.TrimSpace(os.Getenv(constants.EnvCredentialResolverAuth))
+ if raw == "" {
+ return nil, nil
+ }
+ return ParseResolverAuthEnv(raw)
+}
+
+// resolverClient is the UDS/HTTPS resolver transport. The zero value is not
+// usable; construct through NewResolverClient.
+type resolverClient struct {
+ http *http.Client
+ requestURL string
+ hostHeader string // https: endpoint authority; empty for unix (localhost)
+ authorization string // D5: "Bearer <token>" only when the origin matched
+ timeout time.Duration
+ concurrency chan struct{}
+}
+
+var _ ResolverClient = (*resolverClient)(nil)
+
+// Resolve performs one resolution. Failures are typed ResolverError values;
+// envelope violations (D14) are per-request denials.
+func (c *resolverClient) Resolve(ctx context.Context, input ResolveInput) (*ResolverDecision, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, &ResolverError{Kind: ResolverTimeout, err: err}
+ }
+ document, err := marshalResolveInput(input)
+ if err != nil {
+ return nil, err
+ }
+
+ // Bound in-flight resolves; the acquire honors caller cancellation.
+ select {
+ case c.concurrency <- struct{}{}:
+ defer func() { <-c.concurrency }()
+ case <-ctx.Done():
+ return nil, &ResolverError{Kind: ResolverTimeout, err: ctx.Err()}
+ }
+
+ callCtx, cancel := context.WithTimeout(ctx, c.timeout)
+ defer cancel()
+
+ request, err := http.NewRequestWithContext(callCtx, http.MethodPost, c.requestURL, bytes.NewReader(document))
+ if err != nil {
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_build_failed")
+ }
+ request.Header.Set("Content-Type", "application/json")
+ if c.hostHeader != "" {
+ // D15: Host is the endpoint authority (https) or localhost (unix,
+ // applied by the request URL above).
+ request.Host = c.hostHeader
+ }
+ if c.authorization != "" {
+ request.Header.Set("Authorization", c.authorization)
+ }
+ request.Close = true
+
+ response, err := c.http.Do(request)
+ if err != nil {
+ if callCtx.Err() != nil {
+ return nil, &ResolverError{Kind: ResolverTimeout, err: callCtx.Err()}
+ }
+ return nil, &ResolverError{Kind: ResolverUnavailable, err: err}
+ }
+ defer response.Body.Close()
+
+ if response.StatusCode != http.StatusOK {
+ // Drain a little so the connection can be reclaimed without letting
+ // the peer stream unbounded bytes into the client.
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxResolverResponseHeaderBytes))
+ return nil, &ResolverError{Kind: ResolverRejected, Status: response.StatusCode}
+ }
+ if mediaType, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")); err != nil || mediaType != "application/json" {
+ return nil, resolverErrorf(ResolverInvalidResponse, "content_type_not_json")
+ }
+
+ data, err := io.ReadAll(io.LimitReader(response.Body, maxResolverResponseBytes+1))
+ if err != nil {
+ return nil, &ResolverError{Kind: ResolverUnavailable, err: err}
+ }
+ if len(data) > maxResolverResponseBytes {
+ return nil, resolverErrorf(ResolverDenied, "response_too_large")
+ }
+ envelope, err := decodeResolveResponse(data)
+ if err != nil {
+ return nil, err
+ }
+ return deriveResolverDecision(envelope.headers, envelope.redactions), nil
+}
+
+// marshalResolveInput validates the request-side contract (mirror of the
+// resolver's own validation) and encodes the exact request document.
+func marshalResolveInput(input ResolveInput) ([]byte, error) {
+ nonEmpty := func(value string) bool { return value != "" }
+ switch {
+ case !nonEmpty(input.Subject), !nonEmpty(input.Credential), !nonEmpty(input.Binding):
+ return nil, resolverErrorf(ResolverInvalidRequest, "subject_credential_binding_required")
+ case input.Destination.Scheme != "http" && input.Destination.Scheme != "https":
+ return nil, resolverErrorf(ResolverInvalidRequest, "destination_scheme_invalid")
+ case !nonEmpty(input.Destination.Authority), !nonEmpty(input.Destination.SNI):
+ return nil, resolverErrorf(ResolverInvalidRequest, "destination_authority_sni_required")
+ case !nonEmpty(input.Request.Method), !nonEmpty(input.Request.Host):
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_method_host_required")
+ case !strings.HasPrefix(input.Request.Path, "/"):
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_path_must_start_with_slash")
+ }
+ for name, value := range input.Request.Headers {
+ if !nonEmpty(name) || !nonEmpty(value) {
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_headers_must_be_non_empty_strings")
+ }
+ }
+ document := resolveRequestDocument{
+ Subject: input.Subject,
+ Credential: input.Credential,
+ Binding: input.Binding,
+ Destination: resolveDestinationDocument{
+ Scheme: input.Destination.Scheme,
+ Authority: input.Destination.Authority,
+ SNI: input.Destination.SNI,
+ },
+ Request: resolveRequestFrameDocument{
+ Method: input.Request.Method,
+ Host: input.Request.Host,
+ Path: input.Request.Path,
+ Headers: input.Request.Headers,
+ },
+ }
+ encoded, err := json.Marshal(document)
+ if err != nil {
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_encode_failed")
+ }
+ if len(encoded) > maxResolverResponseBytes {
+ return nil, resolverErrorf(ResolverInvalidRequest, "request_too_large")
+ }
+ return encoded, nil
+}
+
+type resolveRequestDocument struct {
+ Subject string `json:"subject"`
+ Credential string `json:"credential"`
+ Binding string `json:"binding"`
+ Destination resolveDestinationDocument `json:"destination"`
+ Request resolveRequestFrameDocument `json:"request"`
+}
+
+type resolveDestinationDocument struct {
+ Scheme string `json:"scheme"`
+ Authority string `json:"authority"`
+ SNI string `json:"sni"`
+}
+
+type resolveRequestFrameDocument struct {
+ Method string `json:"method"`
+ Host string `json:"host"`
+ Path string `json:"path"`
+ Headers map[string]string `json:"headers"`
+}
+
+// decodeResolveResponse strictly decodes the response envelope: exactly the
+// contracted fields, no duplicate keys, no unknown fields, no nulls, no
+// trailing data (D14). Limit violations are ResolverDenied; schema violations
+// are ResolverInvalidResponse.
+func decodeResolveResponse(data []byte) (*resolveResponseDocument, error) {
+ fields, err := strictJSONObject(data)
+ if err != nil {
+ return nil, resolverErrorf(ResolverInvalidResponse, "malformed_json")
+ }
+ for name := range fields {
+ if name != "headers" && name != "redactions" {
+ return nil, resolverErrorf(ResolverInvalidResponse, "unknown_field")
+ }
+ }
+ headersRaw, ok := fields["headers"]
+ if !ok {
+ return nil, resolverErrorf(ResolverInvalidResponse, "headers_field_required")
+ }
+ if len(headersRaw) > maxResolverResponseBytes {
+ return nil, resolverErrorf(ResolverDenied, "response_too_large")
+ }
+ document := &resolveResponseDocument{}
+ if document.headers, err = decodeHeaderMap(headersRaw); err != nil {
+ return nil, err
+ }
+ if redactionsRaw, ok := fields["redactions"]; ok {
+ if document.redactions, err = decodeRedactionMap(redactionsRaw); err != nil {
+ return nil, err
+ }
+ }
+ return document, nil
+}
+
+type resolveResponseDocument struct {
+ headers map[string]string
+ redactions map[string][]string
+}
+
+// decodeHeaderMap validates one resolved header map (D14/R14): names pass the
+// credential-header rules (token pattern + reserved/hop-by-hop blacklist,
+// vault.go reservedHeaderNames), values are non-empty strings within the
+// per-value cap, and the map stays within the entry cap.
+func decodeHeaderMap(raw json.RawMessage) (map[string]string, error) {
+ fields, err := strictJSONObject(raw)
+ if err != nil {
+ return nil, resolverErrorf(ResolverInvalidResponse, "headers_not_object")
+ }
+ if len(fields) > maxResolverHeaderCount {
+ return nil, resolverErrorf(ResolverDenied, "too_many_headers")
+ }
+ headers := make(map[string]string, len(fields))
+ for name, valueRaw := range fields {
+ if len(name) > maxResolverValueBytes {
+ return nil, resolverErrorf(ResolverDenied, "header_name_too_long")
+ }
+ if validateCredentialHeaderName(name) != nil {
+ return nil, resolverErrorf(ResolverDenied, "denied_header_name")
+ }
+ value, err := decodeNonEmptyString(valueRaw, "header_value_too_long")
+ if err != nil {
+ return nil, err
+ }
+ headers[name] = value
+ }
+ return headers, nil
+}
+
+// decodeRedactionMap validates the resolver-provided incremental redactions
+// (R14): total values within the redaction cap, each value non-empty and
+// within the per-value cap.
+func decodeRedactionMap(raw json.RawMessage) (map[string][]string, error) {
+ fields, err := strictJSONObject(raw)
+ if err != nil {
+ return nil, resolverErrorf(ResolverInvalidResponse, "redactions_not_object")
+ }
+ redactions := make(map[string][]string, len(fields))
+ total := 0
+ for name, valuesRaw := range fields {
+ values, err := decodeNonEmptyStringArray(valuesRaw)
+ if err != nil {
+ return nil, err
+ }
+ total += len(values)
+ if total > maxResolverRedactionCount {
+ return nil, resolverErrorf(ResolverDenied, "too_many_redactions")
+ }
+ for _, value := range values {
+ if len(value) > maxResolverValueBytes {
+ return nil, resolverErrorf(ResolverDenied, "redaction_value_too_long")
+ }
+ }
+ redactions[name] = values
+ }
+ return redactions, nil
+}
+
+func decodeNonEmptyString(raw json.RawMessage, tooLongReason string) (string, error) {
+ if trimmed := bytes.TrimSpace(raw); len(trimmed) == 0 || trimmed[0] != '"' {
+ return "", resolverErrorf(ResolverInvalidResponse, "value_not_string")
+ }
+ var value string
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return "", resolverErrorf(ResolverInvalidResponse, "value_not_string")
+ }
+ if value == "" {
+ return "", resolverErrorf(ResolverDenied, "empty_value")
+ }
+ if len(value) > maxResolverValueBytes {
+ return "", resolverErrorf(ResolverDenied, tooLongReason)
+ }
+ return value, nil
+}
+
+func decodeNonEmptyStringArray(raw json.RawMessage) ([]string, error) {
+ trimmed := bytes.TrimSpace(raw)
+ if len(trimmed) == 0 || trimmed[0] != '[' {
+ return nil, resolverErrorf(ResolverInvalidResponse, "redaction_values_not_array")
+ }
+ var values []string
+ if err := json.Unmarshal(raw, &values); err != nil {
+ return nil, resolverErrorf(ResolverInvalidResponse, "redaction_values_not_strings")
+ }
+ if len(values) == 0 {
+ return nil, resolverErrorf(ResolverInvalidResponse, "redaction_values_empty")
+ }
+ for _, value := range values {
+ if value == "" {
+ return nil, resolverErrorf(ResolverInvalidResponse, "redaction_values_not_strings")
+ }
+ if len(value) > maxResolverValueBytes {
+ return nil, resolverErrorf(ResolverDenied, "redaction_value_too_long")
+ }
+ }
+ return values, nil
+}
+
+// strictJSONObject decodes exactly one JSON object with unique keys into
+// name → raw value. Duplicate keys, non-objects, or trailing bytes are
+// rejected.
+func strictJSONObject(data []byte) (map[string]json.RawMessage, error) {
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ token, err := decoder.Token()
+ if err != nil {
+ return nil, err
+ }
+ if delim, ok := token.(json.Delim); !ok || delim != '{' {
+ return nil, errors.New("not an object")
+ }
+ fields := make(map[string]json.RawMessage)
+ for decoder.More() {
+ token, err = decoder.Token()
+ if err != nil {
+ return nil, err
+ }
+ name, ok := token.(string)
+ if !ok {
+ return nil, errors.New("non-string object key")
+ }
+ if _, duplicate := fields[name]; duplicate {
+ return nil, fmt.Errorf("duplicate key %q", name)
+ }
+ var raw json.RawMessage
+ if err := decoder.Decode(&raw); err != nil {
+ return nil, err
+ }
+ fields[name] = raw
+ }
+ if token, err = decoder.Token(); err != nil {
+ return nil, err
+ }
+ if delim, ok := token.(json.Delim); !ok || delim != '}' {
+ return nil, errors.New("unterminated object")
+ }
+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
+ return nil, errors.New("trailing data")
+ }
+ return fields, nil
+}
+
+// canonicalResolverRedactions orders redaction values the way the decision
+// snapshot expects: non-empty, deduped, ascending length then bytes.
+func canonicalResolverRedactions(values []string) []string {
+ seen := make(map[string]struct{}, len(values))
+ merged := make([]string, 0, len(values))
+ for _, value := range values {
+ if value == "" {
+ continue
+ }
+ if _, exists := seen[value]; exists {
+ continue
+ }
+ seen[value] = struct{}{}
+ merged = append(merged, value)
+ }
+ sort.Slice(merged, func(i, j int) bool {
+ if len(merged[i]) != len(merged[j]) {
+ return len(merged[i]) < len(merged[j])
+ }
+ return merged[i] < merged[j]
+ })
+ return merged
+}
diff --git a/components/egress/pkg/credentialvault/resolver_client_test.go b/components/egress/pkg/credentialvault/resolver_client_test.go
new file mode 100644
index 000000000..35c27d13c
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolver_client_test.go
@@ -0,0 +1,625 @@
+// 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"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+ "github.com/stretchr/testify/require"
+)
+
+func resolverTestInput() ResolveInput {
+ return ResolveInput{
+ Subject: "sbx_01HZYEXAMPLE",
+ Credential: "spi-signer",
+ Binding: "internal-api",
+ Destination: ResolveDestination{Scheme: "https", Authority: "api.internal.example.com:443", SNI: "api.internal.example.com"},
+ Request: ResolveRequestFrame{Method: "GET", Host: "api.internal.example.com", Path: "/v1/foo", Headers: map[string]string{"accept": "application/json"}},
+ }
+}
+
+func requireKind(t *testing.T, err error, kind ResolverErrorKind) *ResolverError {
+ t.Helper()
+ require.Error(t, err)
+ var resolverErr *ResolverError
+ require.ErrorAs(t, err, &resolverErr)
+ require.Equal(t, kind, resolverErr.Kind, "unexpected kind for error %v", err)
+ return resolverErr
+}
+
+func TestParseResolverEndpoint(t *testing.T) {
+ parsed, err := parseResolverEndpoint("uds:///run/opensandbox/resolver/resolve.sock")
+ require.NoError(t, err)
+ require.Equal(t, "unix", parsed.network)
+ require.Equal(t, "/run/opensandbox/resolver/resolve.sock", parsed.socketPath)
+ require.Equal(t, "/resolve", parsed.resolvePath)
+
+ parsed, err = parseResolverEndpoint("unix:///tmp/r.sock")
+ require.NoError(t, err)
+ require.Equal(t, "unix", parsed.network)
+
+ parsed, err = parseResolverEndpoint("https://resolver.internal:8443/base")
+ require.NoError(t, err)
+ require.Equal(t, "tcp", parsed.network)
+ require.Equal(t, "resolver.internal:8443", parsed.authority)
+ require.Equal(t, "https://resolver.internal:8443", parsed.origin)
+ require.Equal(t, "/base/resolve", parsed.resolvePath)
+
+ parsed, err = parseResolverEndpoint("https://resolver.internal")
+ require.NoError(t, err)
+ require.Equal(t, "resolver.internal", parsed.authority)
+ require.Equal(t, "https://resolver.internal:443", parsed.origin)
+ require.Equal(t, "/resolve", parsed.resolvePath)
+
+ parsed, err = parseResolverEndpoint("https://RESOLVER.Internal:443")
+ require.NoError(t, err)
+ require.Equal(t, "https://resolver.internal:443", parsed.origin)
+
+ for _, bad := range []string{
+ "",
+ "http://resolver.internal",
+ "uds://host/path",
+ "uds://relative.sock",
+ "https:///nohost",
+ "https://resolver.internal:8443/base?x=1",
+ "https://resolver.internal:8443/base#frag",
+ "https://[email protected]:8443",
+ "https://resolver.internal:8443/base/",
+ "tcp://resolver.internal:8443",
+ } {
+ _, err = parseResolverEndpoint(bad)
+ require.Error(t, err, "endpoint %q must be rejected", bad)
+ }
+}
+
+func TestNormalizeResolverOrigin(t *testing.T) {
+ origin, err := normalizeResolverOriginString("HTTPS://Resolver.Example.COM:8443")
+ require.NoError(t, err)
+ require.Equal(t, "https://resolver.example.com:8443", origin)
+
+ origin, err = normalizeResolverOriginString("https://resolver.example.com")
+ require.NoError(t, err)
+ require.Equal(t, "https://resolver.example.com:443", origin)
+
+ origin, err = normalizeResolverOriginString("https://[::1]:8443")
+ require.NoError(t, err)
+ require.Equal(t, "https://[::1]:8443", origin)
+
+ _, err = normalizeResolverOriginString("http://resolver.example.com:8080")
+ require.Error(t, err)
+}
+
+func TestParseResolverAuthEnv(t *testing.T) {
+ tokens, err := ParseResolverAuthEnv("https://resolver.internal:8443=alpha, https://other.internal=beta ,,")
+ require.NoError(t, err)
+ require.Equal(t, map[string]string{
+ "https://resolver.internal:8443": "alpha",
+ "https://other.internal:443": "beta",
+ }, tokens)
+
+ tokens, err = ParseResolverAuthEnv("")
+ require.NoError(t, err)
+ require.Empty(t, tokens)
+
+ for _, bad := range []string{
+ "resolver.internal=alpha",
+ "https://resolver.internal:8443=",
+ "=alpha",
+ "notaentry",
+ "https://resolver.internal:8443=alpha,https://resolver.internal:8443=beta",
+ } {
+ _, err = ParseResolverAuthEnv(bad)
+ require.Error(t, err, "auth table %q must be rejected", bad)
+ }
+}
+
+func TestResolverEnvDefaults(t *testing.T) {
+ t.Setenv(constants.EnvCredentialResolverTimeout, "")
+ t.Setenv(constants.EnvCredentialResolverMaxConcurrency, "")
+ require.Equal(t, 2*time.Second, ResolverTimeoutFromEnv())
+ require.Equal(t, constants.DefaultCredentialResolverMaxConcurrency, ResolverMaxConcurrencyFromEnv())
+
+ t.Setenv(constants.EnvCredentialResolverTimeout, "5")
+ t.Setenv(constants.EnvCredentialResolverMaxConcurrency, "8")
+ require.Equal(t, 5*time.Second, ResolverTimeoutFromEnv())
+ require.Equal(t, 8, ResolverMaxConcurrencyFromEnv())
+
+ t.Setenv(constants.EnvCredentialResolverTimeout, "bogus")
+ t.Setenv(constants.EnvCredentialResolverMaxConcurrency, "-3")
+ require.Equal(t, 2*time.Second, ResolverTimeoutFromEnv())
+ require.Equal(t, constants.DefaultCredentialResolverMaxConcurrency, ResolverMaxConcurrencyFromEnv())
+}
+
+func TestNewResolverClientFromEnv(t *testing.T) {
+ t.Setenv(constants.EnvCredentialResolverAuth, "https://resolver.internal:8443=alpha")
+ client, err := NewResolverClientFromEnv("https://resolver.internal:8443/base")
+ require.NoError(t, err)
+ require.NotNil(t, client)
+
+ t.Setenv(constants.EnvCredentialResolverAuth, "https://resolver.internal:8443=")
+ _, err = NewResolverClientFromEnv("https://resolver.internal:8443/base")
+ require.Error(t, err)
+
+ t.Setenv(constants.EnvCredentialResolverAuth, "")
+ _, err = NewResolverClientFromEnv("https://resolver.internal:8443/base")
+ require.NoError(t, err)
+}
+
+func TestMarshalResolveInputValidation(t *testing.T) {
+ valid := resolverTestInput()
+ _, err := marshalResolveInput(valid)
+ require.NoError(t, err)
+
+ cases := []func(*ResolveInput){
+ func(i *ResolveInput) { i.Subject = "" },
+ func(i *ResolveInput) { i.Credential = "" },
+ func(i *ResolveInput) { i.Binding = "" },
+ func(i *ResolveInput) { i.Destination.Scheme = "ftp" },
+ func(i *ResolveInput) { i.Destination.Authority = "" },
+ func(i *ResolveInput) { i.Destination.SNI = "" },
+ func(i *ResolveInput) { i.Request.Method = "" },
+ func(i *ResolveInput) { i.Request.Host = "" },
+ func(i *ResolveInput) { i.Request.Path = "v1/foo" },
+ func(i *ResolveInput) { i.Request.Headers = map[string]string{"x-a": ""} },
+ func(i *ResolveInput) { i.Request.Headers = map[string]string{"": "v"} },
+ }
+ for _, mutate := range cases {
+ input := valid
+ mutate(&input)
+ _, err = marshalResolveInput(input)
+ requireKind(t, err, ResolverInvalidRequest)
+ }
+}
+
+func TestDecodeResolveResponseStrictness(t *testing.T) {
+ denied := []struct{ reason, body string }{
+ {"header_name_too_long", `{"headers":{"` + strings.Repeat("n", 9000) + `":"v"}}`},
+ {"header_value_too_long", `{"headers":{"x-a":"` + strings.Repeat("v", 9000) + `"}}`},
+ {"denied_header_name", `{"headers":{"host":"evil"}}`},
+ {"denied_header_name", `{"headers":{"bad name":"v"}}`},
+ {"empty_value", `{"headers":{"x-a":""}}`},
+ {"too_many_redactions", `{"headers":{"x-a":"v"},"redactions":{"x-a":[` + manyStrings(65) + `]}}`},
+ {"redaction_value_too_long", `{"headers":{"x-a":"v"},"redactions":{"x-a":["` + strings.Repeat("v", 9000) + `"]}}`},
+ }
+ for _, testCase := range denied {
+ _, err := decodeResolveResponse([]byte(testCase.body))
+ resolverErr := requireKind(t, err, ResolverDenied)
+ require.Equal(t, testCase.reason, resolverErr.Reason, "body %s", testCase.body)
+ }
+
+ invalid := []string{
+ `not json`,
+ `[]`,
+ `{"headers":{}} extra`,
+ `{"headers":{},"unknown":1}`,
+ `{}`,
+ `{"headers":null}`,
+ `{"headers":[]}`,
+ `{"headers":{"x-a":null}}`,
+ `{"headers":{"x-a":1}}`,
+ `{"headers":{"x-a":"v"},"redactions":[]}`,
+ `{"headers":{"x-a":"v"},"redactions":{"x-a":[]}}`,
+ `{"headers":{"x-a":"v"},"redactions":{"x-a":null}}`,
+ `{"headers":{"x-a":"v"},"redactions":{"x-a":"v"}}`,
+ }
+ for _, body := range invalid {
+ _, err := decodeResolveResponse([]byte(body))
+ requireKind(t, err, ResolverInvalidResponse)
+ }
+
+ // Duplicate object keys are rejected, not last-wins.
+ _, err := decodeResolveResponse([]byte(`{"headers":{"x-a":"1"},"headers":{"x-a":"2"}}`))
+ requireKind(t, err, ResolverInvalidResponse)
+ _, err = decodeResolveResponse([]byte(`{"headers":{"x-a":"1","x-a":"2"}}`))
+ requireKind(t, err, ResolverInvalidResponse)
+
+ document, err := decodeResolveResponse([]byte(`{"headers":{"X-A":"1","x-b":"2"},"redactions":{"X-A":["1"]}}`))
+ require.NoError(t, err)
+ require.Equal(t, map[string]string{"X-A": "1", "x-b": "2"}, document.headers)
+ require.Equal(t, map[string][]string{"X-A": {"1"}}, document.redactions)
+
+ // Redactions are optional.
+ document, err = decodeResolveResponse([]byte(`{"headers":{"x-a":"1"}}`))
+ require.NoError(t, err)
+ require.Empty(t, document.redactions)
+}
+
+func TestNewResolverClientRequiresValidOptions(t *testing.T) {
+ // Non-positive timeout/concurrency mean "use the configured defaults".
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: "uds:///tmp/r.sock", Timeout: -1, MaxConcurrency: -1})
+ require.NoError(t, err)
+ require.NotNil(t, client)
+ _, err = NewResolverClient(ResolverClientOptions{Endpoint: "bogus", Timeout: time.Second, MaxConcurrency: 1})
+ require.Error(t, err)
+}
+
+func TestResolveInputInvalidWithoutRoundTrip(t *testing.T) {
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: "uds:///nonexistent-egress-test.sock", Timeout: time.Second, MaxConcurrency: 1})
+ require.NoError(t, err)
+ input := resolverTestInput()
+ input.Request.Path = "no-slash"
+ _, err = client.Resolve(context.Background(), input)
+ requireKind(t, err, ResolverInvalidRequest)
+}
+
+func TestResolveUnavailableWhenSocketMissing(t *testing.T) {
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: "uds:///nonexistent-egress-test.sock", Timeout: time.Second, MaxConcurrency: 1})
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ requireKind(t, err, ResolverUnavailable)
+}
+
+// startEnvelopeServer runs an HTTPS test resolver answering every POST with
+// status/body. It returns the endpoint URI and the test TLS configuration.
+func startEnvelopeServer(t *testing.T, status int, body string, captured *capturedRequest) (string, *tls.Config) {
+ t.Helper()
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw := make([]byte, r.ContentLength)
+ if len(raw) > 0 {
+ _, _ = io.ReadFull(r.Body, raw)
+ }
+ if captured != nil {
+ captured.record(r, raw)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ server.StartTLS()
+ t.Cleanup(server.Close)
+ return server.URL, server.Client().Transport.(*http.Transport).TLSClientConfig
+}
+
+type capturedRequest struct {
+ mu sync.Mutex
+ method string
+ path string
+ host string
+ auth string
+ content string
+ body map[string]any
+}
+
+func (c *capturedRequest) record(r *http.Request, raw []byte) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.method = r.Method
+ c.path = r.URL.RequestURI()
+ c.host = r.Host
+ c.auth = r.Header.Get("Authorization")
+ c.content = r.Header.Get("Content-Type")
+ _ = json.Unmarshal(raw, &c.body)
+}
+
+func (c *capturedRequest) snapshot() capturedRequest {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return capturedRequest{method: c.method, path: c.path, host: c.host, auth: c.auth, content: c.content, body: c.body}
+}
+
+func TestHTTPSFrameAndHappyPath(t *testing.T) {
+ var captured capturedRequest
+ envelope := `{"headers":{"X-Test-Signature":"abc","authorization":"Bearer test-spi-signer"},"redactions":{"X-Test-Signature":["abc"]}}`
+ endpoint, tlsConfig := startEnvelopeServer(t, http.StatusOK, envelope, &captured)
+ client, err := NewResolverClient(ResolverClientOptions{
+ Endpoint: endpoint + "/egress-resolver",
+ Timeout: time.Second,
+ MaxConcurrency: 1,
+ Auth: map[string]string{endpoint: "secret-token"},
+ TLSClientConfig: tlsConfig,
+ })
+ require.NoError(t, err)
+
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+
+ frame := captured.snapshot()
+ require.Equal(t, http.MethodPost, frame.method)
+ // D15: fixed framing — target is prefix + /resolve, Host is the authority.
+ require.Equal(t, "/egress-resolver/resolve", frame.path)
+ require.Equal(t, strings.TrimPrefix(endpoint, "https://"), frame.host)
+ require.Equal(t, "application/json", frame.content)
+ // D5: only the configured origin's token is presented.
+ require.Equal(t, "Bearer secret-token", frame.auth)
+ require.NotNil(t, frame.body)
+ keys := make([]string, 0, len(frame.body))
+ for key := range frame.body {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ require.Equal(t, []string{"binding", "credential", "destination", "request", "subject"}, keys)
+
+ require.Equal(t, map[string]string{"X-Test-Signature": "abc", "authorization": "Bearer test-spi-signer"}, decision.Headers)
+ require.Equal(t, map[string]struct{}{"x-test-signature": {}, "authorization": {}}, decision.Suppress)
+ require.Contains(t, decision.Redactions, "abc")
+}
+
+func TestUDSFrameAndNoAuthorization(t *testing.T) {
+ dir, err := os.MkdirTemp("", "osbr")
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ socketPath := filepath.Join(dir, "r.sock")
+
+ listener, err := net.Listen("unix", socketPath)
+ require.NoError(t, err)
+ var captured capturedRequest
+ server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw := make([]byte, r.ContentLength)
+ if len(raw) > 0 {
+ _, _ = io.ReadFull(r.Body, raw)
+ }
+ captured.record(r, raw)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"headers":{"x-a":"1"}}`))
+ })}
+ serveDone := make(chan struct{})
+ go func() {
+ defer close(serveDone)
+ _ = server.Serve(listener)
+ }()
+ t.Cleanup(func() {
+ _ = server.Close()
+ <-serveDone
+ })
+
+ client, err := NewResolverClient(ResolverClientOptions{
+ // D5: a UDS endpoint never carries auth — the socket is the boundary.
+ Endpoint: "uds://" + socketPath,
+ Timeout: time.Second,
+ MaxConcurrency: 1,
+ Auth: map[string]string{"https://anything:443": "must-not-leak"},
+ })
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+
+ frame := captured.snapshot()
+ // D15: unix Host is localhost, target fixed at /resolve.
+ require.Equal(t, "localhost", frame.host)
+ require.Equal(t, "/resolve", frame.path)
+ require.Empty(t, frame.auth, "UDS resolves must never carry an Authorization header")
+}
+
+func TestHTTPSUnconfiguredOriginSendsNoAuthorization(t *testing.T) {
+ var captured capturedRequest
+ endpoint, tlsConfig := startEnvelopeServer(t, http.StatusOK, `{"headers":{"x-a":"1"}}`, &captured)
+ client, err := NewResolverClient(ResolverClientOptions{
+ Endpoint: endpoint,
+ Timeout: time.Second,
+ MaxConcurrency: 1,
+ Auth: map[string]string{"https://other-resolver.internal:8443": "global-token"},
+ TLSClientConfig: tlsConfig,
+ })
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ require.Empty(t, captured.snapshot().auth, "an unmatched origin must never carry Authorization")
+}
+
+func TestResolverDeniedLimits(t *testing.T) {
+ cases := []struct {
+ name string
+ body string
+ reason string
+ }{
+ {"tooManyHeaders", `{"headers":{` + manyHeaderEntries(maxResolverHeaderCount+1) + `}}`, "too_many_headers"},
+ {"headerValueTooLong", `{"headers":{"x-a":"` + strings.Repeat("v", maxResolverValueBytes+1) + `"}}`, "header_value_too_long"},
+ {"headerNameTooLong", `{"headers":{"` + strings.Repeat("n", maxResolverValueBytes+1) + `":"v"}}`, "header_name_too_long"},
+ {"reservedHeaderName", `{"headers":{"proxy-authorization":"v"}}`, "denied_header_name"},
+ {"reservedHeaderNameHost", `{"headers":{"Host":"evil"}}`, "denied_header_name"},
+ {"invalidHeaderNameChars", `{"headers":{"bad name":"v"}}`, "denied_header_name"},
+ {"emptyHeaderValue", `{"headers":{"x-a":""}}`, "empty_value"},
+ {"tooManyRedactions", `{"headers":{"x-a":"v"},"redactions":{"x-a":[` + manyStrings(maxResolverRedactionCount+1) + `]}}`, "too_many_redactions"},
+ {"redactionValueTooLong", `{"headers":{"x-a":"v"},"redactions":{"x-a":["` + strings.Repeat("v", maxResolverValueBytes+1) + `"]}}`, "redaction_value_too_long"},
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ endpoint, tlsConfig := startEnvelopeServer(t, http.StatusOK, testCase.body, nil)
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: endpoint, Timeout: 2 * time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ resolverErr := requireKind(t, err, ResolverDenied)
+ require.Equal(t, testCase.reason, resolverErr.Reason)
+ })
+ }
+}
+
+func TestResolverDeniedResponseTooLarge(t *testing.T) {
+ // A 200 with a body over the 64KiB envelope cap is a per-request denial;
+ // the client must also stop reading promptly.
+ large := `{"headers":{"x-a":"` + strings.Repeat("v", maxResolverResponseBytes) + `"}}`
+ endpoint, tlsConfig := startEnvelopeServer(t, http.StatusOK, large, nil)
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: endpoint, Timeout: 5 * time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ resolverErr := requireKind(t, err, ResolverDenied)
+ require.Equal(t, "response_too_large", resolverErr.Reason)
+}
+
+func TestResolverInvalidAndRejectedClasses(t *testing.T) {
+ cases := []struct {
+ name string
+ status int
+ body string
+ kind ResolverErrorKind
+ }{
+ {"badJSON", http.StatusOK, "not-json{", ResolverInvalidResponse},
+ {"unknownField", http.StatusOK, `{"headers":{},"extra":1}`, ResolverInvalidResponse},
+ {"wrongContentType", http.StatusOK, `{"headers":{}}`, ResolverInvalidResponse},
+ {"serverError", http.StatusServiceUnavailable, `{"error":"resolution_refused"}`, ResolverRejected},
+ {"unauthorized", http.StatusUnauthorized, `{"error":"unauthorized"}`, ResolverRejected},
+ {"notFound", http.StatusNotFound, `{"error":"not_found"}`, ResolverRejected},
+ {"redirectNotFollowed", http.StatusFound, "", ResolverRejected},
+ }
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ var captured capturedRequest
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw := make([]byte, r.ContentLength)
+ if len(raw) > 0 {
+ _, _ = io.ReadFull(r.Body, raw)
+ }
+ captured.record(r, raw)
+ if testCase.status == http.StatusOK {
+ w.Header().Set("Content-Type", "text/plain")
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ }
+ w.WriteHeader(testCase.status)
+ _, _ = w.Write([]byte(testCase.body))
+ }))
+ server.StartTLS()
+ defer server.Close()
+ tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: server.URL, Timeout: 2 * time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ resolverErr := requireKind(t, err, testCase.kind)
+ if testCase.kind == ResolverRejected {
+ require.Equal(t, testCase.status, resolverErr.Status)
+ }
+ })
+ }
+}
+
+func TestResolveTimeoutClass(t *testing.T) {
+ release := make(chan struct{})
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ <-release
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"headers":{"x-a":"1"}}`))
+ }))
+ server.StartTLS()
+ defer server.Close()
+ defer close(release)
+ tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig
+
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: server.URL, Timeout: 100 * time.Millisecond, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+
+ start := time.Now()
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ requireKind(t, err, ResolverTimeout)
+ require.Less(t, time.Since(start), time.Second)
+}
+
+func TestResolveCallerDeadlineHonored(t *testing.T) {
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(50 * time.Millisecond)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"headers":{"x-a":"1"}}`))
+ }))
+ server.StartTLS()
+ defer server.Close()
+ tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: server.URL, Timeout: 10 * time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ _, err = client.Resolve(ctx, resolverTestInput())
+ requireKind(t, err, ResolverTimeout)
+}
+
+func TestResolverMaxConcurrencyBounded(t *testing.T) {
+ var mu sync.Mutex
+ var inflight, maxInflight int
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ inflight++
+ if inflight > maxInflight {
+ maxInflight = inflight
+ }
+ mu.Unlock()
+ time.Sleep(50 * time.Millisecond)
+ mu.Lock()
+ inflight--
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"headers":{"x-a":"1"}}`))
+ }))
+ server.StartTLS()
+ defer server.Close()
+ tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig
+
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: server.URL, Timeout: 5 * time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+
+ const calls = 4
+ var wg sync.WaitGroup
+ errs := make([]error, calls)
+ for i := 0; i < calls; i++ {
+ wg.Add(1)
+ go func(slot int) {
+ defer wg.Done()
+ _, errs[slot] = client.Resolve(context.Background(), resolverTestInput())
+ }(i)
+ }
+ wg.Wait()
+ for _, err := range errs {
+ require.NoError(t, err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ require.Equal(t, 1, maxInflight, "MaxConcurrency=1 must serialize resolves")
+}
+
+func TestResolverClientInterfaceContract(t *testing.T) {
+ // The decision shape is the interception contract: headers as returned,
+ // lowercase suppress names, canonically ordered redactions.
+ envelope := `{"headers":{"X-Signature":"sig","X-Token":"tok"},"redactions":{"X-Signature":["sig"]}}`
+ endpoint, tlsConfig := startEnvelopeServer(t, http.StatusOK, envelope, nil)
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: endpoint, Timeout: time.Second, MaxConcurrency: 1, TLSClientConfig: tlsConfig})
+ require.NoError(t, err)
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ require.Equal(t, map[string]string{"X-Signature": "sig", "X-Token": "tok"}, decision.Headers)
+ require.Equal(t, map[string]struct{}{"x-signature": {}, "x-token": {}}, decision.Suppress)
+ require.True(t, slices.Equal(canonicalResolverRedactions(decision.Redactions), decision.Redactions))
+ require.Contains(t, decision.Redactions, "sig")
+ require.Contains(t, decision.Redactions, "tok")
+}
+
+func manyHeaderEntries(count int) string {
+ entries := make([]string, 0, count)
+ for i := 0; i < count; i++ {
+ entries = append(entries, fmt.Sprintf(`"x-h%d":"v"`, i))
+ }
+ return strings.Join(entries, ",")
+}
+
+func manyStrings(count int) string {
+ values := make([]string, 0, count)
+ for i := 0; i < count; i++ {
+ values = append(values, fmt.Sprintf(`"s%d"`, i))
+ }
+ return strings.Join(values, ",")
+}
diff --git a/components/egress/pkg/credentialvault/resolver_redaction.go b/components/egress/pkg/credentialvault/resolver_redaction.go
new file mode 100644
index 000000000..2845defc3
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolver_redaction.go
@@ -0,0 +1,48 @@
+// 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 "strings"
+
+// Resolver response → interception decision (OSEP-0025 R9): the resolved
+// headers themselves drive the suppress and redaction derivation; anything
+// the resolver volunteers as redactions is merged incrementally and is never
+// authoritative. The derived set cannot be shrunk by the response.
+
+// deriveResolverDecision builds the per-request decision from a validated
+// envelope. For every resolved header: the lowercased name joins the suppress
+// set and the value joins the redaction set through the same 7-variant
+// expansion used for substitutions (raw, URL-escaped ×2 case forms,
+// form-escaped ×2 case forms, JSON-escaped ×2 encodings —
+// substitutionRedactionVariants). Resolver-provided redactions are additive
+// only, deduped, and never remove derived entries.
+func deriveResolverDecision(headers map[string]string, resolverRedactions map[string][]string) *ResolverDecision {
+ decision := &ResolverDecision{
+ Headers: headers,
+ Suppress: make(map[string]struct{}, len(headers)),
+ }
+ redactions := make([]string, 0, len(headers)*7)
+ for name, value := range headers {
+ decision.Suppress[strings.ToLower(name)] = struct{}{}
+ redactions = append(redactions, substitutionRedactionVariants(value)...)
+ }
+ // R9: resolver-supplied redactions merge incrementally only — they can
+ // add entries but never remove or replace the derived ones.
+ for _, values := range resolverRedactions {
+ redactions = append(redactions, values...)
+ }
+ decision.Redactions = canonicalResolverRedactions(redactions)
+ return decision
+}
diff --git a/components/egress/pkg/credentialvault/resolver_redaction_test.go b/components/egress/pkg/credentialvault/resolver_redaction_test.go
new file mode 100644
index 000000000..2d5ea7662
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolver_redaction_test.go
@@ -0,0 +1,104 @@
+// 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 (
+ "slices"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestDeriveResolverDecisionVariantCompleteness(t *testing.T) {
+ // One value exercising every encoding family: spaces, plus signs,
+ // reserved URL characters, JSON-escaped quotes/newlines, non-ASCII, and
+ // an astral character (surrogate pair territory).
+ value := "a b+c/d?e=\"f\"&g\nh\U0001F600"
+ decision := deriveResolverDecision(map[string]string{"X-Handled": value}, nil)
+
+ require.Equal(t, map[string]struct{}{"x-handled": {}}, decision.Suppress)
+
+ // All 7 variants of the alignment helper are present.
+ variants := substitutionRedactionVariants(value)
+ require.Len(t, variants, 7)
+ for _, variant := range variants {
+ require.Contains(t, decision.Redactions, variant)
+ }
+
+ // URL encoding appears in both percent-escape cases; form encoding in
+ // both plus/percent forms; JSON escaping in both raw-UTF-8 and
+ // ASCII-escape encodings.
+ expected := []string{
+ value, // raw
+ "a%20b%2Bc%2Fd%3Fe%3D%22f%22%26g%0Ah%F0%9F%98%80", // URL, uppercase escapes, space as %20
+ "a%20b%2bc%2fd%3fe%3d%22f%22%26g%0ah%f0%9f%98%80", // URL, lowercase escapes
+ "a+b%2Bc%2Fd%3Fe%3D%22f%22%26g%0Ah%F0%9F%98%80", // form, uppercase escapes, space as +
+ "a+b%2bc%2fd%3fe%3d%22f%22%26g%0ah%f0%9f%98%80", // form, lowercase escapes
+ }
+ for _, want := range expected {
+ require.Contains(t, decision.Redactions, want)
+ }
+ // JSON escape: quote, newline, and ampersand escaped, non-ASCII kept
+ // as UTF-8 (encoding/json default HTML escaping).
+ require.Contains(t, decision.Redactions, "a b+c/d?e=\\\"f\\\"\\u0026g\\nh\U0001F600")
+ // JSON ASCII escape: emoji as the UTF-16 surrogate pair.
+ require.Contains(t, decision.Redactions, "a b+c/d?e=\\\"f\\\"&g\\nh\\ud83d\\ude00")
+
+ // Exactly the 7 variants, no extras, canonically ordered.
+ require.Len(t, decision.Redactions, len(variants))
+ require.True(t, slices.Equal(canonicalResolverRedactions(decision.Redactions), decision.Redactions))
+}
+
+func TestResolverRedactionsAreIncrementalR9(t *testing.T) {
+ value := "secret"
+ variants := substitutionRedactionVariants(value)
+ // A plain-ASCII value collapses to one deduped variant.
+ expected := canonicalResolverRedactions(variants)
+ require.Equal(t, []string{"secret"}, expected)
+ decision := deriveResolverDecision(
+ map[string]string{"x-a": value},
+ map[string][]string{
+ "x-a": {"extra-token", value}, // resolver may repeat derived values
+ "x-other": {""}, // empty entries are dropped
+ },
+ )
+ for _, variant := range expected {
+ require.Contains(t, decision.Redactions, variant, "derived variants must survive the merge")
+ }
+ require.Contains(t, decision.Redactions, "extra-token")
+ require.NotContains(t, decision.Redactions, "")
+ require.Len(t, decision.Redactions, len(expected)+1)
+
+ // The resolver cannot shrink the set: with no redactions at all the
+ // derived variants remain.
+ decision = deriveResolverDecision(map[string]string{"x-a": value}, nil)
+ require.Equal(t, expected, decision.Redactions)
+}
+
+func TestCanonicalResolverRedactionsOrdering(t *testing.T) {
+ ordered := canonicalResolverRedactions([]string{"ccc", "bb", "a", "bb", ""})
+ require.Equal(t, []string{"a", "bb", "ccc"}, ordered)
+
+ ordered = canonicalResolverRedactions([]string{"b", "a"})
+ require.Equal(t, []string{"a", "b"}, ordered)
+
+ // The order matches the decision-snapshot canonical form.
+ require.True(t, canonicalRedactions(ordered))
+}
+
+func TestSuppressSetLowercase(t *testing.T) {
+ decision := deriveResolverDecision(map[string]string{"X-Signature": "sig", "x-token": "tok"}, nil)
+ require.Equal(t, map[string]struct{}{"x-signature": {}, "x-token": {}}, decision.Suppress)
+}
diff --git a/components/egress/pkg/credentialvault/resolver_stub_integration_test.go b/components/egress/pkg/credentialvault/resolver_stub_integration_test.go
new file mode 100644
index 000000000..045581b2a
--- /dev/null
+++ b/components/egress/pkg/credentialvault/resolver_stub_integration_test.go
@@ -0,0 +1,282 @@
+// 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 (
+ "bufio"
+ "context"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/alibaba/opensandbox/egress/pkg/constants"
+ "github.com/stretchr/testify/require"
+)
+
+// Integration tests against the frozen OSEP-0025 contract stub
+// (tests/resolver/resolver.py, PR #2495). Every stub assertion is based on
+// the deterministic signature sha256(subject|credential|binding|authority|
+// path) or fixed status codes, never on wall-clock behavior beyond injected
+// delays.
+
+const stubResolverReadyPrefix = "test resolver ready: "
+
+func stubResolverPath(t *testing.T, relative string) string {
+ t.Helper()
+ script, err := filepath.Abs(filepath.Join("..", "..", "..", "..", "components", "egress", "tests", "resolver", relative))
+ require.NoError(t, err)
+ require.FileExists(t, script)
+ return script
+}
+
+func stubResolverScript(t *testing.T) string {
+ t.Helper()
+ if _, err := exec.LookPath("python3"); err != nil {
+ t.Skip("python3 is required for resolver stub integration tests")
+ }
+ return stubResolverPath(t, "resolver.py")
+}
+
+func stubResolverTLSConfig(t *testing.T) *tls.Config {
+ t.Helper()
+ certPEM, err := os.ReadFile(stubResolverPath(t, filepath.Join("fixtures", "test-localhost-cert.pem")))
+ require.NoError(t, err)
+ pool := x509.NewCertPool()
+ require.True(t, pool.AppendCertsFromPEM(certPEM), "fixture certificate must parse")
+ return &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}
+}
+
+type stubResolverProcess struct {
+ cmd *exec.Cmd
+ endpoint string
+}
+
+// startStubResolver launches one resolver.py server process and returns the
+// endpoint it printed on the ready line ("uds://<path>" or
+// "https://HOST:PORT").
+func startStubResolver(t *testing.T, stubEnv []string, args ...string) *stubResolverProcess {
+ t.Helper()
+ script := stubResolverScript(t)
+ python, err := exec.LookPath("python3")
+ require.NoError(t, err)
+
+ cmd := exec.Command(python, append([]string{script}, args...)...)
+ cmd.Env = append(os.Environ(), stubEnv...)
+ stderr, err := cmd.StderrPipe()
+ require.NoError(t, err)
+ cmd.Stdout = io.Discard
+ require.NoError(t, cmd.Start())
+
+ ready := make(chan string, 1)
+ go func() {
+ scanner := bufio.NewScanner(stderr)
+ for scanner.Scan() {
+ if endpoint, ok := strings.CutPrefix(scanner.Text(), stubResolverReadyPrefix); ok {
+ ready <- strings.TrimSpace(endpoint)
+ }
+ }
+ }()
+
+ var process *stubResolverProcess
+ select {
+ case endpoint := <-ready:
+ process = &stubResolverProcess{cmd: cmd, endpoint: endpoint}
+ case <-time.After(15 * time.Second):
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ t.Fatal("resolver stub did not become ready in time")
+ }
+
+ t.Cleanup(func() {
+ _ = process.cmd.Process.Signal(os.Interrupt)
+ done := make(chan struct{})
+ go func() {
+ _ = process.cmd.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ _ = process.cmd.Process.Kill()
+ _ = process.cmd.Wait()
+ }
+ })
+ return process
+}
+
+// shortTempDir avoids AF_UNIX sun_path overflow on long test-name temp dirs.
+func shortTempDir(t *testing.T) string {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "osbr")
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ return dir
+}
+
+func stubSignature(subject, credential, binding, authority, path string) string {
+ source := strings.Join([]string{subject, credential, binding, authority, path}, "|")
+ digest := sha256.Sum256([]byte(source))
+ return hex.EncodeToString(digest[:])
+}
+
+// requireStubHappyDecision asserts the stub's deterministic header set and
+// the merged redaction completeness for the shared test input.
+func requireStubHappyDecision(t *testing.T, decision *ResolverDecision) {
+ t.Helper()
+ input := resolverTestInput()
+ expectedSignature := stubSignature(input.Subject, input.Credential, input.Binding, input.Destination.Authority, input.Request.Path)
+ require.Equal(t, map[string]string{
+ "authorization": "Bearer test-" + input.Credential,
+ "x-test-signature": expectedSignature,
+ "x-test-subject": input.Subject,
+ }, decision.Headers)
+ require.Equal(t, map[string]struct{}{
+ "authorization": {}, "x-test-signature": {}, "x-test-subject": {},
+ }, decision.Suppress)
+
+ // R9: the derived 7-variant set covers every resolved header value even
+ // when the resolver reports no redactions for them.
+ for _, value := range decision.Headers {
+ for _, variant := range substitutionRedactionVariants(value) {
+ require.Contains(t, decision.Redactions, variant)
+ }
+ }
+ require.Contains(t, decision.Redactions, expectedSignature)
+}
+
+func TestStubIntegrationUDSHappyPath(t *testing.T) {
+ socketPath := filepath.Join(shortTempDir(t), "r.sock")
+ stub := startStubResolver(t, nil, "--uds", socketPath)
+ require.True(t, strings.HasPrefix(stub.endpoint, "uds://"), "unexpected endpoint %q", stub.endpoint)
+
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: stub.endpoint, Timeout: 5 * time.Second, MaxConcurrency: 4})
+ require.NoError(t, err)
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ requireStubHappyDecision(t, decision)
+}
+
+func TestStubIntegrationUDSIncompleteRedactions(t *testing.T) {
+ // The stub reports redactions for only one header; derivation stays
+ // authoritative (R9) and still covers every header value.
+ socketPath := filepath.Join(shortTempDir(t), "r.sock")
+ stub := startStubResolver(t, nil, "--uds", socketPath, "--incomplete-redactions")
+
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: stub.endpoint, Timeout: 5 * time.Second, MaxConcurrency: 4})
+ require.NoError(t, err)
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ requireStubHappyDecision(t, decision)
+}
+
+func stubHTTPSArgs(t *testing.T, port int) []string {
+ t.Helper()
+ return []string{
+ "--https", fmt.Sprintf("127.0.0.1:%d", port),
+ "--tls-cert", stubResolverPath(t, filepath.Join("fixtures", "test-localhost-cert.pem")),
+ "--tls-key", stubResolverPath(t, filepath.Join("fixtures", "test-localhost-key.pem")),
+ }
+}
+
+func TestStubIntegrationHTTPSAuthOriginTable(t *testing.T) {
+ // Pre-bind a port so both sides can be configured with the origin before
+ // the stub reads its auth table at startup.
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ require.NoError(t, err)
+ port := listener.Addr().(*net.TCPAddr).Port
+ require.NoError(t, listener.Close())
+ origin := fmt.Sprintf("https://127.0.0.1:%d", port)
+
+ // The same env table configures the stub's expected token and the
+ // client's origin-scoped credential (D5).
+ authEntry := constants.EnvCredentialResolverAuth + "=" + origin + "=resolver-token-1"
+ stub := startStubResolver(t, []string{authEntry}, stubHTTPSArgs(t, port)...)
+ require.Equal(t, origin, stub.endpoint)
+
+ client, err := NewResolverClient(ResolverClientOptions{
+ Endpoint: stub.endpoint,
+ Timeout: 5 * time.Second,
+ MaxConcurrency: 4,
+ Auth: map[string]string{origin: "resolver-token-1"},
+ TLSClientConfig: stubResolverTLSConfig(t),
+ })
+ require.NoError(t, err)
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ requireStubHappyDecision(t, decision)
+}
+
+func TestStubIntegrationHTTPSUnmatchedOriginGetsNoToken(t *testing.T) {
+ // The client only holds a token for a different origin; the stub expects
+ // one for its own origin and must answer 401 — proving no token leaked.
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ require.NoError(t, err)
+ port := listener.Addr().(*net.TCPAddr).Port
+ require.NoError(t, listener.Close())
+ origin := fmt.Sprintf("https://127.0.0.1:%d", port)
+
+ authEntry := constants.EnvCredentialResolverAuth + "=" + origin + "=resolver-token-1"
+ stub := startStubResolver(t, []string{authEntry}, stubHTTPSArgs(t, port)...)
+
+ client, err := NewResolverClient(ResolverClientOptions{
+ Endpoint: stub.endpoint,
+ Timeout: 5 * time.Second,
+ MaxConcurrency: 4,
+ Auth: map[string]string{"https://unrelated-resolver.internal:8443": "resolver-token-1"},
+ TLSClientConfig: stubResolverTLSConfig(t),
+ })
+ require.NoError(t, err)
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ resolverErr := requireKind(t, err, ResolverRejected)
+ require.Equal(t, http.StatusUnauthorized, resolverErr.Status)
+}
+
+func TestStubIntegrationTimeoutClass(t *testing.T) {
+ socketPath := filepath.Join(shortTempDir(t), "r.sock")
+ stub := startStubResolver(t, nil, "--uds", socketPath, "--delay", "2000")
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: stub.endpoint, Timeout: 300 * time.Millisecond, MaxConcurrency: 4})
+ require.NoError(t, err)
+ start := time.Now()
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ requireKind(t, err, ResolverTimeout)
+ require.Less(t, time.Since(start), 1500*time.Millisecond)
+}
+
+func TestStubIntegrationFailOnceThenRecover(t *testing.T) {
+ socketPath := filepath.Join(shortTempDir(t), "r.sock")
+ stub := startStubResolver(t, nil, "--uds", socketPath, "--fail", "once")
+ client, err := NewResolverClient(ResolverClientOptions{Endpoint: stub.endpoint, Timeout: 5 * time.Second, MaxConcurrency: 4})
+ require.NoError(t, err)
+
+ _, err = client.Resolve(context.Background(), resolverTestInput())
+ resolverErr := requireKind(t, err, ResolverRejected)
+ require.Equal(t, http.StatusServiceUnavailable, resolverErr.Status)
+
+ // The refusal is per-request: the next resolve succeeds deterministically.
+ decision, err := client.Resolve(context.Background(), resolverTestInput())
+ require.NoError(t, err)
+ requireStubHappyDecision(t, decision)
+}