Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

fix(js-sdk): guard runtime-probed iam token names in network transforms (#1715)

devin-ai-integration[bot]61503f75eb12
diff --git a/.changeset/guard-runtime-probed-iam-token-names.md b/.changeset/guard-runtime-probed-iam-token-names.md
new file mode 100644
index 000000000..2362642f2
--- /dev/null
+++ b/.changeset/guard-runtime-probed-iam-token-names.md
@@ -0,0 +1,33 @@
+---
+'e2b': patch
+---
+
+Report `iam.tokens.toJSON`, `.then`, `.toString` and `.valueOf` as unregistered workload tokens in a network `transform` callback. These four names were exempt from the unknown-token guard because the runtime reads them off any object it serializes, awaits or coerces, so referencing one as a token name used to serialize `Bearer undefined` or a built-in's source text into the rule. Such a value carries no placeholder for the egress proxy to resolve, so it was forwarded verbatim and the destination answered 401 on a garbage credential, with no error from E2B. They now throw `InvalidArgumentError` like any other unregistered name — on use rather than on the read, so serializing, awaiting and coercing the map itself keep working. The Python SDK was not affected.
+
+```ts
+import { Sandbox, Secret } from 'e2b'
+
+await Sandbox.create({
+ iam: {
+ tokens: {
+ aws: Secret.iamToken({
+ audience: 'sts.amazonaws.com',
+ tokenType: 'JWT-SVID',
+ }),
+ },
+ },
+ network: {
+ rules: {
+ 'api.example.com': [
+ {
+ // InvalidArgumentError: Network transform references iam token
+ // 'then', which is not registered. Registered tokens: 'aws'.
+ transform: ({ iam }) => ({
+ headers: { Authorization: `Bearer ${iam.tokens.then}` },
+ }),
+ },
+ ],
+ },
+ },
+})
+```
diff --git a/packages/js-sdk/src/sandbox/iam.ts b/packages/js-sdk/src/sandbox/iam.ts
index d7d960bc6..519813a23 100644
--- a/packages/js-sdk/src/sandbox/iam.ts
+++ b/packages/js-sdk/src/sandbox/iam.ts
@@ -16,12 +16,41 @@ const INVALID_IAM_TOKEN_NAME_CHARS = /[{}\p{Cc}]/u
/**
* Properties the language and the runtime read off any object they serialize,
- * await, or coerce to a string. A token is never named after them, so they
- * resolve normally instead of counting as a token reference — otherwise
- * `JSON.stringify(iam.tokens)` inside a callback would throw.
+ * await, or coerce to a string. A token is never named after them, so reading
+ * one cannot throw — otherwise `JSON.stringify(iam.tokens)` inside a callback
+ * would.
*/
const RUNTIME_PROBED_PROPS = new Set(['toJSON', 'then', 'toString', 'valueOf'])
+/**
+ * Stand-in for a runtime-probed name that is not a registered token: it answers
+ * the probe, and `resolve` decides what using it as a token does — a probe never
+ * coerces or serializes what it reads, a token reference does one or the other.
+ */
+function runtimeProbeValue(
+ prop: string,
+ tokens: () => Record<string, string>,
+ resolve: () => string
+): unknown {
+ // `then` and `toJSON` are only probed for callability, so a non-callable value
+ // reads as absent. `toString` and `valueOf` are called — `String(iam.tokens)`
+ // needs a primitive — and answer over the guarded map, not the record.
+ const value =
+ prop === 'toString'
+ ? () => Object.prototype.toString.call(tokens())
+ : prop === 'valueOf'
+ ? () => tokens()
+ : {}
+
+ Object.defineProperty(value, Symbol.toPrimitive, { value: resolve })
+ // A header value assigned straight through is serialized rather than coerced,
+ // and Bun's `JSON.stringify` only finds an own `toJSON` that is enumerable.
+ return Object.defineProperty(value, 'toJSON', {
+ value: resolve,
+ enumerable: true,
+ })
+}
+
/**
* Reject a token name that cannot survive the placeholder grammar.
*
@@ -70,29 +99,38 @@ export function iamTokenPlaceholders(
tokens[name] = iamTokenPlaceholder(name)
}
- return new Proxy(tokens, {
+ /** Placeholder when names cannot be checked, otherwise the guard's error. */
+ const resolveUnregistered = (prop: string): string => {
+ if (!validate) {
+ return iamTokenPlaceholder(prop)
+ }
+
+ const hint =
+ tokenNames.length === 0
+ ? `Pass it to Sandbox.create as iam: { tokens: { '${prop}': Secret.iamToken({ audience, tokenType }) } }.`
+ : `Registered tokens: ${tokenNames.map((name) => `'${name}'`).join(', ')}.`
+
+ throw new InvalidArgumentError(
+ `Network transform references iam token '${prop}', which is not registered. ${hint}`
+ )
+ }
+
+ const proxy: Record<string, string> = new Proxy(tokens, {
get(target, prop, receiver) {
- if (
- typeof prop === 'string' &&
- // Own keys only: a bare `in` also matches inherited `Object.prototype`
- // members, so an unregistered token named `constructor` or `__proto__`
- // would resolve to a built-in instead of being reported. Python's
- // mapping treats them as missing too.
- !Object.hasOwn(target, prop) &&
- !RUNTIME_PROBED_PROPS.has(prop)
- ) {
- if (!validate) {
- return iamTokenPlaceholder(prop)
+ // Own keys only: a bare `in` also matches inherited `Object.prototype`
+ // members, so an unregistered token named `constructor` or `__proto__`
+ // would resolve to a built-in instead of being reported. Python's
+ // mapping treats them as missing too.
+ if (typeof prop === 'string' && !Object.hasOwn(target, prop)) {
+ if (RUNTIME_PROBED_PROPS.has(prop)) {
+ return runtimeProbeValue(
+ prop,
+ () => proxy,
+ () => resolveUnregistered(prop)
+ )
}
- const hint =
- tokenNames.length === 0
- ? `Pass it to Sandbox.create as iam: { tokens: { '${prop}': Secret.iamToken({ audience, tokenType }) } }.`
- : `Registered tokens: ${tokenNames.map((name) => `'${name}'`).join(', ')}.`
-
- throw new InvalidArgumentError(
- `Network transform references iam token '${prop}', which is not registered. ${hint}`
- )
+ return resolveUnregistered(prop)
}
return Reflect.get(target, prop, receiver)
@@ -106,4 +144,6 @@ export function iamTokenPlaceholders(
return Object.hasOwn(target, prop)
},
})
+
+ return proxy
}
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 5e6f31177..565655535 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -70,7 +70,9 @@ export type SandboxNetworkTransformContext = {
* Reading a name that is not registered throws
* {@link InvalidArgumentError} — the proxy never turns an unregistered name
* into a token, so a typo would surface as a confusing auth failure at the
- * destination.
+ * destination. The four names the runtime reads off any object it
+ * serializes, awaits or coerces (`toJSON`, `then`, `toString`, `valueOf`)
+ * throw on use rather than on the read.
*/
tokens: Record<string, string>
}
diff --git a/packages/js-sdk/tests/sandbox/iam.test.ts b/packages/js-sdk/tests/sandbox/iam.test.ts
index 2cc568d06..4cf768afc 100644
--- a/packages/js-sdk/tests/sandbox/iam.test.ts
+++ b/packages/js-sdk/tests/sandbox/iam.test.ts
@@ -3,8 +3,11 @@ import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { InvalidArgumentError, Sandbox, Secret } from '../../src'
+import { iamTokenPlaceholders } from '../../src/sandbox/iam'
import { TEST_API_KEY, apiUrl } from '../setup'
+const RUNTIME_PROBED_PROPS = ['toJSON', 'then', 'toString', 'valueOf']
+
let lastCreateBody: Record<string, unknown> | undefined
const server = setupServer(
@@ -128,3 +131,54 @@ test('Sandbox.create rejects a token missing audience or tokenType', async () =>
})
).rejects.toThrowError(InvalidArgumentError)
})
+
+test('the token map serializes, awaits and coerces like a plain object', async () => {
+ const tokens = iamTokenPlaceholders(['aws'], { validate: true })
+
+ expect(JSON.stringify(tokens)).toBe('{"aws":"${e2b.identity.tokens.aws}"}')
+ expect(String(tokens)).toBe('[object Object]')
+ expect(`${tokens}`).toBe('[object Object]')
+ expect({ ...tokens }).toEqual({ aws: '${e2b.identity.tokens.aws}' })
+ // A non-callable `then` keeps the map a plain value rather than a thenable.
+ expect(await tokens).toBe(tokens)
+})
+
+test.for(RUNTIME_PROBED_PROPS)(
+ 'reading the unregistered token %s throws instead of resolving',
+ (prop: string) => {
+ const tokens = iamTokenPlaceholders(['aws'], { validate: true })
+
+ expect(() => `${tokens[prop]}`).toThrowError(
+ `iam token '${prop}', which is not registered`
+ )
+ expect(() => String(tokens[prop])).toThrowError(InvalidArgumentError)
+ // Assigned straight through, a header value is serialized, not coerced.
+ expect(() => JSON.stringify({ header: tokens[prop] })).toThrowError(
+ InvalidArgumentError
+ )
+ }
+)
+
+test('the runtime-probed valueOf answers with the guarded map', () => {
+ // It stays callable for `String(iam.tokens)`, so it must not hand out the
+ // unguarded record.
+ const tokens = iamTokenPlaceholders(['aws'], { validate: true })
+
+ expect(tokens.valueOf().aws).toBe('${e2b.identity.tokens.aws}')
+ expect(() => `${tokens.valueOf().gcp}`).toThrowError(
+ /iam token 'gcp'.*Registered tokens: 'aws'/s
+ )
+})
+
+test.for(RUNTIME_PROBED_PROPS)(
+ 'the unchecked token map resolves %s to its placeholder',
+ (prop: string) => {
+ // The update-network payload carries no iam config, so no name can be
+ // reported as unregistered.
+ const tokens = iamTokenPlaceholders([], { validate: false })
+
+ expect(`${tokens[prop]}`).toBe(`\${e2b.identity.tokens.${prop}}`)
+ expect(JSON.stringify(tokens)).toBe('{}')
+ expect(String(tokens)).toBe('[object Object]')
+ }
+)
diff --git a/packages/js-sdk/tests/sandbox/networkTransform.test.ts b/packages/js-sdk/tests/sandbox/networkTransform.test.ts
index 113b0b9ba..9be7b3ab4 100644
--- a/packages/js-sdk/tests/sandbox/networkTransform.test.ts
+++ b/packages/js-sdk/tests/sandbox/networkTransform.test.ts
@@ -189,6 +189,86 @@ test.for(['constructor', '__proto__', 'hasOwnProperty'])(
}
)
+test.for(['toJSON', 'then', 'toString', 'valueOf'])(
+ 'transform callback rejects the runtime-probed iam token name %s',
+ async (name: string) => {
+ // Referencing one as a token used to put 'undefined' or a built-in's source
+ // text on the wire, which carries no placeholder for the proxy to resolve,
+ // so the destination answered 401 on a garbage credential.
+ await expect(
+ Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ iam: { tokens: { aws: awsToken } },
+ network: {
+ rules: {
+ 'api.internal.example.com': [
+ {
+ transform: ({ iam }) => ({
+ headers: { Authorization: `Bearer ${iam.tokens[name]}` },
+ }),
+ },
+ ],
+ },
+ },
+ })
+ ).rejects.toThrowError(`iam token '${name}', which is not registered`)
+
+ expect(lastCreateBody).toBeUndefined()
+ }
+)
+
+test.for(['toJSON', 'then', 'toString', 'valueOf'])(
+ 'transform callback rejects the uncoerced runtime-probed iam token name %s',
+ async (name: string) => {
+ // Assigned straight through, the value is serialized instead of coerced,
+ // which used to send an object where the API wants a string, or drop the
+ // header entirely for the two names that resolve to a function.
+ await expect(
+ Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ iam: { tokens: { aws: awsToken } },
+ network: {
+ rules: {
+ 'api.internal.example.com': [
+ {
+ transform: ({ iam }) => ({
+ headers: { 'X-Api-Key': iam.tokens[name] },
+ }),
+ },
+ ],
+ },
+ },
+ })
+ ).rejects.toThrowError(`iam token '${name}', which is not registered`)
+
+ expect(lastCreateBody).toBeUndefined()
+ }
+)
+
+test('transform callback cannot reach an unguarded token map through valueOf', async () => {
+ await expect(
+ Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ iam: { tokens: { aws: awsToken } },
+ network: {
+ rules: {
+ 'api.internal.example.com': [
+ {
+ transform: ({ iam }) => ({
+ headers: {
+ Authorization: `Bearer ${iam.tokens.valueOf().gcp}`,
+ },
+ }),
+ },
+ ],
+ },
+ },
+ })
+ ).rejects.toThrowError(`iam token 'gcp', which is not registered`)
+
+ expect(lastCreateBody).toBeUndefined()
+})
+
test('transform callback rejects an iam token when no iam config is set', async () => {
await expect(
Sandbox.create('base', {