Skip to content

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

fix(sdks): address review — fail fast on cross-variant and typeless shapes

高然80ccfa467ee7
diff --git a/sdks/sandbox/go/credential_vault_test.go b/sdks/sandbox/go/credential_vault_test.go
index 41d81e566..8d5c3749d 100644
--- a/sdks/sandbox/go/credential_vault_test.go
+++ b/sdks/sandbox/go/credential_vault_test.go
@@ -417,14 +417,24 @@ func TestExchangeCredentialVaultRoundTrip(t *testing.T) {
require.NoError(t, json.Unmarshal(inline, &inlineGot))
require.Equal(t, map[string]any{"type": "inline", "value": "dummy-inline-value"}, inlineGot)
+ // The endpoint-only zero-value form defaults to exchange instead of
+ // mislabeling the source as inline.
+ exchangeDefault, err := json.Marshal(CredentialSource{Endpoint: "unix:///run/spi/spi.sock"})
+ require.NoError(t, err)
+ require.Equal(t, `{"type":"exchange","endpoint":"unix:///run/spi/spi.sock"}`, string(exchangeDefault))
+
// Sanitized typeless metadata round-trips credential-only (no `type`
- // emitted); static metadata never leaks a credential reference.
+ // emitted); static metadata never leaks a credential reference; the
+ // guard is symmetric and also strips name from the typeless form.
typeless, err := json.Marshal(CredentialAuthMetadata{Credential: "spi-signer"})
require.NoError(t, err)
require.Equal(t, `{"credential":"spi-signer"}`, string(typeless))
static, err := json.Marshal(CredentialAuthMetadata{Type: "bearer", Credential: "tok"})
require.NoError(t, err)
require.Equal(t, `{"type":"bearer"}`, string(static))
+ typelessWithName, err := json.Marshal(CredentialAuthMetadata{Name: "X-Api-Key", Credential: "spi-signer"})
+ require.NoError(t, err)
+ require.Equal(t, `{"credential":"spi-signer"}`, string(typelessWithName))
}
func TestCreateSandboxRequestIncludesCredentialProxy(t *testing.T) {
diff --git a/sdks/sandbox/go/types.go b/sdks/sandbox/go/types.go
index bc614d728..5ae98a32a 100644
--- a/sdks/sandbox/go/types.go
+++ b/sdks/sandbox/go/types.go
@@ -673,12 +673,18 @@ type CredentialSource struct {
type InlineCredentialSource = CredentialSource
// MarshalJSON defaults the source type so callers can use the natural
-// zero-value form CredentialSource{Value: secret} for inline material.
+// zero-value forms CredentialSource{Value: secret} (inline) and
+// CredentialSource{Endpoint: resolver} (exchange); an empty Type with both
+// or neither field set stays inline and is rejected downstream.
func (s CredentialSource) MarshalJSON() ([]byte, error) {
type credentialSource CredentialSource
source := credentialSource(s)
if source.Type == "" {
- source.Type = CredentialSourceInline
+ if source.Endpoint != "" && source.Value == "" {
+ source.Type = CredentialSourceExchange
+ } else {
+ source.Type = CredentialSourceInline
+ }
}
return json.Marshal(source)
}
@@ -815,14 +821,16 @@ type CredentialAuthMetadata struct {
Credential string `json:"credential,omitempty"`
}
-// MarshalJSON enforces the sanitized wire shape: static kinds carry type
-// (plus name for apiKey) while only the typeless exchange form carries the
-// credential reference.
+// MarshalJSON enforces the sanitized wire shape symmetrically: static kinds
+// carry type (plus name for apiKey) while the typeless exchange form carries
+// only the credential reference.
func (m CredentialAuthMetadata) MarshalJSON() ([]byte, error) {
type credentialAuthMetadata CredentialAuthMetadata
out := credentialAuthMetadata(m)
if out.Type != "" {
out.Credential = ""
+ } else {
+ out.Name = ""
}
return json.Marshal(out)
}
diff --git a/sdks/sandbox/javascript/src/models/sandboxes.ts b/sdks/sandbox/javascript/src/models/sandboxes.ts
index a4e0628f5..2bfe1ded8 100644
--- a/sdks/sandbox/javascript/src/models/sandboxes.ts
+++ b/sdks/sandbox/javascript/src/models/sandboxes.ts
@@ -209,11 +209,11 @@ export type CredentialAuth =
/**
* Typeless exchange form: only a credential reference whose source must be
* exchange-sourced. The egress resolves the header set per request; static
- * fields (name/headers/substitutions) are not allowed on this form.
+ * fields (name/headers/substitutions) are not allowed on this form. The
+ * `type?: never` constraint keeps typo'd static kinds compile errors
+ * instead of silently matching this member.
*/
- | {
- credential: string;
- };
+ | ({ credential: string } & { type?: never });
export interface CredentialBinding extends Record<string, unknown> {
/**
diff --git a/sdks/sandbox/javascript/tests/credential-vault.test.mjs b/sdks/sandbox/javascript/tests/credential-vault.test.mjs
index 367448a03..e5e7ac837 100644
--- a/sdks/sandbox/javascript/tests/credential-vault.test.mjs
+++ b/sdks/sandbox/javascript/tests/credential-vault.test.mjs
@@ -285,7 +285,15 @@ test("exchange credentials and typeless auth round-trip losslessly (OSEP-0025)",
const exchangeState = {
revision: 3,
- credentials: [{ name: "spi-signer", sourceType: "exchange", revision: 3 }],
+ credentials: [
+ {
+ name: "spi-signer",
+ sourceType: "exchange",
+ revision: 3,
+ // Raw relay-style source rides the wire; the sanitizer must strip it.
+ source: { type: "exchange", endpoint: "unix:///run/spi/spi.sock" },
+ },
+ ],
bindings: [
{
name: "internal-api",
@@ -322,10 +330,34 @@ test("exchange credentials and typeless auth round-trip losslessly (OSEP-0025)",
],
});
assert.deepEqual(state, created);
+ assert.equal(Object.hasOwn(state.credentials[0], "source"), false);
assert.equal(Object.hasOwn(state.bindings[0].auth, "type"), false);
assert.equal(JSON.stringify(state).includes("spi.sock"), false);
});
+test("sanitizer recovers the legacy type:null skew shape", async () => {
+ // During rollout skew a client can still receive the pre-fix sanitized
+ // shape `{"type": null, "credential": ...}`; it must read back as the
+ // typeless form, not crash and not surface `type: null`.
+ const skewState = {
+ revision: 3,
+ credentials: [],
+ bindings: [
+ {
+ name: "internal-api",
+ revision: 3,
+ match: { hosts: ["*.internal.example.com"] },
+ auth: { type: null, credential: "spi-signer" },
+ },
+ ],
+ };
+ const { adapter } = createAdapter(skewState);
+
+ const state = await adapter.get();
+
+ assert.deepEqual(state.bindings[0].auth, { credential: "spi-signer" });
+});
+
test("sanitizer rejects auth metadata without type or credential", async () => {
const brokenState = {
revision: 1,
diff --git a/sdks/sandbox/python/src/opensandbox/models/sandboxes.py b/sdks/sandbox/python/src/opensandbox/models/sandboxes.py
index 5f83dd29b..f8a1bac23 100644
--- a/sdks/sandbox/python/src/opensandbox/models/sandboxes.py
+++ b/sdks/sandbox/python/src/opensandbox/models/sandboxes.py
@@ -445,6 +445,8 @@ class InlineCredentialSource(BaseModel):
Write-only inline credential material for Credential Vault.
"""
+ model_config = ConfigDict(extra="forbid")
+
value: str = Field(repr=False, description="Inline credential value.")
type: Literal["inline"] = Field(
default="inline",
@@ -467,6 +469,8 @@ class ExchangeCredentialSource(BaseModel):
endpoint; ``endpoint`` is configuration, not secret material.
"""
+ model_config = ConfigDict(extra="forbid")
+
type: Literal["exchange"] = Field(
default="exchange", description="Credential source type."
)
@@ -559,6 +563,22 @@ class CredentialAuth(BaseModel):
headers: list[CustomHeaderEntry] | None = None
substitutions: list[CredentialSubstitution] | None = None
+ @model_validator(mode="after")
+ def typeless_form_must_only_carry_credential(self) -> "CredentialAuth":
+ if self.type is not None:
+ return self
+ if not (self.credential or "").strip():
+ raise ValueError(
+ "CredentialAuth requires either a static 'type' or an"
+ " exchange 'credential' reference"
+ )
+ if self.name is not None or self.headers is not None or self.substitutions is not None:
+ raise ValueError(
+ "The typeless exchange auth form carries only 'credential';"
+ " 'name', 'headers', and 'substitutions' require a static 'type'"
+ )
+ return self
+
class CredentialBinding(BaseModel):
"""Sandbox-local Credential Vault binding."""
diff --git a/sdks/sandbox/python/tests/test_credential_source_model.py b/sdks/sandbox/python/tests/test_credential_source_model.py
new file mode 100644
index 000000000..814c456d5
--- /dev/null
+++ b/sdks/sandbox/python/tests/test_credential_source_model.py
@@ -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.
+#
+"""OSEP-0025 credential source / typeless auth model validation tests."""
+
+from __future__ import annotations
+
+import pytest
+from pydantic import ValidationError
+
+from opensandbox.models import Credential, CredentialAuth, ExchangeCredentialSource
+
+
+class TestCredentialSourceVariants:
+ def test_exchange_source_accepts_endpoint_only(self) -> None:
+ source = ExchangeCredentialSource(endpoint="unix:///run/spi/spi.sock")
+ assert source.type == "exchange"
+ assert "endpoint" in repr(source)
+
+ def test_exchange_source_rejects_inline_material(self) -> None:
+ # Cross-variant keys must fail fast client-side instead of being
+ # silently dropped from the outgoing payload.
+ with pytest.raises(ValidationError):
+ Credential.model_validate(
+ {
+ "name": "spi-signer",
+ "source": {
+ "type": "exchange",
+ "endpoint": "unix:///run/spi/spi.sock",
+ "value": "secret",
+ },
+ }
+ )
+
+ def test_inline_source_rejects_endpoint(self) -> None:
+ with pytest.raises(ValidationError):
+ Credential.model_validate(
+ {
+ "name": "tok",
+ "source": {"type": "inline", "value": "secret", "endpoint": "unix:///x"},
+ }
+ )
+
+ def test_valid_variants_round_trip(self) -> None:
+ exchange = Credential.model_validate(
+ {
+ "name": "spi-signer",
+ "source": {"type": "exchange", "endpoint": "https://resolver.internal"},
+ }
+ )
+ dumped = exchange.model_dump(by_alias=True, exclude_none=True)
+ assert dumped["source"] == {
+ "type": "exchange",
+ "endpoint": "https://resolver.internal",
+ }
+
+
+class TestTypelessCredentialAuth:
+ def test_typeless_form_accepts_credential_only(self) -> None:
+ auth = CredentialAuth.model_validate({"credential": "spi-signer"})
+ dumped = auth.model_dump(by_alias=True, exclude_none=True)
+ assert dumped == {"credential": "spi-signer"}
+
+ def test_empty_auth_is_rejected(self) -> None:
+ with pytest.raises(ValidationError):
+ CredentialAuth.model_validate({})
+
+ def test_typeless_form_rejects_static_fields(self) -> None:
+ with pytest.raises(ValidationError):
+ CredentialAuth.model_validate(
+ {"credential": "spi-signer", "substitutions": []}
+ )
+ with pytest.raises(ValidationError):
+ CredentialAuth.model_validate({"credential": "spi-signer", "name": "X-Api-Key"})
+ with pytest.raises(ValidationError):
+ CredentialAuth.model_validate(
+ {
+ "credential": "spi-signer",
+ "headers": [{"name": "X-Sign", "credential": "spi-signer"}],
+ }
+ )
+
+ def test_static_kinds_still_validate(self) -> None:
+ passthrough = CredentialAuth.model_validate({"type": "passthrough"})
+ assert passthrough.model_dump(by_alias=True, exclude_none=True) == {
+ "type": "passthrough"
+ }
+ bearer = CredentialAuth.model_validate({"type": "bearer", "credential": "tok"})
+ assert bearer.model_dump(by_alias=True, exclude_none=True) == {
+ "type": "bearer",
+ "credential": "tok",
+ }