Skip to content

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

feat(egress): add exchange credential source, typeless auth, and vault snapshot markers (OSEP-0025 T1)

高然22741d114628
diff --git a/components/egress/pkg/credentialvault/candidate.go b/components/egress/pkg/credentialvault/candidate.go
index 1d9447b90..f40bcdfb6 100644
--- a/components/egress/pkg/credentialvault/candidate.go
+++ b/components/egress/pkg/credentialvault/candidate.go
@@ -395,6 +395,19 @@ func renderActiveSnapshot(
sort.Strings(names)
for _, name := range names {
binding := bindings[name]
+ if binding.Auth.Type == "" {
+ // Typeless exchange binding: marker-only. No credential material
+ // is rendered locally and no resolve network call happens on this
+ // path — header sets are resolved per request by the resolver.
+ snapshot.Bindings = append(snapshot.Bindings, ActiveBinding{
+ Name: binding.Name,
+ Match: binding.Match,
+ Headers: []InjectionHeader{},
+ Substitutions: &[]InjectionSubstitution{},
+ Exchange: &ExchangeRef{Credential: binding.Auth.Credential},
+ })
+ continue
+ }
headers, values, err := renderInjectionHeaders(ctx, binding.Auth, credentials)
if err != nil {
return ActiveSnapshot{}, err
@@ -403,12 +416,15 @@ func renderActiveSnapshot(
if err != nil {
return ActiveSnapshot{}, err
}
- snapshot.Bindings = append(snapshot.Bindings, ActiveBinding{
- Name: binding.Name,
- Match: binding.Match,
- Headers: headers,
- Substitutions: substitutions,
- })
+ rendered := ActiveBinding{
+ Name: binding.Name,
+ Match: binding.Match,
+ Headers: headers,
+ }
+ if len(substitutions) > 0 {
+ rendered.Substitutions = &substitutions
+ }
+ snapshot.Bindings = append(snapshot.Bindings, rendered)
values = append(values, substitutionValues...)
for _, value := range values {
if value != "" {
@@ -435,19 +451,26 @@ func cloneActiveSnapshot(snapshot ActiveSnapshot) ActiveSnapshot {
Redactions: append([]string(nil), snapshot.Redactions...),
}
for i, binding := range snapshot.Bindings {
- clone.Bindings[i] = ActiveBinding{
- Name: binding.Name,
- Match: cloneMatch(binding.Match),
- Headers: append([]InjectionHeader(nil), binding.Headers...),
- Substitutions: make([]InjectionSubstitution, len(binding.Substitutions)),
+ rendered := ActiveBinding{
+ Name: binding.Name,
+ Match: cloneMatch(binding.Match),
+ Headers: append([]InjectionHeader(nil), binding.Headers...),
}
- for j, substitution := range binding.Substitutions {
- clone.Bindings[i].Substitutions[j] = InjectionSubstitution{
- Placeholder: substitution.Placeholder,
- Value: substitution.Value,
- In: append([]string(nil), substitution.In...),
+ if binding.Substitutions != nil {
+ subs := make([]InjectionSubstitution, len(*binding.Substitutions))
+ for j, substitution := range *binding.Substitutions {
+ subs[j] = InjectionSubstitution{
+ Placeholder: substitution.Placeholder,
+ Value: substitution.Value,
+ In: append([]string(nil), substitution.In...),
+ }
}
+ rendered.Substitutions = &subs
+ }
+ if binding.Exchange != nil {
+ rendered.Exchange = &ExchangeRef{Credential: binding.Exchange.Credential}
}
+ clone.Bindings[i] = rendered
}
return clone
}
diff --git a/components/egress/pkg/credentialvault/decision_snapshot.go b/components/egress/pkg/credentialvault/decision_snapshot.go
index 7d246b5ec..4cf4d3a20 100644
--- a/components/egress/pkg/credentialvault/decision_snapshot.go
+++ b/components/egress/pkg/credentialvault/decision_snapshot.go
@@ -133,13 +133,36 @@ func validRenderedBinding(binding *ActiveBinding, redactions map[string]struct{}
selectors[host] = struct{}{}
}
}
- if len(seenHosts) == 0 || !validRenderedCredentials(binding, redactions) {
+ if len(seenHosts) == 0 {
return false
}
binding.Headers = append([]InjectionHeader{}, binding.Headers...)
- binding.Substitutions = append([]InjectionSubstitution{}, binding.Substitutions...)
- for i := range binding.Substitutions {
- binding.Substitutions[i].In = append([]string{}, binding.Substitutions[i].In...)
+ if binding.Exchange != nil {
+ // OSEP-0025 marker binding: a credential-only reference with no
+ // rendered material, so no redaction coverage is required. The
+ // canonical encoding carries explicit empty headers/substitutions
+ // arrays; readers without exchange support reject the unknown key
+ // (version-skew fail closed).
+ credential := binding.Exchange.Credential
+ if credential == "" || credential != strings.TrimSpace(credential) {
+ return false
+ }
+ if len(binding.Headers) != 0 {
+ return false
+ }
+ empty := []InjectionSubstitution{}
+ binding.Substitutions = &empty
+ return true
+ }
+ if !validRenderedCredentials(binding, redactions) {
+ return false
+ }
+ if binding.Substitutions != nil {
+ subs := append([]InjectionSubstitution{}, *binding.Substitutions...)
+ for i := range subs {
+ subs[i].In = append([]string{}, subs[i].In...)
+ }
+ binding.Substitutions = &subs
}
return true
}
@@ -179,20 +202,22 @@ func validRenderedCredentials(binding *ActiveBinding, redactions map[string]stru
}
}
}
- for _, substitution := range binding.Substitutions {
- if substitution.Placeholder == "" || !validCanonicalStringsOnly(substitution.In, func(value string) bool {
- return value == "path" || value == "query" || value == "header" || value == "body"
- }) {
- return false
- }
- required := append(substitutionRedactionVariants(substitution.Value), substitution.Placeholder)
- for _, value := range required {
- if value == "" {
- continue
- }
- if _, ok := redactions[value]; !ok {
+ if binding.Substitutions != nil {
+ for _, substitution := range *binding.Substitutions {
+ if substitution.Placeholder == "" || !validCanonicalStringsOnly(substitution.In, func(value string) bool {
+ return value == "path" || value == "query" || value == "header" || value == "body"
+ }) {
return false
}
+ required := append(substitutionRedactionVariants(substitution.Value), substitution.Placeholder)
+ for _, value := range required {
+ if value == "" {
+ continue
+ }
+ if _, ok := redactions[value]; !ok {
+ return false
+ }
+ }
}
}
return true
diff --git a/components/egress/pkg/credentialvault/decision_snapshot_test.go b/components/egress/pkg/credentialvault/decision_snapshot_test.go
index b4d7bb296..ebbdb2919 100644
--- a/components/egress/pkg/credentialvault/decision_snapshot_test.go
+++ b/components/egress/pkg/credentialvault/decision_snapshot_test.go
@@ -43,8 +43,7 @@ func renderedBinding(name string, schemes, hosts []string, secret string) Active
Methods: []string{"GET"},
Paths: []string{"/api/*"},
},
- Headers: headers,
- Substitutions: []InjectionSubstitution{},
+ Headers: headers,
}
}
@@ -195,6 +194,65 @@ func TestMarshalDecisionSnapshotRequiresCanonicalRedactionOrder(t *testing.T) {
require.True(t, errors.Is(err, ErrInvalidDecisionSnapshot))
}
+func TestMarshalDecisionSnapshotAcceptsExchangeMarkers(t *testing.T) {
+ exchangeBinding := renderedBinding("exchange-binding", []string{"https"}, []string{"api.internal.example.com"}, "")
+ exchangeBinding.Exchange = &ExchangeRef{Credential: "spi-signer"}
+ snapshot := ActiveSnapshot{Revision: 3, Bindings: []ActiveBinding{exchangeBinding}}
+ payload, err := MarshalDecisionSnapshot(snapshot, 5)
+ require.NoError(t, err)
+ require.JSONEq(t, `{
+ "version": 1,
+ "vaultRevision": 3,
+ "effectivePolicyEpoch": 5,
+ "interceptionMode": "credential-bound",
+ "state": "active",
+ "tlsBindingHostSelectors": ["api.internal.example.com"],
+ "fullRenderedBindings": [{
+ "name": "exchange-binding",
+ "match": {"schemes": ["https"], "hosts": ["api.internal.example.com"], "methods": ["GET"], "paths": ["/api/*"]},
+ "headers": [],
+ "substitutions": [],
+ "exchange": {"credential": "spi-signer"}
+ }],
+ "redactions": []
+ }`, string(payload))
+
+ // The canonical encoding is stable: re-marshaling the decoded payload
+ // reproduces the same bytes.
+ var redecoded decisionSnapshot
+ require.NoError(t, json.Unmarshal(payload, &redecoded))
+ again, err := MarshalDecisionSnapshot(ActiveSnapshot{
+ Revision: redecoded.VaultRevision,
+ Bindings: redecoded.FullRenderedBindings,
+ Redactions: redecoded.Redactions,
+ }, 5)
+ require.NoError(t, err)
+ require.Equal(t, payload, again)
+}
+
+func TestMarshalDecisionSnapshotRejectsNonCanonicalExchangeMarkers(t *testing.T) {
+ valid := renderedBinding("exchange-binding", []string{"https"}, []string{"api.internal.example.com"}, "")
+ valid.Exchange = &ExchangeRef{Credential: "spi-signer"}
+ tests := []struct {
+ name string
+ mutate func(*ActiveBinding)
+ }{
+ {"blank credential", func(b *ActiveBinding) { b.Exchange.Credential = "" }},
+ {"padded credential", func(b *ActiveBinding) { b.Exchange.Credential = " spi-signer " }},
+ {"rendered header", func(b *ActiveBinding) { b.Headers = []InjectionHeader{{Name: "Authorization", Value: "never-log-me"}} }},
+ {"nil exchange credential", func(b *ActiveBinding) { b.Exchange = &ExchangeRef{} }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ candidate := valid
+ tc.mutate(&candidate)
+ _, err := MarshalDecisionSnapshot(ActiveSnapshot{Revision: 1, Bindings: []ActiveBinding{candidate}}, 1)
+ require.ErrorIs(t, err, ErrInvalidDecisionSnapshot)
+ require.NotContains(t, err.Error(), "never-log-me")
+ })
+ }
+}
+
func TestMarshalDecisionSnapshotOmitsAcceptedEmptyWildcardLanguage(t *testing.T) {
base := strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + "." +
strings.Repeat("c", 63) + "." + strings.Repeat("d", 60)
diff --git a/components/egress/pkg/credentialvault/source.go b/components/egress/pkg/credentialvault/source.go
index bbe281049..f7d19ed5f 100644
--- a/components/egress/pkg/credentialvault/source.go
+++ b/components/egress/pkg/credentialvault/source.go
@@ -41,13 +41,14 @@ type SourceRegistry struct {
factories map[string]CredentialSourceFactory
}
-// NewSourceRegistry creates a registry with the built-in inline provider
-// pre-registered.
+// NewSourceRegistry creates a registry with the built-in inline and exchange
+// providers pre-registered.
func NewSourceRegistry() *SourceRegistry {
r := &SourceRegistry{
factories: make(map[string]CredentialSourceFactory),
}
r.Register("inline", inlineSourceFactory)
+ r.Register("exchange", exchangeSourceFactory)
return r
}
diff --git a/components/egress/pkg/credentialvault/source_exchange.go b/components/egress/pkg/credentialvault/source_exchange.go
new file mode 100644
index 000000000..5e66ba4eb
--- /dev/null
+++ b/components/egress/pkg/credentialvault/source_exchange.go
@@ -0,0 +1,84 @@
+// 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"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strings"
+)
+
+// exchangeSource is a credential with no local material: header sets are
+// resolved per request by an external header-resolver service (OSEP-0025).
+// Resolve is deliberately offline — exchange credentials are never rendered
+// into static snapshots; they surface only as binding markers and are
+// resolved on the per-request path.
+type exchangeSource struct {
+ endpoint string
+}
+
+func (s *exchangeSource) Type() string { return "exchange" }
+
+func (s *exchangeSource) Resolve(_ context.Context) (string, error) {
+ return "", fmt.Errorf("exchange credential cannot be resolved inline; it resolves per request via the credential resolver")
+}
+
+// exchangeSourceFactory creates an exchangeSource from the raw JSON "source"
+// object. Expected shape: {"type": "exchange", "endpoint": "<uri>"}.
+// Unknown fields are rejected to match the OpenAPI additionalProperties: false
+// contract. Supported endpoint forms are unix:///absolute/path (HTTP over a
+// Unix domain socket) and https://host[:port] (optionally with a path
+// prefix); anything else is rejected.
+func exchangeSourceFactory(raw json.RawMessage) (CredentialSource, error) {
+ var src struct {
+ Type string `json:"type"`
+ Endpoint string `json:"endpoint"`
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(&src); err != nil {
+ return nil, fmt.Errorf("parse exchange credential source: %w", err)
+ }
+ endpoint, err := validateResolverEndpoint(src.Endpoint)
+ if err != nil {
+ return nil, err
+ }
+ return &exchangeSource{endpoint: endpoint}, nil
+}
+
+func validateResolverEndpoint(endpoint string) (string, error) {
+ switch {
+ case strings.HasPrefix(endpoint, "unix://"):
+ path := strings.TrimPrefix(endpoint, "unix://")
+ if !strings.HasPrefix(path, "/") || len(path) < 2 {
+ return "", fmt.Errorf("exchange credential endpoint %q must be an absolute unix:///path", endpoint)
+ }
+ return endpoint, nil
+ case strings.HasPrefix(endpoint, "https://"):
+ parsed, err := url.Parse(endpoint)
+ if err != nil {
+ return "", fmt.Errorf("exchange credential endpoint %q is not a valid https URL", endpoint)
+ }
+ if parsed.Host == "" || parsed.User != nil {
+ return "", fmt.Errorf("exchange credential endpoint %q must address https://host[:port]", endpoint)
+ }
+ return endpoint, nil
+ default:
+ return "", fmt.Errorf("exchange credential endpoint %q must use the unix:/// or https:// scheme", endpoint)
+ }
+}
diff --git a/components/egress/pkg/credentialvault/source_exchange_test.go b/components/egress/pkg/credentialvault/source_exchange_test.go
new file mode 100644
index 000000000..026b4fb77
--- /dev/null
+++ b/components/egress/pkg/credentialvault/source_exchange_test.go
@@ -0,0 +1,69 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package credentialvault
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExchangeSourceFactoryAcceptsSupportedEndpoints(t *testing.T) {
+ for _, endpoint := range []string{
+ "unix:///run/spi/spi.sock",
+ "https://header-resolver.internal",
+ "https://resolver.internal:8443",
+ "https://resolver.internal/prefix",
+ } {
+ t.Run(endpoint, func(t *testing.T) {
+ source, err := NewSourceRegistry().Create(mustMarshal(map[string]string{"type": "exchange", "endpoint": endpoint}))
+ require.NoError(t, err)
+ require.Equal(t, "exchange", source.Type())
+ })
+ }
+}
+
+func TestExchangeSourceFactoryRejects(t *testing.T) {
+ tests := []struct {
+ name string
+ source string
+ }{
+ {"empty endpoint", `{"type":"exchange","endpoint":""}`},
+ {"http scheme", `{"type":"exchange","endpoint":"http://resolver.internal"}`},
+ {"bare host", `{"type":"exchange","endpoint":"resolver.internal:8443"}`},
+ {"unix relative path", `{"type":"exchange","endpoint":"unix://spi.sock"}`},
+ {"unix empty path", `{"type":"exchange","endpoint":"unix:///"}`},
+ {"unknown field", `{"type":"exchange","endpoint":"unix:///run/spi.sock","value":"secret"}`},
+ {"missing endpoint", `{"type":"exchange"}`},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := NewSourceRegistry().Create(json.RawMessage(tc.source))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "exchange credential")
+ })
+ }
+}
+
+func TestExchangeSourceResolveNeverTouchesTheNetwork(t *testing.T) {
+ source, err := exchangeSourceFactory(mustMarshal(map[string]string{"type": "exchange", "endpoint": "unix:///run/spi/spi.sock"}))
+ require.NoError(t, err)
+ value, err := source.Resolve(context.Background())
+ require.Error(t, err)
+ require.Empty(t, value)
+ require.Contains(t, err.Error(), "cannot be resolved inline")
+}
diff --git a/components/egress/pkg/credentialvault/vault.go b/components/egress/pkg/credentialvault/vault.go
index 2462407f1..bf3894377 100644
--- a/components/egress/pkg/credentialvault/vault.go
+++ b/components/egress/pkg/credentialvault/vault.go
@@ -89,6 +89,7 @@ type Store struct {
strictMatch bool
liveAdmission bool
staticPassthrough mitmpassthrough.Config
+ resolverConfig ResolverConfig
}
type record struct {
@@ -175,7 +176,7 @@ type Match struct {
}
type Auth struct {
- Type string `json:"type"`
+ Type string `json:"type,omitempty"`
Credential string `json:"credential,omitempty"`
Name string `json:"name,omitempty"`
Headers []CustomHeaderEntry `json:"headers,omitempty"`
@@ -223,8 +224,9 @@ type BindingMetadata struct {
}
type AuthMetadata struct {
- Type string `json:"type"`
- Name string `json:"name,omitempty"`
+ Type string `json:"type,omitempty"`
+ Name string `json:"name,omitempty"`
+ Credential string `json:"credential,omitempty"`
}
type ActiveSnapshot struct {
@@ -233,11 +235,20 @@ type ActiveSnapshot struct {
Redactions []string `json:"redactions,omitempty"`
}
+// ExchangeRef marks an exchange-resolved binding in snapshots: header sets
+// are not materialized locally, only the credential that the per-request
+// resolve path must consult. The referenced credential is always
+// exchange-sourced (enforced by validateAuthSourceCrossLock).
+type ExchangeRef struct {
+ Credential string `json:"credential"`
+}
+
type ActiveBinding struct {
- Name string `json:"name"`
- Match Match `json:"match"`
- Headers []InjectionHeader `json:"headers"`
- Substitutions []InjectionSubstitution `json:"substitutions,omitempty"`
+ Name string `json:"name"`
+ Match Match `json:"match"`
+ Headers []InjectionHeader `json:"headers"`
+ Substitutions *[]InjectionSubstitution `json:"substitutions,omitempty"`
+ Exchange *ExchangeRef `json:"exchange,omitempty"`
}
type InjectionHeader struct {
@@ -259,6 +270,31 @@ func NewLiveStore(gate *mitmproxy.HealthGate, requireToken func() bool, config m
return store
}
+// ResolverConfig reports whether the credential resolver operator
+// configuration (OSEP-0025 D13) is ready: a resolve timeout is configured and
+// the endpoint-scoped auth table parsed successfully. The zero value is not
+// ready — vaults referencing exchange credentials fail closed until the
+// transport layer injects its parsed configuration.
+type ResolverConfig struct {
+ TimeoutConfigured bool
+ AuthTableParsed bool
+}
+
+// Ready reports whether vaults referencing exchange credentials may be
+// admitted.
+func (c ResolverConfig) Ready() bool {
+ return c.TimeoutConfigured && c.AuthTableParsed
+}
+
+// SetResolverConfig installs the resolver operator-config readiness used by
+// the exchange capability gate. Callers must invoke it before serving vault
+// mutations.
+func (v *Store) SetResolverConfig(config ResolverConfig) {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ v.resolverConfig = config
+}
+
func NewStore(mitmGate *mitmproxy.HealthGate, requireToken func() bool) *Store {
return NewStoreWithRegistry(mitmGate, requireToken, nil)
}
@@ -495,10 +531,16 @@ func (v *Store) validateCandidate(credentials map[string]record, bindings map[st
if len(bindings) > 0 && pol.DefaultAction != policy.ActionDeny {
log.Warnf("credential vault: default-allow egress policy is deprecated and may allow credential destination bypass; use defaultAction=deny")
}
+ if err := v.validateExchangeAdmission(credentials); err != nil {
+ return err
+ }
for _, b := range bindings {
if err := validateBindingCredentialRefs(b, credentials); err != nil {
return err
}
+ if err := validateAuthSourceCrossLock(b, credentials); err != nil {
+ return err
+ }
if err := v.validateBindingPolicy(b, pol); err != nil {
return err
}
@@ -509,6 +551,31 @@ func (v *Store) validateCandidate(credentials map[string]record, bindings map[st
return nil
}
+// validateExchangeAdmission is the exchange fail-closed gate: a vault that
+// carries exchange-sourced credentials is admitted only by stores with the
+// capability to serve the per-request resolve path. The live revision runtime
+// never supports exchange; ordinary stores require the resolver operator
+// configuration (D13). Inline-only vaults are unaffected.
+func (v *Store) validateExchangeAdmission(credentials map[string]record) error {
+ hasExchange := false
+ for _, credential := range credentials {
+ if credential.SourceType == "exchange" {
+ hasExchange = true
+ break
+ }
+ }
+ if !hasExchange {
+ return nil
+ }
+ if v.liveAdmission {
+ return fmt.Errorf("exchange credentials are not supported in the live revision runtime")
+ }
+ if !v.resolverConfig.Ready() {
+ return fmt.Errorf("exchange credentials are not supported until the credential resolver operator configuration is ready")
+ }
+ return nil
+}
+
func (v *Store) validateBindingPolicy(b Binding, pol *policy.NetworkPolicy) error {
if v.liveAdmission && slices.Contains(b.Match.Schemes, "https") {
for _, host := range b.Match.Hosts {
@@ -692,6 +759,24 @@ func normalizeAuth(a *Auth) error {
if len(a.Headers) != 0 {
return fmt.Errorf("passthrough auth does not accept headers")
}
+ case "":
+ // Typeless: the exchange-only reference form. The referenced
+ // credential must be exchange-sourced (cross-lock) and nothing else
+ // may ride along — header sets resolve per request, never locally.
+ a.Credential = strings.TrimSpace(a.Credential)
+ if a.Credential == "" {
+ return fmt.Errorf("typeless auth requires credential")
+ }
+ if strings.TrimSpace(a.Name) != "" {
+ return fmt.Errorf("typeless auth does not accept name")
+ }
+ if len(a.Headers) != 0 {
+ return fmt.Errorf("typeless auth does not accept headers")
+ }
+ if len(a.Substitutions) != 0 {
+ return fmt.Errorf("typeless auth does not accept substitutions")
+ }
+ return nil
default:
return fmt.Errorf("unsupported auth type %q", a.Type)
}
@@ -717,15 +802,65 @@ func validateBindingCredentialRefs(b Binding, credentials map[string]record) err
return nil
}
+// validateAuthSourceCrossLock pins the OSEP-0025 reference discipline: static
+// auth types render locally and must never consume exchange-sourced
+// credentials, while the typeless exchange form exists only for them.
+// Substitution values always render locally, so they reject exchange
+// credentials for every auth type. passthrough references no auth credential
+// and is otherwise unrestricted. Custom (non-exchange) source types keep
+// working with static auth.
+func validateAuthSourceCrossLock(b Binding, credentials map[string]record) error {
+ for _, name := range authCredentialRefs(b.Auth) {
+ rec, ok := credentials[name]
+ if !ok {
+ continue // unknown references are reported by validateBindingCredentialRefs
+ }
+ switch b.Auth.Type {
+ case "":
+ if rec.SourceType != "exchange" {
+ return fmt.Errorf("binding %q typeless auth requires an exchange credential, but %q is %s-sourced", b.Name, name, rec.SourceType)
+ }
+ case "passthrough":
+ default:
+ if rec.SourceType == "exchange" {
+ return fmt.Errorf("binding %q %s auth cannot reference the exchange credential %q; only the typeless auth form may use exchange credentials", b.Name, b.Auth.Type, name)
+ }
+ }
+ }
+ for _, name := range substitutionCredentialRefs(b.Auth) {
+ rec, ok := credentials[name]
+ if !ok {
+ continue
+ }
+ if rec.SourceType == "exchange" {
+ return fmt.Errorf("binding %q substitution cannot reference the exchange credential %q; substitutions render locally and only inline credentials support that", b.Name, name)
+ }
+ }
+ return nil
+}
+
func credentialRefsForAuth(auth Auth) []string {
+ return append(authCredentialRefs(auth), substitutionCredentialRefs(auth)...)
+}
+
+func authCredentialRefs(auth Auth) []string {
var out []string
- if auth.Type == "customHeaders" {
+ switch auth.Type {
+ case "customHeaders":
for _, h := range auth.Headers {
out = append(out, h.Credential)
}
- } else if auth.Type != "passthrough" && auth.Credential != "" {
- out = append(out, auth.Credential)
+ case "passthrough":
+ default:
+ if auth.Credential != "" {
+ out = append(out, auth.Credential)
+ }
}
+ return out
+}
+
+func substitutionCredentialRefs(auth Auth) []string {
+ var out []string
for _, substitution := range auth.Substitutions {
out = append(out, substitution.Credential)
}
@@ -777,6 +912,12 @@ func renderInjectionHeaders(ctx context.Context, auth Auth, credentials map[stri
redactions = append(redactions, value)
}
case "passthrough":
+ case "":
+ // Typeless bindings reference exchange credentials and are rendered
+ // as snapshot markers only; their header sets come from the
+ // per-request resolve path. Defensive: renderActiveSnapshot never
+ // routes them here.
+ return nil, nil, fmt.Errorf("typeless exchange auth cannot be rendered as static injection headers")
default:
return nil, nil, fmt.Errorf("unsupported auth type %q", auth.Type)
}
@@ -893,6 +1034,8 @@ func sanitizeAuth(auth Auth) AuthMetadata {
switch auth.Type {
case "apiKey":
meta.Name = auth.Name
+ case "":
+ meta.Credential = auth.Credential
}
return meta
}
diff --git a/components/egress/pkg/credentialvault/vault_test.go b/components/egress/pkg/credentialvault/vault_test.go
index e3011f255..7f0e1e65c 100644
--- a/components/egress/pkg/credentialvault/vault_test.go
+++ b/components/egress/pkg/credentialvault/vault_test.go
@@ -25,6 +25,7 @@ import (
"testing"
"github.com/alibaba/opensandbox/egress/pkg/constants"
+ "github.com/alibaba/opensandbox/egress/pkg/mitmpassthrough"
"github.com/alibaba/opensandbox/egress/pkg/policy"
"github.com/stretchr/testify/require"
)
@@ -288,7 +289,7 @@ func TestCredentialVaultRendersScopedSubstitutions(t *testing.T) {
require.NoError(t, err)
require.Equal(t, int64(1), payload.Revision)
require.Empty(t, payload.Bindings[0].Headers)
- require.Equal(t, []InjectionSubstitution{
+ require.Equal(t, &[]InjectionSubstitution{
{
Placeholder: "__client_secret__",
Value: `real "clé"&value😀`,
@@ -606,3 +607,273 @@ ignore_hosts: ['^example\.com$', ".*\.internal$"]
require.Nil(t, parseMitmproxyIgnoreHosts("ignore_hosts: []"))
}
+
+func testExchangeCredential(name string) Credential {
+ return Credential{
+ Name: name,
+ Source: mustMarshal(map[string]string{"type": "exchange", "endpoint": "unix:///run/spi/" + name + ".sock"}),
+ }
+}
+
+func testExchangeVaultRequest() CreateRequest {
+ return CreateRequest{
+ Credentials: []Credential{testExchangeCredential("spi-signer")},
+ Bindings: []Binding{
+ {
+ Name: "internal-api",
+ Match: Match{
+ Hosts: []string{"api.internal.example.com"},
+ Methods: []string{"GET"},
+ Paths: []string{"/*"},
+ },
+ Auth: Auth{Credential: "spi-signer"},
+ },
+ },
+ }
+}
+
+func testExchangePolicy(t *testing.T) *policy.NetworkPolicy {
+ return testCredentialPolicy(t, `{"defaultAction":"deny","egress":[{"action":"allow","target":"api.internal.example.com"}]}`)
+}
+
+func testResolverReadyStore() *Store {
+ store := NewStore(nil, func() bool { return true })
+ store.SetResolverConfig(ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true})
+ return store
+}
+
+func TestCredentialVaultTypelessExchangeAuthSanitizesAndRendersMarker(t *testing.T) {
+ store := testResolverReadyStore()
+ state, err := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, err)
+ require.Equal(t, []Metadata{{Name: "spi-signer", SourceType: "exchange", Revision: 1}}, state.Credentials)
+ require.Equal(t, AuthMetadata{Credential: "spi-signer"}, state.Bindings[0].Auth)
+ require.NotContains(t, string(mustMarshal(state)), "unix:///run/spi/spi-signer.sock")
+
+ snapshot, err := store.ActiveSnapshot()
+ require.NoError(t, err)
+ require.Len(t, snapshot.Bindings, 1)
+ require.Empty(t, snapshot.Bindings[0].Headers)
+ require.Empty(t, *snapshot.Bindings[0].Substitutions)
+ require.Equal(t, &ExchangeRef{Credential: "spi-signer"}, snapshot.Bindings[0].Exchange)
+ require.Empty(t, snapshot.Redactions)
+ require.JSONEq(t, `{
+ "revision": 1,
+ "bindings": [{
+ "name": "internal-api",
+ "match": {"schemes": ["https"], "hosts": ["api.internal.example.com"], "methods": ["GET"], "paths": ["/*"]},
+ "headers": [],
+ "substitutions": [],
+ "exchange": {"credential": "spi-signer"}
+ }]
+ }`, string(mustMarshal(snapshot)))
+}
+
+func TestCredentialVaultTypelessAuthRejectsExtraFields(t *testing.T) {
+ base := testExchangeVaultRequest()
+ tests := []struct {
+ name string
+ auth Auth
+ }{
+ {"missing credential", Auth{}},
+ {"blank credential", Auth{Credential: " "}},
+ {"with name", Auth{Credential: "spi-signer", Name: "x-signature"}},
+ {"with headers", Auth{Credential: "spi-signer", Headers: []CustomHeaderEntry{{Name: "x-a", Credential: "spi-signer"}}}},
+ {"with substitutions", Auth{Credential: "spi-signer", Substitutions: []Substitution{{Credential: "spi-signer", Placeholder: "__t__", In: []string{"header"}}}}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ store := testResolverReadyStore()
+ request := base
+ request.Bindings[0].Auth = tc.auth
+ _, err := store.Create(request, testExchangePolicy(t))
+ require.Error(t, err)
+ response := httptest.NewRecorder()
+ WriteError(response, err)
+ require.Equal(t, http.StatusBadRequest, response.Code)
+ require.NotContains(t, response.Body.String(), "unsupported auth type")
+ })
+ }
+}
+
+func TestCredentialVaultCrossLockRejectsMixedSourceReferences(t *testing.T) {
+ tests := []struct {
+ name string
+ auth Auth
+ unwant string
+ }{
+ {
+ name: "bearer references exchange",
+ auth: Auth{Type: "bearer", Credential: "spi-signer"},
+ unwant: "only the typeless auth form may use exchange credentials",
+ },
+ {
+ name: "apiKey references exchange",
+ auth: Auth{Type: "apiKey", Name: "x-token", Credential: "spi-signer"},
+ unwant: "only the typeless auth form may use exchange credentials",
+ },
+ {
+ name: "customHeaders references exchange",
+ auth: Auth{Type: "customHeaders", Headers: []CustomHeaderEntry{{Name: "x-token", Credential: "spi-signer"}}},
+ unwant: "only the typeless auth form may use exchange credentials",
+ },
+ {
+ name: "typeless references inline",
+ auth: Auth{Credential: "gitlab-token"},
+ unwant: "requires an exchange credential",
+ },
+ {
+ name: "substitution references exchange",
+ auth: Auth{Type: "passthrough", Substitutions: []Substitution{{Credential: "spi-signer", Placeholder: "__t__", In: []string{"header"}}}},
+ unwant: "substitution cannot reference the exchange credential",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ store := testResolverReadyStore()
+ request := CreateRequest{
+ Credentials: []Credential{
+ {Name: "gitlab-token", Source: mustMarshal(map[string]string{"type": "inline", "value": "secret-token"})},
+ testExchangeCredential("spi-signer"),
+ },
+ Bindings: []Binding{{
+ Name: "mixed",
+ Match: Match{Hosts: []string{"api.internal.example.com"}},
+ Auth: tc.auth,
+ }},
+ }
+ _, err := store.Create(request, testExchangePolicy(t))
+ require.ErrorContains(t, err, tc.unwant)
+ _, err = store.PrepareCreate(request, testExchangePolicy(t))
+ require.Error(t, err)
+ })
+ }
+}
+
+func TestCredentialVaultMixedInlineAndExchangeBindingsAreValid(t *testing.T) {
+ store := testResolverReadyStore()
+ request := testExchangeVaultRequest()
+ request.Credentials = append(request.Credentials,
+ Credential{Name: "gitlab-token", Source: mustMarshal(map[string]string{"type": "inline", "value": "secret-token"})},
+ )
+ request.Bindings = append(request.Bindings, Binding{
+ Name: "gitlab-api",
+ Match: Match{Hosts: []string{"code.example.com"}, Methods: []string{"GET"}, Paths: []string{"/api/*"}},
+ Auth: Auth{Type: "apiKey", Name: "private-token", Credential: "gitlab-token"},
+ })
+ pol := testCredentialPolicy(t, `{"defaultAction":"deny","egress":[
+ {"action":"allow","target":"api.internal.example.com"},
+ {"action":"allow","target":"code.example.com"}
+ ]}`)
+ state, err := store.Create(request, pol)
+ require.NoError(t, err)
+ require.Len(t, state.Credentials, 2)
+ require.Len(t, state.Bindings, 2)
+
+ snapshot, err := store.ActiveSnapshot()
+ require.NoError(t, err)
+ byName := map[string]ActiveBinding{}
+ for _, binding := range snapshot.Bindings {
+ byName[binding.Name] = binding
+ }
+ require.Nil(t, byName["gitlab-api"].Exchange)
+ require.Equal(t, &ExchangeRef{Credential: "spi-signer"}, byName["internal-api"].Exchange)
+ require.Equal(t, "secret-token", byName["gitlab-api"].Headers[0].Value)
+ require.Contains(t, snapshot.Redactions, "secret-token")
+}
+
+func TestCredentialVaultExchangeRequiresResolverConfiguration(t *testing.T) {
+ tests := []struct {
+ name string
+ config ResolverConfig
+ }{
+ {"unset", ResolverConfig{}},
+ {"timeout only", ResolverConfig{TimeoutConfigured: true}},
+ {"auth only", ResolverConfig{AuthTableParsed: true}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ store := NewStore(nil, func() bool { return true })
+ store.SetResolverConfig(tc.config)
+ _, err := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.ErrorContains(t, err, "credential resolver operator configuration")
+ _, err = store.PrepareReplace(ReplaceRequest{CreateRequest: testExchangeVaultRequest()}, testExchangePolicy(t))
+ require.Error(t, err)
+ })
+ }
+
+ store := NewStore(nil, func() bool { return true })
+ store.SetResolverConfig(ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true})
+ _, err := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.NoError(t, err)
+}
+
+func TestCredentialVaultExchangeGateCoversUnreferencedCredentials(t *testing.T) {
+ store := NewStore(nil, func() bool { return true })
+ request := CreateRequest{Credentials: []Credential{testExchangeCredential("unused-exchange")}}
+ _, err := store.Create(request, testExchangePolicy(t))
+ require.ErrorContains(t, err, "credential resolver operator configuration")
+
+ store.SetResolverConfig(ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true})
+ _, err = store.Create(request, testExchangePolicy(t))
+ require.NoError(t, err)
+}
+
+func TestCredentialVaultLiveRevisionRuntimeRejectsExchange(t *testing.T) {
+ store := NewLiveStore(nil, func() bool { return true }, mitmpassthrough.Config{})
+ store.SetResolverConfig(ResolverConfig{TimeoutConfigured: true, AuthTableParsed: true})
+ _, err := store.Create(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.ErrorContains(t, err, "exchange credentials are not supported in the live revision runtime")
+ _, err = store.PrepareCreate(testExchangeVaultRequest(), testExchangePolicy(t))
+ require.ErrorContains(t, err, "exchange credentials are not supported in the live revision runtime")
+
+ // The live runtime still admits inline-only vaults unchanged.
+ pol := testCredentialPolicy(t, `{"defaultAction":"deny","egress":[{"action":"allow","target":"code.example.com"}]}`)
+ _, err = store.Create(testCredentialVaultRequest(), pol)
+ require.NoError(t, err)
+}
+
+func TestCredentialVaultExchangeReloadRequiresNoResolverListener(t *testing.T) {
+ // Reload runs factory validation and the capability gate only — it must
+ // never dial the resolver, so it succeeds without anything listening on
+ // the endpoint socket.
+ store := testResolverReadyStore()
+ require.NoError(t, store.Reload(4, testExchangeVaultRequest(), testExchangePolicy(t)))
+ snapshot, err := store.ActiveSnapshot()
+ require.NoError(t, err)
+ require.Equal(t, int64(4), snapshot.Revision)
+ require.Equal(t, &ExchangeRef{Credential: "spi-signer"}, snapshot.Bindings[0].Exchange)
+
+ closed := NewStore(nil, func() bool { return true })
+ err = closed.Reload(4, testExchangeVaultRequest(), testExchangePolicy(t))
+ require.ErrorContains(t, err, "credential resolver operator configuration")
+}
+
+func TestCredentialVaultExchangeVaultFileV1RoundTrip(t *testing.T) {
+ body := VaultFileBody{
+ Credentials: []Credential{testExchangeCredential("spi-signer")},
+ Bindings: testExchangeVaultRequest().Bindings,
+ }
+ encoded, err := EncodeVaultFile("incarnation-1", "attachment-1", 2, body)
+ require.NoError(t, err)
+ _, decoded, err := DecodeVaultFile(encoded)
+ require.NoError(t, err)
+ require.JSONEq(t, string(mustMarshal(body.Credentials[0].Source)), string(decoded.Credentials[0].Source))
+ require.Equal(t, Auth{Credential: "spi-signer"}, decoded.Bindings[0].Auth)
+
+ store := testResolverReadyStore()
+ require.NoError(t, store.Reload(2, CreateRequest(decoded), testExchangePolicy(t)))
+ snapshot, err := store.ActiveSnapshot()
+ require.NoError(t, err)
+ require.Equal(t, &ExchangeRef{Credential: "spi-signer"}, snapshot.Bindings[0].Exchange)
+}
+
+func TestRenderInjectionHeadersRejectsTypelessDefense(t *testing.T) {
+ credentials := map[string]record{
+ "spi-signer": {Name: "spi-signer", SourceType: "exchange", Source: &exchangeSource{endpoint: "unix:///run/spi.sock"}},
+ }
+ headers, redactions, err := renderInjectionHeaders(context.Background(), Auth{Credential: "spi-signer"}, credentials)
+ require.ErrorContains(t, err, "cannot be rendered as static injection headers")
+ require.Nil(t, headers)
+ require.Nil(t, redactions)
+}