Skip to content

An open-source, faster Devin alternative

TypeScript

harden: anchor public-snapshot fallback to a trusted platform org (review fixes)

Igor Zalutskie2b7845b8a39
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index ab2c2ae9..2d2264c3 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1875,8 +1875,15 @@ export default {
// 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 });
+ if (ownerCell) return proxyToCellAuthed(req, env, caller, { cellId: ownerCell });
+ // D1 images_index can lag the cell PG right after a snapshot is built.
+ // For publish/unpublish (idempotent catalog toggles), fall back to the
+ // org's home_cell — where a just-created snapshot lives — and let the
+ // cell be the source of truth (it returns 404 if the row is really
+ // absent). Patches/delete stay strict: a missing index row means the
+ // bytes aren't addressable yet.
+ if (isPublishToggle) return proxyToCellAuthed(req, env, caller);
+ return json({ error: "snapshot not found" }, 404);
}
if (req.method === "GET") return snapshots.getSnapshot(env, caller, name);
return json({ error: "method not allowed" }, 405);
diff --git a/cmd/server/main.go b/cmd/server/main.go
index cf1bde14..eaf3f0d9 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -97,6 +97,7 @@ func main() {
Region: cfg.Region,
HTTPAddr: cfg.HTTPAddr,
CellID: cfg.CellID,
+ PlatformOrgID: cfg.PlatformOrgID,
SessionJWTSecret: cfg.SessionJWTSecret,
CFAdminSecret: cfg.CFAdminSecret,
CFEventSecret: cfg.CFEventSecret,
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index a574fec8..c2b21ab4 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -652,10 +652,12 @@ func (s *Server) resolveSnapshot(ctx context.Context, orgID uuid.UUID, snapshotN
}
// 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)
+ // snapshot published by the platform org (the shared runtime/hands catalog)
+ // when the org doesn't own one. The fallback is anchored to s.platformOrgID
+ // so a customer can't spoof a runtime name. 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, s.platformOrgID, 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 998f2ed2..ef91d771 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -13,6 +13,7 @@ import (
"sync/atomic"
"time"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/redis/go-redis/v9"
@@ -50,6 +51,7 @@ type Server struct {
cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)
cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push paths
cellID string // this control plane's cell_id (for the cap-token cell check)
+ platformOrgID uuid.UUID // owner of the shared catalog snapshots; anchors the public-snapshot fallback + gates publish (uuid.Nil = fallback disabled)
mode string // "server", "worker", "combined"
workerID string // this worker's ID
region string // this worker's region
@@ -142,6 +144,7 @@ type ServerOpts struct {
CFAdminSecret string // HMAC shared with CF CreditAccount DO; enables /admin/halt-org and /admin/resume-org
CFEventSecret string // HMAC shared with the api-edge Worker; enables /internal/secret-refresh and other edge-→cell push paths
CellID string // this control plane's cell_id
+ PlatformOrgID string // owner of the shared catalog snapshots (UUID string); empty disables the public-snapshot fallback
Mode string // "server", "worker", "combined"
WorkerID string
Region string
@@ -189,6 +192,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.cfAdminSecret = opts.CFAdminSecret
s.cfEventSecret = opts.CFEventSecret
s.cellID = opts.CellID
+ if opts.PlatformOrgID != "" {
+ if pid, err := uuid.Parse(opts.PlatformOrgID); err == nil {
+ s.platformOrgID = pid
+ } else {
+ log.Printf("api: ignoring invalid OPENSANDBOX_PLATFORM_ORG_ID %q: %v (public-snapshot fallback disabled)", opts.PlatformOrgID, err)
+ }
+ }
s.mode = opts.Mode
s.workerID = opts.WorkerID
s.region = opts.Region
diff --git a/internal/api/snapshots.go b/internal/api/snapshots.go
index b7ed0b3e..55a2f05d 100644
--- a/internal/api/snapshots.go
+++ b/internal/api/snapshots.go
@@ -335,15 +335,16 @@ 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.
+// publishSnapshot handles POST /api/snapshots/:name/publish — marks one of the
+// platform org's snapshots public so any org can fork it. This is how the
+// runtime/hands catalog is shared with customer-org (act-as-org) sessions.
+// Restricted to the platform org (the only owner the fork fallback trusts);
+// 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.
+// unpublishSnapshot flips is_public back to false. Platform-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 {
@@ -360,6 +361,13 @@ func (s *Server) setSnapshotPublic(c echo.Context, isPublic bool) error {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
}
+ // Publishing to the shared catalog is restricted to the platform org — it's
+ // the only owner the fork fallback trusts (see ResolveImageCacheByName), so
+ // letting any org publish would reintroduce the spoofable-namespace risk.
+ if s.platformOrgID == uuid.Nil || orgID != s.platformOrgID {
+ return c.JSON(http.StatusForbidden, map[string]string{"error": "only the platform org may publish snapshots to the shared catalog"})
+ }
+
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()})
diff --git a/internal/config/config.go b/internal/config/config.go
index 81a9a86c..2d3d3566 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -197,6 +197,16 @@ type Config struct {
// distinguishes multiple cells in the same region.
CellID string
+ // PlatformOrgID — the org that owns the shared "catalog" snapshots (the
+ // runtime/hands base images). A provision under any org falls back to this
+ // org's is_public snapshots when it doesn't own one by that name (see
+ // store.ResolveImageCacheByName), and only this org may publish a snapshot to
+ // the shared catalog. Anchoring the fallback to a single trusted owner is
+ // what keeps the public-snapshot namespace from being spoofable. Empty
+ // disables the fallback (fail-closed: org-scoped resolution only).
+ // Env: OPENSANDBOX_PLATFORM_ORG_ID (a UUID).
+ PlatformOrgID string
+
// CF events-ingest endpoint. When set, the regional control plane runs an
// event_forwarder goroutine that drains the local Redis stream and POSTs
// HMAC-signed batches here.
@@ -392,6 +402,7 @@ func Load() (*Config, error) {
SentryTracesSampleRate: envOrDefaultFloat("OPENSANDBOX_SENTRY_TRACES_SAMPLE_RATE", 0.0),
CellID: os.Getenv("OPENSANDBOX_CELL_ID"),
+ PlatformOrgID: os.Getenv("OPENSANDBOX_PLATFORM_ORG_ID"),
CFEventEndpoint: os.Getenv("OPENSANDBOX_CF_EVENT_ENDPOINT"),
CFEventSecret: os.Getenv("OPENSANDBOX_CF_EVENT_SECRET"),
CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),
diff --git a/internal/db/image_cache_resolve_pgfixture_test.go b/internal/db/image_cache_resolve_pgfixture_test.go
index 6fcfaf1b..e0af533d 100644
--- a/internal/db/image_cache_resolve_pgfixture_test.go
+++ b/internal/db/image_cache_resolve_pgfixture_test.go
@@ -1,10 +1,12 @@
//go:build pgfixture
-// Resolve-path semantics for shared named snapshots. Runs only under
+// Resolve-path semantics for shared "catalog" 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.
+// TEST_DATABASE_URL. Proves the act-as-org SEV fix AND its security property:
+// a customer org can fork a snapshot the PLATFORM org published, the platform
+// row carries a real checkpoint (provision contract), the fallback is anchored
+// to the platform org so a look-alike published by any other org cannot hijack
+// a predictable runtime name, and an unset platform org fails closed.
//
// Run locally:
//
@@ -20,67 +22,113 @@ import (
"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) {
+// seedCheckpoint inserts a minimal ready checkpoint owned by orgID with non-null
+// S3 keys, and returns its id. Snapshots must point at a real checkpoint for the
+// provision path (resolveSnapshot requires Status=ready + CheckpointID != nil).
+func seedCheckpoint(t *testing.T, store *Store, orgID uuid.UUID) uuid.UUID {
t.Helper()
- cp := uuid.New()
+ id := 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 {
+ `INSERT INTO sandbox_checkpoints (id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, status, size_bytes)
+ VALUES ($1, $2, $3, $4, $5, $6, 'ready', 1)`,
+ id, "sbx-"+id.String()[:8], orgID, "cp-"+id.String()[:8],
+ "rootfs/"+id.String(), "ws/"+id.String()); err != nil {
+ t.Fatalf("seed checkpoint for %s: %v", orgID, err)
+ }
+ return id
+}
+
+// seedNamedSnapshot inserts a ready named snapshot owned by orgID, backed by a
+// real checkpoint, with the given is_public flag.
+func seedNamedSnapshot(t *testing.T, store *Store, orgID uuid.UUID, name string, isPublic bool) {
+ t.Helper()
+ cpID := seedCheckpoint(t, store, orgID)
+ id := uuid.New()
+ if _, err := store.pool.Exec(context.Background(),
+ `INSERT INTO image_cache (id, org_id, content_hash, checkpoint_id, name, manifest, status, is_public)
+ VALUES ($1, $2, $3, $4, $5, $6, 'ready', $7)`,
+ id, orgID, "hash-"+id.String(), cpID, name, json.RawMessage(`{}`), isPublic); err != nil {
t.Fatalf("seed snapshot %q for %s: %v", name, orgID, err)
}
}
-func TestResolveImageCacheByName_PublicFallback(t *testing.T) {
+func TestResolveImageCacheByName_PlatformFallback(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)
+ platform := seedOrgWithCap(t, store, 64) // owns the shared catalog
+ customer := seedOrgWithCap(t, store, 64) // act-as-org session
const name = "runtime-claude-pgfixture"
- seedNamedSnapshot(t, store, owner, name, "hash-owner-"+uuid.NewString())
+ // Platform owns the snapshot but hasn't published it yet.
+ seedNamedSnapshot(t, store, platform, name, false)
- // 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")
+ // Private platform snapshot is NOT resolvable by a customer (the SEV state).
+ if _, err := store.ResolveImageCacheByName(ctx, customer, platform, name); err == nil {
+ t.Fatalf("expected not-found: an unpublished platform snapshot must stay private")
}
- // 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)
+ // Platform resolves its own regardless of is_public, with a real checkpoint.
+ got, err := store.ResolveImageCacheByName(ctx, platform, platform, name)
+ if err != nil {
+ t.Fatalf("platform resolve of own snapshot: %v", err)
+ }
+ if got.CheckpointID == nil {
+ t.Fatalf("resolved snapshot must carry a checkpoint_id for provision")
}
- // Publish, then the non-owner resolves it and gets the owner's row.
- if err := store.SetImageCachePublicByName(ctx, owner, name, true); err != nil {
+ // Publish → the customer can fork it and gets the PLATFORM row + checkpoint.
+ if err := store.SetImageCachePublicByName(ctx, platform, name, true); err != nil {
t.Fatalf("publish: %v", err)
}
- got, err := store.ResolveImageCacheByName(ctx, requester, name)
+ got, err = store.ResolveImageCacheByName(ctx, customer, platform, name)
if err != nil {
- t.Fatalf("non-owner resolve of public snapshot: %v", err)
+ t.Fatalf("customer resolve of published platform snapshot: %v", err)
}
- if got.OrgID != owner {
- t.Fatalf("expected owner's row %s, got %s", owner, got.OrgID)
+ if got.OrgID != platform {
+ t.Fatalf("expected platform's row %s, got %s", platform, got.OrgID)
+ }
+ if got.CheckpointID == nil {
+ t.Fatalf("resolved snapshot must carry a checkpoint_id for provision")
}
- // 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)
+ // Fail-closed: with no platform org configured, the fallback is disabled.
+ if _, err := store.ResolveImageCacheByName(ctx, customer, uuid.Nil, name); err == nil {
+ t.Fatalf("expected not-found when platformOrgID is unset (fallback disabled)")
+ }
+}
+
+// The security property: two orgs publish a snapshot under the SAME predictable
+// name; only the platform org's row is ever served to a third org.
+func TestResolveImageCacheByName_NoSpoof(t *testing.T) {
+ store := openPgStore(t)
+ ctx := context.Background()
+
+ platform := seedOrgWithCap(t, store, 64)
+ attacker := seedOrgWithCap(t, store, 64)
+ victim := seedOrgWithCap(t, store, 64)
+ const name = "runtime-claude-0.0.10" // a predictable, guessable runtime label
+
+ // Both publish is_public=true under the identical name (allowed: unique per org).
+ seedNamedSnapshot(t, store, platform, name, true)
+ seedNamedSnapshot(t, store, attacker, name, true)
+
+ // A victim that owns neither must resolve the PLATFORM row, never the attacker's.
+ got, err := store.ResolveImageCacheByName(ctx, victim, platform, name)
if err != nil {
- t.Fatalf("resolve with own + public present: %v", err)
+ t.Fatalf("victim resolve: %v", err)
}
- if got.OrgID != requester {
- t.Fatalf("expected requester's own row %s to win, got %s", requester, got.OrgID)
+ if got.OrgID != platform {
+ t.Fatalf("SPOOF: victim resolved org %s instead of platform %s", got.OrgID, platform)
}
- // 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)
+ // The attacker still resolves its OWN row for itself (own-preference), not the
+ // platform's — confirming ordering doesn't leak across orgs.
+ got, err = store.ResolveImageCacheByName(ctx, attacker, platform, name)
+ if err != nil {
+ t.Fatalf("attacker resolve own: %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")
+ if got.OrgID != attacker {
+ t.Fatalf("expected attacker's own row to win for itself, got %s", got.OrgID)
}
}
@@ -88,17 +136,18 @@ func TestSetImageCachePublicByName_OwnerScoped(t *testing.T) {
store := openPgStore(t)
ctx := context.Background()
- owner := seedOrgWithCap(t, store, 64)
+ platform := seedOrgWithCap(t, store, 64)
other := seedOrgWithCap(t, store, 64)
const name = "runtime-codex-pgfixture"
- seedNamedSnapshot(t, store, owner, name, "hash-"+uuid.NewString())
+ seedNamedSnapshot(t, store, platform, name, false)
- // A non-owner cannot publish someone else's snapshot.
+ // A non-owner cannot publish someone else's snapshot (store-level ownership;
+ // the API layer additionally restricts publish to the platform org).
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 {
+ if _, err := store.ResolveImageCacheByName(ctx, other, platform, 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
index 5191fe7f..8d34a1c7 100644
--- a/internal/db/migrations/051_image_cache_is_public.down.sql
+++ b/internal/db/migrations/051_image_cache_is_public.down.sql
@@ -1,2 +1,4 @@
+DROP INDEX IF EXISTS idx_image_cache_public_name;
+
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
index 7b24abd1..d5b5e6f3 100644
--- a/internal/db/migrations/051_image_cache_is_public.up.sql
+++ b/internal/db/migrations/051_image_cache_is_public.up.sql
@@ -9,18 +9,24 @@
-- 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.
+-- is_public lets the resolve/fork path fall back to a snapshot published by the
+-- platform org, mirroring templates.is_public and sandbox_checkpoints.is_public.
+-- The fallback is anchored to a trusted owner in code (ResolveImageCacheByName:
+-- is_public AND org_id = <platform org>), so this flag alone does NOT open a
+-- snapshot to the world — it only makes it eligible when the platform org owns
+-- it. Management endpoints (get/list/delete/patch) stay strictly org-scoped.
+--
+-- No data backfill here on purpose: which org is "the platform org" is
+-- environment-specific (prod vs dev), so blindly publishing every runtime-%/
+-- hands-% row would expose any customer-owned look-alike. Existing platform
+-- snapshots are published as a one-time, platform-org-scoped cutover step (see
+-- the PR), and future versions via POST /api/snapshots/:name/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-%';
+-- Index the fork fallback path: WHERE name = $3 AND is_public = true AND
+-- org_id = $2. The existing unique index (org_id, name) serves the org-scoped
+-- branch; this partial index serves the public branch and stays tiny (only
+-- catalog rows).
+CREATE INDEX IF NOT EXISTS idx_image_cache_public_name
+ ON image_cache(name) WHERE is_public = true;
diff --git a/internal/db/store.go b/internal/db/store.go
index 7b0593e9..35e4f152 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -2638,26 +2638,36 @@ 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.
+// ResolveImageCacheByName resolves a named snapshot for the FORK/PROVISION path.
+// It prefers the requesting org's own snapshot, then falls back to a snapshot
+// published by the PLATFORM ORG (is_public = true AND org_id = platformOrgID) —
+// the shared runtime/hands catalog. This is what lets sessions running under a
+// customer org (act-as-org) fork the platform base images.
+//
+// The fallback is deliberately anchored to a single trusted owner. image_cache
+// only enforces name uniqueness per org, so a fallback to "any is_public row
+// with this name" would let any org publish a look-alike (e.g. a spoof
+// runtime-claude-0.0.10) and hijack the predictable runtime namespace.
+// Anchoring also makes resolution deterministic: there is at most one platform
+// row per name (unique index on (org_id, name)), so the fallback can never
+// return an arbitrary / failed / spoofed row.
+//
+// platformOrgID == uuid.Nil disables the fallback (org-scoped only) — a cell
+// without OPENSANDBOX_PLATFORM_ORG_ID fails closed (provision fails loudly)
+// rather than open (resolving an untrusted public row).
//
// 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) {
+// or mutate a snapshot.
+func (s *Store) ResolveImageCacheByName(ctx context.Context, orgID, platformOrgID 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)
+ WHERE name = $3 AND (org_id = $1 OR (is_public = true AND org_id = $2))
ORDER BY (org_id = $1) DESC
LIMIT 1`,
- orgID, name,
+ orgID, platformOrgID, 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)