Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add secrets management to JS and Python SDKs (#1728)

devin-ai-integration[bot]f89f8c3f9650
diff --git a/.changeset/sdk-secrets-management.md b/.changeset/sdk-secrets-management.md
new file mode 100644
index 000000000..e078f9f6f
--- /dev/null
+++ b/.changeset/sdk-secrets-management.md
@@ -0,0 +1,6 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Add Secrets Management to the SDK. The `Secret` class (and `AsyncSecret` in Python) now manages E2B secrets: `create` and `update` store secret values (write-only — no read surface returns them), `getInfo` / `get_info` and the paginated `list` read metadata, `exists` and `destroy` are idempotent existence and lifecycle helpers, and `fill` formats the `${e2b.secrets.name}` placeholder that the runtime resolves to the secret's current value.
diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.json
index 387385751..a964362f1 100644
--- a/packages/js-sdk/package.json
+++ b/packages/js-sdk/package.json
@@ -31,7 +31,7 @@
"generate": "npm-run-all generate:* && pnpm run format",
"generate:api": "redocly bundle js-sdk --config ../../redocly.yaml -o ../../spec/openapi_generated.js-sdk.yml && openapi-typescript ../../spec/openapi_generated.js-sdk.yml -x api_key --array-length --alphabetize --default-non-nullable false --output src/api/schema.gen.ts",
"generate:envd": "cd ../../spec/envd && buf generate --template buf-js.gen.yaml\n",
- "generate:envd-api": "openapi-typescript ../../spec/envd/envd.yaml -x api_key --array-length --alphabetize --output src/envd/schema.gen.ts",
+ "generate:envd-api": "redocly bundle envd --config ../../redocly.yaml -o ../../spec/openapi_generated.envd.yml && openapi-typescript ../../spec/openapi_generated.envd.yml -x api_key --array-length --alphabetize --output src/envd/schema.gen.ts",
"generate:volume-api": "openapi-typescript ../../spec/openapi-volumecontent.yml -x api_key --array-length --alphabetize --output src/volume/schema.gen.ts",
"generate:mcp": "json2ts -i ./../../spec/mcp-server.json -o src/sandbox/mcp.d.ts --unreachableDefinitions --style.singleQuote --no-style.semi",
"check-deps": "knip",
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 4ebca8c6c..2f242066a 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -72,6 +72,8 @@ export interface paths {
400: components["responses"]["400"];
401: components["responses"]["401"];
500: components["responses"]["500"];
+ 503: components["responses"]["503"];
+ 504: components["responses"]["504"];
};
};
delete?: never;
@@ -199,7 +201,10 @@ export interface paths {
400: components["responses"]["400"];
401: components["responses"]["401"];
404: components["responses"]["404"];
+ 409: components["responses"]["409"];
500: components["responses"]["500"];
+ 503: components["responses"]["503"];
+ 504: components["responses"]["504"];
};
};
delete?: never;
@@ -249,6 +254,7 @@ export interface paths {
404: components["responses"]["404"];
409: components["responses"]["409"];
500: components["responses"]["500"];
+ 503: components["responses"]["503"];
};
};
delete?: never;
@@ -533,10 +539,13 @@ export interface paths {
"application/json": components["schemas"]["Sandbox"];
};
};
+ 400: components["responses"]["400"];
401: components["responses"]["401"];
404: components["responses"]["404"];
409: components["responses"]["409"];
500: components["responses"]["500"];
+ 503: components["responses"]["503"];
+ 504: components["responses"]["504"];
};
};
delete?: never;
@@ -685,6 +694,216 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/secrets": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * List project secrets
+ * @description List the project's secrets. No response carries a secret value.
+ */
+ get: {
+ parameters: {
+ query?: {
+ /** @description Maximum number of items to return per page */
+ limit?: components["parameters"]["paginationLimit"];
+ /** @description Cursor to start the list from */
+ nextToken?: components["parameters"]["paginationNextToken"];
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successfully listed the project's secrets */
+ 200: {
+ headers: {
+ "X-Next-Token": components["headers"]["XNextToken"];
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Secret"][];
+ };
+ };
+ 400: components["responses"]["400"];
+ 401: components["responses"]["401"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 429: components["responses"]["429"];
+ 500: components["responses"]["500"];
+ 502: components["responses"]["502"];
+ 504: components["responses"]["504"];
+ };
+ };
+ put?: never;
+ /**
+ * Create a secret
+ * @description Create a secret by storing a runtime marker as its first version. The response carries metadata only.
+ */
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["NewSecret"];
+ };
+ };
+ responses: {
+ /** @description Successfully created the secret */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Secret"];
+ };
+ };
+ 400: components["responses"]["400"];
+ 401: components["responses"]["401"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 429: components["responses"]["429"];
+ 500: components["responses"]["500"];
+ 502: components["responses"]["502"];
+ 504: components["responses"]["504"];
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/secrets/{secretID}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get a secret
+ * @description Get one secret's metadata, selected by identifier or name.
+ */
+ get: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ secretID: components["parameters"]["secretID"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successfully retrieved the secret */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Secret"];
+ };
+ };
+ 400: components["responses"]["400"];
+ 401: components["responses"]["401"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 429: components["responses"]["429"];
+ 500: components["responses"]["500"];
+ 502: components["responses"]["502"];
+ 504: components["responses"]["504"];
+ };
+ };
+ put?: never;
+ /**
+ * Update a secret
+ * @description Replace the secret's stored marker by appending a new version. The response carries metadata only.
+ */
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ secretID: components["parameters"]["secretID"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["SecretUpdate"];
+ };
+ };
+ responses: {
+ /** @description Successfully updated the secret */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Secret"];
+ };
+ };
+ 400: components["responses"]["400"];
+ 401: components["responses"]["401"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 429: components["responses"]["429"];
+ 500: components["responses"]["500"];
+ 502: components["responses"]["502"];
+ 504: components["responses"]["504"];
+ };
+ };
+ /**
+ * Delete a secret
+ * @description Revoke the secret and schedule its versions for cleanup.
+ */
+ delete: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ secretID: components["parameters"]["secretID"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successfully deleted the secret */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ 400: components["responses"]["400"];
+ 401: components["responses"]["401"];
+ 403: components["responses"]["403"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 429: components["responses"]["429"];
+ 500: components["responses"]["500"];
+ 502: components["responses"]["502"];
+ 504: components["responses"]["504"];
+ };
+ };
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/snapshots": {
parameters: {
query?: never;
@@ -1468,8 +1687,14 @@ export interface paths {
metadata?: string;
/** @description Cursor to start the list from */
nextToken?: components["parameters"]["paginationNextToken"];
+ /** @description Sort direction by sandbox start time. Defaults to desc (newest first). */
+ order?: components["schemas"]["OrderDirection"];
+ /** @description Return sandboxes started at or after this timestamp. */
+ startedAfter?: string;
/** @description Filter sandboxes by one or more states */
state?: components["schemas"]["SandboxState"][];
+ /** @description Filter sandboxes by a template ID or alias. */
+ template?: string;
};
header?: never;
path?: never;
@@ -2085,6 +2310,8 @@ export interface components {
* @description Error code
*/
code: number;
+ /** @description Machine-readable semantic error code. Not a closed set; initial values: sandbox_capacity_unavailable, sandbox_placement_timeout, sandbox_no_compatible_node, sandbox_create_failed, internal_server_error. */
+ error_code?: string;
/** @description Error */
message: string;
};
@@ -2234,6 +2461,14 @@ export interface components {
timeout?: number;
volumeMounts?: components["schemas"]["SandboxVolumeMount"][];
};
+ NewSecret: {
+ metadata?: components["schemas"]["SecretMetadata"];
+ /** @description Name of the secret, unique within the project. Names are lower-cased before storage and returned in that canonical form; the sec_ prefix is reserved for secret identifiers.
+ * */
+ name: string;
+ /** @description Runtime marker stored as the secret's first version. The runtime resolves it to a value at sandbox egress. */
+ value: string;
+ };
NewTeamAPIKey: {
/** @description Name of the API key */
name: string;
@@ -2388,6 +2623,12 @@ export interface components {
clusterID?: string;
status: components["schemas"]["NodeStatus"];
};
+ /**
+ * @description Sort direction
+ * @default desc
+ * @enum {string}
+ */
+ OrderDirection: "asc" | "desc";
ResumedSandbox: {
/**
* @deprecated
@@ -2692,6 +2933,39 @@ export interface components {
/** @description Path of the volume */
path: string;
};
+ /** @description Metadata of a secret. It never carries the secret value. */
+ Secret: {
+ /**
+ * Format: date-time
+ * @description Time when the secret was created
+ */
+ createdAt: string;
+ /**
+ * Format: int64
+ * @description Version served to readers that do not name one
+ */
+ currentVersion: number;
+ metadata: components["schemas"]["SecretMetadata"];
+ /** @description Name of the secret, unique within the project */
+ name: string;
+ /** @description Identifier of the secret */
+ secretID: string;
+ /**
+ * Format: date-time
+ * @description Time when the secret was last updated
+ */
+ updatedAt: string;
+ };
+ /** @description Customer metadata of the secret. Always present, empty when unset. At most 32 entries; keys are limited to 128 bytes, values to 1024 bytes, and a secret's metadata to 8192 bytes in total.
+ * */
+ SecretMetadata: {
+ [key: string]: string;
+ };
+ SecretUpdate: {
+ metadata?: components["schemas"]["SecretMetadata"];
+ /** @description Runtime marker stored as the secret's new version. The runtime resolves it to a value at sandbox egress. */
+ value: string;
+ };
SnapshotInfo: {
/** @description Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2) */
names: string[];
@@ -3159,6 +3433,15 @@ export interface components {
"application/json": components["schemas"]["Error"];
};
};
+ /** @description Too many requests */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
/** @description Server error */
500: {
headers: {
@@ -3168,6 +3451,33 @@ export interface components {
"application/json": components["schemas"]["Error"];
};
};
+ /** @description Backend error */
+ 502: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Service unavailable */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
+ /** @description Backend timeout */
+ 504: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Error"];
+ };
+ };
};
parameters: {
accessTokenID: string;
@@ -3179,6 +3489,7 @@ export interface components {
/** @description Cursor to start the list from */
paginationNextToken: string;
sandboxID: string;
+ secretID: string;
snapshotID: string;
tag: string;
teamID: string;
diff --git a/packages/js-sdk/src/envd/schema.gen.ts b/packages/js-sdk/src/envd/schema.gen.ts
index 3addc58ec..10877437c 100644
--- a/packages/js-sdk/src/envd/schema.gen.ts
+++ b/packages/js-sdk/src/envd/schema.gen.ts
@@ -4,43 +4,6 @@
*/
export interface paths {
- "/collapse": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Collapse envd's own anonymous heap into 2 MiB transparent hugepages before pause, so on resume envd touches fewer distinct guest-physical frames (each a cold fault). Best-effort. */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Heap collapsed */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["CollapseResult"];
- };
- };
- 500: components["responses"]["InternalServerError"];
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/envs": {
parameters: {
query?: never;
@@ -212,132 +175,6 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/freeze": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Freeze user/pty cgroups before pause. Written directly by envd to avoid Process.Start / shell overhead under load. */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Cgroups frozen */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- 500: components["responses"]["InternalServerError"];
- /** @description Freeze lock is held by another operation */
- 503: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
- "/fsfreeze": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Freeze the guest rootfs (FIFREEZE) before a filesystem-only pause so it is flushed to a consistent on-disk state, closing the sync->pause race. Idempotent. On a successful filesystem-only pause the VM is rebooted, so no thaw is needed; the orchestrator thaws only on the pause-failure path. */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Rootfs frozen */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- 500: components["responses"]["InternalServerError"];
- /** @description Freeze lock is held by another operation */
- 503: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
- "/fsthaw": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Thaw the guest rootfs (FITHAW). Intended ONLY for the orchestrator's pause-failure rollback path, so a frozen filesystem cannot leave the live VM deadlocked. Idempotent. */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Rootfs thawed */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- 500: components["responses"]["InternalServerError"];
- /** @description Freeze lock is held by another operation */
- 503: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/health": {
parameters: {
query?: never;
@@ -372,64 +209,6 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/init": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Set initial vars, ensure the time and metadata is synced with the host */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: {
- content: {
- "application/json": {
- /** @description Access token for secure access to envd service */
- accessToken?: string;
- /** @description PEM-encoded CA certificates to install into the system trust store (may contain multiple concatenated PEM blocks) */
- caBundle?: string;
- /** @description The default user to use for operations */
- defaultUser?: string;
- /** @description The default working directory to use for operations */
- defaultWorkdir?: string;
- envVars?: components["schemas"]["EnvVars"];
- /** @description IP address of the hyperloop server to connect to */
- hyperloopIP?: string;
- /** @description Lifecycle ID of the sandbox */
- lifecycleID?: string;
- /**
- * Format: date-time
- * @description The current timestamp in RFC3339 format
- */
- timestamp?: string;
- volumeMounts?: components["schemas"]["VolumeMount"][];
- };
- };
- };
- responses: {
- /** @description Env vars set, the time and metadata is synced with the host */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/metrics": {
parameters: {
query?: never;
@@ -466,70 +245,10 @@ export interface paths {
patch?: never;
trace?: never;
};
- "/unfreeze": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /** Unfreeze user/pty cgroups. Intended ONLY for the orchestrator's pause-failure rollback path; the normal resume thaw happens via /init's deferred unfreeze, not here. */
- post: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Cgroups unfrozen */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- 500: components["responses"]["InternalServerError"];
- /** @description Freeze lock is held by another operation */
- 503: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
}
export type webhooks = Record<string, never>;
export interface components {
schemas: {
- /** @description Per-call statistics from a heap collapse */
- CollapseResult: {
- /** @description Chunks MADV_COLLAPSE accepted but were already hugepages (no work) */
- alreadyHuge?: number;
- /** @description 2 MiB chunks attempted */
- chunks?: number;
- /** @description Chunks whose base pages were actually migrated into a new hugepage (real work) */
- collapsed?: number;
- /**
- * Format: int64
- * @description Wall-clock time spent collapsing, in milliseconds
- */
- elapsedMs?: number;
- /** @description Anonymous read-write regions scanned */
- regions?: number;
- /** @description Chunks that could not be collapsed (empty or ineligible) */
- skipped?: number;
- };
ComposeRequest: {
/** @description Destination file path for the composed file */
destination: string;
@@ -592,13 +311,6 @@ export interface components {
*/
ts?: number;
};
- /** @description Volume mount configuration */
- VolumeMount: {
- /** @description Server target address */
- nfs_target: string;
- /** @description Mount path inside the sandbox */
- path: string;
- };
};
responses: {
/** @description Entire file downloaded successfully. */
diff --git a/packages/js-sdk/src/errors.ts b/packages/js-sdk/src/errors.ts
index b1e71382b..5ae98e06a 100644
--- a/packages/js-sdk/src/errors.ts
+++ b/packages/js-sdk/src/errors.ts
@@ -197,3 +197,25 @@ export class VolumePathNotFoundError extends VolumeError {
this.name = 'VolumePathNotFoundError'
}
}
+
+/**
+ * Base class for all secret errors.
+ *
+ * Thrown when general secret errors occur.
+ */
+export class SecretError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'SecretError'
+ }
+}
+
+/**
+ * Thrown when a secret is not found.
+ */
+export class SecretNotFoundError extends SecretError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'SecretNotFoundError'
+ }
+}
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 4c8ec4ad0..921087d2b 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -25,6 +25,8 @@ export {
VolumeError,
VolumeNotFoundError,
VolumePathNotFoundError,
+ SecretError,
+ SecretNotFoundError,
} from './errors'
export type { Logger } from './logs'
@@ -91,7 +93,16 @@ export type {
export type { McpServer } from './sandbox/mcp'
-export { Secret } from './secret'
+export { Secret, SecretPaginator } from './secret'
+export type {
+ SecretInfo,
+ SecretCreateOpts,
+ SecretUpdateOpts,
+ SecretGetInfoOpts,
+ SecretExistsOpts,
+ SecretDestroyOpts,
+ SecretListOpts,
+} from './secret'
export { ALL_TRAFFIC } from './sandbox/network'
diff --git a/packages/js-sdk/src/secret.ts b/packages/js-sdk/src/secret.ts
index 3347c90c0..fbe648f0f 100644
--- a/packages/js-sdk/src/secret.ts
+++ b/packages/js-sdk/src/secret.ts
@@ -1,9 +1,384 @@
+import { ApiClient, components, handleApiError } from './api'
+import { ConnectionConfig, ConnectionOpts } from './connectionConfig'
+import {
+ InvalidArgumentError,
+ SecretError,
+ SecretNotFoundError,
+} from './errors'
+import { Paginator } from './paginator'
import type { SandboxIamToken } from './sandbox/sandboxApi'
+const INVALID_SECRET_NAME_CHARS = /[{}\p{Cc}]/u
+
+function validateSecretName(name: string): void {
+ if (name.length === 0 || INVALID_SECRET_NAME_CHARS.test(name)) {
+ throw new InvalidArgumentError(
+ `secret name ${JSON.stringify(name)} is not usable: a secret name cannot be empty or contain '{', '}' or control characters, because it is interpolated into the '\${e2b.secrets.<name>}' placeholder the runtime resolves.`
+ )
+ }
+}
+
+/**
+ * Metadata of a secret. Secret values are write-only and never returned.
+ */
+export interface SecretInfo {
+ /**
+ * Secret ID.
+ */
+ secretId: string
+ /**
+ * Secret name, unique within the project.
+ */
+ name: string
+ /**
+ * Version served to readers that do not name one.
+ */
+ version: number
+ /**
+ * Customer metadata of the secret.
+ */
+ metadata: Record<string, string>
+ /**
+ * Time when the secret was created.
+ */
+ createdAt: Date
+ /**
+ * Time when the secret was last updated.
+ */
+ updatedAt: Date
+}
+
+export interface SecretCreateOpts extends ConnectionOpts {
+ /**
+ * Customer metadata to store with the secret.
+ */
+ metadata?: Record<string, string>
+}
+
+export interface SecretUpdateOpts extends ConnectionOpts {
+ /**
+ * Customer metadata to store with the secret. When provided, replaces the
+ * stored metadata.
+ */
+ metadata?: Record<string, string>
+}
+
+export type SecretGetInfoOpts = ConnectionOpts
+
+export type SecretExistsOpts = ConnectionOpts
+
+export type SecretDestroyOpts = ConnectionOpts
+
+export interface SecretListOpts extends Omit<ConnectionOpts, 'signal'> {
+ /**
+ * Number of secrets to return per page.
+ *
+ * @default 100
+ */
+ limit?: number
+
+ /**
+ * Token to the next page.
+ */
+ nextToken?: string
+}
+
+function convertSecretInfo(
+ secret: components['schemas']['Secret']
+): SecretInfo {
+ return {
+ secretId: secret.secretID,
+ name: secret.name,
+ version: secret.currentVersion,
+ metadata: secret.metadata ?? {},
+ createdAt: new Date(secret.createdAt),
+ updatedAt: new Date(secret.updatedAt),
+ }
+}
+
/**
- * Secrets and workload identity helpers.
+ * Paginator for listing secrets.
+ *
+ * @example
+ * ```ts
+ * const paginator = Secret.list()
+ * while (paginator.hasNext) {
+ * const secrets = await paginator.nextItems()
+ * console.log(secrets)
+ * }
+ * ```
+ */
+export class SecretPaginator extends Paginator<SecretInfo> {
+ constructor(opts?: SecretListOpts) {
+ super(opts, opts?.limit, opts?.nextToken)
+ }
+
+ async nextItems(opts?: ConnectionOpts): Promise<SecretInfo[]> {
+ if (!this.hasNext) {
+ throw new Error('No more items to fetch')
+ }
+
+ const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const client = new ApiClient(config)
+
+ const res = await client.api.GET('/secrets', {
+ params: {
+ query: {
+ limit: this.limit,
+ nextToken: this.nextToken,
+ },
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ const err = handleApiError(res, SecretError)
+ if (err) {
+ throw err
+ }
+
+ this.updatePagination(res.response)
+
+ return (res.data ?? []).map(convertSecretInfo)
+ }
+}
+
+/**
+ * Module for managing E2B secrets and workload identity helpers.
+ *
+ * Secret values are write-only: they are accepted by {@link Secret.create}
+ * and {@link Secret.update} but never returned by any read surface.
*/
export class Secret {
+ /**
+ * Create a new secret and its first value.
+ *
+ * @param name name of the secret, unique within the project.
+ * @param value secret value. Write-only — never returned by the API.
+ * @param opts connection options.
+ *
+ * @returns the secret's ID, name, current version (`1` for a new secret),
+ * metadata, and creation and update times.
+ */
+ static async create(
+ name: string,
+ value: string,
+ opts?: SecretCreateOpts
+ ): Promise<SecretInfo> {
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.POST('/secrets', {
+ body: {
+ name,
+ value,
+ metadata: opts?.metadata,
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ const err = handleApiError(res, SecretError)
+ if (err) {
+ throw err
+ }
+
+ if (!res.data) {
+ throw new Error('Response data is missing')
+ }
+
+ return convertSecretInfo(res.data)
+ }
+
+ /**
+ * Update a secret's value by storing it as the secret's new version.
+ *
+ * @param secret secret ID or name.
+ * @param value new secret value. Write-only — never returned by the API.
+ * @param opts connection options.
+ *
+ * @returns the secret's ID, name, new current version, metadata, and
+ * creation and update times.
+ */
+ static async update(
+ secret: string,
+ value: string,
+ opts?: SecretUpdateOpts
+ ): Promise<SecretInfo> {
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.POST('/secrets/{secretID}', {
+ params: {
+ path: {
+ secretID: secret,
+ },
+ },
+ body: {
+ value,
+ metadata: opts?.metadata,
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ if (res.response.status === 404) {
+ throw new SecretNotFoundError(`Secret ${secret} not found`)
+ }
+
+ const err = handleApiError(res, SecretError)
+ if (err) {
+ throw err
+ }
+
+ if (!res.data) {
+ throw new Error('Response data is missing')
+ }
+
+ return convertSecretInfo(res.data)
+ }
+
+ /**
+ * Get a secret's metadata.
+ *
+ * @param secret secret ID or name.
+ * @param opts connection options.
+ *
+ * @returns the secret's ID, name, current version, metadata, and creation
+ * and update times.
+ */
+ static async getInfo(
+ secret: string,
+ opts?: SecretGetInfoOpts
+ ): Promise<SecretInfo> {
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.GET('/secrets/{secretID}', {
+ params: {
+ path: {
+ secretID: secret,
+ },
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ if (res.response.status === 404) {
+ throw new SecretNotFoundError(`Secret ${secret} not found`)
+ }
+
+ const err = handleApiError(res, SecretError)
+ if (err) {
+ throw err
+ }
+
+ if (!res.data) {
+ throw new Error('Response data is missing')
+ }
+
+ return convertSecretInfo(res.data)
+ }
+
+ /**
+ * List the project's secrets.
+ *
+ * @param opts connection options.
+ *
+ * @returns paginator over the project's secrets. Drain it page by page:
+ * `while (paginator.hasNext) { const secrets = await paginator.nextItems() }`.
+ *
+ * @example
+ * ```ts
+ * const paginator = Secret.list({ limit: 50 })
+ * while (paginator.hasNext) {
+ * const secrets = await paginator.nextItems()
+ * }
+ * ```
+ */
+ static list(opts?: SecretListOpts): SecretPaginator {
+ return new SecretPaginator(opts)
+ }
+
+ /**
+ * Check whether a secret exists.
+ *
+ * @param secret secret ID or name.
+ * @param opts connection options.
+ *
+ * @returns `true` if the secret exists, `false` otherwise.
+ */
+ static async exists(
+ secret: string,
+ opts?: SecretExistsOpts
+ ): Promise<boolean> {
+ try {
+ await Secret.getInfo(secret, opts)
+ return true
+ } catch (err) {
+ if (err instanceof SecretNotFoundError) {
+ return false
+ }
+ throw err
+ }
+ }
+
+ /**
+ * Destroy a secret, making all its versions inaccessible.
+ *
+ * @param secret secret ID or name.
+ * @param opts connection options.
+ *
+ * @returns `true` if the secret was destroyed, `false` if it was not found.
+ */
+ static async destroy(
+ secret: string,
+ opts?: SecretDestroyOpts
+ ): Promise<boolean> {
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.DELETE('/secrets/{secretID}', {
+ params: {
+ path: {
+ secretID: secret,
+ },
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ if (res.response.status === 404) {
+ return false
+ }
+
+ const err = handleApiError(res, SecretError)
+ if (err) {
+ throw err
+ }
+
+ return true
+ }
+
+ /**
+ * Format a placeholder that the runtime resolves to the secret's current
+ * value.
+ *
+ * This is a local formatting helper and makes no network call — it does
+ * not check whether the named secret exists. An unknown reference fails
+ * server-side when the placeholder is resolved.
+ *
+ * @param secret secret name.
+ *
+ * @returns placeholder string resolving to the secret's value.
+ *
+ * @example
+ * ```ts
+ * Secret.fill('openai-api-key')
+ * // '${e2b.secrets.openai-api-key}'
+ * ```
+ */
+ static fill(secret: string): string {
+ validateSecretName(secret)
+
+ return `\${e2b.secrets.${secret}}`
+ }
+
/**
* Define a workload identity token to pass to `iam.tokens` when creating
* a sandbox.
diff --git a/packages/js-sdk/tests/secret/secret.test.ts b/packages/js-sdk/tests/secret/secret.test.ts
new file mode 100644
index 000000000..3714ad774
--- /dev/null
+++ b/packages/js-sdk/tests/secret/secret.test.ts
@@ -0,0 +1,210 @@
+import { describe, it, expect, afterAll, afterEach, beforeAll } from 'vitest'
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+import { randomUUID } from 'node:crypto'
+
+import { InvalidArgumentError, Secret, SecretNotFoundError } from '../../src'
+import { apiUrl } from '../setup'
+
+interface MockSecret {
+ secretID: string
+ name: string
+ currentVersion: number
+ metadata: Record<string, string>
+ createdAt: string
+ updatedAt: string
+}
+
+// In-memory store for mock secrets, keyed by both ID and name
+const secrets = new Map<string, MockSecret>()
+
+function findSecret(selector: string): MockSecret | undefined {
+ return (
+ secrets.get(selector) ??
+ Array.from(secrets.values()).find((s) => s.name === selector)
+ )
+}
+
+const restHandlers = [
+ http.post(apiUrl('/secrets'), async ({ request }) => {
+ const { name, metadata } = (await request.clone().json()) as {
+ name: string
+ value: string
+ metadata?: Record<string, string>
+ }
+ const now = new Date().toISOString()
+ const secret: MockSecret = {
+ secretID: `sec_${randomUUID()}`,
+ name: name.toLowerCase(),
+ currentVersion: 1,
+ metadata: metadata ?? {},
+ createdAt: now,
+ updatedAt: now,
+ }
+ secrets.set(secret.secretID, secret)
+ return HttpResponse.json(secret, { status: 201 })
+ }),
+
+ http.get(apiUrl('/secrets'), ({ request }) => {
+ const url = new URL(request.url)
+ const limit = Number(url.searchParams.get('limit') ?? 100)
+ const nextToken = url.searchParams.get('nextToken')
+
+ const all = Array.from(secrets.values())
+ const start = nextToken ? Number(nextToken) : 0
+ const page = all.slice(start, start + limit)
+ const headers: Record<string, string> = {}
+ if (start + limit < all.length) {
+ headers['x-next-token'] = String(start + limit)
+ }
+ return HttpResponse.json(page, { headers })
+ }),
+
+ http.get<{ secretID: string }>(apiUrl('/secrets/:secretID'), ({ params }) => {
+ const secret = findSecret(params.secretID)
+ if (!secret) {
+ return HttpResponse.json(
+ { code: 404, message: 'Not found' },
+ { status: 404 }
+ )
+ }
+ return HttpResponse.json(secret)
+ }),
+
+ http.post<{ secretID: string }>(
+ apiUrl('/secrets/:secretID'),
+ async ({ params, request }) => {
+ const secret = findSecret(params.secretID)
+ if (!secret) {
+ return HttpResponse.json(
+ { code: 404, message: 'Not found' },
+ { status: 404 }
+ )
+ }
+ const { metadata } = (await request.clone().json()) as {
+ value: string
+ metadata?: Record<string, string>
+ }
+ secret.currentVersion += 1
+ if (metadata) {
+ secret.metadata = metadata
+ }
+ secret.updatedAt = new Date().toISOString()
+ return HttpResponse.json(secret)
+ }
+ ),
+
+ http.delete<{ secretID: string }>(
+ apiUrl('/secrets/:secretID'),
+ ({ params }) => {
+ const secret = findSecret(params.secretID)
+ if (!secret) {
+ return HttpResponse.json(
+ { code: 404, message: 'Not found' },
+ { status: 404 }
+ )
+ }
+ secrets.delete(secret.secretID)
+ return new HttpResponse(null, { status: 204 })
+ }
+ ),
+]
+
+const server = setupServer(...restHandlers)
+
+beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
+afterAll(() => server.close())
+afterEach(() => {
+ server.resetHandlers()
+ secrets.clear()
+})
+
+describe('Secret CRUD', () => {
+ it('should create a secret', async () => {
+ const info = await Secret.create('openai-api-key', 'sk-test', {
+ metadata: { env: 'test' },
+ })
+
+ expect(info.secretId).toMatch(/^sec_/)
+ expect(info.name).toBe('openai-api-key')
+ expect(info.version).toBe(1)
+ expect(info.metadata).toEqual({ env: 'test' })
+ expect(info.createdAt).toBeInstanceOf(Date)
+ expect(info.updatedAt).toBeInstanceOf(Date)
+ expect(info).not.toHaveProperty('value')
+ })
+
+ it('should update a secret', async () => {
+ const created = await Secret.create('rotating-key', 'v1')
+ const updated = await Secret.update(created.secretId, 'v2')
+
+ expect(updated.secretId).toBe(created.secretId)
+ expect(updated.version).toBe(2)
+ })
+
+ it('should throw when updating a non-existent secret', async () => {
+ await expect(Secret.update('missing', 'value')).rejects.toThrow(
+ SecretNotFoundError
+ )
+ })
+
+ it('should get secret info by ID and by name', async () => {
+ const created = await Secret.create('lookup-key', 'value')
+
+ const byId = await Secret.getInfo(created.secretId)
+ expect(byId.name).toBe('lookup-key')
+
+ const byName = await Secret.getInfo('lookup-key')
+ expect(byName.secretId).toBe(created.secretId)
+ })
+
+ it('should throw when getting a non-existent secret', async () => {
+ await expect(Secret.getInfo('missing')).rejects.toThrow(SecretNotFoundError)
+ })
+
+ it('should list secrets with pagination', async () => {
+ await Secret.create('key-a', 'a')
+ await Secret.create('key-b', 'b')
+ await Secret.create('key-c', 'c')
+
+ const paginator = Secret.list({ limit: 2 })
+ const firstPage = await paginator.nextItems()
+ expect(firstPage).toHaveLength(2)
+ expect(paginator.hasNext).toBe(true)
+
+ const secondPage = await paginator.nextItems()
+ expect(secondPage).toHaveLength(1)
+ expect(paginator.hasNext).toBe(false)
+ })
+
+ it('should check secret existence', async () => {
+ await Secret.create('present-key', 'value')
+
+ expect(await Secret.exists('present-key')).toBe(true)
+ expect(await Secret.exists('absent-key')).toBe(false)
+ })
+
+ it('should destroy a secret', async () => {
+ const created = await Secret.create('to-delete', 'value')
+
+ expect(await Secret.destroy(created.secretId)).toBe(true)
+ expect(await Secret.exists(created.secretId)).toBe(false)
+ })
+
+ it('should return false when destroying a non-existent secret', async () => {
+ expect(await Secret.destroy('missing')).toBe(false)
+ })
+})
+
+describe('Secret.fill', () => {
+ it('should format a placeholder', () => {
+ expect(Secret.fill('openai-api-key')).toBe('${e2b.secrets.openai-api-key}')
+ })
+
+ it.each(['', '{name', 'name}', 'name\n', 'name\x00'])(
+ 'should throw InvalidArgumentError for invalid name %j',
+ (name) => {
+ expect(() => Secret.fill(name)).toThrow(InvalidArgumentError)
+ }
+ )
+})
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 62e589b0a..66306a767 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -54,6 +54,8 @@ from .exceptions import (
VolumeException,
VolumeNotFoundException,
VolumePathNotFoundException,
+ SecretException,
+ SecretNotFoundException,
)
from .sandbox.commands.command_handle import (
CommandExitException,
@@ -107,7 +109,13 @@ from .sandbox_async.filesystem.watch_handle import AsyncWatchHandle
from .sandbox_async.main import AsyncSandbox
from .sandbox_async.paginator import AsyncSandboxPaginator, AsyncSnapshotPaginator
from .sandbox_async.utils import OutputHandler
-from .secret import Secret
+from .secret import (
+ AsyncSecret,
+ AsyncSecretPaginator,
+ Secret,
+ SecretInfo,
+ SecretPaginator,
+)
from .sandbox_sync.commands.command_handle import CommandHandle
from .sandbox_sync.filesystem.watch_handle import WatchHandle
from .sandbox_sync.main import Sandbox
@@ -225,6 +233,12 @@ __all__ = [
"SandboxIamToken",
"SandboxIamTokenType",
"Secret",
+ "AsyncSecret",
+ "SecretInfo",
+ "SecretPaginator",
+ "AsyncSecretPaginator",
+ "SecretException",
+ "SecretNotFoundException",
# Snapshot
"SnapshotInfo",
"SnapshotPaginator",
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py b/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py
index 75bfcef7f..90ce4ce2d 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py
@@ -1,3 +1,4 @@
+import datetime
from http import HTTPStatus
from typing import Any, Optional, Union
@@ -7,6 +8,7 @@ from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.error import Error
from ...models.listed_sandbox import ListedSandbox
+from ...models.order_direction import OrderDirection
from ...models.sandbox_state import SandboxState
from ...types import UNSET, Response, Unset
@@ -15,6 +17,9 @@ def _get_kwargs(
*,
metadata: Union[Unset, str] = UNSET,
state: Union[Unset, list[SandboxState]] = UNSET,
+ order: Union[Unset, OrderDirection] = UNSET,
+ started_after: Union[Unset, datetime.datetime] = UNSET,
+ template: Union[Unset, str] = UNSET,
next_token: Union[Unset, str] = UNSET,
limit: Union[Unset, int] = 100,
) -> dict[str, Any]:
@@ -32,6 +37,19 @@ def _get_kwargs(
if not isinstance(json_state, Unset):
params["state"] = ",".join(str(item) for item in json_state)
+ json_order: Union[Unset, str] = UNSET
+ if not isinstance(order, Unset):
+ json_order = order.value
+
+ params["order"] = json_order
+
+ json_started_after: Union[Unset, str] = UNSET
+ if not isinstance(started_after, Unset):
+ json_started_after = started_after.isoformat()
+ params["startedAfter"] = json_started_after
+
+ params["template"] = template
+
params["nextToken"] = next_token
params["limit"] = limit
@@ -93,6 +111,9 @@ def sync_detailed(
client: AuthenticatedClient,
metadata: Union[Unset, str] = UNSET,
state: Union[Unset, list[SandboxState]] = UNSET,
+ order: Union[Unset, OrderDirection] = UNSET,
+ started_after: Union[Unset, datetime.datetime] = UNSET,
+ template: Union[Unset, str] = UNSET,
next_token: Union[Unset, str] = UNSET,
limit: Union[Unset, int] = 100,
) -> Response[Union[Error, list["ListedSandbox"]]]:
@@ -103,6 +124,9 @@ def sync_detailed(
Args:
metadata (Union[Unset, str]):
state (Union[Unset, list[SandboxState]]):
+ order (Union[Unset, OrderDirection]): Sort direction
+ started_after (Union[Unset, datetime.datetime]):
+ template (Union[Unset, str]):
next_token (Union[Unset, str]):
limit (Union[Unset, int]): Default: 100.
@@ -117,6 +141,9 @@ def sync_detailed(
kwargs = _get_kwargs(
metadata=metadata,
state=state,
+ order=order,
+ started_after=started_after,
+ template=template,
next_token=next_token,
limit=limit,
)
@@ -133,6 +160,9 @@ def sync(
client: AuthenticatedClient,
metadata: Union[Unset, str] = UNSET,
state: Union[Unset, list[SandboxState]] = UNSET,
+ order: Union[Unset, OrderDirection] = UNSET,
+ started_after: Union[Unset, datetime.datetime] = UNSET,
+ template: Union[Unset, str] = UNSET,
next_token: Union[Unset, str] = UNSET,
limit: Union[Unset, int] = 100,
) -> Optional[Union[Error, list["ListedSandbox"]]]:
@@ -143,6 +173,9 @@ def sync(
Args:
metadata (Union[Unset, str]):
state (Union[Unset, list[SandboxState]]):
+ order (Union[Unset, OrderDirection]): Sort direction
+ started_after (Union[Unset, datetime.datetime]):
+ template (Union[Unset, str]):
next_token (Union[Unset, str]):
limit (Union[Unset, int]): Default: 100.
@@ -158,6 +191,9 @@ def sync(
client=client,
metadata=metadata,
state=state,
+ order=order,
+ started_after=started_after,
+ template=template,
next_token=next_token,
limit=limit,
).parsed
@@ -168,6 +204,9 @@ async def asyncio_detailed(
client: AuthenticatedClient,
metadata: Union[Unset, str] = UNSET,
state: Union[Unset, list[SandboxState]] = UNSET,
+ order: Union[Unset, OrderDirection] = UNSET,
+ started_after: Union[Unset, datetime.datetime] = UNSET,
+ template: Union[Unset, str] = UNSET,
next_token: Union[Unset, str] = UNSET,
limit: Union[Unset, int] = 100,
) -> Response[Union[Error, list["ListedSandbox"]]]:
@@ -178,6 +217,9 @@ async def asyncio_detailed(
Args:
metadata (Union[Unset, str]):
state (Union[Unset, list[SandboxState]]):
+ order (Union[Unset, OrderDirection]): Sort direction
+ started_after (Union[Unset, datetime.datetime]):
+ template (Union[Unset, str]):
next_token (Union[Unset, str]):
limit (Union[Unset, int]): Default: 100.
@@ -192,6 +234,9 @@ async def asyncio_detailed(
kwargs = _get_kwargs(
metadata=metadata,
state=state,
+ order=order,
+ started_after=started_after,
+ template=template,
next_token=next_token,
limit=limit,
)
@@ -206,6 +251,9 @@ async def asyncio(
client: AuthenticatedClient,
metadata: Union[Unset, str] = UNSET,
state: Union[Unset, list[SandboxState]] = UNSET,
+ order: Union[Unset, OrderDirection] = UNSET,
+ started_after: Union[Unset, datetime.datetime] = UNSET,
+ template: Union[Unset, str] = UNSET,
next_token: Union[Unset, str] = UNSET,
limit: Union[Unset, int] = 100,
) -> Optional[Union[Error, list["ListedSandbox"]]]:
@@ -216,6 +264,9 @@ async def asyncio(
Args:
metadata (Union[Unset, str]):
state (Union[Unset, list[SandboxState]]):
+ order (Union[Unset, OrderDirection]): Sort direction
+ started_after (Union[Unset, datetime.datetime]):
+ template (Union[Unset, str]):
next_token (Union[Unset, str]):
limit (Union[Unset, int]): Default: 100.
@@ -232,6 +283,9 @@ async def asyncio(
client=client,
metadata=metadata,
state=state,
+ order=order,
+ started_after=started_after,
+ template=template,
next_token=next_token,
limit=limit,
)
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes.py
index 95e017c6b..56f5dc155 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes.py
@@ -49,6 +49,14 @@ def _parse_response(
response_500 = Error.from_dict(response.json())
return response_500
+ if response.status_code == 503:
+ response_503 = Error.from_dict(response.json())
+
+ return response_503
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_connect.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_connect.py
index a37aa7508..b2562c449 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_connect.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_connect.py
@@ -54,10 +54,22 @@ def _parse_response(
response_404 = Error.from_dict(response.json())
return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
if response.status_code == 500:
response_500 = Error.from_dict(response.json())
return response_500
+ if response.status_code == 503:
+ response_503 = Error.from_dict(response.json())
+
+ return response_503
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py
index 4387dc28d..9d09e939e 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py
@@ -59,6 +59,10 @@ def _parse_response(
response_500 = Error.from_dict(response.json())
return response_500
+ if response.status_code == 503:
+ response_503 = Error.from_dict(response.json())
+
+ return response_503
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_resume.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_resume.py
index c359aa8ae..6e9116258 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_resume.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_resume.py
@@ -38,6 +38,10 @@ def _parse_response(
response_201 = Sandbox.from_dict(response.json())
return response_201
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
if response.status_code == 401:
response_401 = Error.from_dict(response.json())
@@ -54,6 +58,14 @@ def _parse_response(
response_500 = Error.from_dict(response.json())
return response_500
+ if response.status_code == 503:
+ response_503 = Error.from_dict(response.json())
+
+ return response_503
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/__init__.py b/packages/python-sdk/e2b/api/client/api/secrets/__init__.py
new file mode 100644
index 000000000..2d7c0b23d
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/delete_secrets_secret_id.py b/packages/python-sdk/e2b/api/client/api/secrets/delete_secrets_secret_id.py
new file mode 100644
index 000000000..4f46d31d9
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/delete_secrets_secret_id.py
@@ -0,0 +1,197 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union, cast
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...types import Response
+
+
+def _get_kwargs(
+ secret_id: str,
+) -> dict[str, Any]:
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": f"/secrets/{secret_id}",
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Any, Error]]:
+ if response.status_code == 204:
+ response_204 = cast(Any, None)
+ return response_204
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 429:
+ response_429 = Error.from_dict(response.json())
+
+ return response_429
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if response.status_code == 502:
+ response_502 = Error.from_dict(response.json())
+
+ return response_502
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Any, Error]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Any, Error]]:
+ """Delete a secret
+
+ Revoke the secret and schedule its versions for cleanup.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Any, Error]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Any, Error]]:
+ """Delete a secret
+
+ Revoke the secret and schedule its versions for cleanup.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Any, Error]
+ """
+
+ return sync_detailed(
+ secret_id=secret_id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Any, Error]]:
+ """Delete a secret
+
+ Revoke the secret and schedule its versions for cleanup.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Any, Error]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Any, Error]]:
+ """Delete a secret
+
+ Revoke the secret and schedule its versions for cleanup.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Any, Error]
+ """
+
+ return (
+ await asyncio_detailed(
+ secret_id=secret_id,
+ client=client,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/get_secrets.py b/packages/python-sdk/e2b/api/client/api/secrets/get_secrets.py
new file mode 100644
index 000000000..103739bbc
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/get_secrets.py
@@ -0,0 +1,223 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.secret import Secret
+from ...types import UNSET, Response, Unset
+
+
+def _get_kwargs(
+ *,
+ next_token: Union[Unset, str] = UNSET,
+ limit: Union[Unset, int] = 100,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ params["nextToken"] = next_token
+
+ params["limit"] = limit
+
+ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/secrets",
+ "params": params,
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, list["Secret"]]]:
+ if response.status_code == 200:
+ response_200 = []
+ _response_200 = response.json()
+ for response_200_item_data in _response_200:
+ response_200_item = Secret.from_dict(response_200_item_data)
+
+ response_200.append(response_200_item)
+
+ return response_200
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 429:
+ response_429 = Error.from_dict(response.json())
+
+ return response_429
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if response.status_code == 502:
+ response_502 = Error.from_dict(response.json())
+
+ return response_502
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, list["Secret"]]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ *,
+ client: AuthenticatedClient,
+ next_token: Union[Unset, str] = UNSET,
+ limit: Union[Unset, int] = 100,
+) -> Response[Union[Error, list["Secret"]]]:
+ """List project secrets
+
+ List the project's secrets. No response carries a secret value.
+
+ Args:
+ next_token (Union[Unset, str]):
+ limit (Union[Unset, int]): Default: 100.
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, list['Secret']]]
+ """
+
+ kwargs = _get_kwargs(
+ next_token=next_token,
+ limit=limit,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ *,
+ client: AuthenticatedClient,
+ next_token: Union[Unset, str] = UNSET,
+ limit: Union[Unset, int] = 100,
+) -> Optional[Union[Error, list["Secret"]]]:
+ """List project secrets
+
+ List the project's secrets. No response carries a secret value.
+
+ Args:
+ next_token (Union[Unset, str]):
+ limit (Union[Unset, int]): Default: 100.
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, list['Secret']]
+ """
+
+ return sync_detailed(
+ client=client,
+ next_token=next_token,
+ limit=limit,
+ ).parsed
+
+
+async def asyncio_detailed(
+ *,
+ client: AuthenticatedClient,
+ next_token: Union[Unset, str] = UNSET,
+ limit: Union[Unset, int] = 100,
+) -> Response[Union[Error, list["Secret"]]]:
+ """List project secrets
+
+ List the project's secrets. No response carries a secret value.
+
+ Args:
+ next_token (Union[Unset, str]):
+ limit (Union[Unset, int]): Default: 100.
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, list['Secret']]]
+ """
+
+ kwargs = _get_kwargs(
+ next_token=next_token,
+ limit=limit,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ *,
+ client: AuthenticatedClient,
+ next_token: Union[Unset, str] = UNSET,
+ limit: Union[Unset, int] = 100,
+) -> Optional[Union[Error, list["Secret"]]]:
+ """List project secrets
+
+ List the project's secrets. No response carries a secret value.
+
+ Args:
+ next_token (Union[Unset, str]):
+ limit (Union[Unset, int]): Default: 100.
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, list['Secret']]
+ """
+
+ return (
+ await asyncio_detailed(
+ client=client,
+ next_token=next_token,
+ limit=limit,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/get_secrets_secret_id.py b/packages/python-sdk/e2b/api/client/api/secrets/get_secrets_secret_id.py
new file mode 100644
index 000000000..49ce0b66c
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/get_secrets_secret_id.py
@@ -0,0 +1,199 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.secret import Secret
+from ...types import Response
+
+
+def _get_kwargs(
+ secret_id: str,
+) -> dict[str, Any]:
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": f"/secrets/{secret_id}",
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, Secret]]:
+ if response.status_code == 200:
+ response_200 = Secret.from_dict(response.json())
+
+ return response_200
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 429:
+ response_429 = Error.from_dict(response.json())
+
+ return response_429
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if response.status_code == 502:
+ response_502 = Error.from_dict(response.json())
+
+ return response_502
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, Secret]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Error, Secret]]:
+ """Get a secret
+
+ Get one secret's metadata, selected by identifier or name.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Error, Secret]]:
+ """Get a secret
+
+ Get one secret's metadata, selected by identifier or name.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return sync_detailed(
+ secret_id=secret_id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Response[Union[Error, Secret]]:
+ """Get a secret
+
+ Get one secret's metadata, selected by identifier or name.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+) -> Optional[Union[Error, Secret]]:
+ """Get a secret
+
+ Get one secret's metadata, selected by identifier or name.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return (
+ await asyncio_detailed(
+ secret_id=secret_id,
+ client=client,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/post_secrets.py b/packages/python-sdk/e2b/api/client/api/secrets/post_secrets.py
new file mode 100644
index 000000000..8e250b751
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/post_secrets.py
@@ -0,0 +1,208 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.new_secret import NewSecret
+from ...models.secret import Secret
+from ...types import Response
+
+
+def _get_kwargs(
+ *,
+ body: NewSecret,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/secrets",
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, Secret]]:
+ if response.status_code == 201:
+ response_201 = Secret.from_dict(response.json())
+
+ return response_201
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 429:
+ response_429 = Error.from_dict(response.json())
+
+ return response_429
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if response.status_code == 502:
+ response_502 = Error.from_dict(response.json())
+
+ return response_502
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, Secret]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ *,
+ client: AuthenticatedClient,
+ body: NewSecret,
+) -> Response[Union[Error, Secret]]:
+ """Create a secret
+
+ Create a secret by storing a runtime marker as its first version. The response carries metadata
+ only.
+
+ Args:
+ body (NewSecret):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ *,
+ client: AuthenticatedClient,
+ body: NewSecret,
+) -> Optional[Union[Error, Secret]]:
+ """Create a secret
+
+ Create a secret by storing a runtime marker as its first version. The response carries metadata
+ only.
+
+ Args:
+ body (NewSecret):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return sync_detailed(
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ *,
+ client: AuthenticatedClient,
+ body: NewSecret,
+) -> Response[Union[Error, Secret]]:
+ """Create a secret
+
+ Create a secret by storing a runtime marker as its first version. The response carries metadata
+ only.
+
+ Args:
+ body (NewSecret):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ *,
+ client: AuthenticatedClient,
+ body: NewSecret,
+) -> Optional[Union[Error, Secret]]:
+ """Create a secret
+
+ Create a secret by storing a runtime marker as its first version. The response carries metadata
+ only.
+
+ Args:
+ body (NewSecret):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return (
+ await asyncio_detailed(
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/api/secrets/post_secrets_secret_id.py b/packages/python-sdk/e2b/api/client/api/secrets/post_secrets_secret_id.py
new file mode 100644
index 000000000..f32bdb3c3
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/secrets/post_secrets_secret_id.py
@@ -0,0 +1,221 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.secret import Secret
+from ...models.secret_update import SecretUpdate
+from ...types import Response
+
+
+def _get_kwargs(
+ secret_id: str,
+ *,
+ body: SecretUpdate,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": f"/secrets/{secret_id}",
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, Secret]]:
+ if response.status_code == 200:
+ response_200 = Secret.from_dict(response.json())
+
+ return response_200
+ if response.status_code == 400:
+ response_400 = Error.from_dict(response.json())
+
+ return response_400
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 403:
+ response_403 = Error.from_dict(response.json())
+
+ return response_403
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 429:
+ response_429 = Error.from_dict(response.json())
+
+ return response_429
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if response.status_code == 502:
+ response_502 = Error.from_dict(response.json())
+
+ return response_502
+ if response.status_code == 504:
+ response_504 = Error.from_dict(response.json())
+
+ return response_504
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, Secret]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SecretUpdate,
+) -> Response[Union[Error, Secret]]:
+ """Update a secret
+
+ Replace the secret's stored marker by appending a new version. The response carries metadata only.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+ body (SecretUpdate):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SecretUpdate,
+) -> Optional[Union[Error, Secret]]:
+ """Update a secret
+
+ Replace the secret's stored marker by appending a new version. The response carries metadata only.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+ body (SecretUpdate):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return sync_detailed(
+ secret_id=secret_id,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SecretUpdate,
+) -> Response[Union[Error, Secret]]:
+ """Update a secret
+
+ Replace the secret's stored marker by appending a new version. The response carries metadata only.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+ body (SecretUpdate):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, Secret]]
+ """
+
+ kwargs = _get_kwargs(
+ secret_id=secret_id,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ secret_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SecretUpdate,
+) -> Optional[Union[Error, Secret]]:
+ """Update a secret
+
+ Replace the secret's stored marker by appending a new version. The response carries metadata only.
+
+ Args:
+ secret_id (str): Identifier of the secret (sec_ prefixed), or its canonical lower-case
+ name
+ body (SecretUpdate):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, Secret]
+ """
+
+ return (
+ await asyncio_detailed(
+ secret_id=secret_id,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.py
index 5483749de..135420b69 100644
--- a/packages/python-sdk/e2b/api/client/models/__init__.py
+++ b/packages/python-sdk/e2b/api/client/models/__init__.py
@@ -29,6 +29,7 @@ from .max_team_metric import MaxTeamMetric
from .mcp_type_0 import McpType0
from .new_access_token import NewAccessToken
from .new_sandbox import NewSandbox
+from .new_secret import NewSecret
from .new_team_api_key import NewTeamAPIKey
from .new_volume import NewVolume
from .node import Node
@@ -36,6 +37,7 @@ from .node_detail import NodeDetail
from .node_metrics import NodeMetrics
from .node_status import NodeStatus
from .node_status_change import NodeStatusChange
+from .order_direction import OrderDirection
from .resumed_sandbox import ResumedSandbox
from .sandbox import Sandbox
from .sandbox_auto_resume_config import SandboxAutoResumeConfig
@@ -68,6 +70,9 @@ from .sandbox_state import SandboxState
from .sandbox_timeout_request import SandboxTimeoutRequest
from .sandbox_volume_mount import SandboxVolumeMount
from .sandboxes_with_metrics import SandboxesWithMetrics
+from .secret import Secret
+from .secret_metadata import SecretMetadata
+from .secret_update import SecretUpdate
from .snapshot_info import SnapshotInfo
from .team import Team
from .team_api_key import TeamAPIKey
@@ -126,6 +131,7 @@ __all__ = (
"McpType0",
"NewAccessToken",
"NewSandbox",
+ "NewSecret",
"NewTeamAPIKey",
"NewVolume",
"Node",
@@ -133,6 +139,7 @@ __all__ = (
"NodeMetrics",
"NodeStatus",
"NodeStatusChange",
+ "OrderDirection",
"ResumedSandbox",
"Sandbox",
"SandboxAutoResumeConfig",
@@ -165,6 +172,9 @@ __all__ = (
"SandboxState",
"SandboxTimeoutRequest",
"SandboxVolumeMount",
+ "Secret",
+ "SecretMetadata",
+ "SecretUpdate",
"SnapshotInfo",
"Team",
"TeamAPIKey",
diff --git a/packages/python-sdk/e2b/api/client/models/error.py b/packages/python-sdk/e2b/api/client/models/error.py
index 362b4361e..fec3fa736 100644
--- a/packages/python-sdk/e2b/api/client/models/error.py
+++ b/packages/python-sdk/e2b/api/client/models/error.py
@@ -1,9 +1,11 @@
from collections.abc import Mapping
-from typing import Any, TypeVar
+from typing import Any, TypeVar, Union
from attrs import define as _attrs_define
from attrs import field as _attrs_field
+from ..types import UNSET, Unset
+
T = TypeVar("T", bound="Error")
@@ -13,10 +15,14 @@ class Error:
Attributes:
code (int): Error code
message (str): Error
+ error_code (Union[Unset, str]): Machine-readable semantic error code. Not a closed set; initial values:
+ sandbox_capacity_unavailable, sandbox_placement_timeout, sandbox_no_compatible_node, sandbox_create_failed,
+ internal_server_error.
"""
code: int
message: str
+ error_code: Union[Unset, str] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
@@ -24,6 +30,8 @@ class Error:
message = self.message
+ error_code = self.error_code
+
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
@@ -32,6 +40,8 @@ class Error:
"message": message,
}
)
+ if error_code is not UNSET:
+ field_dict["error_code"] = error_code
return field_dict
@@ -42,9 +52,12 @@ class Error:
message = d.pop("message")
+ error_code = d.pop("error_code", UNSET)
+
error = cls(
code=code,
message=message,
+ error_code=error_code,
)
error.additional_properties = d
diff --git a/packages/python-sdk/e2b/api/client/models/new_secret.py b/packages/python-sdk/e2b/api/client/models/new_secret.py
new file mode 100644
index 000000000..8b9f3cce6
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/new_secret.py
@@ -0,0 +1,95 @@
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar, Union
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.secret_metadata import SecretMetadata
+
+
+T = TypeVar("T", bound="NewSecret")
+
+
+@_attrs_define
+class NewSecret:
+ """
+ Attributes:
+ name (str): Name of the secret, unique within the project. Names are lower-cased before storage and returned in
+ that canonical form; the sec_ prefix is reserved for secret identifiers.
+ value (str): Runtime marker stored as the secret's first version. The runtime resolves it to a value at sandbox
+ egress.
+ metadata (Union[Unset, SecretMetadata]): Customer metadata of the secret. Always present, empty when unset. At
+ most 32 entries; keys are limited to 128 bytes, values to 1024 bytes, and a secret's metadata to 8192 bytes in
+ total.
+ """
+
+ name: str
+ value: str
+ metadata: Union[Unset, "SecretMetadata"] = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ name = self.name
+
+ value = self.value
+
+ metadata: Union[Unset, dict[str, Any]] = UNSET
+ if not isinstance(self.metadata, Unset):
+ metadata = self.metadata.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "name": name,
+ "value": value,
+ }
+ )
+ if metadata is not UNSET:
+ field_dict["metadata"] = metadata
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.secret_metadata import SecretMetadata
+
+ d = dict(src_dict)
+ name = d.pop("name")
+
+ value = d.pop("value")
+
+ _metadata = d.pop("metadata", UNSET)
+ metadata: Union[Unset, SecretMetadata]
+ if isinstance(_metadata, Unset):
+ metadata = UNSET
+ else:
+ metadata = SecretMetadata.from_dict(_metadata)
+
+ new_secret = cls(
+ name=name,
+ value=value,
+ metadata=metadata,
+ )
+
+ new_secret.additional_properties = d
+ return new_secret
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/order_direction.py b/packages/python-sdk/e2b/api/client/models/order_direction.py
new file mode 100644
index 000000000..e650fa2a6
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/order_direction.py
@@ -0,0 +1,9 @@
+from enum import Enum
+
+
+class OrderDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+ def __str__(self) -> str:
+ return str(self.value)
diff --git a/packages/python-sdk/e2b/api/client/models/secret.py b/packages/python-sdk/e2b/api/client/models/secret.py
new file mode 100644
index 000000000..396c0ea44
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/secret.py
@@ -0,0 +1,109 @@
+import datetime
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+from dateutil.parser import isoparse
+
+if TYPE_CHECKING:
+ from ..models.secret_metadata import SecretMetadata
+
+
+T = TypeVar("T", bound="Secret")
+
+
+@_attrs_define
+class Secret:
+ """Metadata of a secret. It never carries the secret value.
+
+ Attributes:
+ secret_id (str): Identifier of the secret
+ name (str): Name of the secret, unique within the project
+ current_version (int): Version served to readers that do not name one
+ metadata (SecretMetadata): Customer metadata of the secret. Always present, empty when unset. At most 32
+ entries; keys are limited to 128 bytes, values to 1024 bytes, and a secret's metadata to 8192 bytes in total.
+ created_at (datetime.datetime): Time when the secret was created
+ updated_at (datetime.datetime): Time when the secret was last updated
+ """
+
+ secret_id: str
+ name: str
+ current_version: int
+ metadata: "SecretMetadata"
+ created_at: datetime.datetime
+ updated_at: datetime.datetime
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ secret_id = self.secret_id
+
+ name = self.name
+
+ current_version = self.current_version
+
+ metadata = self.metadata.to_dict()
+
+ created_at = self.created_at.isoformat()
+
+ updated_at = self.updated_at.isoformat()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "secretID": secret_id,
+ "name": name,
+ "currentVersion": current_version,
+ "metadata": metadata,
+ "createdAt": created_at,
+ "updatedAt": updated_at,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.secret_metadata import SecretMetadata
+
+ d = dict(src_dict)
+ secret_id = d.pop("secretID")
+
+ name = d.pop("name")
+
+ current_version = d.pop("currentVersion")
+
+ metadata = SecretMetadata.from_dict(d.pop("metadata"))
+
+ created_at = isoparse(d.pop("createdAt"))
+
+ updated_at = isoparse(d.pop("updatedAt"))
+
+ secret = cls(
+ secret_id=secret_id,
+ name=name,
+ current_version=current_version,
+ metadata=metadata,
+ created_at=created_at,
+ updated_at=updated_at,
+ )
+
+ secret.additional_properties = d
+ return secret
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/secret_metadata.py b/packages/python-sdk/e2b/api/client/models/secret_metadata.py
new file mode 100644
index 000000000..e81ec007c
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/secret_metadata.py
@@ -0,0 +1,47 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="SecretMetadata")
+
+
+@_attrs_define
+class SecretMetadata:
+ """Customer metadata of the secret. Always present, empty when unset. At most 32 entries; keys are limited to 128
+ bytes, values to 1024 bytes, and a secret's metadata to 8192 bytes in total.
+
+ """
+
+ additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ secret_metadata = cls()
+
+ secret_metadata.additional_properties = d
+ return secret_metadata
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> str:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: str) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/secret_update.py b/packages/python-sdk/e2b/api/client/models/secret_update.py
new file mode 100644
index 000000000..2e320e481
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/secret_update.py
@@ -0,0 +1,86 @@
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar, Union
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.secret_metadata import SecretMetadata
+
+
+T = TypeVar("T", bound="SecretUpdate")
+
+
+@_attrs_define
+class SecretUpdate:
+ """
+ Attributes:
+ value (str): Runtime marker stored as the secret's new version. The runtime resolves it to a value at sandbox
+ egress.
+ metadata (Union[Unset, SecretMetadata]): Customer metadata of the secret. Always present, empty when unset. At
+ most 32 entries; keys are limited to 128 bytes, values to 1024 bytes, and a secret's metadata to 8192 bytes in
+ total.
+ """
+
+ value: str
+ metadata: Union[Unset, "SecretMetadata"] = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ value = self.value
+
+ metadata: Union[Unset, dict[str, Any]] = UNSET
+ if not isinstance(self.metadata, Unset):
+ metadata = self.metadata.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "value": value,
+ }
+ )
+ if metadata is not UNSET:
+ field_dict["metadata"] = metadata
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.secret_metadata import SecretMetadata
+
+ d = dict(src_dict)
+ value = d.pop("value")
+
+ _metadata = d.pop("metadata", UNSET)
+ metadata: Union[Unset, SecretMetadata]
+ if isinstance(_metadata, Unset):
+ metadata = UNSET
+ else:
+ metadata = SecretMetadata.from_dict(_metadata)
+
+ secret_update = cls(
+ value=value,
+ metadata=metadata,
+ )
+
+ secret_update.additional_properties = d
+ return secret_update
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/exceptions.py b/packages/python-sdk/e2b/exceptions.py
index b3626e1e5..7846654da 100644
--- a/packages/python-sdk/e2b/exceptions.py
+++ b/packages/python-sdk/e2b/exceptions.py
@@ -143,3 +143,17 @@ class VolumePathNotFoundException(NotFoundException):
"""
Raised when a file or directory is not found inside a volume.
"""
+
+
+class SecretException(Exception):
+ """
+ Base class for all secret errors.
+
+ Raised when general secret errors occur.
+ """
+
+
+class SecretNotFoundException(SecretException):
+ """
+ Raised when a secret is not found.
+ """
diff --git a/packages/python-sdk/e2b/secret.py b/packages/python-sdk/e2b/secret.py
deleted file mode 100644
index d895bc468..000000000
--- a/packages/python-sdk/e2b/secret.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from e2b.sandbox.sandbox_api import SandboxIamToken, SandboxIamTokenType
-
-
-class Secret:
- """
- Secrets and workload identity helpers.
- """
-
- @staticmethod
- def iam_token(*, audience: str, token_type: SandboxIamTokenType) -> SandboxIamToken:
- """
- Define a workload identity token to pass to ``iam.tokens`` when
- creating a sandbox.
-
- :param audience: Audience of the workload token, stored exactly as provided.
- :param token_type: Workload token type.
-
- :return: A token definition passable to ``iam.tokens``.
-
- Example:
- ```python
- sandbox = Sandbox.create(
- iam={
- "tokens": {
- "aws": Secret.iam_token(
- audience="sts.amazonaws.com",
- token_type="JWT-SVID",
- ),
- },
- },
- )
- ```
- """
- return SandboxIamToken(audience=audience, token_type=token_type)
diff --git a/packages/python-sdk/e2b/secret/__init__.py b/packages/python-sdk/e2b/secret/__init__.py
new file mode 100644
index 000000000..ef1675538
--- /dev/null
+++ b/packages/python-sdk/e2b/secret/__init__.py
@@ -0,0 +1,11 @@
+from e2b.secret.secret_async import AsyncSecret, AsyncSecretPaginator
+from e2b.secret.secret_sync import Secret, SecretPaginator
+from e2b.secret.types import SecretInfo
+
+__all__ = [
+ "AsyncSecret",
+ "AsyncSecretPaginator",
+ "Secret",
+ "SecretPaginator",
+ "SecretInfo",
+]
diff --git a/packages/python-sdk/e2b/secret/base.py b/packages/python-sdk/e2b/secret/base.py
new file mode 100644
index 000000000..e9fe72f0f
--- /dev/null
+++ b/packages/python-sdk/e2b/secret/base.py
@@ -0,0 +1,83 @@
+import re
+
+from e2b.connection_config import ApiParams
+from e2b.exceptions import InvalidArgumentException
+from e2b.paginator import PaginatorBase
+from e2b.sandbox.sandbox_api import SandboxIamToken, SandboxIamTokenType
+from e2b.secret.types import SecretInfo
+
+
+class SecretPaginatorBase(PaginatorBase[SecretInfo, ApiParams]):
+ pass
+
+
+INVALID_SECRET_NAME_CHARS = re.compile(r"[{}\x00-\x1f\x7f-\x9f]")
+
+
+def _validate_secret_name(name: str) -> None:
+ if not isinstance(name, str) or not name or INVALID_SECRET_NAME_CHARS.search(name):
+ raise InvalidArgumentException(
+ f"secret name {name!r} is not usable: a secret name must be a "
+ "non-empty string and cannot contain '{', '}' or control "
+ "characters, because it is interpolated into the "
+ "'${e2b.secrets.<name>}' placeholder the runtime resolves."
+ )
+
+
+class SecretBase:
+ """
+ Module for managing E2B secrets and workload identity helpers.
+
+ Secret values are write-only: they are accepted by ``create`` and
+ ``update`` but never returned by any read surface.
+ """
+
+ @staticmethod
+ def fill(secret: str) -> str:
+ """
+ Format a placeholder that the runtime resolves to the secret's
+ current value.
+
+ This is a local formatting helper and makes no network call — it does
+ not check whether the named secret exists. An unknown reference fails
+ server-side when the placeholder is resolved.
+
+ :param secret: Secret name.
+
+ :return: Placeholder string resolving to the secret's value.
+
+ Example:
+ ```python
+ Secret.fill("openai-api-key")
+ # '${e2b.secrets.openai-api-key}'
+ ```
+ """
+ _validate_secret_name(secret)
+ return f"${{e2b.secrets.{secret}}}"
+
+ @staticmethod
+ def iam_token(*, audience: str, token_type: SandboxIamTokenType) -> SandboxIamToken:
+ """
+ Define a workload identity token to pass to ``iam.tokens`` when
+ creating a sandbox.
+
+ :param audience: Audience of the workload token, stored exactly as provided.
+ :param token_type: Workload token type.
+
+ :return: A token definition passable to ``iam.tokens``.
+
+ Example:
+ ```python
+ sandbox = Sandbox.create(
+ iam={
+ "tokens": {
+ "aws": Secret.iam_token(
+ audience="sts.amazonaws.com",
+ token_type="JWT-SVID",
+ ),
+ },
+ },
+ )
+ ```
+ """
+ return SandboxIamToken(audience=audience, token_type=token_type)
diff --git a/packages/python-sdk/e2b/secret/secret_async.py b/packages/python-sdk/e2b/secret/secret_async.py
new file mode 100644
index 000000000..3094af5e1
--- /dev/null
+++ b/packages/python-sdk/e2b/secret/secret_async.py
@@ -0,0 +1,265 @@
+from typing import Dict, List, Optional
+
+from typing_extensions import Unpack
+
+from e2b.api import handle_api_exception
+from e2b.api.client.api.secrets import (
+ delete_secrets_secret_id,
+ get_secrets,
+ get_secrets_secret_id,
+ post_secrets,
+ post_secrets_secret_id,
+)
+from e2b.api.client.models import (
+ Error,
+ NewSecret as NewSecretModel,
+ SecretMetadata as SecretMetadataModel,
+ SecretUpdate as SecretUpdateModel,
+)
+from e2b.api.client.types import UNSET
+from e2b.api.client_async import get_api_client
+from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.exceptions import SecretException, SecretNotFoundException
+from e2b.secret.base import SecretBase, SecretPaginatorBase
+from e2b.secret.types import SecretInfo
+
+
+def _metadata_model(metadata: Optional[Dict[str, str]]) -> SecretMetadataModel:
+ model = SecretMetadataModel()
+ if metadata:
+ model.additional_properties = dict(metadata)
+ return model
+
+
+class AsyncSecretPaginator(SecretPaginatorBase):
+ """
+ Paginator for listing secrets.
+
+ Example:
+ ```python
+ paginator = AsyncSecret.list()
+
+ while paginator.has_next:
+ secrets = await paginator.next_items()
+ print(secrets)
+ ```
+ """
+
+ async def next_items(self, **opts: Unpack[ApiParams]) -> List[SecretInfo]:
+ """
+ Returns the next page of secrets.
+
+ Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
+ :return: List of secret metadata.
+ """
+ if not self.has_next:
+ raise Exception("No more items to fetch")
+
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
+ res = await get_secrets.asyncio_detailed(
+ client=api_client,
+ limit=self.limit if self.limit else UNSET,
+ next_token=self._next_token if self._next_token else UNSET,
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ self._update_pagination(res.headers)
+
+ if res.parsed is None:
+ return []
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return [SecretInfo._from_model(secret) for secret in res.parsed]
+
+
+class AsyncSecret(SecretBase):
+ """
+ Module for managing E2B secrets and workload identity helpers.
+
+ Secret values are write-only: they are accepted by ``create`` and
+ ``update`` but never returned by any read surface.
+ """
+
+ @staticmethod
+ async def create(
+ name: str,
+ value: str,
+ metadata: Optional[Dict[str, str]] = None,
+ **opts: Unpack[ApiParams],
+ ) -> SecretInfo:
+ """
+ Create a new secret and its first value.
+
+ :param name: Name of the secret, unique within the project.
+ :param value: Secret value. Write-only — never returned by the API.
+ :param metadata: Customer metadata to store with the secret.
+
+ :return: The secret's ID, name, current version (`1` for a new
+ secret), metadata, and creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = await post_secrets.asyncio_detailed(
+ client=api_client,
+ body=NewSecretModel(
+ name=name,
+ value=value,
+ metadata=_metadata_model(metadata) if metadata is not None else UNSET,
+ ),
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ async def update(
+ secret: str,
+ value: str,
+ metadata: Optional[Dict[str, str]] = None,
+ **opts: Unpack[ApiParams],
+ ) -> SecretInfo:
+ """
+ Update a secret's value by storing it as the secret's new version.
+
+ :param secret: Secret ID or name.
+ :param value: New secret value. Write-only — never returned by the API.
+ :param metadata: Customer metadata to store with the secret. When
+ provided, replaces the stored metadata.
+
+ :return: The secret's ID, name, new current version, metadata, and
+ creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = await post_secrets_secret_id.asyncio_detailed(
+ secret,
+ client=api_client,
+ body=SecretUpdateModel(
+ value=value,
+ metadata=_metadata_model(metadata) if metadata is not None else UNSET,
+ ),
+ )
+
+ if res.status_code == 404:
+ raise SecretNotFoundException(f"Secret {secret} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ async def get_info(secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
+ """
+ Get a secret's metadata.
+
+ :param secret: Secret ID or name.
+
+ :return: The secret's ID, name, current version, metadata, and
+ creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = await get_secrets_secret_id.asyncio_detailed(
+ secret,
+ client=api_client,
+ )
+
+ if res.status_code == 404:
+ raise SecretNotFoundException(f"Secret {secret} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ def list(
+ limit: Optional[int] = None,
+ next_token: Optional[str] = None,
+ **opts: Unpack[ApiParams],
+ ) -> AsyncSecretPaginator:
+ """
+ List the project's secrets.
+
+ :param limit: Number of secrets to return per page.
+ :param next_token: Token to the next page.
+
+ :return: Paginator over the project's secrets. Drain it page by page:
+
+ ```python
+ paginator = AsyncSecret.list(limit=50)
+ while paginator.has_next:
+ secrets = await paginator.next_items()
+ ```
+ """
+ return AsyncSecretPaginator(limit=limit, next_token=next_token, **opts)
+
+ @staticmethod
+ async def exists(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ """
+ Check whether a secret exists.
+
+ :param secret: Secret ID or name.
+
+ :return: `True` if the secret exists, `False` otherwise.
+ """
+ try:
+ await AsyncSecret.get_info(secret, **opts)
+ return True
+ except SecretNotFoundException:
+ return False
+
+ @staticmethod
+ async def destroy(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ """
+ Destroy a secret, making all its versions inaccessible.
+
+ :param secret: Secret ID or name.
+
+ :return: `True` if the secret was destroyed, `False` if it was not found.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = await delete_secrets_secret_id.asyncio_detailed(
+ secret,
+ client=api_client,
+ )
+
+ if res.status_code == 404:
+ return False
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ return True
diff --git a/packages/python-sdk/e2b/secret/secret_sync.py b/packages/python-sdk/e2b/secret/secret_sync.py
new file mode 100644
index 000000000..eab2368cf
--- /dev/null
+++ b/packages/python-sdk/e2b/secret/secret_sync.py
@@ -0,0 +1,265 @@
+from typing import Dict, List, Optional
+
+from typing_extensions import Unpack
+
+from e2b.api import handle_api_exception
+from e2b.api.client.api.secrets import (
+ delete_secrets_secret_id,
+ get_secrets,
+ get_secrets_secret_id,
+ post_secrets,
+ post_secrets_secret_id,
+)
+from e2b.api.client.models import (
+ Error,
+ NewSecret as NewSecretModel,
+ SecretMetadata as SecretMetadataModel,
+ SecretUpdate as SecretUpdateModel,
+)
+from e2b.api.client.types import UNSET
+from e2b.api.client_sync import get_api_client
+from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.exceptions import SecretException, SecretNotFoundException
+from e2b.secret.base import SecretBase, SecretPaginatorBase
+from e2b.secret.types import SecretInfo
+
+
+def _metadata_model(metadata: Optional[Dict[str, str]]) -> SecretMetadataModel:
+ model = SecretMetadataModel()
+ if metadata:
+ model.additional_properties = dict(metadata)
+ return model
+
+
+class SecretPaginator(SecretPaginatorBase):
+ """
+ Paginator for listing secrets.
+
+ Example:
+ ```python
+ paginator = Secret.list()
+
+ while paginator.has_next:
+ secrets = paginator.next_items()
+ print(secrets)
+ ```
+ """
+
+ def next_items(self, **opts: Unpack[ApiParams]) -> List[SecretInfo]:
+ """
+ Returns the next page of secrets.
+
+ Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
+ :return: List of secret metadata.
+ """
+ if not self.has_next:
+ raise Exception("No more items to fetch")
+
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
+ res = get_secrets.sync_detailed(
+ client=api_client,
+ limit=self.limit if self.limit else UNSET,
+ next_token=self._next_token if self._next_token else UNSET,
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ self._update_pagination(res.headers)
+
+ if res.parsed is None:
+ return []
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return [SecretInfo._from_model(secret) for secret in res.parsed]
+
+
+class Secret(SecretBase):
+ """
+ Module for managing E2B secrets and workload identity helpers.
+
+ Secret values are write-only: they are accepted by ``create`` and
+ ``update`` but never returned by any read surface.
+ """
+
+ @staticmethod
+ def create(
+ name: str,
+ value: str,
+ metadata: Optional[Dict[str, str]] = None,
+ **opts: Unpack[ApiParams],
+ ) -> SecretInfo:
+ """
+ Create a new secret and its first value.
+
+ :param name: Name of the secret, unique within the project.
+ :param value: Secret value. Write-only — never returned by the API.
+ :param metadata: Customer metadata to store with the secret.
+
+ :return: The secret's ID, name, current version (`1` for a new
+ secret), metadata, and creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = post_secrets.sync_detailed(
+ client=api_client,
+ body=NewSecretModel(
+ name=name,
+ value=value,
+ metadata=_metadata_model(metadata) if metadata is not None else UNSET,
+ ),
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ def update(
+ secret: str,
+ value: str,
+ metadata: Optional[Dict[str, str]] = None,
+ **opts: Unpack[ApiParams],
+ ) -> SecretInfo:
+ """
+ Update a secret's value by storing it as the secret's new version.
+
+ :param secret: Secret ID or name.
+ :param value: New secret value. Write-only — never returned by the API.
+ :param metadata: Customer metadata to store with the secret. When
+ provided, replaces the stored metadata.
+
+ :return: The secret's ID, name, new current version, metadata, and
+ creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = post_secrets_secret_id.sync_detailed(
+ secret,
+ client=api_client,
+ body=SecretUpdateModel(
+ value=value,
+ metadata=_metadata_model(metadata) if metadata is not None else UNSET,
+ ),
+ )
+
+ if res.status_code == 404:
+ raise SecretNotFoundException(f"Secret {secret} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ def get_info(secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
+ """
+ Get a secret's metadata.
+
+ :param secret: Secret ID or name.
+
+ :return: The secret's ID, name, current version, metadata, and
+ creation and update times.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = get_secrets_secret_id.sync_detailed(
+ secret,
+ client=api_client,
+ )
+
+ if res.status_code == 404:
+ raise SecretNotFoundException(f"Secret {secret} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if isinstance(res.parsed, Error):
+ raise SecretException(f"{res.parsed.message}: Request failed")
+
+ return SecretInfo._from_model(res.parsed)
+
+ @staticmethod
+ def list(
+ limit: Optional[int] = None,
+ next_token: Optional[str] = None,
+ **opts: Unpack[ApiParams],
+ ) -> SecretPaginator:
+ """
+ List the project's secrets.
+
+ :param limit: Number of secrets to return per page.
+ :param next_token: Token to the next page.
+
+ :return: Paginator over the project's secrets. Drain it page by page:
+
+ ```python
+ paginator = Secret.list(limit=50)
+ while paginator.has_next:
+ secrets = paginator.next_items()
+ ```
+ """
+ return SecretPaginator(limit=limit, next_token=next_token, **opts)
+
+ @staticmethod
+ def exists(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ """
+ Check whether a secret exists.
+
+ :param secret: Secret ID or name.
+
+ :return: `True` if the secret exists, `False` otherwise.
+ """
+ try:
+ Secret.get_info(secret, **opts)
+ return True
+ except SecretNotFoundException:
+ return False
+
+ @staticmethod
+ def destroy(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ """
+ Destroy a secret, making all its versions inaccessible.
+
+ :param secret: Secret ID or name.
+
+ :return: `True` if the secret was destroyed, `False` if it was not found.
+ """
+ config = ConnectionConfig(**opts)
+ api_client = get_api_client(config)
+ res = delete_secrets_secret_id.sync_detailed(
+ secret,
+ client=api_client,
+ )
+
+ if res.status_code == 404:
+ return False
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res, SecretException)
+
+ return True
diff --git a/packages/python-sdk/e2b/secret/types.py b/packages/python-sdk/e2b/secret/types.py
new file mode 100644
index 000000000..01eafb337
--- /dev/null
+++ b/packages/python-sdk/e2b/secret/types.py
@@ -0,0 +1,34 @@
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Dict
+
+from e2b.api.client.models import Secret as SecretModel
+
+
+@dataclass
+class SecretInfo:
+ """Metadata of a secret. Secret values are write-only and never returned."""
+
+ secret_id: str
+ """Secret ID."""
+ name: str
+ """Secret name, unique within the project."""
+ version: int
+ """Version served to readers that do not name one."""
+ metadata: Dict[str, str]
+ """Customer metadata of the secret."""
+ created_at: datetime
+ """Time when the secret was created."""
+ updated_at: datetime
+ """Time when the secret was last updated."""
+
+ @classmethod
+ def _from_model(cls, secret: SecretModel) -> "SecretInfo":
+ return cls(
+ secret_id=secret.secret_id,
+ name=secret.name,
+ version=secret.current_version,
+ metadata=dict(secret.metadata.additional_properties),
+ created_at=secret.created_at,
+ updated_at=secret.updated_at,
+ )
diff --git a/packages/python-sdk/tests/async/secret_async/test_secret.py b/packages/python-sdk/tests/async/secret_async/test_secret.py
new file mode 100644
index 000000000..90d715a1c
--- /dev/null
+++ b/packages/python-sdk/tests/async/secret_async/test_secret.py
@@ -0,0 +1,206 @@
+from datetime import datetime, timezone
+from http import HTTPStatus
+from uuid import uuid4
+
+import pytest
+
+from e2b import AsyncSecret
+from e2b.api.client.models.secret import Secret as SecretModel
+from e2b.api.client.models.secret_metadata import SecretMetadata
+from e2b.api.client.types import UNSET, Response
+from e2b.exceptions import InvalidArgumentException, SecretNotFoundException
+import e2b.api.client.api.secrets.delete_secrets_secret_id as delete_secret_mod
+import e2b.api.client.api.secrets.get_secrets as get_secrets_mod
+import e2b.api.client.api.secrets.get_secrets_secret_id as get_secret_mod
+import e2b.api.client.api.secrets.post_secrets as post_secrets_mod
+import e2b.api.client.api.secrets.post_secrets_secret_id as update_secret_mod
+
+# In-memory store for mock secrets
+_secrets: dict[str, SecretModel] = {}
+
+
+def _find_secret(selector: str):
+ secret = _secrets.get(selector)
+ if secret is not None:
+ return secret
+ return next((s for s in _secrets.values() if s.name == selector), None)
+
+
+def _not_found():
+ return Response(
+ status_code=HTTPStatus(404),
+ content=b"",
+ headers={},
+ parsed=None,
+ )
+
+
[email protected](autouse=True)
+def mock_secret_api(monkeypatch, test_api_key):
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
+ _secrets.clear()
+
+ async def mock_post_secrets(*, client, body):
+ now = datetime.now(timezone.utc)
+ metadata = SecretMetadata()
+ if body.metadata is not UNSET:
+ metadata = body.metadata
+ secret = SecretModel(
+ secret_id=f"sec_{uuid4()}",
+ name=body.name.lower(),
+ current_version=1,
+ metadata=metadata,
+ created_at=now,
+ updated_at=now,
+ )
+ _secrets[secret.secret_id] = secret
+ return Response(
+ status_code=HTTPStatus(201),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ async def mock_get_secrets(*, client, limit=UNSET, next_token=UNSET):
+ secrets = list(_secrets.values())
+ page_size = limit if isinstance(limit, int) else 100
+ start = int(next_token) if isinstance(next_token, str) else 0
+ page = secrets[start : start + page_size]
+ headers = {}
+ if start + page_size < len(secrets):
+ headers["x-next-token"] = str(start + page_size)
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers=headers,
+ parsed=page,
+ )
+
+ async def mock_get_secret(secret_id, *, client):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ async def mock_update_secret(secret_id, *, client, body):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ secret.current_version += 1
+ if body.metadata is not UNSET:
+ secret.metadata = body.metadata
+ secret.updated_at = datetime.now(timezone.utc)
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ async def mock_delete_secret(secret_id, *, client):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ del _secrets[secret.secret_id]
+ return Response(
+ status_code=HTTPStatus(204),
+ content=b"",
+ headers={},
+ parsed=None,
+ )
+
+ monkeypatch.setattr(post_secrets_mod, "asyncio_detailed", mock_post_secrets)
+ monkeypatch.setattr(get_secrets_mod, "asyncio_detailed", mock_get_secrets)
+ monkeypatch.setattr(get_secret_mod, "asyncio_detailed", mock_get_secret)
+ monkeypatch.setattr(update_secret_mod, "asyncio_detailed", mock_update_secret)
+ monkeypatch.setattr(delete_secret_mod, "asyncio_detailed", mock_delete_secret)
+
+
+async def test_create_secret():
+ info = await AsyncSecret.create(
+ "openai-api-key", "sk-test", metadata={"env": "test"}
+ )
+
+ assert info.secret_id.startswith("sec_")
+ assert info.name == "openai-api-key"
+ assert info.version == 1
+ assert info.metadata == {"env": "test"}
+ assert isinstance(info.created_at, datetime)
+ assert isinstance(info.updated_at, datetime)
+ assert not hasattr(info, "value")
+
+
+async def test_update_secret():
+ created = await AsyncSecret.create("rotating-key", "v1")
+ updated = await AsyncSecret.update(created.secret_id, "v2")
+
+ assert updated.secret_id == created.secret_id
+ assert updated.version == 2
+
+
+async def test_update_nonexistent_secret():
+ with pytest.raises(SecretNotFoundException):
+ await AsyncSecret.update("missing", "value")
+
+
+async def test_get_secret_info():
+ created = await AsyncSecret.create("lookup-key", "value")
+
+ by_id = await AsyncSecret.get_info(created.secret_id)
+ assert by_id.name == "lookup-key"
+
+ by_name = await AsyncSecret.get_info("lookup-key")
+ assert by_name.secret_id == created.secret_id
+
+
+async def test_get_info_nonexistent_secret():
+ with pytest.raises(SecretNotFoundException):
+ await AsyncSecret.get_info("missing")
+
+
+async def test_list_secrets_with_pagination():
+ await AsyncSecret.create("key-a", "a")
+ await AsyncSecret.create("key-b", "b")
+ await AsyncSecret.create("key-c", "c")
+
+ paginator = AsyncSecret.list(limit=2)
+ first_page = await paginator.next_items()
+ assert len(first_page) == 2
+ assert paginator.has_next is True
+
+ second_page = await paginator.next_items()
+ assert len(second_page) == 1
+ assert paginator.has_next is False
+
+
+async def test_secret_exists():
+ await AsyncSecret.create("present-key", "value")
+
+ assert await AsyncSecret.exists("present-key") is True
+ assert await AsyncSecret.exists("absent-key") is False
+
+
+async def test_destroy_secret():
+ created = await AsyncSecret.create("to-delete", "value")
+
+ assert await AsyncSecret.destroy(created.secret_id) is True
+ assert await AsyncSecret.exists(created.secret_id) is False
+
+
+async def test_destroy_nonexistent_secret():
+ assert await AsyncSecret.destroy("missing") is False
+
+
+def test_fill():
+ assert AsyncSecret.fill("openai-api-key") == "${e2b.secrets.openai-api-key}"
+
+
[email protected]("name", ["", "{name", "name}", "name\n", "name\x00"])
+def test_fill_invalid_name_raises(name):
+ with pytest.raises(InvalidArgumentException):
+ AsyncSecret.fill(name)
diff --git a/packages/python-sdk/tests/sync/secret_sync/test_secret.py b/packages/python-sdk/tests/sync/secret_sync/test_secret.py
new file mode 100644
index 000000000..8b4b93998
--- /dev/null
+++ b/packages/python-sdk/tests/sync/secret_sync/test_secret.py
@@ -0,0 +1,204 @@
+from datetime import datetime, timezone
+from http import HTTPStatus
+from uuid import uuid4
+
+import pytest
+
+from e2b import Secret
+from e2b.api.client.models.secret import Secret as SecretModel
+from e2b.api.client.models.secret_metadata import SecretMetadata
+from e2b.api.client.types import UNSET, Response
+from e2b.exceptions import InvalidArgumentException, SecretNotFoundException
+import e2b.api.client.api.secrets.delete_secrets_secret_id as delete_secret_mod
+import e2b.api.client.api.secrets.get_secrets as get_secrets_mod
+import e2b.api.client.api.secrets.get_secrets_secret_id as get_secret_mod
+import e2b.api.client.api.secrets.post_secrets as post_secrets_mod
+import e2b.api.client.api.secrets.post_secrets_secret_id as update_secret_mod
+
+# In-memory store for mock secrets
+_secrets: dict[str, SecretModel] = {}
+
+
+def _find_secret(selector: str):
+ secret = _secrets.get(selector)
+ if secret is not None:
+ return secret
+ return next((s for s in _secrets.values() if s.name == selector), None)
+
+
+def _not_found():
+ return Response(
+ status_code=HTTPStatus(404),
+ content=b"",
+ headers={},
+ parsed=None,
+ )
+
+
[email protected](autouse=True)
+def mock_secret_api(monkeypatch, test_api_key):
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
+ _secrets.clear()
+
+ def mock_post_secrets(*, client, body):
+ now = datetime.now(timezone.utc)
+ metadata = SecretMetadata()
+ if body.metadata is not UNSET:
+ metadata = body.metadata
+ secret = SecretModel(
+ secret_id=f"sec_{uuid4()}",
+ name=body.name.lower(),
+ current_version=1,
+ metadata=metadata,
+ created_at=now,
+ updated_at=now,
+ )
+ _secrets[secret.secret_id] = secret
+ return Response(
+ status_code=HTTPStatus(201),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ def mock_get_secrets(*, client, limit=UNSET, next_token=UNSET):
+ secrets = list(_secrets.values())
+ page_size = limit if isinstance(limit, int) else 100
+ start = int(next_token) if isinstance(next_token, str) else 0
+ page = secrets[start : start + page_size]
+ headers = {}
+ if start + page_size < len(secrets):
+ headers["x-next-token"] = str(start + page_size)
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers=headers,
+ parsed=page,
+ )
+
+ def mock_get_secret(secret_id, *, client):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ def mock_update_secret(secret_id, *, client, body):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ secret.current_version += 1
+ if body.metadata is not UNSET:
+ secret.metadata = body.metadata
+ secret.updated_at = datetime.now(timezone.utc)
+ return Response(
+ status_code=HTTPStatus(200),
+ content=b"",
+ headers={},
+ parsed=secret,
+ )
+
+ def mock_delete_secret(secret_id, *, client):
+ secret = _find_secret(secret_id)
+ if secret is None:
+ return _not_found()
+ del _secrets[secret.secret_id]
+ return Response(
+ status_code=HTTPStatus(204),
+ content=b"",
+ headers={},
+ parsed=None,
+ )
+
+ monkeypatch.setattr(post_secrets_mod, "sync_detailed", mock_post_secrets)
+ monkeypatch.setattr(get_secrets_mod, "sync_detailed", mock_get_secrets)
+ monkeypatch.setattr(get_secret_mod, "sync_detailed", mock_get_secret)
+ monkeypatch.setattr(update_secret_mod, "sync_detailed", mock_update_secret)
+ monkeypatch.setattr(delete_secret_mod, "sync_detailed", mock_delete_secret)
+
+
+def test_create_secret():
+ info = Secret.create("openai-api-key", "sk-test", metadata={"env": "test"})
+
+ assert info.secret_id.startswith("sec_")
+ assert info.name == "openai-api-key"
+ assert info.version == 1
+ assert info.metadata == {"env": "test"}
+ assert isinstance(info.created_at, datetime)
+ assert isinstance(info.updated_at, datetime)
+ assert not hasattr(info, "value")
+
+
+def test_update_secret():
+ created = Secret.create("rotating-key", "v1")
+ updated = Secret.update(created.secret_id, "v2")
+
+ assert updated.secret_id == created.secret_id
+ assert updated.version == 2
+
+
+def test_update_nonexistent_secret():
+ with pytest.raises(SecretNotFoundException):
+ Secret.update("missing", "value")
+
+
+def test_get_secret_info():
+ created = Secret.create("lookup-key", "value")
+
+ by_id = Secret.get_info(created.secret_id)
+ assert by_id.name == "lookup-key"
+
+ by_name = Secret.get_info("lookup-key")
+ assert by_name.secret_id == created.secret_id
+
+
+def test_get_info_nonexistent_secret():
+ with pytest.raises(SecretNotFoundException):
+ Secret.get_info("missing")
+
+
+def test_list_secrets_with_pagination():
+ Secret.create("key-a", "a")
+ Secret.create("key-b", "b")
+ Secret.create("key-c", "c")
+
+ paginator = Secret.list(limit=2)
+ first_page = paginator.next_items()
+ assert len(first_page) == 2
+ assert paginator.has_next is True
+
+ second_page = paginator.next_items()
+ assert len(second_page) == 1
+ assert paginator.has_next is False
+
+
+def test_secret_exists():
+ Secret.create("present-key", "value")
+
+ assert Secret.exists("present-key") is True
+ assert Secret.exists("absent-key") is False
+
+
+def test_destroy_secret():
+ created = Secret.create("to-delete", "value")
+
+ assert Secret.destroy(created.secret_id) is True
+ assert Secret.exists(created.secret_id) is False
+
+
+def test_destroy_nonexistent_secret():
+ assert Secret.destroy("missing") is False
+
+
+def test_fill():
+ assert Secret.fill("openai-api-key") == "${e2b.secrets.openai-api-key}"
+
+
[email protected]("name", ["", "{name", "name}", "name\n", "name\x00"])
+def test_fill_invalid_name_raises(name):
+ with pytest.raises(InvalidArgumentException):
+ Secret.fill(name)
diff --git a/redocly.yaml b/redocly.yaml
index d2602e140..b34a690e6 100644
--- a/redocly.yaml
+++ b/redocly.yaml
@@ -10,13 +10,19 @@
# flag must work on schemas as well as operations. A kept operation that
# still references a dropped schema loses that media-type entry rather
# than keeping a dangling $ref.
+#
+# The envd api filters the synced envd spec (spec/envd/envd.yaml) the same
+# way: operations the upstream spec marks `x-internal: true` belong to the
+# orchestrator's control plane, not to SDKs, so they are dropped before the
+# js-sdk envd schema is generated. remove-unused-components then drops the
+# component schemas only those operations referenced.
apis:
js-sdk:
root: spec/openapi.yml
decorators:
filter-in:
property: tags
- value: [sandboxes, snapshots, templates, tags, auth, volumes]
+ value: [sandboxes, snapshots, templates, tags, auth, volumes, secrets]
matchStrategy: any
applyTo: Operation
filter-out:
@@ -27,9 +33,16 @@ apis:
decorators:
filter-in:
property: tags
- value: [sandboxes, snapshots, templates, tags, volumes]
+ value: [sandboxes, snapshots, templates, tags, volumes, secrets]
matchStrategy: any
applyTo: Operation
filter-out:
property: x-not-implemented
value: [true]
+ envd:
+ root: spec/envd/envd.yaml
+ decorators:
+ filter-out:
+ property: x-internal
+ value: [true]
+ remove-unused-components: on
diff --git a/spec/envd/envd.yaml b/spec/envd/envd.yaml
index 9abd91082..a6c050009 100644
--- a/spec/envd/envd.yaml
+++ b/spec/envd/envd.yaml
@@ -7,6 +7,12 @@ info:
tags:
- name: files
+# Operations marked `x-internal: true` are the orchestrator's control plane. The
+# orchestrator reaches them over the host network, straight at the sandbox slot
+# IP, so they are never a legitimate destination for traffic arriving through the
+# public sandbox URL. The sandbox proxy generates its rejection list from this
+# marker, so adding a control operation here is what closes it to the outside;
+# see the orchestrator's `pkg/sandbox/envd` package.
paths:
/health:
get:
@@ -32,6 +38,7 @@ paths:
/init:
post:
summary: Set initial vars, ensure the time and metadata is synced with the host
+ x-internal: true
security:
- AccessTokenAuth: []
- {}
@@ -77,13 +84,52 @@ paths:
/freeze:
post:
- summary: Freeze user/pty cgroups before pause. Written directly by envd to avoid Process.Start / shell overhead under load.
+ summary: Freeze user/pty cgroups before pause and wait for them to stop. Written directly by envd to avoid Process.Start / shell overhead under load.
+ description: |
+ Writing cgroup.freeze only requests a freeze; the kernel stops each task at its
+ next signal-delivery point. This endpoint therefore polls cgroup.events until the
+ cgroups read back frozen, and returns what it observed, so a caller can tell a
+ freeze that took effect from one that was merely issued.
+
+ cgroup.events reports STATE, not an acknowledgement of our write: a cgroup the
+ guest froze itself reads frozen too. The counts below say what was observed, not
+ what this call caused.
+
+ Best-effort by design: a workload that will not quiesce within the budget is
+ reported as unconfirmed rather than failing the call, and cgroups that reject the
+ write are counted in failed, because neither an unfreezable customer task nor a
+ cgroup disappearing mid-sweep may block their pause.
+
+ Whether this endpoint waits is the caller's choice, expressed by supplying
+ maxWaitMs: see that parameter.
+ x-internal: true
+ parameters:
+ - name: maxWaitMs
+ in: query
+ required: false
+ description: |
+ How long to wait for the cgroups to read back frozen, in milliseconds. The
+ caller owns this budget because it also owns the request timeout, and a wait
+ longer than that timeout cannot be observed.
+
+ Supplying it also selects the response: with it, the call waits and answers 200
+ with a FreezeResult; omitted or non-positive, the call does not wait at all and
+ answers 204, which is the contract callers older than this parameter expect.
+ schema:
+ type: integer
+ format: int64
security:
- AccessTokenAuth: []
- {}
responses:
+ "200":
+ description: Freeze issued and the frozen state awaited (maxWaitMs was supplied); the body reports what was observed
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/FreezeResult"
"204":
- description: Cgroups frozen
+ description: Freeze issued without waiting (maxWaitMs absent), for callers predating the structured result
"500":
$ref: "#/components/responses/InternalServerError"
"503":
@@ -92,6 +138,7 @@ paths:
/unfreeze:
post:
summary: Unfreeze user/pty cgroups. Intended ONLY for the orchestrator's pause-failure rollback path; the normal resume thaw happens via /init's deferred unfreeze, not here.
+ x-internal: true
security:
- AccessTokenAuth: []
- {}
@@ -106,6 +153,7 @@ paths:
/collapse:
post:
summary: Collapse envd's own anonymous heap into 2 MiB transparent hugepages before pause, so on resume envd touches fewer distinct guest-physical frames (each a cold fault). Best-effort.
+ x-internal: true
security:
- AccessTokenAuth: []
- {}
@@ -122,6 +170,7 @@ paths:
/fsfreeze:
post:
summary: Freeze the guest rootfs (FIFREEZE) before a filesystem-only pause so it is flushed to a consistent on-disk state, closing the sync->pause race. Idempotent. On a successful filesystem-only pause the VM is rebooted, so no thaw is needed; the orchestrator thaws only on the pause-failure path.
+ x-internal: true
security:
- AccessTokenAuth: []
- {}
@@ -136,6 +185,7 @@ paths:
/fsthaw:
post:
summary: Thaw the guest rootfs (FITHAW). Intended ONLY for the orchestrator's pause-failure rollback path, so a frozen filesystem cannot leave the live VM deadlocked. Idempotent.
+ x-internal: true
security:
- AccessTokenAuth: []
- {}
@@ -468,6 +518,33 @@ components:
disk_total:
type: integer
description: Total disk space in bytes
+ FreezeResult:
+ type: object
+ description: Per-call statistics from a pre-pause workload freeze
+ properties:
+ requested:
+ type: integer
+ description: Cgroups this call wrote cgroup.freeze to
+ frozen:
+ type: integer
+ description: Cgroups that read back "frozen 1" from cgroup.events within the budget; their tasks have stopped
+ notFrozen:
+ type: integer
+ description: Cgroups still reading "frozen 0" when the budget expired; their tasks may still be running, so a snapshot taken now can capture a live workload
+ failed:
+ type: integer
+ description: Cgroups whose freeze write or state read errored (expected for a threaded cgroup, and for one removed mid-sweep)
+ unobservable:
+ type: integer
+ description: Cgroups whose freeze state cannot be read because this guest has no cgroup manager; the write was accepted but nothing can be read back, so these are neither frozen nor notFrozen
+ sweepMs:
+ type: integer
+ format: int64
+ description: Time spent issuing the freeze writes, in milliseconds (scales with cgroup count)
+ waitMs:
+ type: integer
+ format: int64
+ description: Time spent polling cgroup.events, in milliseconds (scales with how deep in I/O the guest tasks were). Outcome neutral - the wait ends either because everything stopped or because the budget ran out
CollapseResult:
type: object
description: Per-call statistics from a heap collapse
diff --git a/spec/infra-ref b/spec/infra-ref
index a62a397a1..40c51438b 100644
--- a/spec/infra-ref
+++ b/spec/infra-ref
@@ -1 +1 @@
-0716edb9e840f110c5f87c186876c01e61553098
+e19a12b8fc5d318c6e88a8edba0a94d1f153a841
diff --git a/spec/openapi.yml b/spec/openapi.yml
index bb2747b77..6ddde58ad 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -122,6 +122,15 @@ components:
required: true
schema:
type: string
+ secretID:
+ name: secretID
+ in: path
+ required: true
+ schema:
+ type: string
+ description: >
+ Identifier of the secret (sec_ prefixed), or its canonical
+ lower-case name
headers:
XNextToken:
@@ -173,12 +182,36 @@ components:
application/json:
schema:
$ref: "#/components/schemas/Error"
+ "429":
+ description: Too many requests
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
"500":
description: Server error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
+ "502":
+ description: Backend error
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+ "503":
+ description: Service unavailable
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
+ "504":
+ description: Backend timeout
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Error"
schemas:
Team:
@@ -267,6 +300,14 @@ components:
- running
- paused
+ OrderDirection:
+ type: string
+ description: Sort direction
+ default: desc
+ enum:
+ - asc
+ - desc
+
SnapshotInfo:
type: object
required:
@@ -2001,6 +2042,12 @@ components:
type: integer
format: int32
description: Error code
+ error_code:
+ type: string
+ description: >-
+ Machine-readable semantic error code. Not a closed set; initial values:
+ sandbox_capacity_unavailable, sandbox_placement_timeout,
+ sandbox_no_compatible_node, sandbox_create_failed, internal_server_error.
message:
type: string
description: Error
@@ -2072,6 +2119,81 @@ components:
required:
- name
+ SecretMetadata:
+ type: object
+ description: >
+ Customer metadata of the secret. Always present, empty when unset.
+ At most 32 entries; keys are limited to 128 bytes, values to 1024
+ bytes, and a secret's metadata to 8192 bytes in total.
+ maxProperties: 32
+ additionalProperties:
+ type: string
+ maxLength: 1024
+
+ Secret:
+ type: object
+ description: Metadata of a secret. It never carries the secret value.
+ required:
+ - secretID
+ - name
+ - currentVersion
+ - metadata
+ - createdAt
+ - updatedAt
+ properties:
+ secretID:
+ type: string
+ description: Identifier of the secret
+ name:
+ type: string
+ description: Name of the secret, unique within the project
+ currentVersion:
+ type: integer
+ format: int64
+ description: Version served to readers that do not name one
+ metadata:
+ $ref: "#/components/schemas/SecretMetadata"
+ createdAt:
+ type: string
+ format: date-time
+ description: Time when the secret was created
+ updatedAt:
+ type: string
+ format: date-time
+ description: Time when the secret was last updated
+
+ NewSecret:
+ type: object
+ required:
+ - name
+ - value
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 128
+ pattern: '^[a-zA-Z0-9_-]+$'
+ description: >
+ Name of the secret, unique within the project. Names are
+ lower-cased before storage and returned in that canonical form;
+ the sec_ prefix is reserved for secret identifiers.
+ value:
+ type: string
+ description: Runtime marker stored as the secret's first version. The runtime resolves it to a value at sandbox egress.
+ metadata:
+ $ref: "#/components/schemas/SecretMetadata"
+
+ SecretUpdate:
+ type: object
+ required:
+ - value
+ properties:
+ value:
+ type: string
+ description: Runtime marker stored as the secret's new version. The runtime resolves it to a value at sandbox egress.
+ metadata:
+ $ref: "#/components/schemas/SecretMetadata"
+
tags:
- name: templates
- name: sandboxes
@@ -2080,6 +2202,7 @@ tags:
- name: api-keys
- name: tags
- name: volumes
+ - name: secrets
paths:
/health:
@@ -2272,6 +2395,10 @@ paths:
$ref: "#/components/responses/400"
"500":
$ref: "#/components/responses/500"
+ "503":
+ $ref: "#/components/responses/503"
+ "504":
+ $ref: "#/components/responses/504"
/v2/sandboxes:
get:
@@ -2301,6 +2428,25 @@ paths:
$ref: "#/components/schemas/SandboxState"
style: form
explode: false
+ - name: order
+ in: query
+ description: Sort direction by sandbox start time. Defaults to desc (newest first).
+ required: false
+ schema:
+ $ref: "#/components/schemas/OrderDirection"
+ - name: startedAfter
+ in: query
+ description: Return sandboxes started at or after this timestamp.
+ required: false
+ schema:
+ type: string
+ format: date-time
+ - name: template
+ in: query
+ description: Filter sandboxes by a template ID or alias.
+ required: false
+ schema:
+ type: string
- $ref: "#/components/parameters/paginationNextToken"
- $ref: "#/components/parameters/paginationLimit"
responses:
@@ -2621,10 +2767,16 @@ paths:
$ref: "#/components/responses/409"
"404":
$ref: "#/components/responses/404"
+ "400":
+ $ref: "#/components/responses/400"
"401":
$ref: "#/components/responses/401"
"500":
$ref: "#/components/responses/500"
+ "503":
+ $ref: "#/components/responses/503"
+ "504":
+ $ref: "#/components/responses/504"
/sandboxes/{sandboxID}/fork:
post:
@@ -2671,6 +2823,8 @@ paths:
$ref: "#/components/responses/401"
"500":
$ref: "#/components/responses/500"
+ "503":
+ $ref: "#/components/responses/503"
/sandboxes/{sandboxID}/connect:
post:
@@ -2710,8 +2864,14 @@ paths:
$ref: "#/components/responses/401"
"404":
$ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
"500":
$ref: "#/components/responses/500"
+ "503":
+ $ref: "#/components/responses/503"
+ "504":
+ $ref: "#/components/responses/504"
/sandboxes/{sandboxID}/timeout:
post:
@@ -3982,3 +4142,207 @@ paths:
$ref: "#/components/responses/404"
"500":
$ref: "#/components/responses/500"
+
+ /secrets:
+ get:
+ summary: List project secrets
+ description: List the project's secrets. No response carries a secret value.
+ tags: [secrets]
+ security:
+ - ApiKeyAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ - AdminApiKeyAuth: []
+ AdminTeamAuth: []
+ parameters:
+ - $ref: "#/components/parameters/paginationNextToken"
+ - $ref: "#/components/parameters/paginationLimit"
+ responses:
+ "200":
+ description: Successfully listed the project's secrets
+ headers:
+ X-Next-Token:
+ $ref: "#/components/headers/XNextToken"
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/Secret"
+ "400":
+ $ref: "#/components/responses/400"
+ "401":
+ $ref: "#/components/responses/401"
+ "403":
+ $ref: "#/components/responses/403"
+ "404":
+ $ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
+ "429":
+ $ref: "#/components/responses/429"
+ "500":
+ $ref: "#/components/responses/500"
+ "502":
+ $ref: "#/components/responses/502"
+ "504":
+ $ref: "#/components/responses/504"
+
+ post:
+ summary: Create a secret
+ description: Create a secret by storing a runtime marker as its first version. The response carries metadata only.
+ tags: [secrets]
+ security:
+ - ApiKeyAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ - AdminApiKeyAuth: []
+ AdminTeamAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/NewSecret"
+ responses:
+ "201":
+ description: Successfully created the secret
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Secret"
+ "400":
+ $ref: "#/components/responses/400"
+ "401":
+ $ref: "#/components/responses/401"
+ "403":
+ $ref: "#/components/responses/403"
+ "404":
+ $ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
+ "429":
+ $ref: "#/components/responses/429"
+ "500":
+ $ref: "#/components/responses/500"
+ "502":
+ $ref: "#/components/responses/502"
+ "504":
+ $ref: "#/components/responses/504"
+
+ /secrets/{secretID}:
+ get:
+ summary: Get a secret
+ description: Get one secret's metadata, selected by identifier or name.
+ tags: [secrets]
+ security:
+ - ApiKeyAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ - AdminApiKeyAuth: []
+ AdminTeamAuth: []
+ parameters:
+ - $ref: "#/components/parameters/secretID"
+ responses:
+ "200":
+ description: Successfully retrieved the secret
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Secret"
+ "400":
+ $ref: "#/components/responses/400"
+ "401":
+ $ref: "#/components/responses/401"
+ "403":
+ $ref: "#/components/responses/403"
+ "404":
+ $ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
+ "429":
+ $ref: "#/components/responses/429"
+ "500":
+ $ref: "#/components/responses/500"
+ "502":
+ $ref: "#/components/responses/502"
+ "504":
+ $ref: "#/components/responses/504"
+
+ post:
+ summary: Update a secret
+ description: Replace the secret's stored marker by appending a new version. The response carries metadata only.
+ tags: [secrets]
+ security:
+ - ApiKeyAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ - AdminApiKeyAuth: []
+ AdminTeamAuth: []
+ parameters:
+ - $ref: "#/components/parameters/secretID"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SecretUpdate"
+ responses:
+ "200":
+ description: Successfully updated the secret
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Secret"
+ "400":
+ $ref: "#/components/responses/400"
+ "401":
+ $ref: "#/components/responses/401"
+ "403":
+ $ref: "#/components/responses/403"
+ "404":
+ $ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
+ "429":
+ $ref: "#/components/responses/429"
+ "500":
+ $ref: "#/components/responses/500"
+ "502":
+ $ref: "#/components/responses/502"
+ "504":
+ $ref: "#/components/responses/504"
+
+ delete:
+ summary: Delete a secret
+ description: Revoke the secret and schedule its versions for cleanup.
+ tags: [secrets]
+ security:
+ - ApiKeyAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ - AdminApiKeyAuth: []
+ AdminTeamAuth: []
+ parameters:
+ - $ref: "#/components/parameters/secretID"
+ responses:
+ "204":
+ description: Successfully deleted the secret
+ "400":
+ $ref: "#/components/responses/400"
+ "401":
+ $ref: "#/components/responses/401"
+ "403":
+ $ref: "#/components/responses/403"
+ "404":
+ $ref: "#/components/responses/404"
+ "409":
+ $ref: "#/components/responses/409"
+ "429":
+ $ref: "#/components/responses/429"
+ "500":
+ $ref: "#/components/responses/500"
+ "502":
+ $ref: "#/components/responses/502"
+ "504":
+ $ref: "#/components/responses/504"