Skip to content

An open-source, faster Devin alternative

TypeScript

fix: shareable runtime/hands snapshots for act-as-org provisioning (SEV)

Igor Zalutski7555f832b622
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 09e4f661..ab2c2ae9 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1859,17 +1859,21 @@ export default {
return json({ error: "method not allowed" }, 405);
}
{
- // /api/snapshots/:name and /api/snapshots/:name/patches[/:patchId]
- const m = path.match(/^\/api\/snapshots\/([^/]+)(\/patches(?:\/[^/]+)?)?$/);
+ // /api/snapshots/:name, /api/snapshots/:name/patches[/:patchId],
+ // /api/snapshots/:name/publish, /api/snapshots/:name/unpublish
+ const m = path.match(/^\/api\/snapshots\/([^/]+)(\/patches(?:\/[^/]+)?|\/(?:un)?publish)?$/);
if (m) {
const name = decodeURIComponent(m[1]);
- const isPatch = !!m[2];
+ const sub = m[2] ?? "";
+ const isPatch = sub.startsWith("/patches");
+ const isPublishToggle = sub === "/publish" || sub === "/unpublish";
const caller = await authenticate(req, env);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
{ const g = provisionScopeGate(caller, path); if (g) return g; }
- // Patches + delete are cell-work — route to the cell that owns the
- // snapshot bytes (looked up from D1), not "any active cell".
- if (isPatch || req.method === "DELETE") {
+ // Patches, publish/unpublish, and delete are cell-work — route to the
+ // cell that owns the snapshot bytes (looked up from D1), not "any active
+ // cell". is_public lives in the owning cell's image_cache.
+ if (isPatch || isPublishToggle || req.method === "DELETE") {
const ownerCell = await snapshots.ownerCellOfSnapshot(env, caller, name);
if (!ownerCell) return json({ error: "snapshot not found" }, 404);
return proxyToCellAuthed(req, env, caller, { cellId: ownerCell });
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index cf95f4fc..a574fec8 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -651,7 +651,11 @@ func (s *Server) resolveSnapshot(ctx context.Context, orgID uuid.UUID, snapshotN
return uuid.Nil, fmt.Errorf("database not configured")
}
- cached, err := s.store.GetImageCacheByName(ctx, orgID, snapshotName)
+ // Fork/provision path: resolve the org's own snapshot, falling back to a
+ // public one (e.g. the shared platform runtime/hands snapshots) when the org
+ // doesn't own one. Forking only reads the checkpoint, never mutates it, so
+ // sharing is safe. Management endpoints stay org-scoped (GetImageCacheByName).
+ cached, err := s.store.ResolveImageCacheByName(ctx, orgID, snapshotName)
if err != nil {
return uuid.Nil, fmt.Errorf("snapshot %q not found: %w", snapshotName, err)
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 76db323b..998f2ed2 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -585,6 +585,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/snapshots/:name/patches", s.listSnapshotPatches)
api.DELETE("/snapshots/:name/patches/:patchId", s.deleteSnapshotPatch)
+ // Publish/unpublish a named snapshot (owner-org only) so other orgs can fork
+ // it — used to share the platform runtime/hands snapshots.
+ api.POST("/snapshots/:name/publish", s.publishSnapshot)
+ api.POST("/snapshots/:name/unpublish", s.unpublishSnapshot)
+
// Images (all cached images, named or unnamed)
api.GET("/images", s.listImages)
diff --git a/internal/api/snapshots.go b/internal/api/snapshots.go
index 8b088b3c..b7ed0b3e 100644
--- a/internal/api/snapshots.go
+++ b/internal/api/snapshots.go
@@ -334,6 +334,40 @@ func (s *Server) deleteSnapshot(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
+
+// publishSnapshot handles POST /api/snapshots/:name/publish — marks a named
+// snapshot public so any org can fork it. Used to share the platform
+// runtime/hands snapshots with customer-org (act-as-org) sessions. Owner-org
+// only; idempotent. Mirrors publishCheckpoint.
+func (s *Server) publishSnapshot(c echo.Context) error {
+ return s.setSnapshotPublic(c, true)
+}
+
+// unpublishSnapshot flips is_public back to false. Owner-org only, idempotent.
+// In-flight forks that already resolved the snapshot continue; new forks by
+// other orgs stop resolving it.
+func (s *Server) unpublishSnapshot(c echo.Context) error {
+ return s.setSnapshotPublic(c, false)
+}
+
+func (s *Server) setSnapshotPublic(c echo.Context, isPublic bool) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+
+ name := c.Param("name")
+ if err := s.store.SetImageCachePublicByName(c.Request().Context(), orgID, name, isPublic); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+
+ return c.JSON(http.StatusOK, map[string]any{"name": name, "public": isPublic})
+}
+
func (s *Server) resolveNamedCheckpoint(c echo.Context, label string) (uuid.UUID, error) {
orgID, ok := auth.GetOrgID(c)
if !ok {
diff --git a/internal/db/image_cache_resolve_pgfixture_test.go b/internal/db/image_cache_resolve_pgfixture_test.go
new file mode 100644
index 00000000..6fcfaf1b
--- /dev/null
+++ b/internal/db/image_cache_resolve_pgfixture_test.go
@@ -0,0 +1,104 @@
+//go:build pgfixture
+
+// Resolve-path semantics for shared named snapshots. Runs only under
+// `go test -tags=pgfixture` against a real Postgres pointed at by
+// TEST_DATABASE_URL. Proves the act-as-org SEV fix: a customer org can fork a
+// public platform snapshot it does not own, the org's own row still wins when
+// both exist, and publish/unpublish is strictly owner-scoped.
+//
+// Run locally:
+//
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db/ -run ResolveImageCache -v
+package db
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+// seedNamedSnapshot inserts a ready named snapshot owned by orgID. is_public
+// defaults to false (set via SetImageCachePublicByName in the test).
+func seedNamedSnapshot(t *testing.T, store *Store, orgID uuid.UUID, name, contentHash string) {
+ t.Helper()
+ cp := uuid.New()
+ if _, err := store.pool.Exec(context.Background(),
+ `INSERT INTO image_cache (id, org_id, content_hash, checkpoint_id, name, manifest, status)
+ VALUES ($1, $2, $3, NULL, $4, $5, 'ready')`,
+ cp, orgID, contentHash, name, json.RawMessage(`{}`)); err != nil {
+ t.Fatalf("seed snapshot %q for %s: %v", name, orgID, err)
+ }
+}
+
+func TestResolveImageCacheByName_PublicFallback(t *testing.T) {
+ store := openPgStore(t)
+ ctx := context.Background()
+
+ owner := seedOrgWithCap(t, store, 64) // platform org that owns the snapshot
+ requester := seedOrgWithCap(t, store, 64) // customer org (act-as-org)
+ const name = "runtime-claude-pgfixture"
+
+ seedNamedSnapshot(t, store, owner, name, "hash-owner-"+uuid.NewString())
+
+ // Private: a non-owner cannot resolve it (this was the SEV).
+ if _, err := store.ResolveImageCacheByName(ctx, requester, name); err == nil {
+ t.Fatalf("expected not-found resolving private snapshot as non-owner")
+ }
+ // Owner can always resolve their own, public or not.
+ if _, err := store.ResolveImageCacheByName(ctx, owner, name); err != nil {
+ t.Fatalf("owner resolve of own private snapshot: %v", err)
+ }
+
+ // Publish, then the non-owner resolves it and gets the owner's row.
+ if err := store.SetImageCachePublicByName(ctx, owner, name, true); err != nil {
+ t.Fatalf("publish: %v", err)
+ }
+ got, err := store.ResolveImageCacheByName(ctx, requester, name)
+ if err != nil {
+ t.Fatalf("non-owner resolve of public snapshot: %v", err)
+ }
+ if got.OrgID != owner {
+ t.Fatalf("expected owner's row %s, got %s", owner, got.OrgID)
+ }
+
+ // Org's own row wins over a public one with the same name.
+ seedNamedSnapshot(t, store, requester, name, "hash-req-"+uuid.NewString())
+ got, err = store.ResolveImageCacheByName(ctx, requester, name)
+ if err != nil {
+ t.Fatalf("resolve with own + public present: %v", err)
+ }
+ if got.OrgID != requester {
+ t.Fatalf("expected requester's own row %s to win, got %s", requester, got.OrgID)
+ }
+
+ // Unpublish removes the fallback for non-owners; the owner still resolves it.
+ if err := store.SetImageCachePublicByName(ctx, owner, name, false); err != nil {
+ t.Fatalf("unpublish: %v", err)
+ }
+ stranger := seedOrgWithCap(t, store, 64)
+ if _, err := store.ResolveImageCacheByName(ctx, stranger, name); err == nil {
+ t.Fatalf("expected not-found after unpublish for a stranger org")
+ }
+}
+
+func TestSetImageCachePublicByName_OwnerScoped(t *testing.T) {
+ store := openPgStore(t)
+ ctx := context.Background()
+
+ owner := seedOrgWithCap(t, store, 64)
+ other := seedOrgWithCap(t, store, 64)
+ const name = "runtime-codex-pgfixture"
+ seedNamedSnapshot(t, store, owner, name, "hash-"+uuid.NewString())
+
+ // A non-owner cannot publish someone else's snapshot.
+ if err := store.SetImageCachePublicByName(ctx, other, name, true); err == nil {
+ t.Fatalf("expected error publishing a snapshot not owned by org")
+ }
+ // And it stays unresolvable for a non-owner.
+ if _, err := store.ResolveImageCacheByName(ctx, other, name); err == nil {
+ t.Fatalf("expected snapshot to remain private after failed publish")
+ }
+}
diff --git a/internal/db/migrations/051_image_cache_is_public.down.sql b/internal/db/migrations/051_image_cache_is_public.down.sql
new file mode 100644
index 00000000..5191fe7f
--- /dev/null
+++ b/internal/db/migrations/051_image_cache_is_public.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE image_cache
+ DROP COLUMN IF EXISTS is_public;
diff --git a/internal/db/migrations/051_image_cache_is_public.up.sql b/internal/db/migrations/051_image_cache_is_public.up.sql
new file mode 100644
index 00000000..7b24abd1
--- /dev/null
+++ b/internal/db/migrations/051_image_cache_is_public.up.sql
@@ -0,0 +1,26 @@
+-- Make specific named snapshots shareable across orgs.
+--
+-- Background (prod SEV): runtime brain/hands images (runtime-claude-*,
+-- runtime-codex-*, hands-base-*) are stored as named snapshots in image_cache,
+-- all owned by the platform org. Before act-as-org ownership shipped
+-- (2026-06-28) every session provisioned under the platform org, so the
+-- org-scoped snapshot lookup (GetImageCacheByName: WHERE org_id=$1 AND name=$2)
+-- found them. With act-as-org, sessions provision under the CUSTOMER org, and
+-- that lookup returns "snapshot not found" -> provision_failed for every org
+-- except the one that owns the snapshots.
+--
+-- is_public lets the resolve/fork path fall back to a shared snapshot when the
+-- requesting org doesn't own one, mirroring templates.is_public and
+-- sandbox_checkpoints.is_public. Management endpoints (get/list/delete/patch)
+-- stay strictly org-scoped; only the owner may mutate, delete, or publish.
+ALTER TABLE image_cache
+ ADD COLUMN IF NOT EXISTS is_public BOOLEAN NOT NULL DEFAULT false;
+
+-- Backfill: publish the platform runtime/hands snapshots so customer-org
+-- provisions can fork them. Scoped by name pattern; idempotent and a no-op on
+-- cells that don't host these snapshots (only azure-us-east-2-a does today).
+-- Future runtime versions are published explicitly via the publish endpoint
+-- (POST /api/snapshots/:name/publish) by the build tooling.
+UPDATE image_cache
+ SET is_public = true
+ WHERE name LIKE 'runtime-%' OR name LIKE 'hands-%';
diff --git a/internal/db/store.go b/internal/db/store.go
index 04f2ef70..7b0593e9 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -198,6 +198,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{48, "migrations/048_orgs_usage_sync_watermark.up.sql"},
{49, "migrations/049_sandbox_webhooks.up.sql"},
{50, "migrations/050_checkpoint_kind.up.sql"},
+ {51, "migrations/051_image_cache_is_public.up.sql"},
}
for _, m := range migrations {
@@ -2637,6 +2638,33 @@ func (s *Store) GetImageCacheByName(ctx context.Context, orgID uuid.UUID, name s
return ic, nil
}
+// ResolveImageCacheByName resolves a named snapshot for the FORK/PROVISION path,
+// preferring the org's own snapshot but falling back to a public one
+// (is_public = true) when the org doesn't own a snapshot by that name. This is
+// what lets sessions running under a customer org (act-as-org) fork the shared
+// platform runtime/hands snapshots, which are owned by the platform org.
+//
+// Management endpoints (get/list/delete/patch/publish) must keep using
+// GetImageCacheByName (strictly org-scoped) so only the owner can read, delete,
+// or mutate a snapshot. The unique index is (org_id, name), so two orgs may hold
+// the same name; ORDER BY (org_id = $1) DESC ensures the requester's own row
+// wins when both exist.
+func (s *Store) ResolveImageCacheByName(ctx context.Context, orgID uuid.UUID, name string) (*ImageCache, error) {
+ ic := &ImageCache{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, org_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at
+ FROM image_cache
+ WHERE name = $2 AND (org_id = $1 OR is_public = true)
+ ORDER BY (org_id = $1) DESC
+ LIMIT 1`,
+ orgID, name,
+ ).Scan(&ic.ID, &ic.OrgID, &ic.ContentHash, &ic.CheckpointID, &ic.Name, &ic.Manifest, &ic.Status, &ic.CreatedAt, &ic.LastUsedAt)
+ if err != nil {
+ return nil, fmt.Errorf("snapshot %q not found: %w", name, err)
+ }
+ return ic, nil
+}
+
// GetImageCacheByID looks up an image cache entry by its ID, scoped to org.
func (s *Store) GetImageCacheByID(ctx context.Context, orgID uuid.UUID, id uuid.UUID) (*ImageCache, error) {
ic := &ImageCache{}
@@ -2743,6 +2771,24 @@ func (s *Store) DeleteImageCacheByName(ctx context.Context, orgID uuid.UUID, nam
return nil
}
+// SetImageCachePublicByName toggles is_public on a named snapshot the org owns,
+// making it forkable by other orgs via ResolveImageCacheByName. Owner-scoped: an
+// org can only publish/unpublish its own snapshots. Used by the runtime/hands
+// build tooling to share each new platform snapshot version. Mirrors
+// SetCheckpointPublic.
+func (s *Store) SetImageCachePublicByName(ctx context.Context, orgID uuid.UUID, name string, isPublic bool) error {
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE image_cache SET is_public = $3 WHERE org_id = $1 AND name = $2`,
+ orgID, name, isPublic)
+ if err != nil {
+ return err
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("snapshot %q not found or not owned by org", name)
+ }
+ return nil
+}
+
// --- Preview URL operations ---
// PreviewURL represents an on-demand preview URL for a sandbox.