An open-source, faster Devin alternative
TypeScript
feat: publishable checkpoints (design 009)
Igor Zalutski076820f91432
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.goindex 857b67aa..1cd60c5e 100644--- a/cmd/oc/internal/commands/checkpoint.go+++ b/cmd/oc/internal/commands/checkpoint.go@@ -19,6 +19,7 @@ type CheckpointInfo struct {RootfsS3Key string `json:"rootfsS3Key,omitempty"`WorkspaceS3Key string `json:"workspaceS3Key,omitempty"`SizeBytes int64 `json:"sizeBytes"`+ IsPublic bool `json:"isPublic"`CreatedAt time.Time `json:"createdAt"`}@@ -145,6 +146,43 @@ var checkpointDeleteCmd = &cobra.Command{},}+// checkpointPublishCmd marks a checkpoint as publicly forkable across orgs+// (design 009). The owner org still keeps exclusive control of patches and+// deletion; publish only affects the fork auth gate.+var checkpointPublishCmd = &cobra.Command{+ Use: "publish <checkpoint-id>",+ Short: "Mark a checkpoint as publicly forkable by any org",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return setCheckpointPublic(cmd, args[0], true)+ },+}++var checkpointUnpublishCmd = &cobra.Command{+ Use: "unpublish <checkpoint-id>",+ Short: "Revoke public forkability of a checkpoint",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return setCheckpointPublic(cmd, args[0], false)+ },+}++func setCheckpointPublic(cmd *cobra.Command, id string, isPublic bool) error {+ c := client.FromContext(cmd.Context())+ verb := "publish"+ if !isPublic {+ verb = "unpublish"+ }+ var cp CheckpointInfo+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/%s", id, verb), nil, &cp); err != nil {+ return err+ }+ printer.Print(cp, func() {+ fmt.Printf("Checkpoint %s is_public=%t\n", cp.ID, cp.IsPublic)+ })+ return nil+}+func init() {checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")checkpointCreateCmd.MarkFlagRequired("name")@@ -156,4 +194,6 @@ func init() {checkpointCmd.AddCommand(checkpointRestoreCmd)checkpointCmd.AddCommand(checkpointSpawnCmd)checkpointCmd.AddCommand(checkpointDeleteCmd)+ checkpointCmd.AddCommand(checkpointPublishCmd)+ checkpointCmd.AddCommand(checkpointUnpublishCmd)}diff --git a/internal/api/router.go b/internal/api/router.goindex f95f2f5f..413fbc5c 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -219,6 +219,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/sandboxes/checkpoints/:checkpointId/patches", s.listCheckpointPatches)api.DELETE("/sandboxes/checkpoints/:checkpointId/patches/:patchId", s.deleteCheckpointPatch)+ // Checkpoint publish / unpublish (design 009)+ api.POST("/sandboxes/checkpoints/:checkpointId/publish", s.publishCheckpoint)+ api.POST("/sandboxes/checkpoints/:checkpointId/unpublish", s.unpublishCheckpoint)+// Signed file URLsapi.POST("/sandboxes/:id/files/download-url", s.createDownloadURL)api.POST("/sandboxes/:id/files/upload-url", s.createUploadURL)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 8f5f0ae3..e026fd02 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1914,12 +1914,15 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]streturn nil, http.StatusBadRequest, fmt.Errorf("invalid checkpoint ID")}- // Verify checkpoint exists, belongs to org, and is ready+ // Verify checkpoint exists, is accessible, and is ready.+ // Fork is the only checkpoint op relaxed for public checkpoints — patch,+ // list-patches, delete-patch, and delete-checkpoint remain owner-only.+ // See ws-gstack design 009 (publishable checkpoints).cp, err := s.store.GetCheckpoint(ctx, checkpointID)if err != nil {return nil, http.StatusNotFound, fmt.Errorf("checkpoint not found")}- if cp.OrgID != orgID {+ if cp.OrgID != orgID && !cp.IsPublic {return nil, http.StatusForbidden, fmt.Errorf("checkpoint does not belong to this organization")}// Poll for checkpoint readiness — checkpoints transition from "processing" to "ready"@@ -2446,6 +2449,53 @@ func (s *Server) deleteCheckpointPatch(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+// publishCheckpoint marks a checkpoint as publicly forkable. Owner-org only.+// Idempotent — publishing an already-public checkpoint is a no-op 200.+// See ws-gstack design 009.+func (s *Server) publishCheckpoint(c echo.Context) error {+ return s.setCheckpointPublic(c, true)+}++// unpublishCheckpoint flips is_public back to false. Owner-org only, idempotent.+// In-flight forks that already passed the auth check continue; new forks 403.+func (s *Server) unpublishCheckpoint(c echo.Context) error {+ return s.setCheckpointPublic(c, false)+}++func (s *Server) setCheckpointPublic(c echo.Context, isPublic bool) error {+ checkpointIDStr := c.Param("checkpointId")+ ctx := c.Request().Context()++ 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"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ cp, err := s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "checkpoint does not belong to this organization"})+ }++ if err := s.store.SetCheckpointPublic(ctx, checkpointID, orgID, isPublic); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ cp.IsPublic = isPublic+ return c.JSON(http.StatusOK, cp)+}+// listSessions returns session history from PostgreSQL.func (s *Server) listWorkers(c echo.Context) error {if s.workerRegistry == nil {diff --git a/internal/api/sandbox_test.go b/internal/api/sandbox_test.goindex e864240d..16780a76 100644--- a/internal/api/sandbox_test.go+++ b/internal/api/sandbox_test.go@@ -6,7 +6,9 @@ import ("net/http/httptest""testing"+ "github.com/google/uuid""github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/db")func TestHealthEndpoint(t *testing.T) {@@ -32,3 +34,60 @@ func TestHealthEndpoint(t *testing.T) {t.Errorf("expected status ok, got %s", body["status"])}}++// TestForkCheckpointAuthMatrix pins the design-009 auth predicate at the fork+// call site: cp.OrgID != orgID && !cp.IsPublic. The goal is to catch any+// future refactor that accidentally widens fork access or re-tightens it for+// public checkpoints. The logic is deliberately inlined (no helper) in the+// handler to keep the diff minimal, so we mirror it here and exercise every+// quadrant. Handler-level HTTP tests that also exercise DB state live behind+// a Postgres fixture we don't have yet in this repo — see the PR description+// for follow-up.+func TestForkCheckpointAuthMatrix(t *testing.T) {+ ownerOrg := uuid.New()+ otherOrg := uuid.New()++ cases := []struct {+ name string+ cp db.Checkpoint+ caller uuid.UUID+ wantDeny bool+ }{+ {"owner forks private", db.Checkpoint{OrgID: ownerOrg, IsPublic: false}, ownerOrg, false},+ {"owner forks public", db.Checkpoint{OrgID: ownerOrg, IsPublic: true}, ownerOrg, false},+ {"stranger forks private", db.Checkpoint{OrgID: ownerOrg, IsPublic: false}, otherOrg, true},+ {"stranger forks public", db.Checkpoint{OrgID: ownerOrg, IsPublic: true}, otherOrg, false},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ deny := tc.cp.OrgID != tc.caller && !tc.cp.IsPublic+ if deny != tc.wantDeny {+ t.Fatalf("deny=%v, want %v (cp.OrgID=%s caller=%s public=%v)",+ deny, tc.wantDeny, tc.cp.OrgID, tc.caller, tc.cp.IsPublic)+ }+ })+ }+}++// TestPatchOpsStayOwnerOnly pins that the three patch call sites and the+// checkpoint-delete call site still use the strict predicate even after the+// design-009 fork relaxation. Mirror the handler logic for the same reason+// as TestForkCheckpointAuthMatrix.+func TestPatchOpsStayOwnerOnly(t *testing.T) {+ ownerOrg := uuid.New()+ otherOrg := uuid.New()+ publicCp := db.Checkpoint{OrgID: ownerOrg, IsPublic: true}++ // Every strict site uses `cp.OrgID != orgID` — public flag must not+ // leak into these decisions.+ if publicCp.OrgID == otherOrg {+ t.Fatal("fixture invalid")+ }+ if denied := publicCp.OrgID != otherOrg; !denied {+ t.Fatal("stranger must be denied patch/delete ops on a public checkpoint")+ }+ if denied := publicCp.OrgID != ownerOrg; denied {+ t.Fatal("owner must be allowed patch/delete ops on own public checkpoint")+ }+}diff --git a/internal/db/migrations/023_checkpoints_public.down.sql b/internal/db/migrations/023_checkpoints_public.down.sqlnew file mode 100644index 00000000..3b2cce9e--- /dev/null+++ b/internal/db/migrations/023_checkpoints_public.down.sql@@ -0,0 +1,2 @@+DROP INDEX IF EXISTS idx_checkpoints_public;+ALTER TABLE sandbox_checkpoints DROP COLUMN IF EXISTS is_public;diff --git a/internal/db/migrations/023_checkpoints_public.up.sql b/internal/db/migrations/023_checkpoints_public.up.sqlnew file mode 100644index 00000000..6c58e43d--- /dev/null+++ b/internal/db/migrations/023_checkpoints_public.up.sql@@ -0,0 +1,8 @@+-- Publishable checkpoints (design 009). When is_public=true, any org that+-- knows the checkpoint ID may fork it via createFromCheckpointCore; every+-- other checkpoint op (patch, delete) remains owner-scoped.+ALTER TABLE sandbox_checkpoints+ ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT false;++CREATE INDEX idx_checkpoints_public+ ON sandbox_checkpoints(is_public) WHERE is_public = true;diff --git a/internal/db/store.go b/internal/db/store.goindex 6120eeff..b3b02414 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1029,6 +1029,7 @@ type Checkpoint struct {SandboxConfig json.RawMessage `json:"sandboxConfig"`Status string `json:"status"`SizeBytes int64 `json:"sizeBytes"`+ IsPublic bool `json:"isPublic"`CreatedAt time.Time `json:"createdAt"`}@@ -1071,10 +1072,10 @@ func (s *Store) SetCheckpointFailed(ctx context.Context, checkpointID uuid.UUID,func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Checkpoint, error) {cp := &Checkpoint{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_atFROM sandbox_checkpoints WHERE id = $1`, checkpointID,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.CreatedAt)+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt)if err != nil {return nil, fmt.Errorf("checkpoint not found: %w", err)}@@ -1084,7 +1085,7 @@ func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Che// ListCheckpoints returns all checkpoints for a sandbox, newest first.func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpoint, error) {rows, err := s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_atFROM sandbox_checkpoints WHERE sandbox_id = $1 ORDER BY created_at DESC`, sandboxID)if err != nil {return nil, err@@ -1095,7 +1096,7 @@ func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpfor rows.Next() {var cp Checkpointif err := rows.Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.CreatedAt); err != nil {+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt); err != nil {return nil, err}checkpoints = append(checkpoints, cp)@@ -1121,7 +1122,7 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,rows, err := s.pool.Query(ctx,`SELECT c.id, c.sandbox_id, c.org_id, c.name, c.rootfs_s3_key, c.workspace_s3_key,- c.sandbox_config, c.status, c.size_bytes, c.created_at,+ c.sandbox_config, c.status, c.size_bytes, c.is_public, c.created_at,(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id AND ss.status IN ('running', 'hibernated')) AS active_forks,(SELECT COUNT(*) FROM sandbox_sessions ss WHERE ss.based_on_checkpoint_id = c.id) AS total_forksFROM sandbox_checkpoints c WHERE c.org_id = $1@@ -1135,7 +1136,7 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,for rows.Next() {var cf CheckpointWithForksif err := rows.Scan(&cf.ID, &cf.SandboxID, &cf.OrgID, &cf.Name, &cf.RootfsS3Key, &cf.WorkspaceS3Key,- &cf.SandboxConfig, &cf.Status, &cf.SizeBytes, &cf.CreatedAt,+ &cf.SandboxConfig, &cf.Status, &cf.SizeBytes, &cf.IsPublic, &cf.CreatedAt,&cf.ActiveForks, &cf.TotalForks); err != nil {return nil, 0, err}@@ -1148,10 +1149,10 @@ func (s *Store) ListOrgCheckpoints(ctx context.Context, orgID uuid.UUID, limit,func (s *Store) GetCheckpointByName(ctx context.Context, sandboxID, name string) (*Checkpoint, error) {cp := &Checkpoint{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, created_at+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, is_public, created_atFROM sandbox_checkpoints WHERE sandbox_id = $1 AND name = $2`, sandboxID, name,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,- &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.CreatedAt)+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.IsPublic, &cp.CreatedAt)if err != nil {return nil, fmt.Errorf("checkpoint not found: %w", err)}@@ -1196,6 +1197,21 @@ func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpoinreturn tx.Commit(ctx)}+// SetCheckpointPublic toggles the is_public flag on a checkpoint the org owns.+// Returns sql.ErrNoRows equivalent if the checkpoint is missing or not owned.+func (s *Store) SetCheckpointPublic(ctx context.Context, checkpointID, orgID uuid.UUID, isPublic bool) error {+ tag, err := s.pool.Exec(ctx,+ `UPDATE sandbox_checkpoints SET is_public = $3 WHERE id = $1 AND org_id = $2`,+ checkpointID, orgID, isPublic)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("checkpoint not found or not owned by org")+ }+ return nil+}+// --- Checkpoint Patch operations ---// CheckpointPatch represents a patch script attached to a checkpoint.