Skip to content

An open-source, faster Devin alternative

TypeScript

Infisical bridge + AWS SM backend + edge-routed preview URLs

Brian Reardon8ba70474cc06
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 5418b444..67e9d462 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -231,6 +231,74 @@ async function pickCell(
return healthy[0] ?? null;
}
+// ── preview URL dispatch ─────────────────────────────────────────────────
+
+// parsePreviewHost detects whether the request's hostname is a sandbox
+// preview URL of the form `sb-{id}-p{port}.{anything}` and pulls out the
+// sandbox_id + port. Returns null for anything else (the request falls
+// through to the regular /api routes / /health / etc).
+//
+// The sandbox_id itself may contain hyphens (it's "sb-" + 8 hex chars in
+// practice, but we don't lock the format here — only the trailing -p<port>
+// shape matters), so the regex anchors `-p<digits>` at the END of the first
+// subdomain label and grabs everything before it as the id.
+function parsePreviewHost(hostname: string): { sandboxID: string; port: number } | null {
+ const firstLabel = hostname.split(".", 1)[0];
+ if (!firstLabel.startsWith("sb-")) return null;
+ const m = firstLabel.match(/^(sb-.+)-p(\d+)$/);
+ if (!m) return null;
+ const port = Number.parseInt(m[2], 10);
+ if (!Number.isFinite(port) || port < 1 || port > 65535) return null;
+ return { sandboxID: m[1], port };
+}
+
+// handlePreviewURL is the edge-routed equivalent of the cell-local
+// ControlPlaneProxy.Middleware: resolve the sandbox to its owning cell via
+// D1, then forward the request through that cell's Tunnel to its CP's
+// /internal/preview/{id}/{port}/* route. The CP synthesizes the Host
+// header the worker's SandboxProxy expects, then routes to the worker.
+//
+// Cross-cell migration becomes invisible from this design — moving a
+// sandbox from cell A to cell B updates sandboxes_index.cell_id, and the
+// next request resolves to the new cell. No DNS or hostname changes.
+async function handlePreviewURL(
+ req: Request,
+ env: Env,
+ m: { sandboxID: string; port: number },
+): Promise<Response> {
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT s.cell_id, s.status, c.base_url
+ FROM sandboxes_index s
+ JOIN cells c ON s.cell_id = c.cell_id
+ WHERE s.id = ?1`,
+ )
+ .bind(m.sandboxID)
+ .first<{ cell_id: string; status: string; base_url: string }>();
+
+ if (!row) return new Response(`sandbox ${m.sandboxID} not found`, { status: 404 });
+ if (row.status === "stopped" || row.status === "error") {
+ return new Response(`sandbox ${m.sandboxID} is ${row.status}`, { status: 410 });
+ }
+ // status="hibernated" is fine — CP's doProxy will wake-on-request.
+
+ const url = new URL(req.url);
+ const base = row.base_url.replace(/\/$/, "");
+ const target = `${base}/internal/preview/${m.sandboxID}/${m.port}${url.pathname}${url.search}`;
+
+ try {
+ // Forward the request as-is via the Request copy-constructor — preserves
+ // method, body (including streamed/large bodies), headers, AND the
+ // Upgrade: websocket handshake. Cloudflare's fetch propagates WebSocket
+ // pairs transparently when both ends speak it.
+ return await fetch(new Request(target, req));
+ } catch (e) {
+ return new Response(
+ `cell ${row.cell_id} unreachable: ${(e as Error).message}`,
+ { status: 502 },
+ );
+ }
+}
+
// ── route handlers ───────────────────────────────────────────────────────
async function createSandbox(req: Request, env: Env): Promise<Response> {
@@ -355,6 +423,14 @@ export default {
const url = new URL(req.url);
const path = url.pathname;
+ // Sandbox preview URL dispatch — matched by HOSTNAME, not path. Has to
+ // run before the path-based routes below so that a sandbox app serving
+ // its own /health or /api/* doesn't get shadowed by ours.
+ const preview = parsePreviewHost(url.hostname);
+ if (preview) {
+ return handlePreviewURL(req, env, preview);
+ }
+
if (path === "/health") {
return json({ ok: true, env: env.WORKER_ENV, cells: env.CELLS.split(",") });
}
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 9ad975c2..975bbb9d 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -15,10 +15,29 @@ compatibility_date = "2026-04-28"
compatibility_flags = ["nodejs_compat"]
account_id = "1241f114453e32d292197e3fb36210b2"
-# Route the Worker at app.dev.opensandbox.ai once the zone goes live.
-# Until then, accessible at opensandbox-edge-dev.brian-124.workers.dev.
+# Routes (production binding — left off until cert strategy is settled):
+#
+# Sandbox preview URLs match by hostname (sb-{id}-p{port}.<host>) in Worker
+# code regardless of how the request reaches us, so the smoke test works
+# today via Host-header override against the workers.dev URL. For real
+# public traffic, we need a route binding + matching wildcard DNS + cert.
+#
+# CF Workers routes only allow `*` at the START of the hostname, so
+# `sb-*.opensandbox.ai/*` is invalid. Options for production:
+# (a) "*.opensandbox.ai/*" with code that 404s non-sb-prefix hosts —
+# would also intercept cp-dev2.opensandbox.ai (the tunnels), which
+# breaks the edge→cell path. Don't do this.
+# (b) Dedicated subdomain "*.sb.opensandbox.ai/*" — clean separation
+# from cp-*, app, events. But two-level wildcard isn't covered by
+# Cloudflare Universal SSL — needs Advanced Certificate Manager
+# (~$10/mo) OR a self-uploaded wildcard cert.
+# (c) Separate zone for previews (e.g. opensandbox.run) — clean but
+# requires owning + provisioning another domain.
+#
+# Recommended end state: option (b) with Advanced Cert Manager. Until then
+# preview URLs work through code, not DNS — fine for dev validation.
# routes = [
-# { pattern = "app.dev.opensandbox.ai/*", zone_name = "opensandbox.ai" }
+# { pattern = "*.sb.opensandbox.ai/*", zone_name = "opensandbox.ai" },
# ]
[[d1_databases]]
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 435eb8c3..2b52bb66 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -30,10 +30,17 @@ import (
var ServerVersion = "dev"
func main() {
- // Load secrets from Azure Key Vault if configured (before config.Load reads env vars).
+ // Load secrets from the appropriate cloud vault (before config.Load reads
+ // env vars). Each loader is a no-op if its env trigger is unset:
+ // SECRETS_VAULT_NAME → Azure Key Vault (Azure cells)
+ // OPENSANDBOX_SECRETS_ARN → AWS Secrets Manager (AWS cells)
+ // One or the other should be set at a time; neither = env file authoritative.
if err := config.LoadSecretsFromKeyVault(); err != nil {
log.Fatalf("failed to load secrets from Key Vault: %v", err)
}
+ if err := config.LoadSecretsFromSecretsManager(); err != nil {
+ log.Fatalf("failed to load secrets from Secrets Manager: %v", err)
+ }
cfg, err := config.Load()
if err != nil {
diff --git a/cmd/worker/golden_upload.go b/cmd/worker/golden_upload.go
index 3a742cd0..636a2179 100644
--- a/cmd/worker/golden_upload.go
+++ b/cmd/worker/golden_upload.go
@@ -30,13 +30,15 @@ import (
// Reads OPENSANDBOX_GLOBAL_BLOB_* env vars for endpoint + creds. Fails loud
// if blobstore isn't configured.
func uploadGolden(path string) error {
- // Bootstrap from KV the same way the main worker does — so this
- // subcommand picks up worker-global-blob-* secrets when run on a
- // host whose worker.env points at a KV. Without this, the user
- // would have to manually export every Tigris env var inline.
+ // Bootstrap from the appropriate cloud vault — same pattern as main(). One
+ // of these picks up worker-global-blob-* secrets so the upload knows where
+ // to push; the other is a no-op when its trigger env var isn't set.
if err := config.LoadSecretsFromKeyVault(); err != nil {
return fmt.Errorf("keyvault bootstrap: %w", err)
}
+ if err := config.LoadSecretsFromSecretsManager(); err != nil {
+ return fmt.Errorf("secretsmanager bootstrap: %w", err)
+ }
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("config load: %w", err)
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index a0e8971e..fe8e8fcc 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -76,10 +76,17 @@ func main() {
return
}
- // Load secrets from Azure Key Vault if configured (before config.Load reads env vars).
+ // Load secrets from the appropriate cloud vault (before config.Load reads
+ // env vars). Each loader is a no-op if its env trigger is unset:
+ // SECRETS_VAULT_NAME → Azure Key Vault (Azure cells)
+ // OPENSANDBOX_SECRETS_ARN → AWS Secrets Manager (AWS cells)
+ // One or the other should be set at a time; neither = env file authoritative.
if err := config.LoadSecretsFromKeyVault(); err != nil {
log.Fatalf("failed to load secrets from Key Vault: %v", err)
}
+ if err := config.LoadSecretsFromSecretsManager(); err != nil {
+ log.Fatalf("failed to load secrets from Secrets Manager: %v", err)
+ }
cfg, err := config.Load()
if err != nil {
diff --git a/deploy/aws/create-aws-dev3.sh b/deploy/aws/create-aws-dev3.sh
index c1c12ec2..89bf6e19 100755
--- a/deploy/aws/create-aws-dev3.sh
+++ b/deploy/aws/create-aws-dev3.sh
@@ -178,6 +178,45 @@ cmd_create() {
$([ "$REGION" != "us-east-1" ] && echo "--create-bucket-configuration LocationConstraint=$REGION") >/dev/null
save_state "BUCKET" "$BUCKET"
+ # ── IAM role + instance profile for EC2 (reads SM + writes checkpoint S3) ──
+ # The role lets dev3 VMs pull bootstrap secrets from AWS Secrets Manager via
+ # the default credential chain (no static keys on the VM), and write
+ # checkpoints to their cell's S3 bucket. Idempotent — create-role fails
+ # gracefully if it already exists from a prior run.
+ ROLE_NAME="opensandbox-dev3-reader"
+ log "Creating IAM role $ROLE_NAME + instance profile..."
+ aws iam create-role --role-name "$ROLE_NAME" --assume-role-policy-document "$(cat <<'TRUST'
+{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}
+TRUST
+)" >/dev/null 2>&1 || true
+ aws iam put-role-policy --role-name "$ROLE_NAME" --policy-name ReadSecrets --policy-document "$(cat <<'P1'
+{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["secretsmanager:GetSecretValue","secretsmanager:BatchGetSecretValue","secretsmanager:DescribeSecret","secretsmanager:ListSecrets"],"Resource":"*"}]}
+P1
+)" >/dev/null
+ aws iam put-role-policy --role-name "$ROLE_NAME" --policy-name CheckpointBucket --policy-document "$(cat <<EOF
+{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":"arn:aws:s3:::${BUCKET}"},{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:HeadObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":"arn:aws:s3:::${BUCKET}/*"}]}
+EOF
+)" >/dev/null
+ aws iam create-instance-profile --instance-profile-name "$ROLE_NAME" >/dev/null 2>&1 || true
+ aws iam add-role-to-instance-profile --instance-profile-name "$ROLE_NAME" --role-name "$ROLE_NAME" >/dev/null 2>&1 || true
+ save_state "ROLE_NAME" "$ROLE_NAME"
+
+ # ── AWS Secrets Manager: pre-create the cell's secrets so Infisical sync
+ # has a target. The actual values land via Infisical → AWS sync; this just
+ # provisions empty placeholders + an IAM user for Infisical to write with.
+ # NB: Infisical's AWS SM sync creates one SM secret per Infisical secret
+ # (per-key mode), so we don't pre-create individual entries — Infisical
+ # does that. We only create the IAM user it needs.
+ INF_IAM_USER="infisical-secret-sync-dev"
+ log "Creating IAM user $INF_IAM_USER for Infisical → SM sync..."
+ aws iam create-user --user-name "$INF_IAM_USER" >/dev/null 2>&1 || true
+ aws iam put-user-policy --user-name "$INF_IAM_USER" --policy-name InfisicalSecretSync --policy-document "$(cat <<'P2'
+{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["secretsmanager:DescribeSecret","secretsmanager:GetSecretValue","secretsmanager:BatchGetSecretValue","secretsmanager:PutSecretValue","secretsmanager:UpdateSecret","secretsmanager:CreateSecret","secretsmanager:DeleteSecret","secretsmanager:RestoreSecret","secretsmanager:TagResource","secretsmanager:UntagResource","secretsmanager:ListSecrets","secretsmanager:ListSecretVersionIds"],"Resource":"*"}]}
+P2
+)" >/dev/null
+ log " → if this is the first cell using Infisical, create an access key for $INF_IAM_USER"
+ log " via the AWS Console and paste it into Infisical's AWS App Connection."
+
# ── Control Plane EC2 ──
log "Launching control plane ($CP_TYPE)..."
CP_USERDATA=$(cat <<'CPUD'
@@ -195,6 +234,7 @@ CPUD
--key-name "$NAME_PREFIX" --subnet-id "$SUBNET_ID" \
--security-group-ids "$SG_CP" \
--associate-public-ip-address \
+ --iam-instance-profile "Name=$ROLE_NAME" \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$CP_NAME},{Key=opensandbox:role,Value=controlplane}]" \
--user-data "$CP_USERDATA" \
--query 'Instances[0].InstanceId' --output text)
@@ -216,6 +256,7 @@ CPUD
--key-name "$NAME_PREFIX" --subnet-id "$SUBNET_ID" \
--security-group-ids "$SG_WK" \
--associate-public-ip-address \
+ --iam-instance-profile "Name=$ROLE_NAME" \
--block-device-mappings "DeviceName=/dev/sdb,Ebs={VolumeSize=$WK_DATA_GB,VolumeType=gp3,DeleteOnTermination=true}" \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$WK_NAME},{Key=opensandbox:role,Value=worker}]" \
--query 'Instances[0].InstanceId' --output text)
@@ -295,27 +336,76 @@ fi
sudo bash /tmp/setup-host.sh
WKSETUP
- # ── Env files ──
- log "Writing environment files..."
+ # ── Push cell config + secrets to Infisical ──
+ # Infisical is the single source of truth; its AWS Secrets Manager sync
+ # propagates each entry to a per-key SM secret which the EC2 IAM role
+ # above reads at boot. See create-azure-dev2.sh for the full prerequisite
+ # list — same model, different cloud.
+ if [ -z "${INFISICAL_TOKEN:-}" ]; then
+ err "INFISICAL_TOKEN not set — can't seed Infisical. Export it and re-run,"
+ err "or push these secrets manually after the fact."
+ exit 1
+ fi
+ INF_PROJ="${INFISICAL_PROJECT_ID:-6f7fb48e-90bb-4fac-b9a2-c55f06ed00e7}"
+ INF_ENV="${INFISICAL_ENV:-dev}"
+ log "Seeding Infisical project=$INF_PROJ env=$INF_ENV (AWS SM sync will fan out per key)..."
+ inf() { infisical secrets set --projectId="$INF_PROJ" --env="$INF_ENV" --path="$1" --silent "$2=$3" >/dev/null; }
+
+ CELL="/cells/$CELL_ID"
+ inf "$CELL" server-database-url "postgres://opensandbox:$PG_PASSWORD@localhost:5432/opensandbox?sslmode=disable"
+ inf "$CELL" server-redis-url "redis://localhost:6379"
+ inf "$CELL" server-region "$REGION"
+ inf "$CELL" server-sandbox-domain "$DOMAIN"
+ inf "$CELL" server-cell-id "$CELL_ID"
+ inf "$CELL" worker-database-url "postgres://opensandbox:$PG_PASSWORD@$CP_PRIVATE_IP:5432/opensandbox?sslmode=disable"
+ inf "$CELL" worker-redis-url "redis://$CP_PRIVATE_IP:6379"
+ inf "$CELL" worker-region "$REGION"
+ inf "$CELL" worker-cell-id "$CELL_ID"
+ inf "$CELL" worker-sandbox-domain "$DOMAIN"
+ inf "$CELL" worker-max-capacity "10"
+ inf "$CELL" worker-default-sandbox-memory-mb "1024"
+ inf "$CELL" worker-default-sandbox-cpus "2"
+ inf "$CELL" worker-s3-bucket "$BUCKET"
+ inf "$CELL" worker-s3-region "$REGION"
+ inf "$CELL" pg-password "$PG_PASSWORD"
+ # No worker-s3-access-key/secret-key — AWS workers use the EC2 IAM role
+ # for S3 (the CheckpointBucket policy above), so the AWS SDK falls back
+ # to instance creds when env keys are empty.
+
+ if [ "${SEED_SHARED:-0}" = "1" ]; then
+ log " also seeding /shared (SEED_SHARED=1)..."
+ inf "/shared" server-jwt-secret "$JWT_SECRET"
+ inf "/shared" worker-jwt-secret "$JWT_SECRET"
+ inf "/shared" server-api-key "$API_KEY"
+ inf "/shared" server-cf-event-endpoint "$CF_EVENT_ENDPOINT"
+ inf "/shared" worker-cf-event-endpoint "$CF_EVENT_ENDPOINT"
+ inf "/shared" server-cf-event-secret "$CF_EVENT_SECRET"
+ inf "/shared" worker-cf-event-secret "$CF_EVENT_SECRET"
+ inf "/shared" server-cf-admin-secret "$CF_ADMIN_SECRET"
+ inf "/shared" worker-cf-admin-secret "$CF_ADMIN_SECRET"
+ inf "/shared" server-session-jwt-secret "$SESSION_JWT_SECRET"
+ inf "/shared" worker-session-jwt-secret "$SESSION_JWT_SECRET"
+ fi
+
+ # ── Write bootstrap env files ──
+ # OPENSANDBOX_SECRETS_AWS_REGION triggers per-key SM bootstrap in Go
+ # (internal/config/secretsmanager.go). AWS_REGION is the standard SDK var
+ # so the IAM role's default credential chain works without extra config.
+ log "Writing bootstrap env files..."
ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" "sudo tee /etc/opensandbox/server.env > /dev/null" <<CPENV
+# Bootstrap-only — secrets + cell config live in AWS Secrets Manager (synced from Infisical).
OPENSANDBOX_MODE=server
+OPENSANDBOX_SECRETS_AWS_REGION=$REGION
+AWS_REGION=$REGION
OPENSANDBOX_PORT=8080
-OPENSANDBOX_DATABASE_URL=postgres://opensandbox:$PG_PASSWORD@localhost:5432/opensandbox?sslmode=disable
-OPENSANDBOX_REDIS_URL=redis://localhost:6379
-OPENSANDBOX_JWT_SECRET=$JWT_SECRET
-OPENSANDBOX_API_KEY=$API_KEY
-OPENSANDBOX_REGION=$REGION
-OPENSANDBOX_SANDBOX_DOMAIN=$DOMAIN
-OPENSANDBOX_CELL_ID=$CELL_ID
-OPENSANDBOX_CF_EVENT_ENDPOINT=$CF_EVENT_ENDPOINT
-OPENSANDBOX_CF_EVENT_SECRET=$CF_EVENT_SECRET
-OPENSANDBOX_CF_ADMIN_SECRET=$CF_ADMIN_SECRET
-OPENSANDBOX_SESSION_JWT_SECRET=$SESSION_JWT_SECRET
OPENSANDBOX_COMPUTE_PROVIDER=aws
CPENV
ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" "sudo tee /etc/opensandbox/worker.env > /dev/null" <<WKENV
+# Bootstrap-only — secrets + cell config live in AWS Secrets Manager (synced from Infisical).
OPENSANDBOX_MODE=worker
+OPENSANDBOX_SECRETS_AWS_REGION=$REGION
+AWS_REGION=$REGION
OPENSANDBOX_VM_BACKEND=qemu
OPENSANDBOX_QEMU_BIN=qemu-system-x86_64
OPENSANDBOX_DATA_DIR=/data/sandboxes
@@ -323,18 +413,8 @@ OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux
OPENSANDBOX_IMAGES_DIR=/data/firecracker/images
OPENSANDBOX_GRPC_ADVERTISE=$WK_PRIVATE_IP:9090
OPENSANDBOX_HTTP_ADDR=http://$WK_PRIVATE_IP:8081
-OPENSANDBOX_JWT_SECRET=$JWT_SECRET
OPENSANDBOX_WORKER_ID=w-aws-${REGION}-dev3-1
-OPENSANDBOX_REGION=$REGION
-OPENSANDBOX_MAX_CAPACITY=10
OPENSANDBOX_PORT=8081
-OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024
-OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
-OPENSANDBOX_DATABASE_URL=postgres://opensandbox:$PG_PASSWORD@$CP_PRIVATE_IP:5432/opensandbox?sslmode=disable
-OPENSANDBOX_REDIS_URL=redis://$CP_PRIVATE_IP:6379
-OPENSANDBOX_S3_BUCKET=$BUCKET
-OPENSANDBOX_S3_REGION=$REGION
-OPENSANDBOX_CELL_ID=$CELL_ID
WKENV
# Postgres VPC access
diff --git a/deploy/azure/create-azure-dev2.sh b/deploy/azure/create-azure-dev2.sh
index ed411204..ed7688b0 100644
--- a/deploy/azure/create-azure-dev2.sh
+++ b/deploy/azure/create-azure-dev2.sh
@@ -340,49 +340,78 @@ fi
sudo bash /tmp/setup-azure-host.sh
WKSETUP
- # ── Push cell config + secrets to Key Vault ──
- # Everything that isn't bootstrap (mode + vault pointer + paths + per-VM
- # identity) lives in KV. The kvMapping in internal/config/keyvault.go is
- # the allowlist — secrets not in that map are silently ignored, so it's
- # safe to push extra entries here without affecting the running services.
- log "Populating Key Vault with cell config + secrets..."
- set_kv() { az keyvault secret set --vault-name "$KV_NAME" --name "$1" --value "$2" --output none; }
-
- # Server-side bundle (server-* prefix; loaded only when MODE=server)
- set_kv server-database-url "postgres://opensandbox:$PG_PASSWORD@localhost:5432/opensandbox?sslmode=disable"
- set_kv server-redis-url "redis://localhost:6379"
- set_kv server-jwt-secret "$JWT_SECRET"
- set_kv server-api-key "$API_KEY"
- set_kv server-region "$CELL_REGION"
- set_kv server-sandbox-domain "$DOMAIN"
- set_kv server-cell-id "$CELL_ID"
- set_kv server-cf-event-endpoint "$CF_EVENT_ENDPOINT"
- set_kv server-cf-event-secret "$CF_EVENT_SECRET"
- set_kv server-cf-admin-secret "$CF_ADMIN_SECRET"
- set_kv server-session-jwt-secret "$SESSION_JWT_SECRET"
-
- # Worker-side bundle (worker-* prefix; loaded only when MODE=worker)
- set_kv worker-jwt-secret "$JWT_SECRET"
- set_kv worker-database-url "postgres://opensandbox:$PG_PASSWORD@$CP_PRIVATE_IP:5432/opensandbox?sslmode=disable"
- set_kv worker-redis-url "redis://$CP_PRIVATE_IP:6379"
- set_kv worker-region "$CELL_REGION"
- set_kv worker-cell-id "$CELL_ID"
- set_kv worker-max-capacity "10"
- set_kv worker-default-sandbox-memory-mb "1024"
- set_kv worker-default-sandbox-cpus "2"
- set_kv worker-sandbox-domain "$DOMAIN"
- set_kv worker-s3-bucket "$STORAGE_CONTAINER"
- set_kv worker-s3-region "$REGION"
- set_kv worker-s3-endpoint "https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net"
- set_kv worker-s3-access-key "$STORAGE_ACCOUNT_NAME"
- set_kv worker-s3-secret-key "$STORAGE_KEY"
- set_kv worker-cf-event-endpoint "$CF_EVENT_ENDPOINT"
- set_kv worker-cf-event-secret "$CF_EVENT_SECRET"
- set_kv worker-cf-admin-secret "$CF_ADMIN_SECRET"
- set_kv worker-session-jwt-secret "$SESSION_JWT_SECRET"
-
- # Shared (loaded for any mode via the pg-* prefix bypass in keyvault.go)
- set_kv pg-password "$PG_PASSWORD"
+ # ── Push cell config + secrets to Infisical ──
+ # Infisical is the single source of truth for all secrets across all
+ # cells; the Azure KV provisioned above is just a cell-local read cache
+ # populated by the Infisical Secret Sync (set up once per project).
+ #
+ # Prerequisites the operator must have completed BEFORE running this:
+ # 1. Infisical project + `dev` env exist
+ # 2. Folders `/shared` and `/cells/${CELL_ID}` exist in that env
+ # 3. INFISICAL_TOKEN env var is set with write access to those folders
+ # (machine identity created in Infisical UI; one-time setup)
+ # 4. App Connection from Infisical to Azure has secret-officer scope on
+ # this RG's KV (set up after the KV exists — see README)
+ # 5. Secret Syncs configured in Infisical UI:
+ # /shared → osb-dev2-* KV
+ # /cells/${CELL_ID} → osb-dev2-* KV
+ # Both with "Disable Secret Deletion = ON" (two syncs to one dest).
+ #
+ # This step writes the generated secrets to Infisical; the existing
+ # Sync propagates Infisical → KV within ~10s. VM bootstrap reads the KV
+ # at boot via Managed Identity. Editing a secret in Infisical later
+ # propagates everywhere automatically.
+ if [ -z "${INFISICAL_TOKEN:-}" ]; then
+ err "INFISICAL_TOKEN not set — won't seed Infisical. Either export it"
+ err "before re-running, or push these secrets manually after the fact:"
+ err " jwt-secret api-key session-jwt-secret cf-event-secret cf-admin-secret"
+ err " pg-password + cell-scoped DB/Redis URLs, region, sandbox-domain, ..."
+ exit 1
+ fi
+ INF_PROJ="${INFISICAL_PROJECT_ID:-6f7fb48e-90bb-4fac-b9a2-c55f06ed00e7}"
+ INF_ENV="${INFISICAL_ENV:-dev}"
+ log "Seeding Infisical project=$INF_PROJ env=$INF_ENV (sync will fan out to KV)..."
+ inf() { infisical secrets set --projectId="$INF_PROJ" --env="$INF_ENV" --path="$1" --silent "$2=$3" >/dev/null; }
+
+ # Per-cell values (different per cell — DB/Redis URLs, region, S3 endpoint).
+ CELL="/cells/$CELL_ID"
+ inf "$CELL" server-database-url "postgres://opensandbox:$PG_PASSWORD@localhost:5432/opensandbox?sslmode=disable"
+ inf "$CELL" server-redis-url "redis://localhost:6379"
+ inf "$CELL" server-region "$CELL_REGION"
+ inf "$CELL" server-sandbox-domain "$DOMAIN"
+ inf "$CELL" server-cell-id "$CELL_ID"
+ inf "$CELL" worker-database-url "postgres://opensandbox:$PG_PASSWORD@$CP_PRIVATE_IP:5432/opensandbox?sslmode=disable"
+ inf "$CELL" worker-redis-url "redis://$CP_PRIVATE_IP:6379"
+ inf "$CELL" worker-region "$CELL_REGION"
+ inf "$CELL" worker-cell-id "$CELL_ID"
+ inf "$CELL" worker-sandbox-domain "$DOMAIN"
+ inf "$CELL" worker-max-capacity "10"
+ inf "$CELL" worker-default-sandbox-memory-mb "1024"
+ inf "$CELL" worker-default-sandbox-cpus "2"
+ inf "$CELL" worker-s3-bucket "$STORAGE_CONTAINER"
+ inf "$CELL" worker-s3-region "$REGION"
+ inf "$CELL" worker-s3-endpoint "https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net"
+ inf "$CELL" worker-s3-access-key "$STORAGE_ACCOUNT_NAME"
+ inf "$CELL" worker-s3-secret-key "$STORAGE_KEY"
+ inf "$CELL" pg-password "$PG_PASSWORD"
+
+ # Shared values — only push from a NEW cell if the operator wants to (re)set
+ # them globally. By default we skip; the values already exist in Infisical
+ # /shared from the first cell's setup. Override with SEED_SHARED=1.
+ if [ "${SEED_SHARED:-0}" = "1" ]; then
+ log " also seeding /shared (SEED_SHARED=1)..."
+ inf "/shared" server-jwt-secret "$JWT_SECRET"
+ inf "/shared" worker-jwt-secret "$JWT_SECRET"
+ inf "/shared" server-api-key "$API_KEY"
+ inf "/shared" server-cf-event-endpoint "$CF_EVENT_ENDPOINT"
+ inf "/shared" worker-cf-event-endpoint "$CF_EVENT_ENDPOINT"
+ inf "/shared" server-cf-event-secret "$CF_EVENT_SECRET"
+ inf "/shared" worker-cf-event-secret "$CF_EVENT_SECRET"
+ inf "/shared" server-cf-admin-secret "$CF_ADMIN_SECRET"
+ inf "/shared" worker-cf-admin-secret "$CF_ADMIN_SECRET"
+ inf "/shared" server-session-jwt-secret "$SESSION_JWT_SECRET"
+ inf "/shared" worker-session-jwt-secret "$SESSION_JWT_SECRET"
+ fi
# ── Write bootstrap env files ──
# Only what the binary needs to find the KV: mode + vault pointer + paths
diff --git a/internal/api/router.go b/internal/api/router.go
index 8bfb6dea..5e3f27eb 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -159,6 +160,42 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
}
if opts != nil && opts.ControlPlaneProxy != nil {
e.Use(opts.ControlPlaneProxy.Middleware())
+
+ // Edge-forwarded preview URL traffic. The api-edge Worker resolves
+ // the public preview hostname (sb-{id}-p{port}.opensandbox.ai) to a
+ // cell via D1, then forwards via this cell's Tunnel here. We:
+ //
+ // 1. strip the /internal/preview/{id}/{port} prefix so the inner
+ // URL path matches what the user originally requested
+ // 2. synthesize the Host header the downstream worker proxy
+ // expects (sb-{id}-p{port}.{sandbox_domain}) so the worker's
+ // SandboxProxy.Middleware parses it correctly
+ // 3. delegate to ControlPlaneProxy.HandleSandboxRequest, which
+ // reuses the same doProxy logic used by the host-header path —
+ // hibernation wake, worker-loss recovery, all of it.
+ //
+ // No cap-token auth on this route: it's public-internet sandbox
+ // traffic that the edge has already validated (via D1 lookup +
+ // sandbox-running check). The auth model is "edge gate, cell
+ // trust" — same as POST /internal/sandboxes/create.
+ cp := opts.ControlPlaneProxy
+ sandboxDomain := opts.SandboxDomain
+ e.Any("/internal/preview/:id/:port/*", func(c echo.Context) error {
+ id := c.Param("id")
+ portStr := c.Param("port")
+ port, err := strconv.Atoi(portStr)
+ if err != nil || port < 1 || port > 65535 {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid port"})
+ }
+ prefix := "/internal/preview/" + id + "/" + portStr
+ rest := strings.TrimPrefix(c.Request().URL.Path, prefix)
+ if rest == "" {
+ rest = "/"
+ }
+ c.Request().URL.Path = rest
+ c.Request().Host = id + "-p" + portStr + "." + sandboxDomain
+ return cp.HandleSandboxRequest(c, id, port)
+ })
}
// Health checks (no auth)
diff --git a/internal/config/secretsmanager.go b/internal/config/secretsmanager.go
new file mode 100644
index 00000000..69ef2d53
--- /dev/null
+++ b/internal/config/secretsmanager.go
@@ -0,0 +1,58 @@
+package config
+
+import (
+ "context"
+ "os"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/secrets"
+)
+
+// LoadSecretsFromSecretsManager is the AWS analogue of LoadSecretsFromKeyVault.
+// Maps every kebab-case key from kvMapping into the process environment via
+// the same translation Azure KV uses (server-jwt-secret → OPENSANDBOX_JWT_SECRET).
+//
+// Two trigger env vars, picked one at a time:
+//
+// - OPENSANDBOX_SECRETS_ARN: single bundled SM secret with JSON SecretString.
+// One GetSecretValue, one IAM scope. Cheap ($0.40/mo) but requires the
+// producer (Infisical or otherwise) to write a JSON bundle.
+//
+// - OPENSANDBOX_SECRETS_AWS_REGION: per-key mode. Each kvMapping key is its
+// own SM secret. BatchGetSecretValue fetches them in chunks of 20. This
+// is what Infisical's "Sync each secret to its own secret" mode produces.
+// Costs $0.40/mo per secret but matches Infisical's default sync shape.
+//
+// Existing env vars take precedence (emergency override path).
+//
+// Does nothing if neither trigger is set.
+func LoadSecretsFromSecretsManager() error {
+ bundleARN := os.Getenv("OPENSANDBOX_SECRETS_ARN")
+ listRegion := os.Getenv("OPENSANDBOX_SECRETS_AWS_REGION")
+ if bundleARN == "" && listRegion == "" {
+ return nil // not configured; defer to env file / Azure KV / combined mode
+ }
+ mode := os.Getenv("OPENSANDBOX_MODE")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ be, err := secrets.NewSecretsManagerBackend(ctx, listRegion, bundleARN)
+ if err != nil {
+ return err
+ }
+ be.NameMap = kvMapping
+ be.ModePrefixFilter = mode
+
+ if bundleARN != "" {
+ _, _, err = be.LoadAllToEnv(ctx)
+ return err
+ }
+ // list/per-key mode — fetch each kvMapping key as its own SM secret
+ names := make([]string, 0, len(kvMapping))
+ for k := range kvMapping {
+ names = append(names, k)
+ }
+ _, _, err = be.LoadAllByNameList(ctx, names)
+ return err
+}
diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.go
index f4eb78ee..68c97510 100644
--- a/internal/proxy/controlplane_proxy.go
+++ b/internal/proxy/controlplane_proxy.go
@@ -73,6 +73,20 @@ func (p *ControlPlaneProxy) Middleware() echo.MiddlewareFunc {
}
}
+// HandleSandboxRequest is the exported entry point for proxying a sandbox
+// HTTP/WebSocket request when sandbox_id + port are already known from
+// somewhere other than the request's Host header — e.g. the api-edge Worker
+// has resolved the public preview hostname against D1 and forwarded the
+// request to this CP via /internal/preview/:id/:port/* on the cell tunnel.
+//
+// Callers must have already (a) stripped the /internal/preview prefix from
+// the URL path, and (b) synthesized a Host header the downstream worker
+// proxy expects (e.g. "{id}-p{port}.{sandbox_domain}"), so the worker's
+// SandboxProxy.Middleware can parse it correctly.
+func (p *ControlPlaneProxy) HandleSandboxRequest(c echo.Context, sandboxID string, port int) error {
+ return p.doProxy(c, sandboxID, port)
+}
+
// doProxy looks up the worker that owns this sandbox and reverse-proxies to it.
// If the sandbox is hibernated, it triggers a wake-on-request: picks the least
// loaded worker, wakes the sandbox via gRPC, updates the DB, then proxies.
diff --git a/internal/secrets/secretsmanager.go b/internal/secrets/secretsmanager.go
index d8a93db9..ef093c18 100644
--- a/internal/secrets/secretsmanager.go
+++ b/internal/secrets/secretsmanager.go
@@ -3,6 +3,7 @@ package secrets
import (
"context"
"fmt"
+ "log"
"os"
"strings"
@@ -24,6 +25,17 @@ import (
type SecretsManagerBackend struct {
client *secretsmanager.Client
bundledARN string // optional: JSON bundle keyed by secret name
+
+ // NameMap translates bundle key → env var name. Mirrors KeyVaultBackend.NameMap
+ // so the same kvMapping in internal/config can drive both Azure KV and AWS SM
+ // bootstrap. Nil/empty = LoadAllToEnv writes bundle keys verbatim as env vars
+ // (legacy behavior; only safe if the bundle already uses SCREAMING_SNAKE).
+ NameMap map[string]string
+
+ // ModePrefixFilter restricts LoadAllToEnv to bundle keys whose name starts
+ // with "{ModePrefixFilter}-" (plus shared "pg-*"). Empty = no filter.
+ // Typical: "server" or "worker". Same semantics as KeyVaultBackend.
+ ModePrefixFilter string
}
// NewSecretsManagerBackend constructs a backend using the default AWS
@@ -69,16 +81,25 @@ func (b *SecretsManagerBackend) Get(ctx context.Context, key string) (string, er
return v, nil
}
-// LoadAllToEnv satisfies BulkLoader. SecretsManager's bootstrap pattern
-// is "one secret holds JSON; expand to env vars by key name." Reads
-// BundledARN and Setenv each KEY=value pair from the JSON object,
-// skipping any that are already present in the env (local overrides win).
+// LoadAllToEnv satisfies BulkLoader. SecretsManager's bootstrap pattern is
+// "one secret holds JSON; expand to env vars by key name." Reads BundledARN
+// and Setenv each KEY=value pair from the JSON object, skipping any that are
+// already present in the env (local overrides win).
+//
+// If NameMap is non-empty, bundle keys are translated to env var names via
+// the map AND restricted to keys present in the map (allowlist). This mirrors
+// KeyVaultBackend.LoadAllToEnv so a single kvMapping drives both backends —
+// the Infisical sync writes bundle keys as kebab-case (server-jwt-secret,
+// worker-cell-id, ...) and the map turns them into OPENSANDBOX_* env vars.
//
-// Returns (loaded, 0, err) — SecretsManager doesn't track skipped because
-// the bundle keys are arbitrary, not enumerated through a name map.
+// If NameMap is empty, bundle keys are written verbatim (legacy path —
+// caller responsible for bundle keys already being env-var-shaped).
+//
+// ModePrefixFilter additionally restricts to keys with "{mode}-" or "pg-"
+// prefix, same as KeyVaultBackend.
func (b *SecretsManagerBackend) LoadAllToEnv(ctx context.Context) (loaded, skipped int, err error) {
if b.bundledARN == "" {
- return 0, 0, nil // nothing to bulk-load
+ return 0, 0, nil
}
bundleStr, err := b.getRaw(ctx, b.bundledARN)
if err != nil {
@@ -89,13 +110,98 @@ func (b *SecretsManagerBackend) LoadAllToEnv(ctx context.Context) (loaded, skipp
return 0, 0, err
}
for k, v := range pairs {
- if os.Getenv(k) != "" {
+ envVar := k
+ if len(b.NameMap) > 0 {
+ mapped, ok := b.NameMap[k]
+ if !ok {
+ continue // not in allowlist — silently skip
+ }
+ envVar = mapped
+ }
+ if b.ModePrefixFilter != "" &&
+ !strings.HasPrefix(k, b.ModePrefixFilter+"-") &&
+ !strings.HasPrefix(k, "pg-") {
+ continue
+ }
+ if os.Getenv(envVar) != "" {
skipped++
continue
}
- os.Setenv(k, v)
+ os.Setenv(envVar, v)
loaded++
}
+ if len(b.NameMap) > 0 {
+ log.Printf("secretsmanager: loaded %d secrets from bundle %s (%d skipped, already set)", loaded, b.bundledARN, skipped)
+ }
+ return loaded, skipped, nil
+}
+
+// LoadAllByNameList is the per-key counterpart to LoadAllToEnv: instead of
+// pulling one bundled JSON secret, it fetches N individual SM secrets by
+// name (one BatchGetSecretValue round-trip when N <= 20, paginated otherwise)
+// and applies NameMap + ModePrefixFilter the same way KeyVaultBackend does.
+//
+// Use this when the secrets are stored as separate SM resources (which is
+// what Infisical's AWS Secrets Manager sync writes by default — each
+// Infisical secret becomes its own SM secret, named verbatim or with a
+// configurable prefix).
+//
+// `names` is the list of SM secret names to fetch. The caller is expected
+// to pass the kebab-case names from kvMapping; unknown names in SM are
+// ignored and missing names in SM produce log warnings (not fatal).
+func (b *SecretsManagerBackend) LoadAllByNameList(ctx context.Context, names []string) (loaded, skipped int, err error) {
+ if len(names) == 0 {
+ return 0, 0, nil
+ }
+ // BatchGetSecretValue caps at 20 names per call; chunk if needed.
+ const batchSize = 20
+ for i := 0; i < len(names); i += batchSize {
+ end := i + batchSize
+ if end > len(names) {
+ end = len(names)
+ }
+ chunk := names[i:end]
+ out, callErr := b.client.BatchGetSecretValue(ctx, &secretsmanager.BatchGetSecretValueInput{
+ SecretIdList: chunk,
+ })
+ if callErr != nil {
+ return loaded, skipped, fmt.Errorf("secretsmanager: BatchGetSecretValue: %w", callErr)
+ }
+ for _, sv := range out.SecretValues {
+ if sv.Name == nil || sv.SecretString == nil {
+ continue
+ }
+ name := *sv.Name
+ val := *sv.SecretString
+ envVar := name
+ if len(b.NameMap) > 0 {
+ mapped, ok := b.NameMap[name]
+ if !ok {
+ continue // not in allowlist
+ }
+ envVar = mapped
+ }
+ if b.ModePrefixFilter != "" &&
+ !strings.HasPrefix(name, b.ModePrefixFilter+"-") &&
+ !strings.HasPrefix(name, "pg-") {
+ continue
+ }
+ if os.Getenv(envVar) != "" {
+ skipped++
+ continue
+ }
+ os.Setenv(envVar, val)
+ loaded++
+ }
+ // out.Errors contains names that failed individually (e.g. not found).
+ // Log but don't fail — missing entries are expected during partial migrations.
+ for _, e := range out.Errors {
+ if e.SecretId != nil && e.Message != nil {
+ log.Printf("secretsmanager: %s: %s (skipping)", *e.SecretId, *e.Message)
+ }
+ }
+ }
+ log.Printf("secretsmanager: loaded %d secrets via batch list (%d skipped, already set)", loaded, skipped)
return loaded, skipped, nil
}
diff --git a/scripts/infisical-diff-kv.sh b/scripts/infisical-diff-kv.sh
new file mode 100755
index 00000000..06798205
--- /dev/null
+++ b/scripts/infisical-diff-kv.sh
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# infisical-diff-kv.sh — verify Infisical's resolved set for a cell matches
+# the source Azure Key Vault byte-for-byte. This is the safety gate before
+# flipping the Infisical → KV sync to push-authoritative. After flip,
+# re-running this verifies drift is zero.
+#
+# Resolved set = `/shared` ∪ `/cells/<cell_id>` from Infisical (in that
+# precedence order; cell-scoped wins on name collision — though our import
+# guarantees no collisions).
+#
+# Usage:
+# scripts/infisical-diff-kv.sh <azure_kv_name> <cell_id>
+#
+# Exits 0 if identical (proof Infisical can take over without changing
+# observed behavior). Exits 1 if mismatched, printing each difference.
+
+set -euo pipefail
+
+KV_NAME="${1:?usage: $0 <azure_kv_name> <cell_id>}"
+CELL_ID="${2:?usage: $0 <azure_kv_name> <cell_id>}"
+
+: "${INFISICAL_PROJECT_ID:=6f7fb48e-90bb-4fac-b9a2-c55f06ed00e7}"
+: "${INFISICAL_ENV:=dev}"
+: "${INFISICAL_TOKEN:?INFISICAL_TOKEN not set — run infisical login first}"
+
+# --- gather KV side ---
+KV_DUMP=$(mktemp)
+trap 'rm -f "$KV_DUMP" "$INF_DUMP"' EXIT
+az keyvault secret list --vault-name "$KV_NAME" --query "[].name" -o tsv 2>/dev/null \
+ | while IFS= read -r name; do
+ [ -z "$name" ] && continue
+ val=$(az keyvault secret show --vault-name "$KV_NAME" --name "$name" --query value -o tsv 2>/dev/null)
+ printf '%s\t%s\n' "$name" "$val"
+ done | sort > "$KV_DUMP"
+
+# --- gather Infisical side ---
+# `infisical export --format=dotenv` returns KEY=VALUE pairs for the current
+# path. We resolve /shared and /cells/<cell_id> separately and union them.
+# The dotenv quoting is what we need — values with spaces / special chars
+# come through correctly.
+INF_DUMP=$(mktemp)
+parse_dotenv() {
+ # Read KEY=VALUE lines from infisical's dotenv export. Infisical wraps every
+ # value in single quotes (KEY='value'); we strip them. Double quotes too in
+ # case the format changes upstream.
+ while IFS='=' read -r key val; do
+ [ -z "$key" ] && continue
+ case "$key" in \#*) continue ;; esac
+ val="${val#\'}"; val="${val%\'}"
+ val="${val#\"}"; val="${val%\"}"
+ printf '%s\t%s\n' "$key" "$val"
+ done
+}
+
+{
+ infisical export \
+ --projectId="$INFISICAL_PROJECT_ID" \
+ --env="$INFISICAL_ENV" \
+ --path="/shared" \
+ --format=dotenv 2>/dev/null | parse_dotenv
+ infisical export \
+ --projectId="$INFISICAL_PROJECT_ID" \
+ --env="$INFISICAL_ENV" \
+ --path="/cells/$CELL_ID" \
+ --format=dotenv 2>/dev/null | parse_dotenv
+} | sort > "$INF_DUMP"
+
+# --- diff ---
+KV_COUNT=$(wc -l < "$KV_DUMP")
+INF_COUNT=$(wc -l < "$INF_DUMP")
+echo "KV side ($KV_NAME): $KV_COUNT entries"
+echo "Infisical side (env=$INFISICAL_ENV, /shared + /cells/$CELL_ID): $INF_COUNT entries"
+echo
+
+if diff -u "$KV_DUMP" "$INF_DUMP" >/dev/null; then
+ echo "✓ MATCH — Infisical's resolved set matches $KV_NAME byte-for-byte."
+ exit 0
+else
+ echo "✗ MISMATCH:"
+ diff -u "$KV_DUMP" "$INF_DUMP" | head -40
+ exit 1
+fi
diff --git a/scripts/infisical-import-from-kv.sh b/scripts/infisical-import-from-kv.sh
new file mode 100755
index 00000000..0794a7e8
--- /dev/null
+++ b/scripts/infisical-import-from-kv.sh
@@ -0,0 +1,109 @@
+#!/usr/bin/env bash
+# infisical-import-from-kv.sh — one-time seed: read every secret from an Azure
+# Key Vault and push it to Infisical, classifying each as shared (env-wide) or
+# cell-scoped. Idempotent — re-running updates existing secrets in place.
+#
+# After this completes, the diff script (infisical-diff.sh) should confirm
+# Infisical's resolved view matches the source KV byte-for-byte. Only then is
+# it safe to flip the Infisical → KV sync to push-authoritative.
+#
+# Usage:
+# scripts/infisical-import-from-kv.sh <azure_kv_name> <cell_id> [--dry-run]
+#
+# Example:
+# scripts/infisical-import-from-kv.sh osb-dev2-d656dc azure-us-west-2-b --dry-run
+# scripts/infisical-import-from-kv.sh osb-dev2-d656dc azure-us-west-2-b
+#
+# Requires:
+# INFISICAL_TOKEN env var (issued by `infisical login --method=universal-auth`)
+# az login + read access to the source KV
+# INFISICAL_PROJECT_ID env var (defaults to opencomputer)
+
+set -euo pipefail
+
+KV_NAME="${1:?usage: $0 <azure_kv_name> <cell_id> [--dry-run]}"
+CELL_ID="${2:?usage: $0 <azure_kv_name> <cell_id> [--dry-run]}"
+DRY_RUN=0
+[ "${3:-}" = "--dry-run" ] && DRY_RUN=1
+
+: "${INFISICAL_PROJECT_ID:=6f7fb48e-90bb-4fac-b9a2-c55f06ed00e7}"
+: "${INFISICAL_ENV:=dev}"
+
+if [ -z "${INFISICAL_TOKEN:-}" ]; then
+ echo "ERROR: INFISICAL_TOKEN not set. Run:" >&2
+ echo " export INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=..." >&2
+ echo " export INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=..." >&2
+ echo " export INFISICAL_TOKEN=\$(infisical login --method=universal-auth --silent --plain)" >&2
+ exit 1
+fi
+
+# Classify a KV secret name as either "shared" or "cell".
+#
+# Rules (ordered):
+# - Anything under the `worker-global-blob-*` umbrella → shared (Tigris is
+# a single global store; every cell reads the same bucket+creds).
+# - URLs/endpoints that point at the *edge* (cf-event-endpoint, halt-list,
+# api-key, all jwt/HMAC secrets) → shared.
+# - Everything else with worker-/server- prefix (cell-id, region, s3-*,
+# database-url, redis-url, capacity tuning) → cell-scoped.
+classify() {
+ local n="$1"
+ case "$n" in
+ worker-global-blob-*) echo "shared" ;;
+ *-cf-event-endpoint|*-cf-event-secret|*-cf-admin-secret) echo "shared" ;;
+ *-jwt-secret|*-session-jwt-secret|*-api-key) echo "shared" ;;
+ *-secret-encryption-key|*-stripe-*|*-workos-*|*-sentry-dsn|*-segment-write-key) echo "shared" ;;
+ *-halt-list-url) echo "shared" ;;
+ pg-*) echo "cell" ;; # pg-password is per-cell (each cell's own PG)
+ *) echo "cell" ;;
+ esac
+}
+
+infisical_path() {
+ case "$1" in
+ shared) echo "/shared" ;;
+ cell) echo "/cells/$CELL_ID" ;;
+ esac
+}
+
+echo "=== import plan: $KV_NAME → Infisical project $INFISICAL_PROJECT_ID env=$INFISICAL_ENV ==="
+[ "$DRY_RUN" -eq 1 ] && echo " (DRY RUN — no writes)"
+echo
+
+NAMES=$(az keyvault secret list --vault-name "$KV_NAME" --query "[].name" -o tsv 2>/dev/null | sort)
+SHARED_COUNT=0
+CELL_COUNT=0
+FAIL_COUNT=0
+
+while IFS= read -r name; do
+ [ -z "$name" ] && continue
+ bucket=$(classify "$name")
+ path=$(infisical_path "$bucket")
+ value=$(az keyvault secret show --vault-name "$KV_NAME" --name "$name" --query value -o tsv 2>/dev/null)
+ if [ -z "$value" ]; then
+ echo " SKIP $name (empty value)"
+ continue
+ fi
+ printf " %-7s %s → %s\n" "$bucket" "$name" "$path"
+ if [ "$DRY_RUN" -eq 0 ]; then
+ # `infisical secrets set` upserts by default; --type shared for non-personal.
+ if ! infisical secrets set \
+ --projectId="$INFISICAL_PROJECT_ID" \
+ --env="$INFISICAL_ENV" \
+ --path="$path" \
+ --silent \
+ "$name=$value" >/dev/null 2>&1; then
+ echo " FAILED to set $name"
+ FAIL_COUNT=$((FAIL_COUNT+1))
+ continue
+ fi
+ fi
+ [ "$bucket" = "shared" ] && SHARED_COUNT=$((SHARED_COUNT+1)) || CELL_COUNT=$((CELL_COUNT+1))
+done <<< "$NAMES"
+
+echo
+echo "=== summary ==="
+echo " shared: $SHARED_COUNT secrets → /shared"
+echo " cell: $CELL_COUNT secrets → /cells/$CELL_ID"
+echo " failed: $FAIL_COUNT"
+[ "$DRY_RUN" -eq 1 ] && echo " (dry-run — re-run without --dry-run to apply)"