Skip to content

An open-source, faster Devin alternative

TypeScript

Delete attached secret store on sandbox kill (#477)

Mohamed Habibc7bfb65eeb73
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 5b74396c..98b383d4 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1838,8 +1838,9 @@ export default {
{
const m = path.match(/^\/internal\/secret-stores\/([^/]+)$/);
if (m) {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return secretStores.internalGetStore(req, env, m[1]);
+ if (req.method === "GET") return secretStores.internalGetStore(req, env, m[1]);
+ if (req.method === "DELETE") return secretStores.internalDeleteStore(req, env, m[1]);
+ return json({ error: "method not allowed" }, 405);
}
}
diff --git a/cloudflare-workers/api-edge/src/secret_stores.ts b/cloudflare-workers/api-edge/src/secret_stores.ts
index 6202f061..93d378d7 100644
--- a/cloudflare-workers/api-edge/src/secret_stores.ts
+++ b/cloudflare-workers/api-edge/src/secret_stores.ts
@@ -396,6 +396,26 @@ export async function internalGetStore(req: Request, env: SecretStoresEnv, store
return bundleStore(env, store);
}
+export async function internalDeleteStore(req: Request, env: SecretStoresEnv, storeID: string): Promise<Response> {
+ if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);
+ const url = new URL(req.url);
+ const orgID = url.searchParams.get("org_id") ?? "";
+ if (!orgID) return json({ error: "org_id is required" }, 400);
+
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT id FROM secret_stores WHERE id = ?1 AND org_id = ?2`,
+ )
+ .bind(storeID, orgID)
+ .first<{ id: string }>();
+ if (!row) return json({ error: "secret store not found" }, 404);
+
+ await env.OPENCOMPUTER_DB.batch([
+ env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_store_entries WHERE store_id = ?1`).bind(storeID),
+ env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_stores WHERE id = ?1 AND org_id = ?2`).bind(storeID, orgID),
+ ]);
+ return new Response(null, { status: 204 });
+}
+
// Lookup by (org_id, name) — what CP's resolveSecretStoreInto calls with
// the user-supplied cfg.SecretStore string at sandbox-create time. Same
// HMAC scheme as internalGetStore. Returns 404 if no store matches.
diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.go
index 330a86fc..0bad5e54 100644
--- a/cmd/oc/internal/commands/sandbox.go
+++ b/cmd/oc/internal/commands/sandbox.go
@@ -154,7 +154,12 @@ var sandboxKillCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c := client.FromContext(cmd.Context())
- if err := c.Delete(cmd.Context(), "/sandboxes/"+args[0]); err != nil {
+ path := "/sandboxes/" + args[0]
+ deleteSecretStore, _ := cmd.Flags().GetBool("delete-secret-store")
+ if deleteSecretStore {
+ path += "?deleteSecretStore=true"
+ }
+ if err := c.Delete(cmd.Context(), path); err != nil {
return err
}
fmt.Printf("Sandbox %s killed.\n", args[0])
@@ -299,6 +304,7 @@ func init() {
// sandbox wake flags
sandboxWakeCmd.Flags().Int("timeout", 0, "Idle timeout in seconds after wake (0 = never hibernate)")
+ sandboxKillCmd.Flags().Bool("delete-secret-store", false, "Also delete the secret store attached to the sandbox")
sandboxCmd.AddCommand(sandboxCreateCmd)
sandboxCmd.AddCommand(sandboxListCmd)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 02f3ef03..b9b3d94b 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -942,9 +942,11 @@ func (s *Server) killSandbox(c echo.Context) error {
}
func (s *Server) killSandboxByID(c echo.Context, sandboxID string) error {
+ deleteSecretStore := shouldDeleteAttachedSecretStore(c)
+
// Server mode with worker registry: dispatch destroy via gRPC
if s.workerRegistry != nil {
- return s.killSandboxRemote(c, sandboxID)
+ return s.killSandboxRemote(c, sandboxID, deleteSecretStore)
}
// Combined/worker mode: kill locally
@@ -952,6 +954,11 @@ func (s *Server) killSandboxByID(c echo.Context, sandboxID string) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ var session *db.SandboxSession
+ if deleteSecretStore && s.store != nil {
+ session = s.getSandboxSessionForCleanup(c, sandboxID)
+ }
+
// Mark stopped immediately so it no longer counts toward concurrency limits.
if s.store != nil {
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
@@ -973,11 +980,15 @@ func (s *Server) killSandboxByID(c echo.Context, sandboxID string) error {
_ = s.sandboxDBs.Remove(sandboxID)
}
+ if deleteSecretStore {
+ s.deleteAttachedSecretStoreBestEffort(c.Request().Context(), sandboxID, session)
+ }
+
return c.NoContent(http.StatusNoContent)
}
// killSandboxRemote dispatches sandbox destruction to the appropriate worker via gRPC.
-func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
+func (s *Server) killSandboxRemote(c echo.Context, sandboxID string, deleteSecretStore bool) error {
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
"error": "database not configured",
@@ -1005,6 +1016,9 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
// while cell PG says "stopped". Emit a CP-side fallback to close the
// drift. status is already marked stopped on cell PG above.
s.publishSandboxLifecycleEvent(c.Request().Context(), "stopped", sandboxID, session.OrgID, session.WorkerID, "worker_unreachable")
+ if deleteSecretStore {
+ s.deleteAttachedSecretStoreBestEffort(c.Request().Context(), sandboxID, session)
+ }
return c.NoContent(http.StatusNoContent)
}
@@ -1026,6 +1040,10 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
}
+ if deleteSecretStore {
+ s.deleteAttachedSecretStoreBestEffort(c.Request().Context(), sandboxID, session)
+ }
+
s.emitEvent("destroy", sandboxID, session.WorkerID, "destroyed")
// Note: the worker emits the "stopped" lifecycle event via sdb.LogEvent
// in its DestroySandbox handler, and the SandboxDBManager.OnRemove hook
@@ -1035,6 +1053,92 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
return c.NoContent(http.StatusNoContent)
}
+func shouldDeleteAttachedSecretStore(c echo.Context) bool {
+ switch strings.ToLower(strings.TrimSpace(c.QueryParam("deleteSecretStore"))) {
+ case "1", "true", "yes", "y", "on":
+ return true
+ default:
+ return false
+ }
+}
+
+func (s *Server) getSandboxSessionForCleanup(c echo.Context, sandboxID string) *db.SandboxSession {
+ if s.store == nil {
+ return nil
+ }
+ ctx := c.Request().Context()
+ if orgID, ok := auth.GetOrgID(c); ok {
+ session, err := s.store.GetSandboxSessionInOrg(ctx, orgID, sandboxID)
+ if err == nil {
+ return session
+ }
+ log.Printf("sandbox: failed to load sandbox session %s in org for cleanup: %v", sandboxID, err)
+ return nil
+ }
+ session, err := s.store.GetSandboxSession(ctx, sandboxID)
+ if err != nil {
+ log.Printf("sandbox: failed to load sandbox session %s for cleanup: %v", sandboxID, err)
+ return nil
+ }
+ return session
+}
+
+func (s *Server) deleteAttachedSecretStoreBestEffort(ctx context.Context, sandboxID string, session *db.SandboxSession) {
+ if s.store == nil || session == nil {
+ return
+ }
+ if s.edge != nil {
+ if session.SecretStoreID != nil {
+ if err := s.edge.DeleteSecretStore(ctx, session.OrgID, *session.SecretStoreID); err != nil {
+ if !errors.Is(err, edgeclient.ErrNotFound) {
+ log.Printf("sandbox: failed to delete attached edge secret store %s for sandbox %s: %v", session.SecretStoreID.String(), sandboxID, err)
+ return
+ }
+ log.Printf("sandbox: attached secret store %s for sandbox %s already missing at edge; trying persisted name fallback", session.SecretStoreID.String(), sandboxID)
+ } else {
+ return
+ }
+ }
+ if s.store.Encryptor() == nil {
+ return
+ }
+ storeName := attachedSecretStoreName(session)
+ if storeName == "" {
+ return
+ }
+ bundle, err := s.edge.LookupSecretStore(ctx, session.OrgID, storeName, s.store.Encryptor())
+ if err != nil {
+ if errors.Is(err, edgeclient.ErrNotFound) {
+ log.Printf("sandbox: attached secret store %q for sandbox %s already missing at edge", storeName, sandboxID)
+ return
+ }
+ log.Printf("sandbox: failed to lookup attached edge secret store %q for sandbox %s: %v", storeName, sandboxID, err)
+ return
+ }
+ if err := s.edge.DeleteSecretStore(ctx, session.OrgID, bundle.Store.ID); err != nil && !errors.Is(err, edgeclient.ErrNotFound) {
+ log.Printf("sandbox: failed to delete attached edge secret store %s (%q) for sandbox %s: %v", bundle.Store.ID.String(), storeName, sandboxID, err)
+ }
+ return
+ }
+ if session.SecretStoreID == nil {
+ return
+ }
+ if err := s.store.DeleteSecretStore(ctx, session.OrgID, *session.SecretStoreID); err != nil {
+ log.Printf("sandbox: failed to delete attached secret store %s for sandbox %s: %v", session.SecretStoreID.String(), sandboxID, err)
+ }
+}
+
+func attachedSecretStoreName(session *db.SandboxSession) string {
+ if session == nil || len(session.Config) == 0 {
+ return ""
+ }
+ var cfg types.SandboxConfig
+ if err := json.Unmarshal(session.Config, &cfg); err != nil {
+ return ""
+ }
+ return cfg.SecretStore
+}
+
func (s *Server) listSandboxes(c echo.Context) error {
// Server mode with worker registry: query PG for org's running sandboxes
if s.workerRegistry != nil {
diff --git a/internal/api/sandbox_allowed_hosts.go b/internal/api/sandbox_allowed_hosts.go
index 529286b8..12389449 100644
--- a/internal/api/sandbox_allowed_hosts.go
+++ b/internal/api/sandbox_allowed_hosts.go
@@ -2,11 +2,13 @@ package api
import (
"context"
+ "errors"
"net/http"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/edgeclient"
)
// AllowedHostsResponse is the shape returned by GET /api/sandboxes/:id/allowed-hosts.
@@ -57,14 +59,14 @@ func (s *Server) getSandboxAllowedHosts(c echo.Context) error {
sandboxID := c.Param("id")
ctx := c.Request().Context()
- primaryID, baseStoreName, err := s.store.GetSandboxStoreRefs(ctx, orgID, sandboxID)
+ primaryID, primaryName, baseStoreName, err := s.store.GetSandboxStoreRefs(ctx, orgID, sandboxID)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
}
// Sandbox has neither a primary store nor an inherited base. Return an
// empty (well-formed) response so callers always see the same shape.
- if primaryID == nil && baseStoreName == "" {
+ if primaryID == nil && primaryName == "" && baseStoreName == "" {
return c.JSON(http.StatusOK, AllowedHostsResponse{
SandboxID: sandboxID,
EgressAllowlist: []string{},
@@ -81,16 +83,46 @@ func (s *Server) getSandboxAllowedHosts(c echo.Context) error {
// Fetch base store first so primary's per-secret entries can shadow on
// name collision (matches the runtime proxy: later layer wins for envs).
if baseStoreName != "" {
- base, err := s.store.GetSecretStoreByName(ctx, orgID, baseStoreName)
- if err == nil {
- resp.BaseSecretStoreName = base.Name
- mergeStoreInto(ctx, s.store, base, &resp)
+ if s.edge != nil && s.store.Encryptor() != nil {
+ base, err := s.edge.LookupSecretStore(ctx, orgID, baseStoreName, s.store.Encryptor())
+ if err == nil {
+ resp.BaseSecretStoreName = base.Store.Name
+ mergeSecretBundleInto(base, &resp)
+ } else if !errors.Is(err, edgeclient.ErrNotFound) {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": err.Error()})
+ }
+ } else {
+ base, err := s.store.GetSecretStoreByName(ctx, orgID, baseStoreName)
+ if err == nil {
+ resp.BaseSecretStoreName = base.Name
+ mergeStoreInto(ctx, s.store, base, &resp)
+ }
}
// Base store missing (deleted under us) is treated as a soft no-op
// rather than 500 — proxy already snapshotted whatever it needs.
}
- if primaryID != nil {
+ if s.edge != nil && s.store.Encryptor() != nil {
+ if primaryID != nil {
+ primary, err := s.edge.LookupSecretStoreByID(ctx, *primaryID, s.store.Encryptor())
+ if err == nil {
+ resp.SecretStoreName = primary.Store.Name
+ mergeSecretBundleInto(primary, &resp)
+ return c.JSON(http.StatusOK, resp)
+ } else if !errors.Is(err, edgeclient.ErrNotFound) {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": err.Error()})
+ }
+ }
+ if primaryName != "" {
+ primary, err := s.edge.LookupSecretStore(ctx, orgID, primaryName, s.store.Encryptor())
+ if err == nil {
+ resp.SecretStoreName = primary.Store.Name
+ mergeSecretBundleInto(primary, &resp)
+ } else if !errors.Is(err, edgeclient.ErrNotFound) {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": err.Error()})
+ }
+ }
+ } else if primaryID != nil {
primary, err := s.store.GetSecretStore(ctx, orgID, *primaryID)
if err == nil {
resp.SecretStoreName = primary.Name
@@ -133,3 +165,21 @@ func mergeStoreInto(ctx context.Context, store *db.Store, ss *db.SecretStore, re
}
}
+func mergeSecretBundleInto(bundle *edgeclient.SecretStoreBundle, resp *AllowedHostsResponse) {
+ existing := make(map[string]bool, len(resp.EgressAllowlist))
+ for _, h := range resp.EgressAllowlist {
+ existing[h] = true
+ }
+ for _, h := range bundle.Store.EgressAllowlist {
+ if !existing[h] {
+ existing[h] = true
+ resp.EgressAllowlist = append(resp.EgressAllowlist, h)
+ }
+ }
+ for _, e := range bundle.Entries {
+ if len(e.AllowedHosts) == 0 {
+ continue
+ }
+ resp.PerSecretAllowedHosts[e.Name] = e.AllowedHosts
+ }
+}
diff --git a/internal/db/store.go b/internal/db/store.go
index 45648447..a6ff7308 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -742,6 +742,7 @@ type SandboxSession struct {
MigratingToWorker string `json:"migratingToWorker,omitempty"`
PatchError *string `json:"patchError,omitempty"`
GoldenVersion *string `json:"goldenVersion,omitempty"`
+ SecretStoreID *uuid.UUID `json:"secretStoreId,omitempty"`
// PreviewAuthHash is the SHA-256 hex of the bearer token required on
// preview-URL requests. NULL = open (the default). Plaintext is never
// stored — set once via SetSandboxPreviewAuth and rotated via the same.
@@ -1307,12 +1308,12 @@ func (s *Store) ReapStalePendingSessions(ctx context.Context, olderThan time.Dur
func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, preview_auth_hash, preview_auth_scheme
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, secret_store_id, preview_auth_hash, preview_auth_scheme
FROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`, sandboxID,
).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
&session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion,
- &session.PreviewAuthHash, &session.PreviewAuthScheme)
+ &session.SecretStoreID, &session.PreviewAuthHash, &session.PreviewAuthScheme)
if err != nil {
return nil, fmt.Errorf("sandbox session not found: %w", err)
}
@@ -1328,14 +1329,14 @@ func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*Sandb
func (s *Store) GetSandboxSessionInOrg(ctx context.Context, orgID uuid.UUID, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, preview_auth_hash, preview_auth_scheme
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, secret_store_id, preview_auth_hash, preview_auth_scheme
FROM sandbox_sessions
WHERE org_id = $1 AND sandbox_id = $2
ORDER BY started_at DESC LIMIT 1`, orgID, sandboxID,
).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
&session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion,
- &session.PreviewAuthHash, &session.PreviewAuthScheme)
+ &session.SecretStoreID, &session.PreviewAuthHash, &session.PreviewAuthScheme)
if err != nil {
return nil, fmt.Errorf("sandbox session not found: %w", err)
}
@@ -3026,6 +3027,9 @@ func (s *Store) GetSecretStoreByName(ctx context.Context, orgID uuid.UUID, name
//
// - primaryID is sandbox_sessions.secret_store_id, the "winning" store on
// the row (last layer for env-collision resolution; nil if no store).
+// - primaryName is config->>'secretStore', retained as a fallback for rows
+// where the edge-owned store resolved at create time but secret_store_id
+// was not persisted.
// - baseStoreName is config->>'baseSecretStore' (parent store from the
// fork chain), populated when a fork layered an additional store on top
// of an inherited one. Empty string when there's no parent.
@@ -3038,17 +3042,17 @@ func (s *Store) GetSecretStoreByName(ctx context.Context, orgID uuid.UUID, name
//
// Org-scoped: sandbox IDs aren't globally unique, so a leaked ID from
// another org won't return that org's data.
-func (s *Store) GetSandboxStoreRefs(ctx context.Context, orgID uuid.UUID, sandboxID string) (primaryID *uuid.UUID, baseStoreName string, err error) {
+func (s *Store) GetSandboxStoreRefs(ctx context.Context, orgID uuid.UUID, sandboxID string) (primaryID *uuid.UUID, primaryName string, baseStoreName string, err error) {
err = s.pool.QueryRow(ctx,
- `SELECT secret_store_id, COALESCE(config->>'baseSecretStore', '')
+ `SELECT secret_store_id, COALESCE(config->>'secretStore', ''), COALESCE(config->>'baseSecretStore', '')
FROM sandbox_sessions
WHERE org_id = $1 AND sandbox_id = $2 ORDER BY started_at DESC LIMIT 1`,
orgID, sandboxID,
- ).Scan(&primaryID, &baseStoreName)
+ ).Scan(&primaryID, &primaryName, &baseStoreName)
if err != nil {
- return nil, "", fmt.Errorf("get sandbox store refs: %w", err)
+ return nil, "", "", fmt.Errorf("get sandbox store refs: %w", err)
}
- return primaryID, baseStoreName, nil
+ return primaryID, primaryName, baseStoreName, nil
}
// ListSecretStores returns all secret stores for an org.
diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.go
index 88c6be01..f513c263 100644
--- a/internal/edgeclient/client.go
+++ b/internal/edgeclient/client.go
@@ -393,6 +393,24 @@ func (c *Client) LookupSecretStoreByID(ctx context.Context, id uuid.UUID, enc *c
return c.lookupStoreByQuery(ctx, "/internal/secret-stores/"+escapeQuery(id.String()), enc)
}
+// DeleteSecretStore deletes an org-scoped secret store from the edge D1 store.
+// Used by the CP's single-use-store cleanup path after it has already verified
+// the sandbox belongs to orgID.
+func (c *Client) DeleteSecretStore(ctx context.Context, orgID, id uuid.UUID) error {
+ q := "/internal/secret-stores/" + escapeQuery(id.String()) + "?org_id=" + escapeQuery(orgID.String())
+ body, status, err := c.do(ctx, "DELETE", q, nil)
+ if err != nil {
+ return err
+ }
+ if status == 404 {
+ return ErrNotFound
+ }
+ if status != 204 {
+ return fmt.Errorf("edge status %d: %s", status, string(body))
+ }
+ return nil
+}
+
// ── Webhooks (inline-on-create) ──────────────────────────────────────────
// RegisterInlineWebhooks registers inline sandbox webhooks at the edge (Svix
diff --git a/scripts/qemu-tests/45-secret-store-checkpoint-kill.ts b/scripts/qemu-tests/45-secret-store-checkpoint-kill.ts
new file mode 100644
index 00000000..65d1537c
--- /dev/null
+++ b/scripts/qemu-tests/45-secret-store-checkpoint-kill.ts
@@ -0,0 +1,164 @@
+/**
+ * Repro: create a sandbox with a single-use secret store, create a checkpoint,
+ * then kill the sandbox and delete the attached secret store.
+ *
+ * Usage:
+ * OPENSANDBOX_API_URL=https://mo-oc-dev.com OPENSANDBOX_API_KEY=... \
+ * npx tsx scripts/qemu-tests/45-secret-store-checkpoint-kill.ts
+ *
+ * Optional:
+ * CHECKPOINT_KIND=disk_only|full default: disk_only
+ * READY_TIMEOUT_SECONDS=900 checkpoint wait timeout
+ * SANDBOX_TIMEOUT_SECONDS=3600 sandbox idle timeout
+ * KEEP_ON_FAILURE=1 leave resources behind for inspection
+ */
+
+import { Sandbox, SecretStore } from "../../sdks/typescript/src/index.ts";
+
+const API_URL = process.env.OPENCOMPUTER_API_URL || process.env.OPENSANDBOX_API_URL;
+const API_KEY = process.env.OPENCOMPUTER_API_KEY || process.env.OPENSANDBOX_API_KEY;
+const CHECKPOINT_KIND = process.env.CHECKPOINT_KIND === "full" ? "full" : "disk_only";
+const READY_TIMEOUT_SECONDS = Number(process.env.READY_TIMEOUT_SECONDS || "900");
+const SANDBOX_TIMEOUT_SECONDS = Number(process.env.SANDBOX_TIMEOUT_SECONDS || "3600");
+const KEEP_ON_FAILURE = process.env.KEEP_ON_FAILURE === "1";
+
+let pass = 0;
+let fail = 0;
+
+function ok(message: string) {
+ pass += 1;
+ console.log(`PASS ${message}`);
+}
+
+function bad(message: string) {
+ fail += 1;
+ console.error(`FAIL ${message}`);
+}
+
+function summary() {
+ console.log(`${pass} passed, ${fail} failed`);
+ if (fail > 0) process.exit(1);
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function waitForCheckpointReady(sandbox: Sandbox, checkpointId: string) {
+ const deadline = Date.now() + READY_TIMEOUT_SECONDS * 1000;
+ while (Date.now() < deadline) {
+ const checkpoints = await sandbox.listCheckpoints();
+ const cp = checkpoints.find((checkpoint) => checkpoint.id === checkpointId);
+ if (cp?.status === "ready") return cp;
+ if (cp && cp.status !== "processing") {
+ throw new Error(`checkpoint ${checkpointId} ended with status ${cp.status}`);
+ }
+ await sleep(5000);
+ }
+ throw new Error(`checkpoint ${checkpointId} did not become ready within ${READY_TIMEOUT_SECONDS}s`);
+}
+
+async function expectSecretStoreGone(storeId: string) {
+ try {
+ await SecretStore.get(storeId, { apiUrl: API_URL, apiKey: API_KEY });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (message.includes("404")) {
+ ok(`attached secret store was deleted: ${storeId}`);
+ return;
+ }
+ throw err;
+ }
+ throw new Error(`secret store still exists after sandbox kill: ${storeId}`);
+}
+
+async function main() {
+ if (!API_URL) throw new Error("set OPENSANDBOX_API_URL or OPENCOMPUTER_API_URL");
+ if (!API_KEY) throw new Error("set OPENSANDBOX_API_KEY or OPENCOMPUTER_API_KEY");
+ if (!Number.isFinite(READY_TIMEOUT_SECONDS) || READY_TIMEOUT_SECONDS <= 0) {
+ throw new Error("READY_TIMEOUT_SECONDS must be a positive number");
+ }
+
+ const suffix = `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
+ const storeName = `repro-delete-attached-${suffix}`;
+ const checkpointName = `repro-cp-${suffix}`;
+ const secretValue = `marker-${suffix}`;
+
+ let storeId: string | undefined;
+ let sandbox: Sandbox | undefined;
+ let killedWithDelete = false;
+
+ try {
+ const store = await SecretStore.create({
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ name: storeName,
+ egressAllowlist: ["example.com"],
+ });
+ storeId = store.id;
+ ok(`secret store created: ${storeName} (${storeId})`);
+
+ await SecretStore.setSecret(store.id, "OC_REPRO_SECRET", secretValue, {
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ allowedHosts: ["example.com"],
+ });
+ const entries = await SecretStore.listSecrets(store.id, { apiUrl: API_URL, apiKey: API_KEY });
+ if (!entries.some((entry) => entry.name === "OC_REPRO_SECRET")) {
+ throw new Error("secret entry was not listed after setSecret");
+ }
+ ok("secret entry created");
+
+ sandbox = await Sandbox.create({
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ timeout: SANDBOX_TIMEOUT_SECONDS,
+ secretStore: storeName,
+ metadata: { repro: "secret-store-checkpoint-kill", storeId },
+ });
+ ok(`sandbox created with attached secret store: ${sandbox.sandboxId}`);
+
+ const allowedHosts = await sandbox.getAllowedHosts();
+ if (allowedHosts.secretStore !== storeName) {
+ throw new Error(`sandbox reports secretStore=${allowedHosts.secretStore || "<empty>"}, expected ${storeName}`);
+ }
+ if (!allowedHosts.egressAllowlist.includes("example.com")) {
+ throw new Error(`sandbox egress allowlist does not include example.com: ${allowedHosts.egressAllowlist.join(",")}`);
+ }
+ ok("sandbox reports attached secret store allowlist");
+
+ const envCheck = await sandbox.exec.run("test -n \"$OC_REPRO_SECRET\" && printf present", {
+ timeout: 30,
+ timeoutMs: 120_000,
+ });
+ if (envCheck.exitCode !== 0 || envCheck.stdout.trim() !== "present") {
+ throw new Error(`secret env marker not visible in sandbox: exit=${envCheck.exitCode} stdout=${JSON.stringify(envCheck.stdout)} stderr=${JSON.stringify(envCheck.stderr)}`);
+ }
+ ok("secret env marker is visible in sandbox");
+
+ const checkpoint = await sandbox.createCheckpoint(checkpointName, { kind: CHECKPOINT_KIND });
+ ok(`checkpoint requested: ${checkpointName} (${checkpoint.id}, kind=${CHECKPOINT_KIND})`);
+ const ready = await waitForCheckpointReady(sandbox, checkpoint.id);
+ ok(`checkpoint ready: ${ready.name} (${ready.id})`);
+
+ await sandbox.kill({ deleteSecretStore: true });
+ killedWithDelete = true;
+ ok("sandbox killed with deleteSecretStore=true");
+
+ await expectSecretStoreGone(store.id);
+ } finally {
+ if (!killedWithDelete && sandbox && !KEEP_ON_FAILURE) {
+ await sandbox.kill({ deleteSecretStore: true }).catch(() => undefined);
+ }
+ if (storeId && !killedWithDelete && !KEEP_ON_FAILURE) {
+ await SecretStore.delete(storeId, { apiUrl: API_URL, apiKey: API_KEY }).catch(() => undefined);
+ }
+ }
+
+ summary();
+}
+
+main().catch((err) => {
+ bad(err instanceof Error ? err.stack || err.message : String(err));
+ summary();
+});
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index 83ccb1fa..0c8ce270 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -68,4 +68,4 @@ __all__ = [
"TagKeyInfo",
]
-__version__ = "0.6.3"
+__version__ = "0.6.7"
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 6b189cde..628f9904 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -288,9 +288,16 @@ class Sandbox:
which handles readiness waiting and proxies to workers."""
return self._client
- async def kill(self) -> None:
- """Kill and remove the sandbox."""
- resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}")
+ async def kill(self, delete_secret_store: bool = False) -> None:
+ """Kill and remove the sandbox.
+
+ Args:
+ delete_secret_store: Also delete the secret store currently attached
+ to this sandbox. Defaults to ``False``. Only use this for
+ single-use stores that should not outlive the sandbox.
+ """
+ params = {"deleteSecretStore": "true"} if delete_secret_store else None
+ resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}", params=params)
resp.raise_for_status()
self.status = "stopped"
diff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.toml
index 4d210e99..b7dbe84e 100644
--- a/sdks/python/pyproject.toml
+++ b/sdks/python/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "opencomputer-sdk"
-version = "0.6.5"
+version = "0.6.7"
description = "Python SDK for OpenComputer - cloud sandbox platform"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index c8f1456b..df80ae95 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.11.1",
+ "version": "0.11.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.11.1",
+ "version": "0.11.2",
"license": "MIT",
"devDependencies": {
"@types/node": "^25.3.0",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index cb98d66c..ebf58bab 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.11.1",
+ "version": "0.11.2",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index be6e871c..1a017168 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -14,6 +14,7 @@ export {
type AutoscaleStatus,
type ScalingLockStatus,
type AllowedHostsInfo,
+ type SandboxKillOptions,
} from "./sandbox.js";
export { Browser, BrowserProfile, type BrowserCreateOpts, type BrowserData, type BrowserProfileCreateOpts, type BrowserProfileData } from "./browser.js";
export { SandboxAgent, type SandboxAgentEvent, type SandboxAgentConfig, type SandboxAgentStartOpts, type SandboxAgentSession, type McpServerConfig } from "./agent.js";
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 1aef2806..11370ba0 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -247,6 +247,16 @@ export interface AllowedHostsInfo {
perSecretAllowedHosts: Record<string, string[]>;
}
+export interface SandboxKillOptions {
+ /**
+ * Also delete the secret store currently attached to this sandbox.
+ *
+ * Defaults to false. Only set this for single-use stores that should not
+ * outlive the sandbox.
+ */
+ deleteSecretStore?: boolean;
+}
+
export class Sandbox {
readonly sandboxId: string;
readonly id: string;
@@ -424,8 +434,9 @@ export class Sandbox {
return this.previewAuthToken;
}
- async kill(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
+ async kill(opts: SandboxKillOptions = {}): Promise<void> {
+ const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}${query}`, {
method: "DELETE",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});