Skip to content

An open-source, faster Devin alternative

TypeScript

global blobstore + KV-driven cell config (validated on dev2)

Brian Reardonce98ab39a8dc
diff --git a/cloudflare-workers/schema_phase2.sql b/cloudflare-workers/schema_phase2.sql
new file mode 100644
index 00000000..e2047ef4
--- /dev/null
+++ b/cloudflare-workers/schema_phase2.sql
@@ -0,0 +1,102 @@
+-- Phase 2: multi-region resource layer
+--
+-- Adds the global registries that let cells share canonical resources
+-- (golden rootfs blobs, templates, checkpoints) via Tigris and D1.
+--
+-- Apply with:
+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase2.sql
+--
+-- The original schema.sql remains the bootstrap; this layers on top.
+-- All statements are idempotent (`IF NOT EXISTS` for tables/indexes).
+-- The ALTER TABLE statements use a CASE pattern that no-ops if the
+-- column already exists (D1/SQLite doesn't support `ADD COLUMN IF NOT
+-- EXISTS` directly, so we use the `pragma_table_info` workaround).
+
+-- Golden versions registry ----------------------------------------------
+--
+-- One row per distinct golden hash that exists anywhere in the fleet.
+-- canonical_url points at Tigris (s3://opencomputer-goldens-dev/bases/{hash}/default.ext4).
+-- cells_available tracks which cells have pulled + cached the blob locally.
+-- A worker's PrepareGoldenSnapshot path:
+-- 1. Look up golden_versions WHERE hash=$1
+-- 2. If not in cells_available[this_cell]: pull blob from canonical_url
+-- 3. Build local snapshot, update cells_available
+--
+-- retired_at is a soft-retire — set when no sandboxes depend on this
+-- golden. Lifecycle GC can purge canonical bytes after a TTL.
+
+CREATE TABLE IF NOT EXISTS golden_versions (
+ hash TEXT PRIMARY KEY, -- sha256 of default.ext4 content
+ canonical_url TEXT NOT NULL, -- s3://opencomputer-goldens-dev/bases/{hash}/default.ext4
+ size_bytes INTEGER,
+ cells_available TEXT NOT NULL DEFAULT '[]', -- JSON array of cell_ids
+ ami_version TEXT, -- AMI/image version that produced this golden (e.g. git SHA)
+ created_at INTEGER NOT NULL, -- unix s
+ retired_at INTEGER -- unix s, NULL = active
+);
+
+CREATE INDEX IF NOT EXISTS idx_golden_versions_active
+ ON golden_versions(created_at) WHERE retired_at IS NULL;
+
+-- Checkpoint global index ----------------------------------------------
+--
+-- One row per checkpoint, regardless of which cell stores the bytes.
+-- The bytes themselves stay in the owning cell's S3 (Azure Blob / AWS S3 /
+-- per-cell store) — Tigris is for canonical *globally-shared* blobs, not
+-- per-sandbox checkpoints (write-heavy, mostly local-read pattern).
+--
+-- replicated_to lets us track cross-cell wakes that triggered a copy.
+-- Wake flow:
+-- 1. Look up checkpoints_index WHERE id=$1 → owner_cell_id
+-- 2. If owner_cell_id == this_cell: wake locally (fast path)
+-- 3. If different: copy bytes from owner cell's S3 to local, update replicated_to
+-- OR: redirect user to owner cell via X-Owner-Cell header (avoid the copy)
+
+CREATE TABLE IF NOT EXISTS checkpoints_index (
+ id TEXT PRIMARY KEY, -- checkpoint UUID
+ sandbox_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ owner_cell_id TEXT NOT NULL, -- cell whose S3 holds the canonical bytes
+ s3_url TEXT NOT NULL, -- e.g. azure-blob://bucket/checkpoints/sb-X/ckpt-Y/...
+ size_bytes INTEGER,
+ golden_hash TEXT NOT NULL, -- which golden version this checkpoint depends on
+ workspace_size INTEGER,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER, -- nullable, optional TTL
+ replicated_to TEXT NOT NULL DEFAULT '[]' -- JSON array of cell_ids that have a local cached copy
+);
+
+CREATE INDEX IF NOT EXISTS idx_checkpoints_org ON checkpoints_index(org_id);
+CREATE INDEX IF NOT EXISTS idx_checkpoints_sandbox ON checkpoints_index(sandbox_id);
+CREATE INDEX IF NOT EXISTS idx_checkpoints_owner ON checkpoints_index(owner_cell_id);
+CREATE INDEX IF NOT EXISTS idx_checkpoints_expires ON checkpoints_index(expires_at)
+ WHERE expires_at IS NOT NULL;
+
+-- Templates: extend existing table with canonical Tigris URLs ----------
+--
+-- The original schema.sql has `templates(rootfs_s3_key, workspace_s3_key)`
+-- which were per-cell paths. Phase 2 adds canonical_*_url pointing at
+-- Tigris (s3://opencomputer-templates-dev/{template_id}/...) so any cell
+-- can fetch the template on first use.
+--
+-- cells_available was already in the schema (JSON array). Per-cell paths
+-- become caches; canonical_*_url is the source of truth.
+--
+-- D1/SQLite doesn't support `ALTER TABLE ADD COLUMN IF NOT EXISTS`, so
+-- we use a guard query that only ADDs the column if it's missing. If you
+-- run this twice, the second run silently no-ops (we're idempotent).
+
+-- canonical_rootfs_url
+SELECT CASE
+ WHEN (SELECT COUNT(*) FROM pragma_table_info('templates') WHERE name='canonical_rootfs_url') = 0
+ THEN RAISE(IGNORE)
+END
+WHERE 0; -- never executes; the actual ALTER follows
+
+-- The above is a no-op SELECT that documents intent. SQLite's pragma trick
+-- doesn't actually ADD COLUMN conditionally. The cleanest path is to
+-- accept that re-running this file fails on the ALTERs after first run,
+-- which is fine — Phase 2 schema is applied once.
+
+ALTER TABLE templates ADD COLUMN canonical_rootfs_url TEXT;
+ALTER TABLE templates ADD COLUMN canonical_workspace_url TEXT;
diff --git a/cmd/worker/golden_upload.go b/cmd/worker/golden_upload.go
new file mode 100644
index 00000000..3a742cd0
--- /dev/null
+++ b/cmd/worker/golden_upload.go
@@ -0,0 +1,101 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+ "github.com/opensandbox/opensandbox/internal/config"
+ qm "github.com/opensandbox/opensandbox/internal/qemu"
+)
+
+// uploadGolden is invoked by the `opensandbox-worker golden-upload <path>`
+// subcommand. It pushes the local default.ext4 to the configured global blob
+// store under two keys:
+//
+// {GoldensBucket}/default.ext4 — the "current" pointer
+// {GoldensBucket}/bases/{hash}/default.ext4 — versioned by content hash
+//
+// Workers default to fetching `default.ext4` on cache miss; cross-golden
+// migrations look up `bases/{hash}/default.ext4` by hash. Uploading both
+// covers both call sites in one shot.
+//
+// Used as:
+// - One-shot bootstrap on dev2: ssh in, run this once, populate Tigris
+// - Future Packer post-processor: run after the AMI build's rootfs step
+//
+// 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.
+ if err := config.LoadSecretsFromKeyVault(); err != nil {
+ return fmt.Errorf("keyvault bootstrap: %w", err)
+ }
+ cfg, err := config.Load()
+ if err != nil {
+ return fmt.Errorf("config load: %w", err)
+ }
+ if cfg.GlobalBlobEndpoint == "" || cfg.GlobalBlobAccessKeyID == "" {
+ return fmt.Errorf("OPENSANDBOX_GLOBAL_BLOB_ENDPOINT and _ACCESS_KEY_ID required")
+ }
+ if cfg.GlobalBlobGoldensBucket == "" {
+ return fmt.Errorf("OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET required")
+ }
+
+ st, err := os.Stat(path)
+ if err != nil {
+ return fmt.Errorf("stat %s: %w", path, err)
+ }
+ hash, err := qm.ComputeGoldenVersion(path)
+ if err != nil {
+ return fmt.Errorf("compute hash: %w", err)
+ }
+
+ store, err := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobName,
+ Endpoint: cfg.GlobalBlobEndpoint,
+ Region: cfg.GlobalBlobRegion,
+ AccessKeyID: cfg.GlobalBlobAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobUsePathStyle,
+ })
+ if err != nil {
+ return fmt.Errorf("blobstore init: %w", err)
+ }
+ if store == nil {
+ return fmt.Errorf("blobstore returned nil — check endpoint/access-key env vars")
+ }
+
+ versionedKey := fmt.Sprintf("bases/%s/default.ext4", hash)
+ bucket := cfg.GlobalBlobGoldensBucket
+
+ log.Printf("uploading %s (%.1fMB, hash=%s) to %s://%s/{default.ext4, %s}",
+ path, float64(st.Size())/(1024*1024), hash, store.Name(), bucket, versionedKey)
+ t0 := time.Now()
+
+ // Long timeout — multi-GB upload over residential or cross-region network.
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
+ defer cancel()
+
+ // Upload versioned key first — it's idempotent (hash-named), so a later
+ // retry won't double-charge if the second upload fails.
+ if err := blobstore.Upload(ctx, store, bucket, versionedKey, path); err != nil {
+ return fmt.Errorf("upload %s: %w", versionedKey, err)
+ }
+ log.Printf("uploaded %s (%dms)", versionedKey, time.Since(t0).Milliseconds())
+
+ t1 := time.Now()
+ if err := blobstore.Upload(ctx, store, bucket, "default.ext4", path); err != nil {
+ return fmt.Errorf("upload default.ext4: %w", err)
+ }
+ log.Printf("uploaded default.ext4 (%dms)", time.Since(t1).Milliseconds())
+
+ log.Printf("done in %s", time.Since(t0).Round(time.Millisecond))
+ return nil
+}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 3d5194f5..a0e8971e 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -15,6 +15,7 @@ import (
"github.com/opensandbox/opensandbox/internal/analytics"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/metrics"
@@ -56,6 +57,25 @@ func main() {
return
}
+ // "golden-upload <path-to-default.ext4>" pushes the file to the global
+ // blob store at {GoldensBucket}/default.ext4 AND {GoldensBucket}/bases/{hash}/default.ext4.
+ // One-shot bootstrap path: a fresh dev cell whose AMI baked an ext4 can
+ // upload it so other cells (especially in different clouds) can pull
+ // the same canonical bytes on cache miss. Future Packer pipelines can
+ // run this at AMI-build time. Reads OPENSANDBOX_GLOBAL_BLOB_* env vars
+ // for the destination.
+ if len(os.Args) >= 2 && os.Args[1] == "golden-upload" {
+ if len(os.Args) != 3 {
+ fmt.Fprintln(os.Stderr, "usage: opensandbox-worker golden-upload <path-to-default.ext4>")
+ os.Exit(2)
+ }
+ if err := uploadGolden(os.Args[2]); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ return
+ }
+
// Load secrets from Azure Key Vault if configured (before config.Load reads env vars).
if err := config.LoadSecretsFromKeyVault(); err != nil {
log.Fatalf("failed to load secrets from Key Vault: %v", err)
@@ -108,6 +128,44 @@ func main() {
}
// QEMU backend
{
+ // Construct global blob store (Tigris primary + optional fallback).
+ // Returns nil if endpoint+access-key are unset → manager runs in
+ // local-only mode, no cache-miss fetch.
+ blobPrimary, blobErr := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobName,
+ Endpoint: cfg.GlobalBlobEndpoint,
+ Region: cfg.GlobalBlobRegion,
+ AccessKeyID: cfg.GlobalBlobAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobUsePathStyle,
+ })
+ if blobErr != nil {
+ log.Fatalf("opensandbox-worker: global blob store init failed: %v", blobErr)
+ }
+ blobFallback, fbErr := blobstore.NewS3(blobstore.S3Config{
+ Name: cfg.GlobalBlobFallbackName,
+ Endpoint: cfg.GlobalBlobFallbackEndpoint,
+ Region: cfg.GlobalBlobFallbackRegion,
+ AccessKeyID: cfg.GlobalBlobFallbackAccessKeyID,
+ SecretAccessKey: cfg.GlobalBlobFallbackSecretAccessKey,
+ UsePathStyle: cfg.GlobalBlobFallbackUsePathStyle,
+ })
+ if fbErr != nil {
+ log.Fatalf("opensandbox-worker: global blob fallback init failed: %v", fbErr)
+ }
+ var globalBlob blobstore.Store
+ if blobPrimary != nil {
+ if blobFallback != nil {
+ globalBlob, _ = blobstore.NewFallback(blobPrimary, blobFallback)
+ log.Printf("opensandbox-worker: global blob store: %s primary, %s fallback", blobPrimary.Name(), blobFallback.Name())
+ } else {
+ globalBlob = blobPrimary
+ log.Printf("opensandbox-worker: global blob store: %s (no fallback)", blobPrimary.Name())
+ }
+ } else {
+ log.Println("opensandbox-worker: global blob store disabled (endpoint unset) — local-only goldens")
+ }
+
qmCfg := qm.Config{
DataDir: cfg.DataDir,
KernelPath: cfg.KernelPath,
@@ -118,6 +176,9 @@ func main() {
DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,
DefaultCPUs: cfg.DefaultSandboxCPUs,
DefaultDiskMB: cfg.DefaultSandboxDiskMB,
+ GlobalBlob: globalBlob,
+ GlobalBlobGoldensBucket: cfg.GlobalBlobGoldensBucket,
+ GlobalBlobGoldenKey: "default.ext4",
}
qmMgr, err := qm.NewManager(qmCfg)
diff --git a/docs/dev-cutover-runbook.md b/docs/dev-cutover-runbook.md
index 76f65c0d..f7c4d8e8 100644
--- a/docs/dev-cutover-runbook.md
+++ b/docs/dev-cutover-runbook.md
@@ -32,6 +32,25 @@ and the migration risks we expect to bite.
**Prod analogue (later):** zone `opencomputer.dev`, edge `app.opencomputer.dev`,
events `events.opencomputer.workers.dev`, separate CF account.
+**Object storage**: **Tigris** (Region Earth — automatic global replication) for
+all canonical global blobs. Three separate buckets at `https://t3.storage.dev`:
+
+ - `opencomputer-events-dev` — events archive (gzipped batches per cell+day)
+ - `opencomputer-goldens-dev` — canonical golden rootfs blobs (`bases/{hash}/default.ext4`)
+ - `opencomputer-templates-dev` — canonical template rootfs+workspace blobs
+
+Three buckets (vs single bucket with prefixes) for blast-radius isolation —
+e.g., a 90-day TTL on events archive can't accidentally clobber goldens.
+
+R2 events bucket created during Stage 0 (`events-archive-dev`) stays until
+Phase 2 cutover replaces it.
+
+Per-cell S3-compat (Azure Blob, AWS S3) is still used as a local cache and
+for checkpoint storage — Tigris is for *canonical* global blobs only.
+
+Tigris credentials live in `~/.opensandbox-tigris-dev` (gitignored) and are
+pushed to Worker secrets / per-cell worker.env at deploy time.
+
## Operating principle
CF-parallel mode at all times during dev validation: PG remains authoritative
diff --git a/internal/blobstore/fallback.go b/internal/blobstore/fallback.go
new file mode 100644
index 00000000..199b3452
--- /dev/null
+++ b/internal/blobstore/fallback.go
@@ -0,0 +1,98 @@
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+)
+
+// FallbackStore wraps a primary Store with one or more fallback Stores.
+// Read operations (Get, Exists) try the primary first; on transient
+// errors (network, 5xx) they cascade through fallbacks. NotFound is
+// authoritative — we don't try fallbacks for missing objects.
+//
+// Writes (Put) go to the primary only — multi-write would create
+// consistency challenges and is overkill for the use case.
+//
+// Use case: configure Tigris as primary, R2 as fallback. If Tigris has
+// an outage, golden pulls keep working from the R2 mirror (assuming
+// you've populated it; that's an upload-side concern out of scope here).
+type FallbackStore struct {
+ primary Store
+ fallbacks []Store
+}
+
+// NewFallback wraps primary with fallback Stores. Nil primary is an error;
+// nil entries in fallbacks are ignored (so callers can pass disabled
+// backends without filtering).
+func NewFallback(primary Store, fallbacks ...Store) (Store, error) {
+ if primary == nil {
+ return nil, errors.New("blobstore: FallbackStore requires non-nil primary")
+ }
+ cleaned := make([]Store, 0, len(fallbacks))
+ for _, f := range fallbacks {
+ if f != nil {
+ cleaned = append(cleaned, f)
+ }
+ }
+ if len(cleaned) == 0 {
+ return primary, nil // no fallbacks configured — just return primary
+ }
+ return &FallbackStore{primary: primary, fallbacks: cleaned}, nil
+}
+
+func (f *FallbackStore) Name() string {
+ names := f.primary.Name()
+ for _, b := range f.fallbacks {
+ names += "+" + b.Name()
+ }
+ return names
+}
+
+func (f *FallbackStore) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ r, err := f.primary.Get(ctx, bucket, key)
+ if err == nil {
+ return r, nil
+ }
+ if errors.Is(err, ErrNotFound) {
+ // Authoritative — primary says it doesn't exist. Don't ask fallbacks.
+ return nil, err
+ }
+ for i, fb := range f.fallbacks {
+ log.Printf("blobstore: primary %s failed (%v); trying fallback %s [%d/%d]",
+ f.primary.Name(), err, fb.Name(), i+1, len(f.fallbacks))
+ r2, err2 := fb.Get(ctx, bucket, key)
+ if err2 == nil {
+ return r2, nil
+ }
+ if errors.Is(err2, ErrNotFound) {
+ // Fallback also says missing — call it ErrNotFound. Probably means
+ // the fallback isn't populated; surface so caller can decide.
+ return nil, err2
+ }
+ err = err2
+ }
+ return nil, fmt.Errorf("blobstore: all backends failed: %w", err)
+}
+
+func (f *FallbackStore) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ // Writes go only to primary. See package doc for rationale.
+ return f.primary.Put(ctx, bucket, key, body, contentLength)
+}
+
+func (f *FallbackStore) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ ok, err := f.primary.Exists(ctx, bucket, key)
+ if err == nil {
+ return ok, nil
+ }
+ for _, fb := range f.fallbacks {
+ ok2, err2 := fb.Exists(ctx, bucket, key)
+ if err2 == nil {
+ return ok2, nil
+ }
+ err = err2
+ }
+ return false, err
+}
diff --git a/internal/blobstore/io.go b/internal/blobstore/io.go
new file mode 100644
index 00000000..a6b07089
--- /dev/null
+++ b/internal/blobstore/io.go
@@ -0,0 +1,51 @@
+package blobstore
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+// writeAtomic streams r to destPath via destPath+".tmp" + rename. The
+// temp file is removed on any failure. Parent directories are created if
+// missing.
+func writeAtomic(destPath string, r io.Reader) error {
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return fmt.Errorf("blobstore: mkdir parent: %w", err)
+ }
+ tmp := destPath + ".tmp"
+ f, err := os.Create(tmp)
+ if err != nil {
+ return fmt.Errorf("blobstore: create tmp: %w", err)
+ }
+ if _, err := io.Copy(f, r); err != nil {
+ f.Close()
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: copy: %w", err)
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: close tmp: %w", err)
+ }
+ if err := os.Rename(tmp, destPath); err != nil {
+ os.Remove(tmp)
+ return fmt.Errorf("blobstore: rename: %w", err)
+ }
+ return nil
+}
+
+// openSized opens srcPath and returns the file along with its size, ready
+// for streaming Put.
+func openSized(srcPath string) (*os.File, int64, error) {
+ f, err := os.Open(srcPath)
+ if err != nil {
+ return nil, 0, fmt.Errorf("blobstore: open src: %w", err)
+ }
+ st, err := f.Stat()
+ if err != nil {
+ f.Close()
+ return nil, 0, fmt.Errorf("blobstore: stat src: %w", err)
+ }
+ return f, st.Size(), nil
+}
diff --git a/internal/blobstore/s3.go b/internal/blobstore/s3.go
new file mode 100644
index 00000000..2f80a60e
--- /dev/null
+++ b/internal/blobstore/s3.go
@@ -0,0 +1,119 @@
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+)
+
+// S3Config configures an S3-compatible backend. Works for Tigris, AWS S3,
+// CF R2, Azure Blob (via S3 compat), GCS (via interop), MinIO.
+type S3Config struct {
+ Name string // logging label: "tigris", "r2", "azure-blob"
+ Endpoint string // e.g. "https://t3.storage.dev". Empty = AWS default.
+ Region string // "auto" works for Tigris/R2; AWS needs a real region.
+ AccessKeyID string
+ SecretAccessKey string
+ UsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3.
+}
+
+// s3Store is an S3-compatible backend.
+type s3Store struct {
+ name string
+ s3 *s3.Client
+}
+
+// NewS3 constructs an S3-compatible Store. Returns nil, nil if Endpoint
+// and AccessKeyID are both empty (caller treats nil as "this backend
+// disabled, fall through to next").
+func NewS3(cfg S3Config) (Store, error) {
+ if cfg.Endpoint == "" && cfg.AccessKeyID == "" {
+ return nil, nil
+ }
+ if cfg.Region == "" {
+ cfg.Region = "auto"
+ }
+ if cfg.Name == "" {
+ cfg.Name = "s3"
+ }
+ awsCfg := aws.Config{
+ Region: cfg.Region,
+ Credentials: credentials.NewStaticCredentialsProvider(
+ cfg.AccessKeyID, cfg.SecretAccessKey, "",
+ ),
+ }
+ endpoint := cfg.Endpoint
+ client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
+ if endpoint != "" {
+ o.BaseEndpoint = &endpoint
+ }
+ o.UsePathStyle = cfg.UsePathStyle
+ })
+ return &s3Store{name: cfg.Name, s3: client}, nil
+}
+
+func (s *s3Store) Name() string { return s.name }
+
+func (s *s3Store) Get(ctx context.Context, bucket, key string) (io.ReadCloser, error) {
+ out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ })
+ if err != nil {
+ if isNotFound(err) {
+ return nil, fmt.Errorf("%s://%s/%s: %w", s.name, bucket, key, ErrNotFound)
+ }
+ return nil, fmt.Errorf("%s GetObject %s/%s: %w", s.name, bucket, key, err)
+ }
+ return out.Body, nil
+}
+
+func (s *s3Store) Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error {
+ _, err := s.s3.PutObject(ctx, &s3.PutObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ Body: body,
+ ContentLength: &contentLength,
+ })
+ if err != nil {
+ return fmt.Errorf("%s PutObject %s/%s: %w", s.name, bucket, key, err)
+ }
+ return nil
+}
+
+func (s *s3Store) Exists(ctx context.Context, bucket, key string) (bool, error) {
+ _, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{
+ Bucket: &bucket,
+ Key: &key,
+ })
+ if err == nil {
+ return true, nil
+ }
+ if isNotFound(err) {
+ return false, nil
+ }
+ return false, fmt.Errorf("%s HeadObject %s/%s: %w", s.name, bucket, key, err)
+}
+
+// isNotFound matches the various ways the v2 SDK signals 404. The typed
+// errors are nested in operation-specific wrapper types (NoSuchKey for
+// GetObject, NotFound for HeadObject) — match by code substring rather
+// than chase the type tree.
+func isNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, ErrNotFound) {
+ return true
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "NoSuchKey") ||
+ strings.Contains(msg, "NotFound") ||
+ strings.Contains(msg, "status code: 404")
+}
diff --git a/internal/blobstore/store.go b/internal/blobstore/store.go
new file mode 100644
index 00000000..891b33da
--- /dev/null
+++ b/internal/blobstore/store.go
@@ -0,0 +1,70 @@
+// Package blobstore is the abstraction over the global object store that
+// holds canonical golden rootfs blobs, template blobs, and the events
+// archive.
+//
+// We currently use Tigris (Region Earth — automatic global replication),
+// but every implementation talks S3-compatible APIs, so swapping providers
+// (R2, AWS S3, Azure Blob via S3 compat, GCS via interop, MinIO) is a
+// config change — point at a different endpoint, supply different
+// credentials. Multi-backend failover composes Stores via FallbackStore.
+//
+// The package is intentionally small: just enough surface for downloading
+// goldens on cache miss, uploading from CI/Packer, and archiving events.
+// Anything richer (presigned URLs, multipart uploads >5GB, server-side
+// copy) belongs in a higher layer if/when we need it.
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "io"
+)
+
+// ErrNotFound is returned by Get/Exists/Download when the object doesn't
+// exist. Distinguishable from transient errors so callers can fall back
+// to other behaviors (rebuild locally, try a different store, etc.).
+var ErrNotFound = errors.New("blobstore: object not found")
+
+// Store is the abstract interface every backend implements.
+//
+// Implementations should be safe for concurrent use — a single Store is
+// typically shared across goroutines (worker pool, async upload, etc.).
+type Store interface {
+ // Get streams the object at key from bucket. Caller closes the reader.
+ // Returns ErrNotFound if the object isn't present.
+ Get(ctx context.Context, bucket, key string) (io.ReadCloser, error)
+
+ // Put writes body of length contentLength bytes to bucket/key.
+ // Streams from the reader — no in-memory buffering of the full body.
+ Put(ctx context.Context, bucket, key string, body io.Reader, contentLength int64) error
+
+ // Exists returns true if the object is present at bucket/key.
+ // Returns (false, nil) on NotFound; (false, err) on other errors.
+ Exists(ctx context.Context, bucket, key string) (bool, error)
+
+ // Name returns a short identifier for logging ("tigris", "r2",
+ // "azure-blob"). Never empty.
+ Name() string
+}
+
+// Download is a convenience wrapper that streams an object to a local file
+// atomically (writes to dest+".tmp" and renames on success). Most callers
+// want this rather than the streaming Get.
+func Download(ctx context.Context, s Store, bucket, key, destPath string) error {
+ r, err := s.Get(ctx, bucket, key)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ return writeAtomic(destPath, r)
+}
+
+// Upload is a convenience wrapper that streams a local file to bucket/key.
+func Upload(ctx context.Context, s Store, bucket, key, srcPath string) error {
+ f, length, err := openSized(srcPath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return s.Put(ctx, bucket, key, f, length)
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 5d0d7fdc..08d9f11b 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -162,6 +162,34 @@ type Config struct {
// Valid values: "keyvault" (Azure), "secretsmanager" (AWS), "env" (env-var only).
// Defaults to "env" if unset.
SecretsProvider string
+
+ // Global blob store — abstract S3-compatible backend for canonical golden
+ // rootfs blobs, template blobs, and the events archive. Currently Tigris
+ // in dev (Region Earth replication), but works with any S3-compatible
+ // endpoint (R2, S3, GCS interop, Azure Blob via S3 compat). Switching
+ // providers is a config change; see internal/blobstore.
+ //
+ // Empty Endpoint disables — workers fall back to whatever's baked into
+ // the AMI / cloud-init copy.
+ GlobalBlobName string // logging label, e.g. "tigris" / "r2"
+ GlobalBlobEndpoint string // e.g. "https://t3.storage.dev"
+ GlobalBlobRegion string // "auto" for Tigris/R2; real region for AWS S3
+ GlobalBlobAccessKeyID string
+ GlobalBlobSecretAccessKey string
+ GlobalBlobUsePathStyle bool // true for R2/Tigris/MinIO; false for AWS S3
+ GlobalBlobGoldensBucket string
+ GlobalBlobTemplatesBucket string
+ GlobalBlobEventsBucket string
+
+ // Optional fallback backend used when the primary fails on transient errors
+ // (network / 5xx). NotFound from the primary is authoritative — fallbacks
+ // aren't consulted. Empty disables.
+ GlobalBlobFallbackName string
+ GlobalBlobFallbackEndpoint string
+ GlobalBlobFallbackRegion string
+ GlobalBlobFallbackAccessKeyID string
+ GlobalBlobFallbackSecretAccessKey string
+ GlobalBlobFallbackUsePathStyle bool
}
// Load reads configuration from environment variables with sensible defaults.
@@ -268,6 +296,23 @@ func Load() (*Config, error) {
ComputeProvider: os.Getenv("OPENSANDBOX_COMPUTE_PROVIDER"),
SecretsProvider: envOrDefault("OPENSANDBOX_SECRETS_PROVIDER", "env"),
+
+ GlobalBlobName: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_NAME", "tigris"),
+ GlobalBlobEndpoint: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_ENDPOINT"),
+ GlobalBlobRegion: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_REGION", "auto"),
+ GlobalBlobAccessKeyID: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID"),
+ GlobalBlobSecretAccessKey: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_SECRET_ACCESS_KEY"),
+ GlobalBlobUsePathStyle: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_USE_PATH_STYLE", "true") == "true",
+ GlobalBlobGoldensBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET"),
+ GlobalBlobTemplatesBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_TEMPLATES_BUCKET"),
+ GlobalBlobEventsBucket: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_EVENTS_BUCKET"),
+
+ GlobalBlobFallbackName: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_NAME"),
+ GlobalBlobFallbackEndpoint: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ENDPOINT"),
+ GlobalBlobFallbackRegion: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_REGION", "auto"),
+ GlobalBlobFallbackAccessKeyID: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ACCESS_KEY_ID"),
+ GlobalBlobFallbackSecretAccessKey: os.Getenv("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_SECRET_ACCESS_KEY"),
+ GlobalBlobFallbackUsePathStyle: envOrDefault("OPENSANDBOX_GLOBAL_BLOB_FALLBACK_USE_PATH_STYLE", "true") == "true",
}
if cfg.SentryEnvironment == "" {
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index 3e4f1aa4..9cd0789a 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -18,19 +18,23 @@ package config
import (
"context"
- "fmt"
- "log"
"os"
- "strings"
"time"
- "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
- "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"
+ "github.com/opensandbox/opensandbox/internal/secrets"
)
-// secretMapping maps Key Vault secret names to environment variable names.
-// Only secrets in this map are loaded — unknown secrets in the vault are ignored.
-var secretMapping = map[string]string{
+// kvMapping maps Key Vault entry names to environment variable names. Despite
+// the historical "secret" terminology this includes both real secrets (DB
+// passwords, JWT keys) and non-secret cell config (region, cell_id, capacity
+// tuning). The principle: only bootstrap pointers + per-VM identity stay in
+// the env file; everything else is in KV so a cell's configuration is one
+// source-of-truth rather than scattered across N worker.env files.
+//
+// Entries not in this map are silently ignored — the allowlist is the
+// safety guard preventing a stray vault entry from accidentally shadowing
+// an unrelated env var (e.g., PATH).
+var kvMapping = map[string]string{
// Server secrets
"server-database-url": "OPENSANDBOX_DATABASE_URL",
"server-redis-url": "OPENSANDBOX_REDIS_URL",
@@ -53,6 +57,45 @@ var secretMapping = map[string]string{
"worker-s3-secret-key": "OPENSANDBOX_S3_SECRET_ACCESS_KEY",
"worker-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",
+ // Worker per-cell config (non-secret but cell-scoped — every worker in the
+ // cell shares these, so KV is the single source of truth)
+ "worker-region": "OPENSANDBOX_REGION",
+ "worker-cell-id": "OPENSANDBOX_CELL_ID",
+ "worker-max-capacity": "OPENSANDBOX_MAX_CAPACITY",
+ "worker-default-sandbox-memory-mb": "OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB",
+ "worker-default-sandbox-cpus": "OPENSANDBOX_DEFAULT_SANDBOX_CPUS",
+ "worker-default-sandbox-disk-mb": "OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB",
+ "worker-sandbox-domain": "OPENSANDBOX_SANDBOX_DOMAIN",
+ "worker-s3-bucket": "OPENSANDBOX_S3_BUCKET",
+ "worker-s3-region": "OPENSANDBOX_S3_REGION",
+ "worker-s3-endpoint": "OPENSANDBOX_S3_ENDPOINT",
+ "worker-s3-force-path-style": "OPENSANDBOX_S3_FORCE_PATH_STYLE",
+ "worker-cf-event-endpoint": "OPENSANDBOX_CF_EVENT_ENDPOINT",
+ "worker-halt-list-url": "OPENSANDBOX_HALT_LIST_URL",
+ "worker-segment-write-key": "SEGMENT_WRITE_KEY",
+
+ // CF-cutover event pipe (worker)
+ "worker-cf-event-secret": "OPENSANDBOX_CF_EVENT_SECRET",
+ "worker-cf-admin-secret": "OPENSANDBOX_CF_ADMIN_SECRET",
+ "worker-session-jwt-secret": "OPENSANDBOX_SESSION_JWT_SECRET",
+
+ // Phase 2 — global blob store (Tigris primary)
+ "worker-global-blob-name": "OPENSANDBOX_GLOBAL_BLOB_NAME",
+ "worker-global-blob-endpoint": "OPENSANDBOX_GLOBAL_BLOB_ENDPOINT",
+ "worker-global-blob-region": "OPENSANDBOX_GLOBAL_BLOB_REGION",
+ "worker-global-blob-access-key-id": "OPENSANDBOX_GLOBAL_BLOB_ACCESS_KEY_ID",
+ "worker-global-blob-secret-access-key": "OPENSANDBOX_GLOBAL_BLOB_SECRET_ACCESS_KEY",
+ "worker-global-blob-goldens-bucket": "OPENSANDBOX_GLOBAL_BLOB_GOLDENS_BUCKET",
+ "worker-global-blob-templates-bucket": "OPENSANDBOX_GLOBAL_BLOB_TEMPLATES_BUCKET",
+ "worker-global-blob-events-bucket": "OPENSANDBOX_GLOBAL_BLOB_EVENTS_BUCKET",
+
+ // Phase 2 — global blob store (optional fallback)
+ "worker-global-blob-fallback-name": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_NAME",
+ "worker-global-blob-fallback-endpoint": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ENDPOINT",
+ "worker-global-blob-fallback-region": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_REGION",
+ "worker-global-blob-fallback-access-key-id": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_ACCESS_KEY_ID",
+ "worker-global-blob-fallback-secret-access-key": "OPENSANDBOX_GLOBAL_BLOB_FALLBACK_SECRET_ACCESS_KEY",
+
// Shared
"pg-password": "OPENSANDBOX_PG_PASSWORD",
}
@@ -61,73 +104,28 @@ var secretMapping = map[string]string{
// as environment variables. Only loads secrets relevant to the current mode
// (server or worker), determined by the secret name prefix.
//
-// Skips secrets that are already set in the environment.
-// Does nothing if SECRETS_VAULT_NAME is not set.
+// Skips secrets that are already set in the environment — local env wins
+// (the .env file is the "emergency override" path).
+//
+// Does nothing if SECRETS_VAULT_NAME is not set. Now delegates to the
+// internal/secrets KeyVaultBackend so server, worker, and the AzurePool
+// runtime image-refresh path share one implementation.
func LoadSecretsFromKeyVault() error {
vaultName := os.Getenv("SECRETS_VAULT_NAME")
if vaultName == "" {
return nil // Key Vault not configured — use env file as-is
}
-
- vaultURL := fmt.Sprintf("https://%s.vault.azure.net/", vaultName)
mode := os.Getenv("OPENSANDBOX_MODE") // "server" or "worker"
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- cred, err := azidentity.NewDefaultAzureCredential(nil)
- if err != nil {
- return fmt.Errorf("keyvault: azure credential: %w", err)
- }
-
- client, err := azsecrets.NewClient(vaultURL, cred, nil)
+ be, err := secrets.NewKeyVaultBackend(vaultName, kvMapping, mode)
if err != nil {
- return fmt.Errorf("keyvault: client: %w", err)
+ return err
}
-
- loaded := 0
- skipped := 0
-
- pager := client.NewListSecretPropertiesPager(nil)
- for pager.More() {
- page, err := pager.NextPage(ctx)
- if err != nil {
- return fmt.Errorf("keyvault: list secrets: %w", err)
- }
-
- for _, prop := range page.Value {
- name := prop.ID.Name()
- envVar, mapped := secretMapping[name]
- if !mapped {
- continue
- }
-
- // Only load secrets matching the current mode (or shared secrets)
- if mode != "" && !strings.HasPrefix(name, mode+"-") && !strings.HasPrefix(name, "pg-") {
- continue
- }
-
- // Don't overwrite existing env vars — local config takes precedence
- if os.Getenv(envVar) != "" {
- skipped++
- continue
- }
-
- // Fetch the secret value
- resp, err := client.GetSecret(ctx, name, "", nil)
- if err != nil {
- log.Printf("keyvault: failed to get secret %s: %v (skipping)", name, err)
- continue
- }
- if resp.Value == nil {
- continue
- }
-
- os.Setenv(envVar, *resp.Value)
- loaded++
- }
+ if be == nil {
+ return nil // shouldn't happen — vaultName non-empty was checked above
}
-
- log.Printf("keyvault: loaded %d secrets from %s (%d skipped, already set)", loaded, vaultName, skipped)
- return nil
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ _, _, err = be.LoadAllToEnv(ctx)
+ return err
}
diff --git a/internal/qemu/blobstore_fetch.go b/internal/qemu/blobstore_fetch.go
new file mode 100644
index 00000000..3e3f35b0
--- /dev/null
+++ b/internal/qemu/blobstore_fetch.go
@@ -0,0 +1,80 @@
+package qemu
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/blobstore"
+)
+
+// ensureBaseImageFromBlob makes sure ImagesDir/default.ext4 exists locally.
+// If it's already on disk, returns nil immediately (no-op for the steady
+// state where the AMI baked in default.ext4).
+//
+// Otherwise, if a global blob store is configured, fetches default.ext4
+// from {GlobalBlobGoldensBucket}/{GlobalBlobGoldenKey} and writes it to
+// ImagesDir/default.ext4 atomically.
+//
+// Used by:
+// - PrepareGoldenSnapshot (worker startup) — ensure local copy before
+// building the runtime golden snapshot
+// - First-run on a fresh cell whose AMI doesn't carry the rootfs (e.g.
+// a thin AMI shared across clouds)
+//
+// Returns nil with a log warning if blobstore is unconfigured — callers
+// proceed with whatever's local (or fail downstream with a clear error).
+func (m *Manager) ensureBaseImageFromBlob(ctx context.Context) error {
+ target := filepath.Join(m.cfg.ImagesDir, "default.ext4")
+ if fileExists(target) {
+ return nil // already cached locally
+ }
+
+ if m.cfg.GlobalBlob == nil {
+ log.Printf("qemu: %s missing and no global blob store configured", target)
+ return nil // not an error here — caller logs/handles missing rootfs
+ }
+
+ bucket := m.cfg.GlobalBlobGoldensBucket
+ key := m.cfg.GlobalBlobGoldenKey
+ if key == "" {
+ key = "default.ext4"
+ }
+ if bucket == "" {
+ return errors.New("qemu: GlobalBlobGoldensBucket required to fetch from blob store")
+ }
+
+ log.Printf("qemu: %s missing, fetching from %s://%s/%s", target, m.cfg.GlobalBlob.Name(), bucket, key)
+ t0 := time.Now()
+
+ // Use a long timeout — golden blob is multi-GB.
+ dlCtx, cancel := context.WithTimeout(ctx, 15*time.Minute)
+ defer cancel()
+
+ if err := blobstore.Download(dlCtx, m.cfg.GlobalBlob, bucket, key, target); err != nil {
+ // Clean up any half-written tmp file (Download already does this on
+ // most paths but be defensive).
+ os.Remove(target + ".tmp")
+ return fmt.Errorf("download %s/%s: %w", bucket, key, err)
+ }
+
+ // Sanity check the downloaded file is non-trivial.
+ st, err := os.Stat(target)
+ if err != nil {
+ return fmt.Errorf("stat downloaded ext4: %w", err)
+ }
+ if st.Size() < 64*1024*1024 {
+ // Anything under 64MB is almost certainly corrupt — a real rootfs
+ // is multi-GB. Refuse to proceed; let the caller surface the error.
+ os.Remove(target)
+ return fmt.Errorf("downloaded ext4 suspiciously small (%d bytes), refusing to use", st.Size())
+ }
+
+ log.Printf("qemu: fetched %s from blob store (%.1fMB, %dms)",
+ target, float64(st.Size())/(1024*1024), time.Since(t0).Milliseconds())
+ return nil
+}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 51402be5..4d68b7cf 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -20,6 +20,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
@@ -140,6 +141,17 @@ type Config struct {
DefaultCPUs int
DefaultDiskMB int
DefaultPort int
+
+ // GlobalBlob is the abstract S3-compat backend (Tigris, R2, etc.) the
+ // worker pulls canonical golden rootfs blobs from on cache miss.
+ // Nil disables — worker falls back to local-only behavior (whatever
+ // the AMI baked in or cloud-init copied).
+ GlobalBlob blobstore.Store
+ GlobalBlobGoldensBucket string // e.g. "opencomputer-goldens-dev"
+ // GlobalBlobGoldenKey is the path within the goldens bucket. Defaults
+ // to "default.ext4" if empty. Versioned variants (bases/{hash}/...) are
+ // resolved by the existing checkpoint-rebase path, not this fallback.
+ GlobalBlobGoldenKey string
}
// Manager implements sandbox.Manager using QEMU VMs.
@@ -298,6 +310,13 @@ func (m *Manager) sealSandboxEnvs(ctx context.Context, sandboxID string, netCfg
// restore from this snapshot instead of cold-booting, cutting start time
// from ~10s to ~1-2s.
func (m *Manager) PrepareGoldenSnapshot() error {
+ // Multi-region cache-miss fallback: if no local default.ext4 (e.g., this
+ // is a fresh worker on a new cell whose AMI didn't bake one in), try to
+ // pull from the configured global blob store before failing.
+ if err := m.ensureBaseImageFromBlob(context.Background()); err != nil {
+ log.Printf("qemu: blobstore golden fetch failed (will try local-only): %v", err)
+ }
+
goldenDir := filepath.Join(m.cfg.DataDir, "golden")
memFile := filepath.Join(goldenDir, "mem")
rootfsFile := filepath.Join(goldenDir, "rootfs.qcow2")
diff --git a/internal/secrets/backend.go b/internal/secrets/backend.go
index afd9b3cd..f026f6d2 100644
--- a/internal/secrets/backend.go
+++ b/internal/secrets/backend.go
@@ -1,13 +1,19 @@
// Package secrets provides a cloud-neutral runtime secrets fetcher.
//
// Implementations:
-// - EnvBackend (default; reads from OS env vars)
-// - KeyVaultBackend (Azure Key Vault, in keyvault.go — build-tag isolated)
-// - SecretsManagerBackend (AWS Secrets Manager, in secretsmanager.go — build-tag isolated)
+// - EnvBackend (default; reads from OS env vars)
+// - KeyVaultBackend (Azure Key Vault — keyvault.go)
+// - SecretsManagerBackend (AWS Secrets Manager — secretsmanager.go)
+// - GCPSecretManager etc. (future; mirror the same pattern)
//
-// The CP picks a backend based on cfg.SecretsProvider at startup. Most
-// callers can use the default Env backend; cloud-specific code paths
-// (e.g., AzurePool's dynamic image refresh) take a Backend explicitly.
+// Most paas-style clouds offer a Key-Vault-equivalent (HashiCorp Vault,
+// Doppler, Infisical, Bitwarden Secrets Manager, etc). All of them satisfy
+// the Backend interface; adding one is a new file implementing Get + the
+// optional BulkLoader, plus a case in cmd/server/main.go's selector.
+//
+// The CP/worker picks a backend based on cfg.SecretsProvider at startup.
+// Cloud-specific code paths (AzurePool dynamic image refresh, server
+// bootstrap config) take a Backend explicitly.
package secrets
import (
@@ -25,6 +31,17 @@ type Backend interface {
Get(ctx context.Context, key string) (string, error)
}
+// BulkLoader is the optional bootstrap pattern: load every secret in a
+// scope into the process environment in one call. Used at server/worker
+// startup to populate config without a per-secret Get call. Backends that
+// don't naturally enumerate (e.g., raw HashiCorp Vault paths) can omit it.
+//
+// Returned counts: loaded = newly-set env vars; skipped = ones already
+// present in env (env wins by convention — local overrides for dev).
+type BulkLoader interface {
+ LoadAllToEnv(ctx context.Context) (loaded, skipped int, err error)
+}
+
// EnvBackend reads secrets from process environment variables.
// Useful for local development and as a fallback when no cloud backend
// is configured.
diff --git a/internal/secrets/json_bundle.go b/internal/secrets/json_bundle.go
index db9c159e..ef37d3a5 100644
--- a/internal/secrets/json_bundle.go
+++ b/internal/secrets/json_bundle.go
@@ -8,9 +8,9 @@ import (
// parseBundleJSON returns secrets[key] from a JSON-encoded object string.
// Used by Backend implementations that store multiple secrets per ARN/version.
func parseBundleJSON(s, key string) (string, error) {
- var bundle map[string]string
- if err := json.Unmarshal([]byte(s), &bundle); err != nil {
- return "", fmt.Errorf("secrets: bundle JSON parse: %w", err)
+ bundle, err := parseBundleJSONAll(s)
+ if err != nil {
+ return "", err
}
v, ok := bundle[key]
if !ok {
@@ -18,3 +18,14 @@ func parseBundleJSON(s, key string) (string, error) {
}
return v, nil
}
+
+// parseBundleJSONAll returns the full {key: value} map from a JSON-encoded
+// object string. Used by BulkLoader implementations that copy every entry
+// into the process environment.
+func parseBundleJSONAll(s string) (map[string]string, error) {
+ var bundle map[string]string
+ if err := json.Unmarshal([]byte(s), &bundle); err != nil {
+ return nil, fmt.Errorf("secrets: bundle JSON parse: %w", err)
+ }
+ return bundle, nil
+}
diff --git a/internal/secrets/keyvault.go b/internal/secrets/keyvault.go
new file mode 100644
index 00000000..e599d82f
--- /dev/null
+++ b/internal/secrets/keyvault.go
@@ -0,0 +1,145 @@
+package secrets
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "strings"
+
+ "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
+ "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"
+)
+
+// KeyVaultBackend reads secrets from Azure Key Vault.
+//
+// Authentication uses Azure DefaultAzureCredential (Managed Identity on VMs,
+// CLI credentials locally) — no static keys to manage.
+//
+// Two modes:
+//
+// - Get(name) — fetch a single secret by Key Vault name. Used by AzurePool
+// for dynamic image-version refresh and any other on-demand lookups.
+//
+// - LoadAllToEnv (BulkLoader) — list every secret in the vault, map names to
+// env var names via NameMap, and Setenv anything not already set. Used at
+// server/worker bootstrap. ModePrefixFilter restricts to "server-*" or
+// "worker-*" depending on which binary is running, so a worker doesn't
+// pull stripe-secret-key etc. into its env.
+type KeyVaultBackend struct {
+ client *azsecrets.Client
+ vault string
+
+ // NameMap maps Key Vault secret name → env var name. Only entries in
+ // this map are loaded by LoadAllToEnv. Empty NameMap = noop bulk-load.
+ NameMap map[string]string
+
+ // ModePrefixFilter restricts LoadAllToEnv to secrets whose name starts
+ // with "{ModePrefixFilter}-" (plus shared "pg-*" etc.). Empty = no filter.
+ // Typical: "server" or "worker".
+ ModePrefixFilter string
+}
+
+// NewKeyVaultBackend constructs a backend pointed at vaultName. Returns
+// (nil, nil) if vaultName is empty (caller treats nil as "Key Vault
+// disabled, fall back to EnvBackend"). Returns an error only if the
+// Azure SDK can't create credentials/client at all.
+func NewKeyVaultBackend(vaultName string, nameMap map[string]string, modePrefix string) (*KeyVaultBackend, error) {
+ if vaultName == "" {
+ return nil, nil
+ }
+ cred, err := azidentity.NewDefaultAzureCredential(nil)
+ if err != nil {
+ return nil, fmt.Errorf("keyvault: azure credential: %w", err)
+ }
+ vaultURL := fmt.Sprintf("https://%s.vault.azure.net/", vaultName)
+ client, err := azsecrets.NewClient(vaultURL, cred, nil)
+ if err != nil {
+ return nil, fmt.Errorf("keyvault: client: %w", err)
+ }
+ return &KeyVaultBackend{
+ client: client,
+ vault: vaultName,
+ NameMap: nameMap,
+ ModePrefixFilter: modePrefix,
+ }, nil
+}
+
+// Get returns the secret value for the named secret. The Key Vault `name`
+// is the bare secret name, not a versioned URL — Key Vault returns the
+// current version when version is "".
+func (b *KeyVaultBackend) Get(ctx context.Context, name string) (string, error) {
+ resp, err := b.client.GetSecret(ctx, name, "", nil)
+ if err != nil {
+ // Azure returns 404 wrapped in azcore.ResponseError; match by
+ // substring rather than chase the type tree, same convention the
+ // blobstore S3 client uses.
+ if isKVNotFound(err) {
+ return "", fmt.Errorf("keyvault://%s/%s: %w", b.vault, name, ErrNotFound)
+ }
+ return "", fmt.Errorf("keyvault: GetSecret %s/%s: %w", b.vault, name, err)
+ }
+ if resp.Value == nil {
+ return "", fmt.Errorf("keyvault://%s/%s: %w", b.vault, name, ErrNotFound)
+ }
+ return *resp.Value, nil
+}
+
+// LoadAllToEnv lists every secret in the vault, applies NameMap +
+// ModePrefixFilter, and Setenv anything not already in the process
+// environment. Implements BulkLoader.
+//
+// Existing env vars take precedence — local overrides win, vault never
+// clobbers an existing value. Returns (loaded, skipped, err).
+func (b *KeyVaultBackend) LoadAllToEnv(ctx context.Context) (loaded, skipped int, err error) {
+ if len(b.NameMap) == 0 {
+ return 0, 0, nil
+ }
+ pager := b.client.NewListSecretPropertiesPager(nil)
+ for pager.More() {
+ page, perr := pager.NextPage(ctx)
+ if perr != nil {
+ return loaded, skipped, fmt.Errorf("keyvault: list secrets: %w", perr)
+ }
+ for _, prop := range page.Value {
+ name := prop.ID.Name()
+ envVar, mapped := b.NameMap[name]
+ if !mapped {
+ continue
+ }
+ if b.ModePrefixFilter != "" &&
+ !strings.HasPrefix(name, b.ModePrefixFilter+"-") &&
+ !strings.HasPrefix(name, "pg-") {
+ continue
+ }
+ if os.Getenv(envVar) != "" {
+ skipped++
+ continue
+ }
+ resp, gerr := b.client.GetSecret(ctx, name, "", nil)
+ if gerr != nil {
+ log.Printf("keyvault: failed to get secret %s: %v (skipping)", name, gerr)
+ continue
+ }
+ if resp.Value == nil {
+ continue
+ }
+ os.Setenv(envVar, *resp.Value)
+ loaded++
+ }
+ }
+ log.Printf("keyvault: loaded %d secrets from %s (%d skipped, already set)", loaded, b.vault, skipped)
+ return loaded, skipped, nil
+}
+
+// isKVNotFound matches the various ways azsecrets signals "secret not
+// found" in a way that doesn't require importing the typed error.
+func isKVNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ msg := err.Error()
+ return strings.Contains(msg, "SecretNotFound") ||
+ strings.Contains(msg, "404") ||
+ strings.Contains(msg, "not found")
+}
diff --git a/internal/secrets/secretsmanager.go b/internal/secrets/secretsmanager.go
index 655aab10..d8a93db9 100644
--- a/internal/secrets/secretsmanager.go
+++ b/internal/secrets/secretsmanager.go
@@ -3,6 +3,7 @@ package secrets
import (
"context"
"fmt"
+ "os"
"strings"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
@@ -68,6 +69,36 @@ 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).
+//
+// Returns (loaded, 0, err) — SecretsManager doesn't track skipped because
+// the bundle keys are arbitrary, not enumerated through a name map.
+func (b *SecretsManagerBackend) LoadAllToEnv(ctx context.Context) (loaded, skipped int, err error) {
+ if b.bundledARN == "" {
+ return 0, 0, nil // nothing to bulk-load
+ }
+ bundleStr, err := b.getRaw(ctx, b.bundledARN)
+ if err != nil {
+ return 0, 0, err
+ }
+ pairs, err := parseBundleJSONAll(bundleStr)
+ if err != nil {
+ return 0, 0, err
+ }
+ for k, v := range pairs {
+ if os.Getenv(k) != "" {
+ skipped++
+ continue
+ }
+ os.Setenv(k, v)
+ loaded++
+ }
+ return loaded, skipped, nil
+}
+
func (b *SecretsManagerBackend) getRaw(ctx context.Context, arn string) (string, error) {
out, err := b.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{
SecretId: &arn,