Skip to content

An open-source, faster Devin alternative

TypeScript

move to cp, revert edge

Brian Reardon6fa95d7f9287
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index ce50f80e..0aafc639 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -286,31 +286,6 @@ function parsePreviewHost(hostname: string): { sandboxID: string; port: number }
return { sandboxID: m[1], port };
}
-// generatePreviewToken produces a 32-byte random token, URL-safe base64
-// encoded. The output is ~43 chars, no padding, 256 bits of entropy — more
-// than enough that a SHA-256 of it is fine for the at-rest hash (we don't
-// need PBKDF2/scrypt because there's no low-entropy input to stretch).
-function generatePreviewToken(): string {
- const bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes);
- let bin = "";
- for (const b of bytes) bin += String.fromCharCode(b);
- return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-}
-
-// extractPreviewToken pulls the bearer token from one of two accepted
-// headers. Returns null when neither is present or the Authorization header
-// uses a non-Bearer scheme. Tokens-in-querystring are deliberately not
-// supported — they leak into logs and browser history.
-function extractPreviewToken(req: Request): string | null {
- const x = req.headers.get("X-OC-Preview-Token");
- if (x) return x.trim();
- const auth = req.headers.get("Authorization");
- if (!auth) return null;
- const m = auth.match(/^Bearer\s+(.+)$/i);
- return m ? m[1].trim() : null;
-}
-
// handlePreviewURL is the edge-routed equivalent of the cell-local
// ControlPlaneProxy.Middleware: resolve the sandbox to its owning cell via
// D1, then forward the request through that cell's Tunnel to its CP's
@@ -326,13 +301,13 @@ async function handlePreviewURL(
m: { sandboxID: string; port: number },
): Promise<Response> {
const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT s.cell_id, s.status, s.preview_auth_hash, s.preview_auth_scheme, c.base_url
+ `SELECT s.cell_id, s.status, c.base_url
FROM sandboxes_index s
JOIN cells c ON s.cell_id = c.cell_id
WHERE s.id = ?1`,
)
.bind(m.sandboxID)
- .first<{ cell_id: string; status: string; preview_auth_hash: string | null; preview_auth_scheme: string | null; base_url: string }>();
+ .first<{ cell_id: string; status: string; base_url: string }>();
if (!row) return new Response(`sandbox ${m.sandboxID} not found`, { status: 404 });
if (row.status === "stopped" || row.status === "error") {
@@ -340,26 +315,6 @@ async function handlePreviewURL(
}
// status="hibernated" is fine — CP's doProxy will wake-on-request.
- // Bearer auth gate. When preview_auth_hash is NULL the URL is open (legacy
- // default). With a hash set, require a matching token in either
- // `Authorization: Bearer <t>` or `X-OC-Preview-Token: <t>`. We never accept
- // the token in the query string — that would leak into browser history and
- // server logs. Check happens before forwarding so a brute-force run hits
- // the edge worker, not the customer's VM.
- if (row.preview_auth_hash) {
- const presented = extractPreviewToken(req);
- if (!presented) {
- return new Response("preview URL requires authentication", {
- status: 401,
- headers: { "WWW-Authenticate": 'Bearer realm="preview"' },
- });
- }
- const presentedHash = await sha256Hex(presented);
- if (!constantTimeEqual(presentedHash, row.preview_auth_hash)) {
- return new Response("invalid preview token", { status: 401 });
- }
- }
-
const url = new URL(req.url);
const base = row.base_url.replace(/\/$/, "");
const target = `${base}/internal/preview/${m.sandboxID}/${m.port}${url.pathname}${url.search}`;
@@ -490,41 +445,13 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
let bodyCpuCount = 0;
let bodyMemoryMB = 0;
let bodyDiskMB = 0;
- // Preview-URL bearer auth (opt-in). Caller sends `previewAuth: { scheme,
- // token }`. `token: "auto"` (or omitted) → we generate a random one.
- // An explicit string lets the caller bring its own (e.g. so its gateway
- // can mint and share a token with both ends in one round-trip).
- // The plaintext is returned exactly once in the create response; only
- // the SHA-256 hex lives in D1.
- let previewAuthScheme: string | null = null;
- let previewAuthHash: string | null = null;
- let previewAuthPlaintext: string | null = null;
try {
if (bodyText) {
- const parsed = JSON.parse(bodyText) as {
- cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown; diskMB?: unknown;
- previewAuth?: { scheme?: unknown; token?: unknown };
- };
+ const parsed = JSON.parse(bodyText) as { cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown; diskMB?: unknown };
if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;
if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;
if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;
if (typeof parsed.diskMB === "number") bodyDiskMB = parsed.diskMB;
- if (parsed.previewAuth && typeof parsed.previewAuth === "object") {
- const scheme = typeof parsed.previewAuth.scheme === "string" ? parsed.previewAuth.scheme : "bearer";
- if (scheme !== "bearer") {
- return json({ error: `previewAuth.scheme must be "bearer" (got ${JSON.stringify(scheme)})` }, 400);
- }
- const t = parsed.previewAuth.token;
- if (t === undefined || t === "auto" || t === null) {
- previewAuthPlaintext = generatePreviewToken();
- } else if (typeof t === "string" && t.length >= 16) {
- previewAuthPlaintext = t;
- } else {
- return json({ error: "previewAuth.token must be omitted, \"auto\", or a string of at least 16 characters" }, 400);
- }
- previewAuthScheme = "bearer";
- previewAuthHash = await sha256Hex(previewAuthPlaintext);
- }
}
} catch {
/* malformed JSON — let the CP reject with a proper 400 */
@@ -596,8 +523,8 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
if (parsed.sandboxID) {
await env.OPENCOMPUTER_DB.prepare(
`INSERT OR REPLACE INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, preview_auth_hash, preview_auth_scheme)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10, ?11)`,
+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,
)
.bind(
parsed.sandboxID,
@@ -609,23 +536,9 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
bodyCpuCount,
parsed.memoryMB ?? bodyMemoryMB,
Math.floor(Date.now() / 1000),
- previewAuthHash,
- previewAuthScheme,
)
.run();
}
- // Overlay the plaintext preview-auth token onto the CP's response body so
- // the caller gets `previewAuthToken` alongside `sandboxID` in one round
- // trip. We do this only on success and only when one was generated/set.
- // The token is never persisted at the edge in plaintext and never
- // returned again — rotation issues a new one.
- if (previewAuthPlaintext) {
- const merged = { ...parsed, previewAuthToken: previewAuthPlaintext };
- return new Response(JSON.stringify(merged), {
- status: cpResp.status,
- headers: { "content-type": "application/json" },
- });
- }
}
// Pass the CP's response through verbatim (status + body).
return new Response(cpText, {
@@ -679,29 +592,6 @@ function sandboxRowToJSON(r: SandboxRow): Record<string, unknown> {
};
}
-// rotatePreviewAuth issues a new bearer token, swaps the hash on
-// sandboxes_index, and returns the plaintext exactly once. Idempotent in the
-// sense that calling it again produces a fresh token and invalidates the
-// previous one — there is no zero-downtime dual-token mode yet, so the
-// gateway should be able to absorb a brief window of 401s during rollover.
-async function rotatePreviewAuth(req: Request, env: Env, id: string): Promise<Response> {
- const caller = await authenticate(req, env);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT org_id, status FROM sandboxes_index WHERE id = ?1",
- ).bind(id).first<{ org_id: string; status: string }>();
- if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- if (row.status === "stopped" || row.status === "error") {
- return json({ error: `sandbox is ${row.status}` }, 410);
- }
- const token = generatePreviewToken();
- const hash = await sha256Hex(token);
- await env.OPENCOMPUTER_DB.prepare(
- "UPDATE sandboxes_index SET preview_auth_hash = ?1, preview_auth_scheme = 'bearer' WHERE id = ?2",
- ).bind(hash, id).run();
- return json({ previewAuthToken: token, scheme: "bearer" });
-}
-
async function listSandboxes(req: Request, env: Env): Promise<Response> {
const caller = await authenticate(req, env);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
@@ -1802,11 +1692,6 @@ export default {
}
return json({ error: "method not allowed" }, 405);
}
- // Preview-URL auth lives purely at the edge — the cell never sees the
- // hash. Intercept the rotate before the cell-proxy fallback catches it.
- if (rest === "/preview/rotate" && req.method === "POST") {
- return rotatePreviewAuth(req, env, id);
- }
// Anything under /:id/* (exec, files, pty, hibernate, …) lives on the
// cell — proxy with an edge-minted IdentityToken (the cell's existing
// API-key middleware accepts that JWT shape) so we don't depend on the
diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sql
index 0e707618..20f11441 100644
--- a/cloudflare-workers/schema.sql
+++ b/cloudflare-workers/schema.sql
@@ -132,18 +132,16 @@ CREATE TABLE IF NOT EXISTS cells (
-- Global sandbox index (cross-region routing and listing) -----------------
CREATE TABLE IF NOT EXISTS sandboxes_index (
- id TEXT PRIMARY KEY, -- sandbox_id
- org_id TEXT NOT NULL,
- user_id TEXT,
- cell_id TEXT NOT NULL,
- worker_id TEXT,
- status TEXT NOT NULL, -- running | hibernated | stopped | error
- template_id TEXT,
- created_at INTEGER NOT NULL,
- last_event_at INTEGER,
- stopped_at INTEGER,
- preview_auth_hash TEXT, -- SHA-256 hex of the bearer token (NULL = open)
- preview_auth_scheme TEXT -- "bearer" today; reserved for HMAC/JWT later
+ id TEXT PRIMARY KEY, -- sandbox_id
+ org_id TEXT NOT NULL,
+ user_id TEXT,
+ cell_id TEXT NOT NULL,
+ worker_id TEXT,
+ status TEXT NOT NULL, -- running | hibernated | stopped | error
+ template_id TEXT,
+ created_at INTEGER NOT NULL,
+ last_event_at INTEGER,
+ stopped_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_sandboxes_org_status ON sandboxes_index(org_id, status);
CREATE INDEX IF NOT EXISTS idx_sandboxes_cell ON sandboxes_index(cell_id, status);
diff --git a/cloudflare-workers/schema_phase5_preview_auth.sql b/cloudflare-workers/schema_phase5_preview_auth.sql
deleted file mode 100644
index 2675c415..00000000
--- a/cloudflare-workers/schema_phase5_preview_auth.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- Phase 5: preview URL authentication.
---
--- Adds a per-sandbox bearer token check enforced at the edge. The plaintext
--- token is shown once on sandbox create (or rotate); only its SHA-256 hex
--- digest lands here. When preview_auth_hash IS NULL the preview URL is open
--- (current behavior — backwards compatible).
---
--- Scheme is split into its own column so we can add HMAC / JWT verification
--- later without another migration. Today only "bearer" is supported.
-
-ALTER TABLE sandboxes_index ADD COLUMN preview_auth_hash TEXT;
-ALTER TABLE sandboxes_index ADD COLUMN preview_auth_scheme TEXT;
diff --git a/internal/api/router.go b/internal/api/router.go
index 5a60c576..bb591619 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -442,6 +442,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.POST("/sandboxes/:id/preview", s.createPreviewURL)
api.GET("/sandboxes/:id/preview", s.listPreviewURLs)
api.DELETE("/sandboxes/:id/preview/:port", s.deletePreviewURL)
+ api.POST("/sandboxes/:id/preview/rotate", s.rotateSandboxPreviewAuth)
// Data-plane routes: in server mode, proxy to workers; otherwise handle locally
if s.sandboxAPIProxy != nil {
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index fe81f3ac..fb170331 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -17,6 +17,7 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/edgeclient"
"github.com/opensandbox/opensandbox/internal/observability"
+ "github.com/opensandbox/opensandbox/internal/previewauth"
"github.com/opensandbox/opensandbox/pkg/types"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
@@ -247,6 +248,24 @@ func (s *Server) createSandbox(c echo.Context) error {
_, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON, secretStoreID)
}
+ // Preview-URL auth: same flow as createSandboxRemote — validate the
+ // payload, hash, persist; return plaintext exactly once via sb.PreviewAuthToken.
+ if cfg.PreviewAuth != nil {
+ pt, hash, scheme, vStatus, vErr := previewauth.ProcessRequest(cfg.PreviewAuth.Scheme, cfg.PreviewAuth.Token)
+ if vErr != nil {
+ if vStatus >= 400 && vStatus < 500 {
+ return c.JSON(vStatus, map[string]string{"error": vErr.Error()})
+ }
+ log.Printf("sandbox: %s preview auth setup failed: %v", sb.ID, vErr)
+ } else if hash != "" && s.store != nil {
+ if pErr := s.store.SetSandboxPreviewAuth(ctx, sb.ID, hash, scheme); pErr != nil {
+ log.Printf("sandbox: %s SetSandboxPreviewAuth failed: %v", sb.ID, pErr)
+ } else {
+ sb.PreviewAuthToken = pt
+ }
+ }
+ }
+
return c.JSON(http.StatusCreated, sb)
}
@@ -644,6 +663,27 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
_ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)
}
+ // Preview-URL auth: validate the payload, hash the token, persist it on
+ // the freshly-promoted session row. Done after the running-promotion so
+ // SetSandboxPreviewAuth's row-state check finds the right row. The
+ // plaintext is returned exactly once in the response below.
+ var previewAuthPlaintext string
+ if cfg.PreviewAuth != nil {
+ pt, hash, scheme, vStatus, vErr := previewauth.ProcessRequest(cfg.PreviewAuth.Scheme, cfg.PreviewAuth.Token)
+ if vErr != nil {
+ log.Printf("sandbox: %s preview auth setup failed: %v", grpcResp.SandboxId, vErr)
+ if vStatus >= 400 && vStatus < 500 {
+ return c.JSON(vStatus, map[string]string{"error": vErr.Error()})
+ }
+ } else if hash != "" && s.store != nil {
+ if pErr := s.store.SetSandboxPreviewAuth(ctx, grpcResp.SandboxId, hash, scheme); pErr != nil {
+ log.Printf("sandbox: %s SetSandboxPreviewAuth failed: %v", grpcResp.SandboxId, pErr)
+ } else {
+ previewAuthPlaintext = pt
+ }
+ }
+ }
+
// Scale to requested resources after creation (virtio-mem hotplug + cgroup).
// Golden snapshot has fixed CPU/RAM — we create with defaults then scale up.
if requestedMemoryMB > 0 || requestedCpuCount > 0 {
@@ -698,6 +738,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
if s.sandboxDomain != "" {
resp["sandboxDomain"] = s.sandboxDomain
}
+ if previewAuthPlaintext != "" {
+ resp["previewAuthToken"] = previewAuthPlaintext
+ }
return c.JSON(http.StatusCreated, resp)
}
@@ -3361,6 +3404,48 @@ func (s *Server) deletePreviewURL(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
+// rotateSandboxPreviewAuth mints a fresh preview-URL bearer token, replaces
+// the stored hash, and returns the new plaintext exactly once. The old
+// token stops working immediately — v1 has no dual-token grace period, so
+// callers must be able to tolerate a brief window of 401s during rollover.
+//
+// Org-scoped: callers can only rotate sandboxes they own. Status is
+// checked via SetSandboxPreviewAuth's WHERE clause (running / pending /
+// hibernated only) — rotating a stopped sandbox is a 404 from the store's
+// row-not-found error.
+func (s *Server) rotateSandboxPreviewAuth(c echo.Context) error {
+ sandboxID := c.Param("id")
+ ctx := c.Request().Context()
+
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+
+ // Org-scope check: a different org's sandbox should 404, not 200.
+ orgID, hasOrg := auth.GetOrgID(c)
+ if hasOrg {
+ if _, err := s.store.GetSandboxSessionInOrg(ctx, orgID, sandboxID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+ }
+
+ token, err := previewauth.GenerateToken()
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ if err := s.store.SetSandboxPreviewAuth(ctx, sandboxID, previewauth.SHA256Hex(token), "bearer"); err != nil {
+ // Distinguish "no rows updated" (gone / wrong state) from a real DB error.
+ if strings.Contains(err.Error(), "not found or not in a settable state") {
+ return c.JSON(http.StatusGone, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, map[string]string{
+ "previewAuthToken": token,
+ "scheme": "bearer",
+ })
+}
+
// previewURLToMap converts a PreviewURL to a response map, including customHostname if provided.
func previewURLToMap(u db.PreviewURL, customDomain string) map[string]interface{} {
m := map[string]interface{}{
diff --git a/internal/db/migrations/046_preview_auth.down.sql b/internal/db/migrations/046_preview_auth.down.sql
new file mode 100644
index 00000000..c212de97
--- /dev/null
+++ b/internal/db/migrations/046_preview_auth.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE sandbox_sessions DROP COLUMN preview_auth_scheme;
+ALTER TABLE sandbox_sessions DROP COLUMN preview_auth_hash;
diff --git a/internal/db/migrations/046_preview_auth.up.sql b/internal/db/migrations/046_preview_auth.up.sql
new file mode 100644
index 00000000..148b6220
--- /dev/null
+++ b/internal/db/migrations/046_preview_auth.up.sql
@@ -0,0 +1,14 @@
+-- Add a per-sandbox bearer-token gate on preview URLs.
+--
+-- When preview_auth_hash IS NULL the preview URL is open (current default).
+-- With a hash set, the CP's preview-URL proxy (ControlPlaneProxy.doProxy)
+-- requires a matching token in `Authorization: Bearer X` or `X-OC-Preview-Token`
+-- and 401s otherwise. The check happens at the CP, not the edge, so any
+-- entry path that lands at the cell (edge-forwarded, Caddy, direct tunnel,
+-- self-hosted) enforces the same gate.
+--
+-- preview_auth_scheme is split into its own column so future schemes (HMAC,
+-- JWT) can land without another migration. Today only "bearer" is supported.
+
+ALTER TABLE sandbox_sessions ADD COLUMN preview_auth_hash TEXT;
+ALTER TABLE sandbox_sessions ADD COLUMN preview_auth_scheme TEXT;
diff --git a/internal/db/store.go b/internal/db/store.go
index b7765256..8e8450db 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -143,6 +143,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{43, "migrations/043_credit_halt.up.sql"},
{44, "migrations/044_drop_secret_store_fk.up.sql"},
{45, "migrations/045_sandbox_mounts.up.sql"},
+ {46, "migrations/046_preview_auth.up.sql"},
}
for _, m := range migrations {
@@ -649,6 +650,44 @@ type SandboxSession struct {
MigratingToWorker string `json:"migratingToWorker,omitempty"`
PatchError *string `json:"patchError,omitempty"`
GoldenVersion *string `json:"goldenVersion,omitempty"`
+ // PreviewAuthHash is the SHA-256 hex of the bearer token required on
+ // preview-URL requests. NULL = open (the default). Plaintext is never
+ // stored — set once via SetSandboxPreviewAuth and rotated via the same.
+ PreviewAuthHash *string `json:"-"`
+ PreviewAuthScheme *string `json:"-"`
+}
+
+// SetSandboxPreviewAuth installs or rotates the per-sandbox bearer-token gate
+// used by ControlPlaneProxy.doProxy. Passing empty hash + scheme clears the
+// gate (leaves the preview URL open). The hash is plain SHA-256 hex; the
+// scheme column is reserved for future variants (HMAC, JWT) but is "bearer"
+// for everything generated today.
+func (s *Store) SetSandboxPreviewAuth(ctx context.Context, sandboxID, hash, scheme string) error {
+ var hashArg, schemeArg interface{}
+ if hash == "" {
+ hashArg = nil
+ } else {
+ hashArg = hash
+ }
+ if scheme == "" {
+ schemeArg = nil
+ } else {
+ schemeArg = scheme
+ }
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions
+ SET preview_auth_hash = $1, preview_auth_scheme = $2
+ WHERE sandbox_id = $3
+ AND status IN ('running', 'pending', 'hibernated')`,
+ hashArg, schemeArg, sandboxID,
+ )
+ if err != nil {
+ return fmt.Errorf("set preview auth: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("sandbox %s not found or not in a settable state", sandboxID)
+ }
+ return nil
}
func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage, secretStoreID *uuid.UUID) (*SandboxSession, error) {
@@ -875,11 +914,12 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin
func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, preview_auth_hash, preview_auth_scheme
FROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`, sandboxID,
).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
- &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion)
+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion,
+ &session.PreviewAuthHash, &session.PreviewAuthScheme)
if err != nil {
return nil, fmt.Errorf("sandbox session not found: %w", err)
}
@@ -895,13 +935,14 @@ func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*Sandb
func (s *Store) GetSandboxSessionInOrg(ctx context.Context, orgID uuid.UUID, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version
+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version, preview_auth_hash, preview_auth_scheme
FROM sandbox_sessions
WHERE org_id = $1 AND sandbox_id = $2
ORDER BY started_at DESC LIMIT 1`, orgID, sandboxID,
).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
- &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion)
+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion,
+ &session.PreviewAuthHash, &session.PreviewAuthScheme)
if err != nil {
return nil, fmt.Errorf("sandbox session not found: %w", err)
}
diff --git a/internal/previewauth/previewauth.go b/internal/previewauth/previewauth.go
new file mode 100644
index 00000000..7c09db11
--- /dev/null
+++ b/internal/previewauth/previewauth.go
@@ -0,0 +1,93 @@
+// Package previewauth provides the bearer-token primitives used by the CP's
+// preview-URL gate. Both the create/rotate handlers in internal/api and the
+// proxy enforcement in internal/proxy share this code so the token format,
+// hash algorithm, and header parsing stay in sync.
+package previewauth
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+// GenerateToken returns a 32-byte (256-bit) random token, URL-safe base64
+// encoded without padding (~43 chars). The entropy is sufficient that we
+// store only a plain SHA-256 hex; PBKDF2/Argon2 would buy nothing here
+// because the input is already incompressible.
+func GenerateToken() (string, error) {
+ var buf [32]byte
+ if _, err := rand.Read(buf[:]); err != nil {
+ return "", fmt.Errorf("rand: %w", err)
+ }
+ return base64.RawURLEncoding.EncodeToString(buf[:]), nil
+}
+
+// SHA256Hex returns the lowercase hex SHA-256 digest of s.
+func SHA256Hex(s string) string {
+ sum := sha256.Sum256([]byte(s))
+ return hex.EncodeToString(sum[:])
+}
+
+// ExtractToken pulls the bearer token from one of two accepted headers.
+// Returns "" when neither is present or the Authorization header uses a
+// non-Bearer scheme. Tokens-in-querystring are deliberately not supported —
+// they leak into logs and browser history.
+func ExtractToken(r *http.Request) string {
+ if x := r.Header.Get("X-OC-Preview-Token"); x != "" {
+ return strings.TrimSpace(x)
+ }
+ auth := r.Header.Get("Authorization")
+ if auth == "" {
+ return ""
+ }
+ if len(auth) < 7 || !strings.EqualFold(auth[:7], "Bearer ") {
+ return ""
+ }
+ return strings.TrimSpace(auth[7:])
+}
+
+// ConstantTimeEqualString wraps subtle.ConstantTimeCompare for two strings.
+// Used by the preview-URL gate so a timing oracle can't distinguish "wrong
+// by one character" from "wrong by all characters" on the hash compare.
+func ConstantTimeEqualString(a, b string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
+}
+
+// ProcessRequest validates a create / rotate request and produces the
+// plaintext token that will be returned to the caller plus the hash +
+// scheme to persist. status > 0 indicates a 4xx that should be returned
+// directly. The plaintext is the only value the caller ever sees.
+//
+// - scheme defaults to "bearer"; any other value is a 400
+// - token == "" or "auto" → server generates a 256-bit token
+// - token == "<≥16-char string>" → bring-your-own; echoed back to caller
+// - token == "<<16-char string>" → 400
+func ProcessRequest(scheme, token string) (plaintext, hash, normalizedScheme string, status int, err error) {
+ if scheme == "" {
+ scheme = "bearer"
+ }
+ if scheme != "bearer" {
+ return "", "", "", http.StatusBadRequest, fmt.Errorf("previewAuth.scheme must be %q (got %q)", "bearer", scheme)
+ }
+ switch {
+ case token == "" || token == "auto":
+ t, gErr := GenerateToken()
+ if gErr != nil {
+ return "", "", "", http.StatusInternalServerError, gErr
+ }
+ plaintext = t
+ case len(token) >= 16:
+ plaintext = token
+ default:
+ return "", "", "", http.StatusBadRequest, fmt.Errorf("previewAuth.token must be omitted, \"auto\", or a string of at least 16 characters")
+ }
+ return plaintext, SHA256Hex(plaintext), scheme, 0, nil
+}
diff --git a/internal/previewauth/previewauth_test.go b/internal/previewauth/previewauth_test.go
new file mode 100644
index 00000000..315ed1b3
--- /dev/null
+++ b/internal/previewauth/previewauth_test.go
@@ -0,0 +1,129 @@
+package previewauth
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestGenerateTokenUniqueAndCorrectLength(t *testing.T) {
+ seen := make(map[string]struct{})
+ for i := 0; i < 100; i++ {
+ tok, err := GenerateToken()
+ if err != nil {
+ t.Fatalf("GenerateToken: %v", err)
+ }
+ // 32 bytes → ceil(32*4/3) = 43 chars (RawURLEncoding, no padding).
+ if got := len(tok); got != 43 {
+ t.Fatalf("token len = %d, want 43", got)
+ }
+ if _, dup := seen[tok]; dup {
+ t.Fatalf("duplicate token in 100 draws — entropy is broken")
+ }
+ seen[tok] = struct{}{}
+ }
+}
+
+func TestSHA256Hex(t *testing.T) {
+ // Known vector: SHA-256 of "abc" = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
+ if got, want := SHA256Hex("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; got != want {
+ t.Fatalf("SHA256Hex(\"abc\") = %q, want %q", got, want)
+ }
+}
+
+func TestExtractToken(t *testing.T) {
+ cases := []struct {
+ name string
+ setup func(r *http.Request)
+ want string
+ }{
+ {
+ name: "Authorization: Bearer X",
+ setup: func(r *http.Request) { r.Header.Set("Authorization", "Bearer my-token-123") },
+ want: "my-token-123",
+ },
+ {
+ name: "Authorization case-insensitive Bearer",
+ setup: func(r *http.Request) { r.Header.Set("Authorization", "bearer my-token-123") },
+ want: "my-token-123",
+ },
+ {
+ name: "X-OC-Preview-Token wins over Authorization when both set",
+ setup: func(r *http.Request) { r.Header.Set("X-OC-Preview-Token", "from-x"); r.Header.Set("Authorization", "Bearer from-auth") },
+ want: "from-x",
+ },
+ {
+ name: "trailing whitespace trimmed",
+ setup: func(r *http.Request) { r.Header.Set("X-OC-Preview-Token", " spaced-token ") },
+ want: "spaced-token",
+ },
+ {
+ name: "Authorization: Basic — not Bearer, ignored",
+ setup: func(r *http.Request) { r.Header.Set("Authorization", "Basic dXNlcjpwYXNz") },
+ want: "",
+ },
+ {
+ name: "no headers",
+ setup: func(r *http.Request) {},
+ want: "",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ tc.setup(r)
+ if got := ExtractToken(r); got != tc.want {
+ t.Fatalf("ExtractToken = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestConstantTimeEqualString(t *testing.T) {
+ if !ConstantTimeEqualString("abc", "abc") {
+ t.Fatalf("equal strings should compare equal")
+ }
+ if ConstantTimeEqualString("abc", "abd") {
+ t.Fatalf("one-char different should not be equal")
+ }
+ if ConstantTimeEqualString("abc", "abcd") {
+ t.Fatalf("different lengths should not be equal")
+ }
+}
+
+func TestProcessRequest(t *testing.T) {
+ // auto → generated
+ pt, hash, scheme, status, err := ProcessRequest("", "auto")
+ if err != nil || status != 0 {
+ t.Fatalf("auto: err=%v status=%d", err, status)
+ }
+ if scheme != "bearer" || len(pt) != 43 || SHA256Hex(pt) != hash {
+ t.Fatalf("auto: bad output pt=%q hash=%q scheme=%q", pt, hash, scheme)
+ }
+
+ // empty token → generated (same as "auto")
+ pt2, _, _, _, err := ProcessRequest("bearer", "")
+ if err != nil || pt2 == pt {
+ t.Fatalf("empty token: pt2=%q err=%v (should differ from prior draw)", pt2, err)
+ }
+
+ // BYO ≥16 chars → echoed back
+ byo := "my-supersecret-token-1234567890abcdef"
+ pt3, hash3, scheme3, status3, err := ProcessRequest("bearer", byo)
+ if err != nil || status3 != 0 || pt3 != byo || hash3 != SHA256Hex(byo) || scheme3 != "bearer" {
+ t.Fatalf("BYO: pt=%q hash=%q scheme=%q status=%d err=%v", pt3, hash3, scheme3, status3, err)
+ }
+
+ // BYO <16 chars → 400
+ _, _, _, status4, err := ProcessRequest("bearer", "short")
+ if err == nil || status4 != http.StatusBadRequest || !strings.Contains(err.Error(), "at least 16") {
+ t.Fatalf("short BYO: status=%d err=%v", status4, err)
+ }
+
+ // unsupported scheme → 400
+ _, _, _, status5, err := ProcessRequest("hmac", "auto")
+ if err == nil || status5 != http.StatusBadRequest {
+ t.Fatalf("unsupported scheme: status=%d err=%v", status5, err)
+ }
+}
diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.go
index 68c97510..d621f707 100644
--- a/internal/proxy/controlplane_proxy.go
+++ b/internal/proxy/controlplane_proxy.go
@@ -16,6 +16,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/previewauth"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
@@ -102,6 +103,28 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int)
})
}
+ // Preview-URL bearer auth gate. When session.PreviewAuthHash is NULL the
+ // URL is open (the legacy default). With a hash set, every request must
+ // present a matching token in `Authorization: Bearer X` or
+ // `X-OC-Preview-Token: X`. The check runs before the worker lookup +
+ // wake-on-request so a brute-force run never spins up a hibernated
+ // sandbox or burns wake capacity. Constant-time compare so the hex
+ // digest doesn't leak through timing.
+ if session.PreviewAuthHash != nil && *session.PreviewAuthHash != "" {
+ presented := previewauth.ExtractToken(c.Request())
+ if presented == "" {
+ c.Response().Header().Set("WWW-Authenticate", `Bearer realm="preview"`)
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "preview URL requires authentication",
+ })
+ }
+ if !previewauth.ConstantTimeEqualString(previewauth.SHA256Hex(presented), *session.PreviewAuthHash) {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "invalid preview token",
+ })
+ }
+ }
+
// If the sandbox is hibernated, wake it on-demand before proxying
if session.Status == "hibernated" {
// Free-tier credits gate: don't auto-wake via preview URL if the
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index c2790ab7..8c57f8ae 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -41,16 +41,30 @@ type Sandbox struct {
PreviewAuthToken string `json:"previewAuthToken,omitempty"`
}
+// SandboxPreviewAuth controls the per-sandbox bearer-token gate that the CP
+// enforces on preview-URL traffic. The plaintext token is returned exactly
+// once in the create response (Sandbox.PreviewAuthToken) and never stored
+// outside the request-handling path; only the SHA-256 hex hash is persisted.
+type SandboxPreviewAuth struct {
+ // Scheme is "bearer" today. Reserved for HMAC/JWT later.
+ Scheme string `json:"scheme,omitempty"`
+ // Token is "auto" (or omitted) to have the server generate a 256-bit
+ // random token, or an explicit string of at least 16 chars to bring
+ // your own. Echoed back as Sandbox.PreviewAuthToken on success.
+ Token string `json:"token,omitempty"`
+}
+
// SandboxConfig is the request body for creating a sandbox.
type SandboxConfig struct {
- Template string `json:"templateID,omitempty"`
- Alias string `json:"alias,omitempty"`
- Metadata map[string]string `json:"metadata,omitempty"`
- Timeout int `json:"timeout,omitempty"` // seconds, default 300
- CpuCount int `json:"cpuCount,omitempty"` // default 1
- MemoryMB int `json:"memoryMB,omitempty"` // default 256
- DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)
- Envs map[string]string `json:"envs,omitempty"`
+ Template string `json:"templateID,omitempty"`
+ Alias string `json:"alias,omitempty"`
+ Metadata map[string]string `json:"metadata,omitempty"`
+ Timeout int `json:"timeout,omitempty"` // seconds, default 300
+ CpuCount int `json:"cpuCount,omitempty"` // default 1
+ MemoryMB int `json:"memoryMB,omitempty"` // default 256
+ DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)
+ Envs map[string]string `json:"envs,omitempty"`
+ PreviewAuth *SandboxPreviewAuth `json:"previewAuth,omitempty"`
Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)
// NetworkEnabled is a pointer so we can distinguish "unset" from
// "explicitly false". Unset defaults to true (see IsNetworkEnabled).