Skip to content

An open-source, faster Devin alternative

TypeScript

Fix secret-store sealing on QEMU + propagate allowedHosts + inherit on fork (#109)

Mohamed Habiba496c50b0e23
diff --git a/deploy/azure/deploy-azure-dev.sh b/deploy/azure/deploy-azure-dev.sh
index 6e9ee903..97066abb 100755
--- a/deploy/azure/deploy-azure-dev.sh
+++ b/deploy/azure/deploy-azure-dev.sh
@@ -15,6 +15,7 @@ AZURE_IMAGE="${AZURE_IMAGE:-Canonical:ubuntu-24_04-lts:server:latest}"
AZURE_ADMIN_USER="${AZURE_ADMIN_USER:-ubuntu}"
AZURE_DATA_DISK_GB="${AZURE_DATA_DISK_GB:-500}"
OPENSANDBOX_API_KEY="${OPENSANDBOX_API_KEY:-opensandbox-dev}"
+OPENSANDBOX_SECRET_ENCRYPTION_KEY="${OPENSANDBOX_SECRET_ENCRYPTION_KEY:-}"
SSH_KEY_PATH="${SSH_KEY_PATH:-$HOME/.ssh/id_rsa}"
STATE_DIR="$SCRIPT_DIR"
@@ -149,6 +150,16 @@ cmd_deploy() {
log "Deploying to $VM_PUBLIC_IP..."
+ # Persist a stable secret-store encryption key per environment.
+ # Without this, OPENSANDBOX_SECRET_ENCRYPTION_KEY is unset and SecretStore.setSecret
+ # fails with HTTP 500 ("encryption not configured"). Reuse across redeploys so
+ # secrets stored before a redeploy remain decryptable.
+ if [ -z "${OPENSANDBOX_SECRET_ENCRYPTION_KEY:-}" ]; then
+ OPENSANDBOX_SECRET_ENCRYPTION_KEY=$(openssl rand -hex 32)
+ save_state "OPENSANDBOX_SECRET_ENCRYPTION_KEY" "$OPENSANDBOX_SECRET_ENCRYPTION_KEY"
+ log "Generated new secret encryption key (persisted to state file)"
+ fi
+
# Sync code
log "Syncing code..."
rsync -az --progress \
@@ -244,6 +255,7 @@ OPENSANDBOX_NATS_URL=
OPENSANDBOX_PORT=8081
OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024
OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+OPENSANDBOX_SECRET_ENCRYPTION_KEY=${OPENSANDBOX_SECRET_ENCRYPTION_KEY}
EOF
# Server env
@@ -256,6 +268,7 @@ OPENSANDBOX_REDIS_URL=redis://localhost:6379
OPENSANDBOX_SANDBOX_DOMAIN=${SANDBOX_DOMAIN}
OPENSANDBOX_PORT=8080
OPENSANDBOX_REGION=azure-${AZURE_LOCATION}
+OPENSANDBOX_SECRET_ENCRYPTION_KEY=${OPENSANDBOX_SECRET_ENCRYPTION_KEY}
EOF
ENVSETUP
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 9e1ed788..348d1661 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -65,39 +65,16 @@ func (s *Server) createSandbox(c echo.Context) error {
}
}
- // Resolve secret store: decrypt secrets + inherit egress config
- if cfg.SecretStore != "" && s.store != nil && hasOrg {
- store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)
- if err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "secret store not found: " + cfg.SecretStore,
- })
- }
-
- cfg.EgressAllowlist = store.EgressAllowlist
-
- secrets, err := s.store.DecryptSecretEntries(ctx, store.ID)
+ // Resolve secret store: decrypt secrets + inherit egress config.
+ // secretEnvKeys tracks which env vars came from the store so we can strip
+ // only those (not user-supplied envs) before persisting cfg into PG.
+ var secretEnvKeys map[string]struct{}
+ if cfg.SecretStore != "" && hasOrg {
+ var err error
+ secretEnvKeys, err = s.resolveSecretStoreInto(ctx, orgID, &cfg)
if err != nil {
- log.Printf("api: decrypt secrets failed for store %s: %v", cfg.SecretStore, err)
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "failed to decrypt secrets",
- })
- }
- if len(secrets) > 0 {
- if cfg.Envs == nil {
- cfg.Envs = make(map[string]string)
- }
- for _, secret := range secrets {
- if _, exists := cfg.Envs[secret.Name]; !exists {
- cfg.Envs[secret.Name] = secret.Value
- }
- if len(secret.AllowedHosts) > 0 {
- if cfg.SecretAllowedHosts == nil {
- cfg.SecretAllowedHosts = make(map[string][]string)
- }
- cfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts
- }
- }
+ log.Printf("api: %v", err)
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
}
@@ -134,7 +111,7 @@ func (s *Server) createSandbox(c echo.Context) error {
// Server mode with worker registry: dispatch to remote worker via gRPC
if s.workerRegistry != nil {
- return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)
+ return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretEnvKeys)
}
// Combined/worker mode: create locally
@@ -179,7 +156,7 @@ func (s *Server) createSandbox(c echo.Context) error {
// Write session record to PG if available
if s.store != nil && hasOrg {
- cfgJSON, _ := json.Marshal(cfg)
+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg, secretEnvKeys))
metadataJSON, _ := json.Marshal(cfg.Metadata)
region := s.region
if region == "" {
@@ -279,8 +256,122 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID
return nil
}
+// resolveSecretStoreInto looks up the named secret store, decrypts its
+// entries, and writes Envs / SecretAllowedHosts / EgressAllowlist into cfg in
+// place. Existing Envs entries with the same key are NOT overwritten — they
+// were set explicitly by the caller and win over store-derived defaults.
+//
+// Returns the set of env var names that were populated from the store, so the
+// caller can strip exactly those (and their per-secret allowedHosts entries)
+// before persisting cfg into PG. User-supplied envs are preserved.
+//
+// This helper is the single place where secret store name → resolved values
+// happens, so the same logic runs on both fresh creates and on
+// fork-from-checkpoint inheritance. If the user updates a secret between
+// snapshot and fork, the fork sees the new value.
+func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) (addedKeys map[string]struct{}, err error) {
+ addedKeys = map[string]struct{}{}
+ if cfg.SecretStore == "" || s.store == nil {
+ return addedKeys, nil
+ }
+ store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)
+ if err != nil {
+ return addedKeys, fmt.Errorf("secret store not found: %s", cfg.SecretStore)
+ }
+
+ cfg.EgressAllowlist = store.EgressAllowlist
+
+ secrets, err := s.store.DecryptSecretEntries(ctx, store.ID)
+ if err != nil {
+ return addedKeys, fmt.Errorf("failed to decrypt secrets for store %s: %w", cfg.SecretStore, err)
+ }
+ if len(secrets) == 0 {
+ return addedKeys, nil
+ }
+ if cfg.Envs == nil {
+ cfg.Envs = make(map[string]string, len(secrets))
+ }
+ for _, secret := range secrets {
+ if _, exists := cfg.Envs[secret.Name]; !exists {
+ cfg.Envs[secret.Name] = secret.Value
+ addedKeys[secret.Name] = struct{}{}
+ }
+ if len(secret.AllowedHosts) > 0 {
+ if cfg.SecretAllowedHosts == nil {
+ cfg.SecretAllowedHosts = make(map[string][]string)
+ }
+ cfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts
+ }
+ }
+ return addedKeys, nil
+}
+
+// cfgForPersistence returns a copy of cfg suitable for marshaling into PG
+// (cp.SandboxConfig / sandbox_sessions.config_json) with secret-store-derived
+// values stripped. User-supplied envs are preserved.
+//
+// - secret VALUES (for keys in resolvedKeys) are removed from Envs
+// - SecretAllowedHosts entries for those same keys are removed
+// - store-level EgressAllowlist is cleared (it's a property of the store,
+// re-derived on fork)
+//
+// Only the store NAME is kept on the persisted config. Forks re-resolve fresh
+// against the DB on load, so plaintext secrets never sit at rest in PG.
+func cfgForPersistence(cfg types.SandboxConfig, resolvedKeys map[string]struct{}) types.SandboxConfig {
+ if cfg.SecretStore == "" || len(resolvedKeys) == 0 {
+ return cfg
+ }
+ if len(cfg.Envs) > 0 {
+ stripped := make(map[string]string, len(cfg.Envs))
+ for k, v := range cfg.Envs {
+ if _, isSecret := resolvedKeys[k]; !isSecret {
+ stripped[k] = v
+ }
+ }
+ if len(stripped) == 0 {
+ cfg.Envs = nil
+ } else {
+ cfg.Envs = stripped
+ }
+ }
+ if len(cfg.SecretAllowedHosts) > 0 {
+ strippedHosts := make(map[string][]string, len(cfg.SecretAllowedHosts))
+ for k, v := range cfg.SecretAllowedHosts {
+ if _, isSecret := resolvedKeys[k]; !isSecret {
+ strippedHosts[k] = v
+ }
+ }
+ if len(strippedHosts) == 0 {
+ cfg.SecretAllowedHosts = nil
+ } else {
+ cfg.SecretAllowedHosts = strippedHosts
+ }
+ }
+ cfg.EgressAllowlist = nil
+ return cfg
+}
+
+// flattenSecretAllowedHosts converts the internal per-secret allowed-hosts map
+// (env var → host slice) into the proto wire shape (env var → comma-joined string).
+// Mirror of parseSecretAllowedHosts in internal/worker/grpc_server.go.
+func flattenSecretAllowedHosts(m map[string][]string) map[string]string {
+ if len(m) == 0 {
+ return nil
+ }
+ out := make(map[string]string, len(m))
+ for name, hosts := range m {
+ if len(hosts) > 0 {
+ out[name] = strings.Join(hosts, ",")
+ }
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
// createSandboxRemote dispatches sandbox creation to a remote worker via gRPC.
-func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool) error {
+func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool, secretEnvKeys map[string]struct{}) error {
// Select region (explicit header, or default to server's region)
region := c.Request().Header.Get("Fly-Region")
if region == "" {
@@ -336,6 +427,8 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
Port: int32(cfg.Port),
TemplateRootfsKey: templateRootfsKey,
TemplateWorkspaceKey: templateWorkspaceKey,
+ EgressAllowlist: cfg.EgressAllowlist,
+ SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
@@ -391,7 +484,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
if template == "" {
template = "default"
}
- cfgJSON, _ := json.Marshal(cfg)
+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg, secretEnvKeys))
metadataJSON, _ := json.Marshal(cfg.Metadata)
_, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)
if templateID != nil {
@@ -1449,6 +1542,12 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {
// createFromCheckpointCore contains the core logic for creating a sandbox from a checkpoint.
// Returns the result map, HTTP status, or an error.
+//
+// Secret store inheritance: if the original sandbox was created with a
+// secretStore, that store NAME is persisted in cp.SandboxConfig and the fork
+// re-resolves it fresh against the DB at this point. So if the user updated a
+// secret in the store between snapshot and fork, the fork sees the new value.
+// The fork itself does NOT support overriding the secret store — it inherits.
func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{}, int, error) {
checkpointIDStr := c.Param("checkpointId")
ctx := c.Request().Context()
@@ -1514,6 +1613,20 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
var originalCfg types.SandboxConfig
_ = json.Unmarshal(cp.SandboxConfig, &originalCfg)
+ // Re-resolve the inherited secret store fresh against the DB. The
+ // checkpoint persists the store NAME (not the decrypted values) so this
+ // picks up any secret changes the user made between snapshot and fork.
+ // User-supplied envs that were on the original config are preserved by
+ // resolveSecretStoreInto (it never overwrites existing keys).
+ var secretEnvKeys map[string]struct{}
+ if originalCfg.SecretStore != "" {
+ var err error
+ secretEnvKeys, err = s.resolveSecretStoreInto(ctx, orgID, &originalCfg)
+ if err != nil {
+ return nil, http.StatusBadRequest, err
+ }
+ }
+
timeout := req.Timeout
if timeout <= 0 {
timeout = originalCfg.Timeout
@@ -1575,7 +1688,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
if template == "" {
template = "default"
}
- cfgJSON, _ := json.Marshal(originalCfg)
+ cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg, secretEnvKeys))
metadataJSON, _ := json.Marshal(originalCfg.Metadata)
_, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, nil, template, region, workerID, cfgJSON, metadataJSON)
// Track checkpoint lineage for patch system
@@ -1603,6 +1716,8 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
TemplateWorkspaceKey: *cp.WorkspaceS3Key,
CheckpointId: checkpointID.String(),
SandboxId: sandboxID,
+ EgressAllowlist: originalCfg.EgressAllowlist,
+ SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),
})
} else {
// Combined mode: create locally — no external timeout, same reasoning as above
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 47b5a71c..87a65b3f 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -205,6 +205,36 @@ func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
m.secretsProxy = sp
}
+// sealSandboxEnvs runs cfg.Envs through the secrets proxy to swap real values
+// for sealed tokens, registers a proxy session for the guest IP, and writes the
+// proxy CA cert into the guest trust store. Returns the env map that should be
+// injected into the VM (sealed tokens + HTTP_PROXY/CA env vars), or cfg.Envs
+// unchanged if the secrets proxy is not configured.
+//
+// IMPORTANT: This is the QEMU equivalent of internal/firecracker/manager.go:451.
+// The QEMU manager originally shipped without this call, so secrets were
+// injected into the guest as plaintext — see git history for f2e64e3.
+func (m *Manager) sealSandboxEnvs(ctx context.Context, sandboxID string, netCfg *NetworkConfig, agent *AgentClient, cfg types.SandboxConfig) map[string]string {
+ if m.secretsProxy == nil || len(cfg.Envs) == 0 {
+ return cfg.Envs
+ }
+ sealed := m.secretsProxy.CreateSealedEnvs(sandboxID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)
+ if sealed == nil {
+ return cfg.Envs
+ }
+ // Inject the proxy CA cert so HTTPS apps inside the VM trust the MITM proxy.
+ // CreateSealedEnvs already populates NODE_EXTRA_CA_CERTS / REQUESTS_CA_BUNDLE /
+ // SSL_CERT_FILE pointing at this path; without the file the env vars are dead.
+ if certPEM := m.secretsProxy.CACertPEM(); len(certPEM) > 0 {
+ writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ if err := agent.WriteFile(writeCtx, "/usr/local/share/ca-certificates/opensandbox-proxy.crt", certPEM); err != nil {
+ log.Printf("qemu: warning: write proxy CA cert failed for %s: %v", sandboxID, err)
+ }
+ cancel()
+ }
+ return sealed
+}
+
// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then
// hibernates it to create a reusable snapshot. Subsequent Create() calls
// restore from this snapshot instead of cold-booting, cutting start time
@@ -705,9 +735,10 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
}
log.Printf("qemu: golden-create %s: network patched (%dms)", id, time.Since(t0).Milliseconds())
- if len(cfg.Envs) > 0 {
+ envsToInject := m.sealSandboxEnvs(context.Background(), id, netCfg, agentClient, cfg)
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {
+ if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
envCancel()
log.Printf("qemu: warning: SetEnvs failed for %s: %v", id, err)
}
@@ -1087,9 +1118,10 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
}
vm.agent = agentClient
- if len(cfg.Envs) > 0 {
+ envsToInject := m.sealSandboxEnvs(context.Background(), id, netCfg, agentClient, cfg)
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {
+ if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
envCancel()
log.Printf("qemu: warning: SetEnvs failed for %s: %v", id, err)
}
@@ -2381,10 +2413,11 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)
}
- // Set env vars
- if len(cfg.Envs) > 0 {
+ // Set env vars (sealed via secrets proxy if configured)
+ envsToInject := m.sealSandboxEnvs(context.Background(), id, netCfg, agent, cfg)
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- agent.SetEnvs(envCtx, cfg.Envs)
+ agent.SetEnvs(envCtx, envsToInject)
envCancel()
}
diff --git a/sdks/typescript/examples/test-secret-seal-e2e.ts b/sdks/typescript/examples/test-secret-seal-e2e.ts
new file mode 100644
index 00000000..e7a1b2b4
--- /dev/null
+++ b/sdks/typescript/examples/test-secret-seal-e2e.ts
@@ -0,0 +1,286 @@
+/**
+ * End-to-end secret-seal verification.
+ *
+ * Single script covering all the things that have silently broken before:
+ * 1. Secrets land in the guest as `osb_sealed_*` tokens, never plaintext
+ * (echo, file write+read, hex roundtrip).
+ * 2. Per-secret `allowedHosts` is honored on outbound: a secret marked
+ * allowed for httpbin.org IS substituted when curling httpbin.org;
+ * a secret NOT allowed for httpbin.org is left as the literal token.
+ * 3. Store-level `egressAllowlist` blocks connections to disallowed hosts
+ * entirely (regardless of any secret).
+ *
+ * Usage:
+ * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-secret-seal-e2e.ts
+ */
+
+import { Sandbox, SecretStore } from "../src/index";
+import { randomBytes } from "node:crypto";
+
+const ALLOWED_VAL = `allowed_${randomBytes(12).toString("hex")}`;
+const DENIED_VAL = `denied_${randomBytes(12).toString("hex")}`;
+
+let storeId: string | null = null;
+let sandbox: Sandbox | null = null;
+let forkedSandbox: Sandbox | null = null;
+let passed = 0;
+let failed = 0;
+
+const green = (s: string) => console.log(`\x1b[32m\u2713 ${s}\x1b[0m`);
+const red = (s: string, detail?: string) =>
+ console.log(`\x1b[31m\u2717 ${s}${detail ? ` — ${detail}` : ""}\x1b[0m`);
+const bold = (s: string) => console.log(`\x1b[1m${s}\x1b[0m`);
+const dim = (s: string) => console.log(`\x1b[2m ${s}\x1b[0m`);
+
+function check(desc: string, condition: boolean, detail?: string) {
+ if (condition) {
+ green(desc);
+ passed++;
+ } else {
+ red(desc, detail);
+ failed++;
+ }
+}
+
+async function execStdout(cmd: string): Promise<string> {
+ const r = await sandbox!.exec.run(cmd);
+ return r.stdout;
+}
+
+async function main() {
+ const storeName = `seal-e2e-${Date.now()}`;
+ try {
+ bold("\n=== 1. Setup: store + secrets ===\n");
+
+ // Store-level egressAllowlist: only httpbin.org reachable.
+ // example.com is intentionally OUT of the allowlist to test blocking.
+ const store = await SecretStore.create({
+ name: storeName,
+ egressAllowlist: ["httpbin.org"],
+ });
+ storeId = store.id;
+ dim(`Store: ${storeName} (id=${store.id})`);
+
+ // Two secrets with different per-secret allowedHosts:
+ // ALLOWED — should be substituted ONLY on httpbin.org
+ // DENIED — allowed on a host the sandbox can't reach, so should
+ // never be substituted on httpbin.org
+ await SecretStore.setSecret(storeId, "SECRET_ALLOWED", ALLOWED_VAL, {
+ allowedHosts: ["httpbin.org"],
+ });
+ await SecretStore.setSecret(storeId, "SECRET_DENIED", DENIED_VAL, {
+ allowedHosts: ["api.example.com"],
+ });
+ green("Created 2 secrets with distinct allowedHosts");
+
+ bold("\n=== 2. Create sandbox bound to store ===\n");
+ sandbox = await Sandbox.create({ secretStore: storeName, timeout: 180 });
+ dim(`Sandbox: ${sandbox.sandboxId}`);
+ green("Sandbox created");
+
+ bold("\n=== 3. In-guest: secrets must be sealed tokens ===\n");
+
+ const allowedEcho = (await execStdout("printf %s \"$SECRET_ALLOWED\"")).trim();
+ const deniedEcho = (await execStdout("printf %s \"$SECRET_DENIED\"")).trim();
+
+ check(
+ "SECRET_ALLOWED is sealed in env",
+ allowedEcho.startsWith("osb_sealed_") && !allowedEcho.includes(ALLOWED_VAL),
+ `got "${allowedEcho}"`,
+ );
+ check(
+ "SECRET_DENIED is sealed in env",
+ deniedEcho.startsWith("osb_sealed_") && !deniedEcho.includes(DENIED_VAL),
+ `got "${deniedEcho}"`,
+ );
+
+ // file roundtrip — different agent code path than env echo
+ await sandbox.exec.run('printf %s "$SECRET_ALLOWED" > /tmp/s.txt');
+ const fileBuf = await sandbox.files.read("/tmp/s.txt");
+ const fileVal = (typeof fileBuf === "string" ? fileBuf : Buffer.from(fileBuf).toString("utf-8")).trim();
+ check(
+ "file write+read of secret stays sealed",
+ fileVal.startsWith("osb_sealed_") && !fileVal.includes(ALLOWED_VAL),
+ `got "${fileVal}"`,
+ );
+
+ bold("\n=== 4. Egress: per-secret allowedHosts on httpbin.org ===\n");
+
+ // Single httpbin call carries BOTH headers. httpbin echoes them back in
+ // its JSON response. Expected behavior:
+ // X-Allowed → real value (proxy substituted, host matches allowedHosts)
+ // X-Denied → still the sealed token (proxy did NOT substitute)
+ const httpbinOut = await execStdout(
+ `curl -sS -m 10 https://httpbin.org/headers -H "X-Allowed: $SECRET_ALLOWED" -H "X-Denied: $SECRET_DENIED"`,
+ );
+ dim(`httpbin response (first 400 chars):`);
+ dim(httpbinOut.replace(/\s+/g, " ").slice(0, 400));
+
+ check(
+ "httpbin echoed REAL value for SECRET_ALLOWED (substituted on allowed host)",
+ httpbinOut.includes(ALLOWED_VAL),
+ "expected substitution on httpbin.org since it's in SECRET_ALLOWED.allowedHosts",
+ );
+ check(
+ "httpbin did NOT echo real value for SECRET_DENIED",
+ !httpbinOut.includes(DENIED_VAL),
+ "real DENIED value leaked to httpbin even though it's not in SECRET_DENIED.allowedHosts",
+ );
+ check(
+ "httpbin echoed sealed token literal for SECRET_DENIED",
+ httpbinOut.includes("osb_sealed_") && /X-Denied[^\n]*osb_sealed_/i.test(httpbinOut),
+ "expected literal osb_sealed_* token in X-Denied header",
+ );
+
+ bold("\n=== 5. Egress: store-level egressAllowlist blocks unrelated hosts ===\n");
+
+ // example.com is NOT in egressAllowlist=["httpbin.org"], so the proxy
+ // should refuse the CONNECT entirely. Curl exits non-zero / no body.
+ const blockedOut = await sandbox.exec.run(
+ `curl -sS -m 10 -o /tmp/blocked.body -w '%{http_code}\\n' https://example.com/ ; echo "exit=$?"`,
+ );
+ const blockedBody = await sandbox.exec.run("cat /tmp/blocked.body 2>/dev/null || true");
+ dim(`curl status line: ${blockedOut.stdout.trim().replace(/\n/g, " | ")}`);
+ dim(`body bytes: ${blockedBody.stdout.length}`);
+
+ const reachedExample = /<title>Example Domain<\/title>/i.test(blockedBody.stdout);
+ check(
+ "example.com (not in egressAllowlist) is BLOCKED",
+ !reachedExample,
+ "fetched example.com despite it not being in the store's egressAllowlist",
+ );
+
+ // Sanity: an allowed host still works (proves we didn't just kill all egress)
+ const sanity = await execStdout(`curl -sS -m 10 -o /dev/null -w '%{http_code}' https://httpbin.org/get`);
+ check("sanity: httpbin.org (in egressAllowlist) is reachable", sanity.trim() === "200", `got "${sanity.trim()}"`);
+
+ bold("\n=== 6. Snapshot/fork inheritance: secret store binds at first creation ===\n");
+
+ // Take a checkpoint of the running sandbox, wait for it to be ready,
+ // then fork. The fork must inherit the secret store binding without the
+ // user passing secretStore again — and the seal/proxy semantics must
+ // continue to hold on the fork.
+ dim("Creating checkpoint of running sandbox...");
+ const cp = await sandbox.createCheckpoint(`seal-e2e-cp-${Date.now()}`);
+ dim(`Checkpoint id: ${cp.id}`);
+
+ // Poll until ready — generous timeout because S3 upload can be slow on
+ // dev boxes. Print status periodically so a hang is visible.
+ let cpReady = false;
+ let lastStatus: string | undefined;
+ for (let i = 0; i < 180; i++) {
+ const list = await sandbox.listCheckpoints();
+ const found = list.find((c) => c.id === cp.id);
+ if (found?.status !== lastStatus) {
+ dim(` [t=${i}s] checkpoint status: ${found?.status ?? "(missing)"}`);
+ lastStatus = found?.status;
+ }
+ if (found?.status === "ready") { cpReady = true; break; }
+ if (found?.status === "failed") break;
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ check("checkpoint reached ready state", cpReady, `last status: ${lastStatus}`);
+ if (!cpReady) throw new Error(`checkpoint never became ready (last status: ${lastStatus})`);
+
+ // Mutate the secret store BETWEEN snapshot and fork. The fork should see
+ // the new value because we re-resolve the store name fresh on fork load.
+ const ROTATED_VAL = `rotated_${randomBytes(12).toString("hex")}`;
+ await SecretStore.setSecret(storeId!, "SECRET_ALLOWED", ROTATED_VAL, {
+ allowedHosts: ["httpbin.org"],
+ });
+ dim(`Rotated SECRET_ALLOWED to ${ROTATED_VAL}`);
+
+ // Fork. The SDK's createFromCheckpoint takes no secretStore — inheritance
+ // is the only contract.
+ forkedSandbox = await Sandbox.createFromCheckpoint(cp.id, { timeout: 180 });
+ dim(`Forked sandbox: ${forkedSandbox.sandboxId}`);
+ check("forked sandbox created without re-passing secretStore", !!forkedSandbox.sandboxId);
+
+ // In-guest: the inherited secret must still be sealed (token, not value)
+ const forkEcho = (await forkedSandbox.exec.run('printf %s "$SECRET_ALLOWED"')).stdout.trim();
+ check(
+ "forked sandbox: SECRET_ALLOWED is sealed (inherited)",
+ forkEcho.startsWith("osb_sealed_") && !forkEcho.includes(ROTATED_VAL) && !forkEcho.includes(ALLOWED_VAL),
+ `got "${forkEcho}"`,
+ );
+
+ // The DENIED secret must also have inherited
+ const forkDeniedEcho = (await forkedSandbox.exec.run('printf %s "$SECRET_DENIED"')).stdout.trim();
+ check(
+ "forked sandbox: SECRET_DENIED is sealed (inherited)",
+ forkDeniedEcho.startsWith("osb_sealed_") && !forkDeniedEcho.includes(DENIED_VAL),
+ `got "${forkDeniedEcho}"`,
+ );
+
+ // Egress on the fork: hit httpbin and assert
+ // - SECRET_ALLOWED is substituted with the *ROTATED* value (proves we
+ // re-resolved the store fresh, instead of replaying baked-in values)
+ // - SECRET_DENIED is left as the literal sealed token (per-host filter still active)
+ const forkHttpbinOut = (await forkedSandbox.exec.run(
+ `curl -sS -m 10 https://httpbin.org/headers -H "X-Allowed: $SECRET_ALLOWED" -H "X-Denied: $SECRET_DENIED"`,
+ )).stdout;
+ dim(`forked httpbin response (first 400 chars):`);
+ dim(forkHttpbinOut.replace(/\s+/g, " ").slice(0, 400));
+
+ check(
+ "forked sandbox: httpbin sees ROTATED value for SECRET_ALLOWED",
+ forkHttpbinOut.includes(ROTATED_VAL),
+ "fork should re-resolve the store fresh, picking up the rotated secret value",
+ );
+ check(
+ "forked sandbox: httpbin does NOT see old (pre-rotation) value",
+ !forkHttpbinOut.includes(ALLOWED_VAL),
+ "fork served stale baked-in value instead of re-resolving",
+ );
+ check(
+ "forked sandbox: SECRET_DENIED still not substituted on httpbin",
+ !forkHttpbinOut.includes(DENIED_VAL),
+ "per-secret allowedHosts filter regressed on the fork path",
+ );
+
+ // Egress allowlist still enforced on the fork
+ const forkBlocked = await forkedSandbox.exec.run(
+ `curl -sS -m 10 -o /tmp/blocked.body -w '%{http_code}' https://example.com/ ; cat /tmp/blocked.body 2>/dev/null || true`,
+ );
+ check(
+ "forked sandbox: example.com still blocked by inherited egressAllowlist",
+ !/<title>Example Domain<\/title>/i.test(forkBlocked.stdout),
+ "egress allowlist not inherited on fork",
+ );
+ } catch (err: any) {
+ red(`Fatal: ${err.message}`);
+ if (err.stack) dim(err.stack);
+ failed++;
+ } finally {
+ bold("\n=== Cleanup ===\n");
+ if (forkedSandbox) {
+ try { await forkedSandbox.kill(); green("Forked sandbox killed"); } catch (e: any) { red(`fork kill failed: ${e.message}`); }
+ }
+ if (sandbox) {
+ try {
+ await sandbox.kill();
+ green("Sandbox killed");
+ } catch (e: any) {
+ red(`kill failed: ${e.message}`);
+ }
+ }
+ if (storeId) {
+ try {
+ await SecretStore.delete(storeId);
+ green("Store deleted");
+ } catch (e: any) {
+ red(`store delete failed: ${e.message}`);
+ }
+ }
+ }
+
+ bold("\n========================================");
+ bold(` Results: ${passed} passed, ${failed} failed`);
+ bold("========================================\n");
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("Unhandled:", err);
+ process.exit(1);
+});