An open-source, faster Devin alternative
TypeScript
Fix Sandbox.create envs on snapshot/fork and stop sealing user envs (#113)
Mohamed Habib16fd3fe10294
diff --git a/.gitignore b/.gitignoreindex 0a4d5e9e..690fe1f9 100644--- a/.gitignore+++ b/.gitignore@@ -59,4 +59,6 @@ deploy/ec2/*.pem*.logdelmedeploy/azure/.dev-env-state-*+deploy/azure/.dev-env-secrets*+!deploy/azure/.dev-env-secrets.example/serverdiff --git a/deploy/azure/.dev-env-secrets.example b/deploy/azure/.dev-env-secrets.examplenew file mode 100644index 00000000..a36ea1d4--- /dev/null+++ b/deploy/azure/.dev-env-secrets.example@@ -0,0 +1,10 @@+# Per-location secrets sourced by deploy-azure-dev.sh during `deploy`.+# Copy to .dev-env-secrets-<AZURE_LOCATION> (e.g. .dev-env-secrets-westeurope)+# and fill in. The real file is gitignored.+#+# Fetch the key with:+# az storage account keys list -n <account> -g <rg> --query '[0].value' -o tsv++CHECKPOINT_STORAGE_ACCOUNT=<storage-account-name>+CHECKPOINT_STORAGE_CONTAINER=<container-name>+CHECKPOINT_STORAGE_KEY=<account-key>diff --git a/deploy/azure/deploy-azure-dev.sh b/deploy/azure/deploy-azure-dev.shindex 97066abb..9989369d 100755--- a/deploy/azure/deploy-azure-dev.sh+++ b/deploy/azure/deploy-azure-dev.sh@@ -150,6 +150,32 @@ cmd_deploy() {log "Deploying to $VM_PUBLIC_IP..."+ # Load checkpoint-store secrets from a gitignored per-location file. Without+ # these the worker logs "checkpoint store not configured" and every+ # snapshot/fork RPC fails with no obvious cause, so the deploy fails fast.+ #+ # File format (deploy/azure/.dev-env-secrets-<location>):+ # CHECKPOINT_STORAGE_ACCOUNT=deveuwest1+ # CHECKPOINT_STORAGE_CONTAINER=checkpoints+ # CHECKPOINT_STORAGE_KEY=...+ # See deploy/azure/.dev-env-secrets.example. The file is gitignored.+ SECRETS_FILE="$STATE_DIR/.dev-env-secrets-${AZURE_LOCATION}"+ if [ -f "$SECRETS_FILE" ]; then+ # shellcheck disable=SC1090+ source "$SECRETS_FILE"+ log "Loaded secrets from $(basename "$SECRETS_FILE")"+ fi+ if [ -z "${CHECKPOINT_STORAGE_ACCOUNT:-}" ] || [ -z "${CHECKPOINT_STORAGE_KEY:-}" ] || [ -z "${CHECKPOINT_STORAGE_CONTAINER:-}" ]; then+ log "ERROR: checkpoint storage not configured for ${AZURE_LOCATION}."+ log " Create $SECRETS_FILE with CHECKPOINT_STORAGE_ACCOUNT,"+ log " CHECKPOINT_STORAGE_CONTAINER, and CHECKPOINT_STORAGE_KEY."+ log " See deploy/azure/.dev-env-secrets.example."+ log " To fetch the key:"+ log " az storage account keys list -n <account> -g <rg> --query '[0].value' -o tsv"+ exit 1+ fi+ log "Checkpoint store: https://${CHECKPOINT_STORAGE_ACCOUNT}.blob.core.windows.net/${CHECKPOINT_STORAGE_CONTAINER}"+# 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@@ -256,6 +282,15 @@ OPENSANDBOX_PORT=8081OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2OPENSANDBOX_SECRET_ENCRYPTION_KEY=${OPENSANDBOX_SECRET_ENCRYPTION_KEY}+# Checkpoint store — Azure Blob Storage. The worker switches backends when+# OPENSANDBOX_S3_ENDPOINT contains .blob.core.windows.net (see+# internal/storage/blob.go:39). Without these, snapshot/fork RPCs fail with+# "checkpoint store not configured on this worker".+OPENSANDBOX_S3_ENDPOINT=https://${CHECKPOINT_STORAGE_ACCOUNT}.blob.core.windows.net+OPENSANDBOX_S3_ACCESS_KEY_ID=${CHECKPOINT_STORAGE_ACCOUNT}+OPENSANDBOX_S3_SECRET_ACCESS_KEY=${CHECKPOINT_STORAGE_KEY}+OPENSANDBOX_S3_BUCKET=${CHECKPOINT_STORAGE_CONTAINER}+OPENSANDBOX_S3_REGION=${AZURE_LOCATION}EOF# Server envdiff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 348d1661..fb14e280 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -65,24 +65,19 @@ func (s *Server) createSandbox(c echo.Context) error {}}- // 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: %v", err)- return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})- }- }-// Declarative image or named snapshot → resolve to checkpoint and use createFromCheckpoint flowif len(cfg.ImageManifest) > 0 || cfg.Snapshot != "" {if !hasOrg {return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required for image/snapshot creation"})}+ // A fork inherits the snapshot's secret store and cannot override it.+ // Reject the combination explicitly so users can't trip a silent leak+ // by mixing a fresh secret store with a snapshot/image fork.+ if cfg.SecretStore != "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "secretStore cannot be combined with snapshot or image — the fork inherits the snapshot's secret store",+ })+ }// Check if the client wants build log streaming (SSE)wantsSSE := c.Request().Header.Get("Accept") == "text/event-stream"@@ -106,12 +101,30 @@ func (s *Server) createSandbox(c echo.Context) error {c.SetParamNames("checkpointId")c.SetParamValues(checkpointID.String())- return s.createFromCheckpoint(c)+ // Forward user-supplied envs so they override the checkpoint's stored+ // envs on a fork. Without this, Sandbox.create({snapshot, envs}) silently+ // drops the envs because the core path uses originalCfg.Envs from+ // cp.SandboxConfig (the envs the snapshot was originally built with).+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs)+ if cpErr != nil {+ return c.JSON(status, map[string]string{"error": cpErr.Error()})+ }+ return c.JSON(status, result)+ }++ // Fresh-create path: resolve the secret store (if any) into cfg.SecretEnvs.+ // This is intentionally below the snapshot/image branch so the snapshot+ // path never resolves a user-supplied store — forks inherit only.+ if cfg.SecretStore != "" && hasOrg {+ if err := s.resolveSecretStoreInto(ctx, orgID, &cfg); err != nil {+ log.Printf("api: %v", err)+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }}// Server mode with worker registry: dispatch to remote worker via gRPCif s.workerRegistry != nil {- return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretEnvKeys)+ return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)}// Combined/worker mode: create locally@@ -156,7 +169,7 @@ func (s *Server) createSandbox(c echo.Context) error {// Write session record to PG if availableif s.store != nil && hasOrg {- cfgJSON, _ := json.Marshal(cfgForPersistence(cfg, secretEnvKeys))+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))metadataJSON, _ := json.Marshal(cfg.Metadata)region := s.regionif region == "" {@@ -246,7 +259,7 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgIDc.SetParamNames("checkpointId")c.SetParamValues(checkpointID.String())- result, _, cpErr := s.createFromCheckpointCore(c)+ result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs)if cpErr != nil {emit("error", map[string]string{"error": cpErr.Error()})return nil@@ -257,45 +270,38 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID}// 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.+// entries, and writes them into cfg.SecretEnvs (NOT cfg.Envs) so the+// store-derived values are kept distinct from user-supplied envs all the way+// to the worker. EgressAllowlist and SecretAllowedHosts are also derived from+// the store. cfg.Envs is left untouched.//// 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{}{}+func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) error {if cfg.SecretStore == "" || s.store == nil {- return addedKeys, nil+ return nil}store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)if err != nil {- return addedKeys, fmt.Errorf("secret store not found: %s", cfg.SecretStore)+ return fmt.Errorf("secret store not found: %s", cfg.SecretStore)}cfg.EgressAllowlist = store.EgressAllowlistsecrets, 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)+ return fmt.Errorf("failed to decrypt secrets for store %s: %w", cfg.SecretStore, err)}if len(secrets) == 0 {- return addedKeys, nil+ return nil}- if cfg.Envs == nil {- cfg.Envs = make(map[string]string, len(secrets))+ if cfg.SecretEnvs == nil {+ cfg.SecretEnvs = 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{}{}- }+ cfg.SecretEnvs[secret.Name] = secret.Valueif len(secret.AllowedHosts) > 0 {if cfg.SecretAllowedHosts == nil {cfg.SecretAllowedHosts = make(map[string][]string)@@ -303,48 +309,31 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfgcfg.SecretAllowedHosts[secret.Name] = secret.AllowedHosts}}- return addedKeys, nil+ return 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.+// (cp.SandboxConfig / sandbox_sessions.config_json).//-// - 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)+// SecretEnvs is json:"-" so plaintext secret values never reach PG by+// construction. We still scrub:+// - SecretAllowedHosts entries that name store-derived keys (those names+// are a property of the store and should be re-derived on fork)+// - the store-level EgressAllowlist (same reason)//-// 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 {+// Only the store NAME is kept on the persisted config; forks re-resolve fresh.+func cfgForPersistence(cfg types.SandboxConfig) types.SandboxConfig {+ if len(cfg.SecretEnvs) > 0 && len(cfg.SecretAllowedHosts) > 0 {+ stripped := make(map[string][]string, len(cfg.SecretAllowedHosts))+ for k, v := range cfg.SecretAllowedHosts {+ if _, isSecret := cfg.SecretEnvs[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.SecretAllowedHosts = stripped}}cfg.EgressAllowlist = nil@@ -371,7 +360,7 @@ func flattenSecretAllowedHosts(m map[string][]string) map[string]string {}// 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, secretEnvKeys map[string]struct{}) error {+func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg types.SandboxConfig, orgID [16]byte, hasOrg bool) error {// Select region (explicit header, or default to server's region)region := c.Request().Header.Get("Fly-Region")if region == "" {@@ -429,6 +418,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyTemplateWorkspaceKey: templateWorkspaceKey,EgressAllowlist: cfg.EgressAllowlist,SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),+ SecretEnvs: cfg.SecretEnvs,})if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{@@ -484,7 +474,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyif template == "" {template = "default"}- cfgJSON, _ := json.Marshal(cfgForPersistence(cfg, secretEnvKeys))+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))metadataJSON, _ := json.Marshal(cfg.Metadata)_, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)if templateID != nil {@@ -1533,7 +1523,14 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {// createFromCheckpoint creates a new sandbox from an existing checkpoint (fork).func (s *Server) createFromCheckpoint(c echo.Context) error {- result, httpStatus, err := s.createFromCheckpointCore(c)+ // Direct route (POST /sandboxes/from-checkpoint/:checkpointId): only the+ // envs override is currently supported on the fork path; everything else+ // is inherited from the checkpoint's stored config.+ var body struct {+ Envs map[string]string `json:"envs"`+ }+ _ = c.Bind(&body)+ result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs)if err != nil {return c.JSON(httpStatus, map[string]string{"error": err.Error()})}@@ -1548,7 +1545,10 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {// 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) {+// userEnvs (may be nil) overrides the envs from the checkpoint's stored config.+// User keys win over keys re-resolved from the inherited secret store, matching+// the precedence used on the fresh-create path in resolveSecretStoreInto.+func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string) (map[string]interface{}, int, error) {checkpointIDStr := c.Param("checkpointId")ctx := c.Request().Context()@@ -1616,17 +1616,27 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{// 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{}+ // Resolved values land in originalCfg.SecretEnvs; originalCfg.Envs is+ // untouched, so the user-envs merge below cannot collide with them in a+ // way that smuggles secrets to the guest as plaintext.if originalCfg.SecretStore != "" {- var err error- secretEnvKeys, err = s.resolveSecretStoreInto(ctx, orgID, &originalCfg)- if err != nil {+ if err := s.resolveSecretStoreInto(ctx, orgID, &originalCfg); err != nil {return nil, http.StatusBadRequest, err}}+ // Merge user-supplied envs over the checkpoint's envs. User keys win.+ // Without this merge, Sandbox.create({snapshot, envs}) silently dropped+ // user envs because only originalCfg flowed down to the worker.+ if len(userEnvs) > 0 {+ if originalCfg.Envs == nil {+ originalCfg.Envs = make(map[string]string, len(userEnvs))+ }+ for k, v := range userEnvs {+ originalCfg.Envs[k] = v+ }+ }+timeout := req.Timeoutif timeout <= 0 {timeout = originalCfg.Timeout@@ -1688,7 +1698,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{if template == "" {template = "default"}- cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg, secretEnvKeys))+ cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg))metadataJSON, _ := json.Marshal(originalCfg.Metadata)_, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, nil, template, region, workerID, cfgJSON, metadataJSON)// Track checkpoint lineage for patch system@@ -1718,6 +1728,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{SandboxId: sandboxID,EgressAllowlist: originalCfg.EgressAllowlist,SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),+ SecretEnvs: originalCfg.SecretEnvs,})} else {// Combined mode: create locally — no external timeout, same reasoning as abovediff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex d640f929..c2ebf1ce 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -72,7 +72,7 @@ type SecretsProxyIntegration interface {// CreateSealedEnvs generates sealed tokens for env vars, registers a proxy session,// and returns the full env map (sealed tokens + proxy config vars) to inject into the VM.// secretAllowedHosts maps env var name → allowed hosts for that secret (nil = all allowed hosts).- CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string+ CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, plaintextEnvs, secretEnvs map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string// UnregisterSession removes the proxy session for the given guest IP.UnregisterSession(guestIP string)// GetSessionTokens returns the sealed token → real value map for persisting during hibernate.@@ -447,8 +447,11 @@ func (m *Manager) createWithID(ctx context.Context, id string, cfg types.Sandbox// Sealed tokens replace real values inside the VM — the MITM proxy swaps// them back to real values on outbound HTTPS requests.envsToInject := cfg.Envs- if m.secretsProxy != nil && len(cfg.Envs) > 0 {- sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)+ if m.secretsProxy != nil && (len(cfg.Envs) > 0 || len(cfg.SecretEnvs) > 0) {+ // Envs are user-supplied plaintext; SecretEnvs originated from a+ // SecretStore and are sealed by the proxy. See the QEMU-side+ // equivalent in internal/qemu/manager.go:sealSandboxEnvs.+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.SecretEnvs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)if sealedEnvs != nil {envsToInject = sealedEnvs// Redirect VM HTTPS traffic through the proxydiff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex d8504b06..91fac014 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -73,9 +73,12 @@ type SandboxMeta struct {// SecretsProxyIntegration provides the interface for the secrets proxy to integrate// with VM lifecycle.type SecretsProxyIntegration interface {- // CreateSealedEnvs generates sealed tokens for env vars, registers a proxy session,- // and returns the full env map (sealed tokens + proxy config vars) to inject into the VM.- CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string+ // CreateSealedEnvs tokenizes every entry in secretEnvs, copies plaintextEnvs+ // through verbatim, and returns the full env map to inject into the VM+ // (sealed + plaintext + proxy config vars HTTP_PROXY/CA cert). plaintextEnvs+ // wins on collision (matches the API-layer rule that user envs override+ // store-derived values of the same name).+ CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, plaintextEnvs, secretEnvs map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string// UnregisterSession removes the proxy session for the given guest IP.UnregisterSession(guestIP string)// GetSessionTokens returns the sealed token → real value map for persisting during hibernate.@@ -215,10 +218,26 @@ func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {// 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 {+ // If the secrets proxy is not configured, just merge the two maps with+ // user (Envs) winning. This keeps non-prod environments working without+ // the proxy registered while preserving the user-wins precedence rule.+ if m.secretsProxy == nil {+ if len(cfg.SecretEnvs) == 0 {+ return cfg.Envs+ }+ merged := make(map[string]string, len(cfg.Envs)+len(cfg.SecretEnvs))+ for k, v := range cfg.SecretEnvs {+ merged[k] = v+ }+ for k, v := range cfg.Envs {+ merged[k] = v+ }+ return merged+ }+ if len(cfg.Envs) == 0 && len(cfg.SecretEnvs) == 0 {return cfg.Envs}- sealed := m.secretsProxy.CreateSealedEnvs(sandboxID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)+ sealed := m.secretsProxy.CreateSealedEnvs(sandboxID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.SecretEnvs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)if sealed == nil {return cfg.Envs}diff --git a/internal/secretsproxy/proxy.go b/internal/secretsproxy/proxy.goindex 37906f54..652f86bb 100644--- a/internal/secretsproxy/proxy.go+++ b/internal/secretsproxy/proxy.go@@ -202,15 +202,25 @@ func (p *SecretsProxy) ReregisterSession(sandboxID, guestIP string, tokens map[s//// allowlist controls which hosts the sandbox can reach (nil = all).// secretAllowedHosts maps env var name → allowed hosts for that secret (nil = all allowed hosts).-func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string {- if len(envVars) == 0 {+func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, plaintextEnvs, secretEnvs map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string {+ if len(plaintextEnvs) == 0 && len(secretEnvs) == 0 {return nil}- sealed := make(map[string]string, len(envVars)) // envVar → token- tokenMap := make(map[string]string, len(envVars)) // token → real value-- for envVar, realValue := range envVars {+ // Tokenize every entry in secretEnvs. plaintextEnvs entries are forwarded+ // as-is — they were either supplied by the user directly to the API or+ // originated outside any SecretStore, so sealing them would silently break+ // non-HTTP usage (echo $VAR, file writes, subprocess env) without adding+ // any protection.+ sealed := make(map[string]string, len(secretEnvs)) // envVar → token+ tokenMap := make(map[string]string, len(secretEnvs)) // token → real value+ for envVar, realValue := range secretEnvs {+ // User-supplied envs win on collision: if the same name appears in+ // both maps the plaintext value is the one the caller asked for, so+ // don't seal it. The merge below will copy the plaintext through.+ if _, userSet := plaintextEnvs[envVar]; userSet {+ continue+ }token := "osb_sealed_" + randomHex(16)sealed[envVar] = tokentokenMap[token] = realValue@@ -227,21 +237,27 @@ func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, en}}- p.RegisterSession(guestIP, &Session{- SandboxID: sandboxID,- Secrets: tokenMap,- TokenHosts: tokenHosts,- Allowlist: allowlist,- })+ // Only register a proxy session if there's actually something to substitute.+ if len(tokenMap) > 0 {+ p.RegisterSession(guestIP, &Session{+ SandboxID: sandboxID,+ Secrets: tokenMap,+ TokenHosts: tokenHosts,+ Allowlist: allowlist,+ })+ }- // Build the complete env map for the VM+ // Merge into the env map for the VM. plaintextEnvs win on collision.proxyURL := fmt.Sprintf("http://%s:3128", gatewayIP)caCertPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"noProxy := "localhost,127.0.0.1,::1"- result := make(map[string]string, len(sealed)+9)- for k, v := range sealed {+ result := make(map[string]string, len(plaintextEnvs)+len(sealed)+9)+ for k, token := range sealed {+ result[k] = token+ }+ for k, v := range plaintextEnvs {result[k] = v}result["HTTP_PROXY"] = proxyURLdiff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex aaee04e5..5e85f69b 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -134,6 +134,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqCheckpointID: req.CheckpointId, // for per-template golden snapshotsEgressAllowlist: req.EgressAllowlist,SecretAllowedHosts: parseSecretAllowedHosts(req.SecretAllowedHosts),+ SecretEnvs: req.SecretEnvs,}// Warm fork: if checkpoint_id is set, fork from the local checkpoint cache.diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex ff4c3d14..d0bd6cbe 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -75,6 +75,13 @@ type SandboxConfig struct {// CheckpointID is the source checkpoint for template/snapshot creates.// Used by the worker to key per-template golden snapshots.CheckpointID string `json:"-"`+ // SecretEnvs holds env vars resolved from a SecretStore. Carrying them in+ // a separate field (rather than mixing them into Envs) preserves their+ // provenance end-to-end: the worker's secrets proxy seals exactly these+ // entries and passes everything in Envs through as plaintext. Never+ // persisted (json:"-") and never set directly by the SDK — populated by+ // the API layer in resolveSecretStoreInto and re-derived on every fork.+ SecretEnvs map[string]string `json:"-"`}// ResourceTier defines an allowed memory/CPU combination.diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex 973d0dee..86bc6fa4 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go. DO NOT EDIT.// versions:// protoc-gen-go v1.36.11-// protoc v6.33.4+// protoc v7.34.0// source: proto/worker/worker.protopackage worker@@ -88,8 +88,11 @@ type CreateSandboxRequest struct {EgressAllowlist []string `protobuf:"bytes,13,rep,name=egress_allowlist,json=egressAllowlist,proto3" json:"egress_allowlist,omitempty"`// Per-secret host restrictions for secrets proxy.SecretAllowedHosts map[string]string `protobuf:"bytes,14,rep,name=secret_allowed_hosts,json=secretAllowedHosts,proto3" json:"secret_allowed_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Env vars resolved from a SecretStore. Sealed by the worker's secrets proxy+ // before injection into the VM. Disjoint from `envs` (which is plaintext).+ SecretEnvs map[string]string `protobuf:"bytes,15,rep,name=secret_envs,json=secretEnvs,proto3" json:"secret_envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *CreateSandboxRequest) Reset() {@@ -220,6 +223,13 @@ func (x *CreateSandboxRequest) GetSecretAllowedHosts() map[string]string {return nil}+func (x *CreateSandboxRequest) GetSecretEnvs() map[string]string {+ if x != nil {+ return x.SecretEnvs+ }+ return nil+}+type CreateSandboxResponse struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -3027,7 +3037,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptorconst file_proto_worker_worker_proto_rawDesc = "" +"\n" +- "\x19proto/worker/worker.proto\x12\x06worker\"\xd9\x05\n" ++ "\x19proto/worker/worker.proto\x12\x06worker\"\xe7\x06\n" +"\x14CreateSandboxRequest\x12\x1a\n" +"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +@@ -3044,12 +3054,17 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\n" +"sandbox_id\x18\f \x01(\tR\tsandboxId\x12)\n" +"\x10egress_allowlist\x18\r \x03(\tR\x0fegressAllowlist\x12f\n" +- "\x14secret_allowed_hosts\x18\x0e \x03(\v24.worker.CreateSandboxRequest.SecretAllowedHostsEntryR\x12secretAllowedHosts\x1a7\n" ++ "\x14secret_allowed_hosts\x18\x0e \x03(\v24.worker.CreateSandboxRequest.SecretAllowedHostsEntryR\x12secretAllowedHosts\x12M\n" ++ "\vsecret_envs\x18\x0f \x03(\v2,.worker.CreateSandboxRequest.SecretEnvsEntryR\n" ++ "secretEnvs\x1a7\n" +"\tEnvsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aE\n" +"\x17SecretAllowedHostsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a=\n" ++ "\x0fSecretEnvsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +"\x15CreateSandboxResponse\x12\x1d\n" +"\n" +@@ -3313,7 +3328,7 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {}var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 56)+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 57)var file_proto_worker_worker_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest@@ -3370,74 +3385,76 @@ var file_proto_worker_worker_proto_goTypes = []any{(*CompleteMigrationIncomingResponse)(nil), // 52: worker.CompleteMigrationIncomingResponsenil, // 53: worker.CreateSandboxRequest.EnvsEntrynil, // 54: worker.CreateSandboxRequest.SecretAllowedHostsEntry- nil, // 55: worker.ExecCommandRequest.EnvsEntry- nil, // 56: worker.ExecSessionCreateRequest.EnvsEntry+ nil, // 55: worker.CreateSandboxRequest.SecretEnvsEntry+ nil, // 56: worker.ExecCommandRequest.EnvsEntry+ nil, // 57: worker.ExecSessionCreateRequest.EnvsEntry}var file_proto_worker_worker_proto_depIdxs = []int32{53, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry54, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry- 6, // 2: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 55, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry- 0, // 4: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream- 17, // 5: worker.ListDirResponse.entries:type_name -> worker.DirEntry- 22, // 6: worker.PTYInput.resize:type_name -> worker.PTYResize- 56, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry- 36, // 8: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry- 1, // 9: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest- 3, // 10: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest- 5, // 11: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest- 7, // 12: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest- 9, // 13: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest- 9, // 14: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest- 12, // 15: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest- 14, // 16: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest- 16, // 17: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest- 19, // 18: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest- 21, // 19: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput- 32, // 20: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest- 34, // 21: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest- 37, // 22: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest- 24, // 23: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest- 26, // 24: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest- 28, // 25: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest- 41, // 26: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest- 43, // 27: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest- 30, // 28: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest- 39, // 29: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 45, // 30: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest- 47, // 31: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest- 49, // 32: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest- 51, // 33: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest- 2, // 34: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 35: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 36: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 37: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 38: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 39: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 40: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 41: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 42: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 43: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 44: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 33, // 45: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse- 35, // 46: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse- 38, // 47: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse- 25, // 48: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 49: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 50: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse- 42, // 51: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse- 44, // 52: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse- 31, // 53: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 40, // 54: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 46, // 55: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse- 48, // 56: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse- 50, // 57: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse- 52, // 58: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse- 34, // [34:59] is the sub-list for method output_type- 9, // [9:34] is the sub-list for method input_type- 9, // [9:9] is the sub-list for extension type_name- 9, // [9:9] is the sub-list for extension extendee- 0, // [0:9] is the sub-list for field type_name+ 55, // 2: worker.CreateSandboxRequest.secret_envs:type_name -> worker.CreateSandboxRequest.SecretEnvsEntry+ 6, // 3: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse+ 56, // 4: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 0, // 5: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream+ 17, // 6: worker.ListDirResponse.entries:type_name -> worker.DirEntry+ 22, // 7: worker.PTYInput.resize:type_name -> worker.PTYResize+ 57, // 8: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry+ 36, // 9: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry+ 1, // 10: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest+ 3, // 11: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest+ 5, // 12: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest+ 7, // 13: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest+ 9, // 14: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest+ 9, // 15: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest+ 12, // 16: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest+ 14, // 17: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest+ 16, // 18: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest+ 19, // 19: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest+ 21, // 20: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput+ 32, // 21: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest+ 34, // 22: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest+ 37, // 23: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest+ 24, // 24: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest+ 26, // 25: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest+ 28, // 26: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest+ 41, // 27: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest+ 43, // 28: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest+ 30, // 29: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest+ 39, // 30: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest+ 45, // 31: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest+ 47, // 32: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest+ 49, // 33: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest+ 51, // 34: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest+ 2, // 35: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse+ 4, // 36: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse+ 6, // 37: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse+ 8, // 38: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse+ 10, // 39: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse+ 11, // 40: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk+ 13, // 41: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse+ 15, // 42: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse+ 18, // 43: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse+ 20, // 44: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse+ 23, // 45: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput+ 33, // 46: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse+ 35, // 47: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse+ 38, // 48: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse+ 25, // 49: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse+ 27, // 50: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse+ 29, // 51: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse+ 42, // 52: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse+ 44, // 53: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse+ 31, // 54: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse+ 40, // 55: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse+ 46, // 56: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse+ 48, // 57: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse+ 50, // 58: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse+ 52, // 59: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse+ 35, // [35:60] is the sub-list for method output_type+ 10, // [10:35] is the sub-list for method input_type+ 10, // [10:10] is the sub-list for extension type_name+ 10, // [10:10] is the sub-list for extension extendee+ 0, // [0:10] is the sub-list for field type_name}func init() { file_proto_worker_worker_proto_init() }@@ -3455,7 +3472,7 @@ func file_proto_worker_worker_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),NumEnums: 1,- NumMessages: 56,+ NumMessages: 57,NumExtensions: 0,NumServices: 1,},diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex 4eda2233..1254347d 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -64,6 +64,9 @@ message CreateSandboxRequest {repeated string egress_allowlist = 13;// Per-secret host restrictions for secrets proxy.map<string, string> secret_allowed_hosts = 14;+ // Env vars resolved from a SecretStore. Sealed by the worker's secrets proxy+ // before injection into the VM. Disjoint from `envs` (which is plaintext).+ map<string, string> secret_envs = 15;}message CreateSandboxResponse {diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.goindex 8df2045a..7b0eb273 100644--- a/proto/worker/worker_grpc.pb.go+++ b/proto/worker/worker_grpc.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go-grpc. DO NOT EDIT.// versions:// - protoc-gen-go-grpc v1.6.1-// - protoc v6.33.4+// - protoc v7.34.0// source: proto/worker/worker.protopackage workerdiff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.tsindex c59b968d..376c3851 100644--- a/sdks/typescript/examples/run-all-tests.ts+++ b/sdks/typescript/examples/run-all-tests.ts@@ -53,6 +53,7 @@ const SUITES: TestSuite[] = [{ name: "Concurrent", file: "test-concurrent.ts", description: "5 sandboxes in parallel, isolation, parallel ops" },{ name: "Hibernation", file: "test-hibernation-stress.ts", description: "Multi-cycle hibernate/wake, large state, auto-wake" },{ name: "Checkpoints", file: "test-checkpoints.ts", description: "Create, list, restore, fork, delete checkpoints, limits" },+ { name: "Snapshot Envs", file: "test-snapshot-envs.ts", description: "User envs survive snapshot fork as plaintext; secret-store envs stay sealed" },{ name: "Timeout", file: "test-timeout.ts", slow: true, description: "30s timeout, setTimeout(), rolling timeout (takes ~2min)" },];diff --git a/sdks/typescript/examples/test-snapshot-envs.ts b/sdks/typescript/examples/test-snapshot-envs.tsnew file mode 100644index 00000000..8345516c--- /dev/null+++ b/sdks/typescript/examples/test-snapshot-envs.ts@@ -0,0 +1,210 @@+/**+ * Snapshot Envs & Secret-Sealing Test+ *+ * Regression coverage for two bugs that previously interacted around+ * Sandbox.create({ envs }):+ *+ * 1. The snapshot/fork path silently dropped user-supplied envs because+ * createFromCheckpointCore re-bound only `Timeout` from the request body+ * and forwarded `originalCfg.Envs` from the checkpoint instead.+ *+ * 2. Every env var was tokenized into an `osb_sealed_…` value by the+ * secrets proxy regardless of source, so `echo $TEST_VAR` inside the+ * guest returned the sealed token rather than the plaintext the user+ * passed. Sealing should only apply to envs that originated from a+ * SecretStore — those are the ones the MITM proxy needs to swap on+ * outbound HTTPS.+ *+ * What this test asserts:+ * - Plain `Sandbox.create({ envs })` → guest sees plaintext.+ * - `Sandbox.create({ snapshot, envs })` → user envs survive the fork AND+ * reach the guest as plaintext.+ * - `Sandbox.create({ secretStore, envs })` → user-supplied envs are+ * plaintext, store-derived envs are sealed (`osb_sealed_…`).+ *+ * Usage:+ * npx tsx examples/test-snapshot-envs.ts+ */++import { Sandbox, SecretStore } from "../src/index";+import { Snapshots, Image } from "../src/node";++function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }++let passed = 0;+let failed = 0;++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) {+ green(desc);+ passed++;+ } else {+ red(`${desc}${detail ? ` (${detail})` : ""}`);+ failed++;+ }+}++// Unique names so concurrent runs / reruns don't collide.+const RUN_ID = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+const SNAPSHOT_NAME = `test-snapshot-envs-${RUN_ID}`;+const STORE_NAME = `test-snapshot-envs-store-${RUN_ID}`;+const USER_VALUE = "plaintext-from-user";+const SECRET_VALUE = "plaintext-from-store";++async function readVar(sb: Sandbox, name: string): Promise<string> {+ // -n to avoid trailing newline; printenv would also work but echo matches+ // the original repro and is universally available in the base image.+ const out = await sb.commands.run(`echo -n "$${name}"`);+ return out.stdout;+}++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Snapshot Envs & Secret Sealing Test ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ const snapshots = new Snapshots();+ let storeId: string | null = null;+ let createdSnapshot = false;+ const sandboxes: Sandbox[] = [];++ try {+ // ── Test 1: Plain create — user envs reach guest as plaintext ──+ bold("━━━ Test 1: envs without snapshot or secret store ━━━\n");++ const a = await Sandbox.create({ timeout: 60, envs: { TEST_VAR: USER_VALUE } });+ sandboxes.push(a);+ const aVal = await readVar(a, "TEST_VAR");+ dim(`TEST_VAR=${JSON.stringify(aVal)}`);+ check("plain create: user env is plaintext", aVal === USER_VALUE,+ `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(aVal)}`);+ check("plain create: user env is NOT sealed", !aVal.startsWith("osb_sealed_"));+ console.log();++ // ── Test 2: Snapshot fork preserves user envs as plaintext ──+ // Bug #1 regression: this returned "" before the fix because the fork+ // path dropped envs from the request body.+ // Bug #2 regression: even after #1 was fixed it returned an osb_sealed_+ // token because every env was tokenized unconditionally.+ bold("━━━ Test 2: envs survive snapshot fork as plaintext ━━━\n");++ dim(`creating snapshot ${SNAPSHOT_NAME}...`);+ await snapshots.create({ name: SNAPSHOT_NAME, image: Image.base() });+ createdSnapshot = true;++ const b = await Sandbox.create({+ snapshot: SNAPSHOT_NAME,+ timeout: 60,+ envs: { TEST_VAR: USER_VALUE },+ });+ sandboxes.push(b);+ const bVal = await readVar(b, "TEST_VAR");+ dim(`TEST_VAR=${JSON.stringify(bVal)}`);+ check("snapshot fork: user env survives the fork", bVal.length > 0,+ "got empty string — bug #1 (createFromCheckpointCore drops req body)");+ check("snapshot fork: user env is NOT sealed", !bVal.startsWith("osb_sealed_"),+ "bug #2 (CreateSealedEnvs tokenizes every env)");+ check("snapshot fork: user env equals plaintext", bVal === USER_VALUE,+ `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(bVal)}`);+ console.log();++ // ── Test 3: Secret store envs are still sealed; user envs are not ──+ // Selective sealing: passing both a SecretStore *and* explicit envs in+ // the same create should produce mixed plaintext/sealed values.+ bold("━━━ Test 3: secret store envs sealed, user envs plaintext ━━━\n");++ const store = await SecretStore.create({ name: STORE_NAME });+ storeId = store.id;+ await SecretStore.setSecret(storeId, "STORE_VAR", SECRET_VALUE);++ const c = await Sandbox.create({+ timeout: 60,+ secretStore: STORE_NAME,+ envs: { USER_VAR: USER_VALUE },+ });+ sandboxes.push(c);+ const userVal = await readVar(c, "USER_VAR");+ const storeVal = await readVar(c, "STORE_VAR");+ dim(`USER_VAR=${JSON.stringify(userVal)}`);+ dim(`STORE_VAR=${JSON.stringify(storeVal)}`);+ check("mixed: user env is plaintext", userVal === USER_VALUE,+ `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(userVal)}`);+ check("mixed: user env is NOT sealed", !userVal.startsWith("osb_sealed_"));+ check("mixed: store env IS sealed", storeVal.startsWith("osb_sealed_"),+ `store-derived env should be tokenized by secrets proxy, got ${JSON.stringify(storeVal)}`);+ console.log();++ // ── Test 4: secretStore + snapshot must NOT silently leak secrets ──+ // Regression guard. The combination used to silently drop the user's+ // secret store on fork; the bug-#1 fix turned that silent drop into a+ // silent plaintext leak (the parent handler eagerly resolved the store+ // into cfg.Envs, which the fix then merged into the fork — but the+ // seal-set is computed from the snapshot's *original* store, so the+ // smuggled values reached the guest unsealed).+ //+ // The supported semantics are: a fork inherits the snapshot's secret+ // store and cannot override it. The API must reject the combination+ // explicitly so users can't trip the leak by accident.+ bold("━━━ Test 4: secretStore + snapshot is rejected (no leak) ━━━\n");++ let rejected = false;+ let leaked = false;+ let leakedValue = "";+ let d: Sandbox | null = null;+ try {+ d = await Sandbox.create({+ snapshot: SNAPSHOT_NAME,+ timeout: 60,+ secretStore: STORE_NAME,+ });+ // Reached this point: API accepted the combo. Verify it didn't leak.+ sandboxes.push(d);+ leakedValue = await readVar(d, "STORE_VAR");+ leaked = leakedValue === SECRET_VALUE;+ } catch (err: any) {+ rejected = true;+ dim(`API rejected combo: ${err.message}`);+ }+ check(+ "secretStore + snapshot is rejected at the API edge",+ rejected,+ leaked+ ? `LEAK: STORE_VAR reached the guest as plaintext (${JSON.stringify(leakedValue)})`+ : "API accepted the combo without leaking, but the supported contract is rejection",+ );+ check(+ "secretStore + snapshot does not leak plaintext into the guest",+ !leaked,+ `STORE_VAR=${JSON.stringify(leakedValue)} — secret-store value reached the guest unsealed`,+ );+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ for (const sb of sandboxes) {+ await sb.kill().catch(() => {});+ }+ if (createdSnapshot) {+ await snapshots.delete(SNAPSHOT_NAME).catch(() => {});+ }+ if (storeId) {+ await SecretStore.delete(storeId).catch(() => {});+ }+ }++ bold("========================================");+ bold(` Results: ${passed} passed, ${failed} failed`);+ bold("========================================\n");+ if (failed > 0) process.exit(1);+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});