Skip to content

An open-source, faster Devin alternative

TypeScript

fix(webhooks): review round 3 — metadata org-scope, data normalization, reasons

Igor Zalutskib0a8bfd0a18e
diff --git a/.agents/work/sandbox-lifecycle-webhooks.md b/.agents/work/sandbox-lifecycle-webhooks.md
index e09aa1e1..9144b42d 100644
--- a/.agents/work/sandbox-lifecycle-webhooks.md
+++ b/.agents/work/sandbox-lifecycle-webhooks.md
@@ -47,6 +47,22 @@ polish (per-type payload normalization at the ingress, LISTEN/NOTIFY latency) tr
worker via a stream ingress), and **one materializer** creates delivery rows from it — no
per-origin delivery logic to drift. Dedupe happens once (`sandbox_lifecycle_events.id`); the
watermark unifies to a DB-assigned `seq` (drops the Redis-stream-id scheme).
+- **Rev 8 — review round 3 (2026-06-24).** (P0) metadata hydration is org-scoped
+ (`getSandboxMetadataTx` keys on `(org_id, sandbox_id)`) — sandbox ids aren't globally
+ unique, so a sandbox_id-only lookup could leak another org's metadata. (P1) worker-origin
+ `event.data` is normalized in the ingress to the public contract (`created`→`{template}`,
+ `resumed`→`{}`); `migrated` is now recorded CP-side in `CompleteMigration` (the worker never
+ emits it — the old ingress mapping was dead) and dropped from the ingress; `scaled` fires on
+ every successful scale (not gated on the 4096 default); stop reasons are explicit
+ (`UpdateSandboxSessionStatusReason` — idle-timeout `OnKill`→`expired`, crashes/orphans→`crash`,
+ user/API→`user_requested`); idempotency hash + name get-or-create now include `enabled` (+ the
+ hash includes `secret`) so a different paused-state/secret isn't a silent reuse. (P2) redeliver
+ refuses a soft-deleted destination (would strand pending). (P3) preview-delete emits only after
+ the DB delete commits (`url:null`); docs say `url` is nullable. **Ordering:** deliveries are
+ parallel and NOT strictly ordered (e.g. `ready` can precede `created`) — documented; strict
+ per-sandbox ordering would need serialized delivery (deferred, out of scope). **Failed creates
+ don't emit:** a never-started sandbox (pending→failed, e.g. `ReapStalePendingSessions`) records
+ no lifecycle event — only sandboxes that reached `created` emit a terminal event.
- **Rev 7 — post-build review fixes (2026-06-24).** (P0) inline webhooks now register on the
**remote** create path too (`createSandboxRemote`, before the gRPC call using the pre-generated
id → reliably catches `created`; cleaned up on create failure). (P1) `RecordDeliveryResult` now
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 22cf177c..6fb4ec6e 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -565,7 +565,8 @@ func main() {
log.Printf("opensandbox-worker: sandbox %s killed on timeout", sandboxID)
execMgr.RemoveSessions(sandboxID)
if store != nil {
- _ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "stopped", nil)
+ // Idle-timeout kill → sandbox.stopped reason "expired".
+ _ = store.UpdateSandboxSessionStatusReason(context.Background(), sandboxID, "stopped", nil, "expired")
}
// Same fix as OnHibernate above — D1 needs a "stopped" event so
// the dashboard doesn't keep the row at "running" forever.
diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdx
index d8b73be0..4e6f64fc 100644
--- a/docs/sandboxes/webhooks.mdx
+++ b/docs/sandboxes/webhooks.mdx
@@ -43,7 +43,7 @@ Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stoppe
| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` |
| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` |
| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` |
-| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` |
+| `sandbox.preview_url.changed` | a preview-URL port mapping was added or removed | `port`, `url` (`url` is `null` when the mapping was removed) |
## Destinations
@@ -179,6 +179,7 @@ Redelivery re-sends the **same** delivery (same `webhook-id`) with a fresh retry
- **HTTPS only.** Private, loopback, link-local, and cloud-metadata addresses are refused (at registration and at send).
- **Always signed** with [Standard Webhooks](https://www.standardwebhooks.com). Every request carries `webhook-id` (= `deliveryId`), `webhook-timestamp`, and `webhook-signature` = `v1,<base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{rawBody}"))>`. Verify against the **raw request body, before parsing it**; the timestamp guards replay. Plus `X-OC-Delivery-ID`, `X-OC-Sandbox-ID` (correlation) and `User-Agent: OpenComputer-Webhooks/1`. Your `secret` is write-only.
- **At-least-once, once accepted.** Once an event is accepted it's retried until it succeeds or is **dead-lettered** (inspect + redeliver it). A duplicate can still arrive, so **dedupe on `webhook-id`** (= `deliveryId`).
+- **Not strictly ordered.** Deliveries are sent in parallel, so events for one sandbox can arrive out of order (e.g. `sandbox.ready` before `sandbox.created`). Treat each event independently and key off `event.type`; don't assume an ordering.
- **Success / retry / give-up.** A delivery succeeds on HTTP `2xx`. A `5xx`, network error, or timeout is **retried** on a backoff of `10s, 30s, 60s, 5m, 15m` (capped), up to **12 attempts**, then **`dead_letter`**. A `429` is retried honoring its `Retry-After`. A `4xx` (other than 429), a `3xx` redirect, or an SSRF-blocked address is treated as **permanent → immediate `dead_letter`** (no retries). Redirects are not followed.
### Verify a webhook
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 96031f4e..d56cea0b 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1519,13 +1519,15 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
if migrated {
s.emitEvent("migrate", sandboxID, workerID, fmt.Sprintf("auto-migrated for scale to %dMB", requestedMemMB))
}
- // Only emit scale events for non-default sizes (4096MB is the creation default)
+ // Only emit the admin SSE scale event for non-default sizes (4096MB is the
+ // creation default — avoids noise on the implicit create-time scale).
if requestedMemMB != 4096 || migrated {
s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))
- s.recordLifecycle(ctx, session.OrgID, sandboxID, types.WebhookEventScaled, map[string]any{
- "cpuCount": requestedCPUs, "memoryMB": requestedMemMB,
- })
}
+ // The sandbox.scaled webhook fires on every successful explicit scale request.
+ s.recordLifecycle(ctx, session.OrgID, sandboxID, types.WebhookEventScaled, map[string]any{
+ "cpuCount": requestedCPUs, "memoryMB": requestedMemMB,
+ })
resp := map[string]any{
"sandboxID": sandboxID,
@@ -3403,8 +3405,11 @@ func (s *Server) deletePreviewURL(c echo.Context) error {
}
}
- _ = s.store.DeletePreviewURL(ctx, previewURL.ID)
+ if err := s.store.DeletePreviewURL(ctx, previewURL.ID); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ // Emit only after the delete commits; url is null for a removed mapping.
if orgID, ok := auth.GetOrgID(c); ok {
s.recordLifecycle(ctx, orgID, sandboxID, types.WebhookEventPreviewURLChanged, map[string]any{
"port": port, "url": nil,
diff --git a/internal/api/webhooks.go b/internal/api/webhooks.go
index 6cb3fe06..4eedc74a 100644
--- a/internal/api/webhooks.go
+++ b/internal/api/webhooks.go
@@ -113,6 +113,14 @@ func webhookRequestHash(req types.CreateWebhookRequest) string {
nm = *req.Name
}
fmt.Fprintf(h, "name=%s\n", nm)
+ // Include enabled + secret so the same key with a different paused state or
+ // signing secret is a different request (→ 409), not a silent reuse.
+ en := "unset"
+ if req.Enabled != nil {
+ en = fmt.Sprintf("%t", *req.Enabled)
+ }
+ fmt.Fprintf(h, "enabled=%s\n", en)
+ fmt.Fprintf(h, "secret=%s\n", req.Secret)
return hex.EncodeToString(h.Sum(nil))
}
diff --git a/internal/controlplane/lifecycle_ingress.go b/internal/controlplane/lifecycle_ingress.go
index cc18c66b..7c67add5 100644
--- a/internal/controlplane/lifecycle_ingress.go
+++ b/internal/controlplane/lifecycle_ingress.go
@@ -46,14 +46,30 @@ type LifecycleIngress struct {
// types. Only these worker-origin events become webhooks via the ingress; every
// other stream entry is acked and ignored by this consumer group.
//
-// Note: there is intentionally NO "running" entry — the worker does not emit a
-// post-boot "running"/"ready" stream event (sessions are created directly as
-// running), so sandbox.ready has no producer yet (P3 gap). "woke" is the
-// worker's wake signal (grpc_server.go WakeSandbox) → sandbox.resumed.
+// Notes:
+// - No "running" entry: the worker emits no post-boot stream event (sessions
+// are created directly as running), so sandbox.ready is recorded CP-side.
+// - No "migrated" entry: the worker never emits "migrated"; it's recorded
+// CP-side in CompleteMigration (the migration-completion funnel).
+// - "woke" is the worker's wake signal (grpc_server.go WakeSandbox) → resumed.
var ingressTypeMap = map[string]string{
- "created": types.WebhookEventCreated,
- "woke": types.WebhookEventResumed,
- "migrated": types.WebhookEventMigrated,
+ "created": types.WebhookEventCreated,
+ "woke": types.WebhookEventResumed,
+}
+
+// normalizeIngressData maps an internal worker payload to the PUBLIC event.data
+// contract (the worker logs include internal fields like sandbox_id; the public
+// data is clean camelCase per docs). created → {template}; everything else → {}.
+func normalizeIngressData(publicType string, payload json.RawMessage) json.RawMessage {
+ if publicType == types.WebhookEventCreated {
+ var p struct {
+ Template string `json:"template"`
+ }
+ _ = json.Unmarshal(payload, &p)
+ b, _ := json.Marshal(map[string]string{"template": p.Template})
+ return b
+ }
+ return json.RawMessage("{}")
}
// streamLifecycleEnvelope is the subset of the stream "event" payload we need.
@@ -271,12 +287,8 @@ func (g *LifecycleIngress) process(ctx context.Context, m redis.XMessage) {
if id == "" {
id = fmt.Sprintf("%s:%s:%s", env.SandboxID, env.Type, m.ID)
}
- // P3 normalizes worker payload keys to the documented camelCase taxonomy
- // (e.g. created → {template,cpuCount,memoryMB}); for now we pass it through.
- data := env.Payload
- if len(data) == 0 {
- data = json.RawMessage("{}")
- }
+ // Map the internal worker payload to the public event.data contract.
+ data := normalizeIngressData(publicType, env.Payload)
if err := g.store.RecordLifecycleEvent(ctx, db.LifecycleEvent{
ID: id,
OrgID: orgID,
diff --git a/internal/db/store.go b/internal/db/store.go
index 46c48bb1..874a3f28 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -809,6 +809,18 @@ func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID st
}
func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, status string, errorMsg *string) error {
+ return s.updateSandboxSessionStatus(ctx, sandboxID, status, errorMsg, "")
+}
+
+// UpdateSandboxSessionStatusReason is UpdateSandboxSessionStatus with an explicit
+// sandbox.stopped reason (one of user_requested | expired | crash). Use it where
+// the reason is known — e.g. "expired" for an idle-timeout kill. An empty reason
+// defaults by status (stopped→user_requested, error→crash).
+func (s *Store) UpdateSandboxSessionStatusReason(ctx context.Context, sandboxID, status string, errorMsg *string, reason string) error {
+ return s.updateSandboxSessionStatus(ctx, sandboxID, status, errorMsg, reason)
+}
+
+func (s *Store) updateSandboxSessionStatus(ctx context.Context, sandboxID, status string, errorMsg *string, reason string) error {
var query string
var args []interface{}
if status == "stopped" || status == "error" {
@@ -871,9 +883,13 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
var data json.RawMessage
switch status {
case "stopped":
+ r := reason
+ if r != "expired" && r != "crash" {
+ r = "user_requested" // default / sanitize
+ }
evType = "sandbox.stopped"
evID = sandboxID + ":sandbox.stopped" // terminal: once per sandbox
- data = json.RawMessage(`{"reason":"user_requested"}`)
+ data, _ = json.Marshal(map[string]string{"reason": r})
case "error":
evType = "sandbox.stopped"
evID = sandboxID + ":sandbox.stopped"
@@ -929,22 +945,40 @@ func (s *Store) SetMigrating(ctx context.Context, sandboxID, targetWorkerID stri
return err
}
-// CompleteMigration marks a sandbox as running on the new worker after successful migration.
+// CompleteMigration marks a sandbox as running on the new worker after successful
+// migration, and records sandbox.migrated in the same tx (the worker does not emit
+// it; this is the single migration-completion funnel for both manual and
+// scale-triggered migrations).
func (s *Store) CompleteMigration(ctx context.Context, sandboxID, newWorkerID string) error {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
// Use status IN ('migrating', 'running', 'stopped') — a race with the source
// worker's cleanup may have already set it to 'stopped' or reverted to 'running'.
// The migration DID succeed (QEMU is running on the target), so force the update.
- tag, err := s.pool.Exec(ctx,
+ var orgID uuid.UUID
+ err = tx.QueryRow(ctx,
`UPDATE sandbox_sessions SET status = 'running', worker_id = $1, migrating_to_worker = '', stopped_at = NULL, error_msg = NULL
- WHERE sandbox_id = $2 AND status IN ('migrating', 'running', 'stopped')`,
- newWorkerID, sandboxID)
+ WHERE sandbox_id = $2 AND status IN ('migrating', 'running', 'stopped')
+ RETURNING org_id`,
+ newWorkerID, sandboxID).Scan(&orgID)
if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("no session found for %s in migrating/running/stopped state", sandboxID)
+ }
return err
}
- if tag.RowsAffected() == 0 {
- return fmt.Errorf("no session found for %s in migrating/running/stopped state", sandboxID)
+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{
+ ID: fmt.Sprintf("%s:sandbox.migrated:%s", sandboxID, newWorkerID),
+ OrgID: orgID,
+ SandboxID: sandboxID,
+ Type: "sandbox.migrated",
+ }); err != nil {
+ return fmt.Errorf("record migrated event: %w", err)
}
- return nil
+ return tx.Commit(ctx)
}
// FailMigration reverts a sandbox to running on its original worker after a failed migration.
diff --git a/internal/db/webhooks.go b/internal/db/webhooks.go
index dbee3f07..bf7b7c61 100644
--- a/internal/db/webhooks.go
+++ b/internal/db/webhooks.go
@@ -227,7 +227,7 @@ func (s *Store) CreateWebhookDestination(ctx context.Context, p CreateDestinatio
return nil, false, ferr
}
if found {
- if existing.URL == p.URL && sameStrSlice(existing.EventTypes, p.EventTypes) && samePtrStr(existing.SandboxID, p.SandboxID) {
+ if existing.URL == p.URL && sameStrSlice(existing.EventTypes, p.EventTypes) && samePtrStr(existing.SandboxID, p.SandboxID) && existing.Enabled == p.Enabled {
return existing, true, nil
}
return nil, false, ErrWebhookNameConflict
@@ -563,7 +563,7 @@ func (s *Store) MaterializePendingLifecycleEvents(ctx context.Context, batch int
}
for _, e := range events {
- metadata, err := getSandboxMetadataTx(ctx, tx, e.SandboxID)
+ metadata, err := getSandboxMetadataTx(ctx, tx, e.OrgID, e.SandboxID)
if err != nil {
return 0, err
}
@@ -631,11 +631,13 @@ func matchDestinationsTx(ctx context.Context, tx pgx.Tx, e lifecycleEventRow) ([
return out, rows.Err()
}
-func getSandboxMetadataTx(ctx context.Context, tx pgx.Tx, sandboxID string) (map[string]string, error) {
+func getSandboxMetadataTx(ctx context.Context, tx pgx.Tx, orgID uuid.UUID, sandboxID string) (map[string]string, error) {
var raw []byte
+ // Scope by org too: sandbox ids are NOT globally unique, so a sandbox_id-only
+ // lookup could pull another org's metadata into this org's webhook payload.
err := tx.QueryRow(ctx,
- `SELECT metadata FROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`,
- sandboxID).Scan(&raw)
+ `SELECT metadata FROM sandbox_sessions WHERE org_id = $1 AND sandbox_id = $2 ORDER BY started_at DESC LIMIT 1`,
+ orgID, sandboxID).Scan(&raw)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
@@ -875,13 +877,17 @@ func (s *Store) ReclaimStaleDeliveries(ctx context.Context) (int64, error) {
// RedeliverDelivery re-enqueues any delivery with a fresh retry budget
// (retry_count=0), preserving lifetime attempts, and returns the updated row.
-// Org+destination scoped.
+// Org+destination scoped. Refuses a soft-deleted destination — the dispatcher
+// would never claim it (its claim filters deleted), so re-enqueuing would just
+// strand the row in pending; callers should treat this as 404.
func (s *Store) RedeliverDelivery(ctx context.Context, orgID uuid.UUID, destID, deliveryID string) (*WebhookDeliveryRow, error) {
r, err := scanDelivery(s.pool.QueryRow(ctx,
- `UPDATE webhook_deliveries
+ `UPDATE webhook_deliveries d
SET status = 'pending', next_attempt_at = now(), retry_count = 0,
response_code = NULL, error = NULL, locked_by = NULL, locked_until = NULL, updated_at = now()
- WHERE id = $1 AND destination_id = $2 AND org_id = $3
+ WHERE d.id = $1 AND d.destination_id = $2 AND d.org_id = $3
+ AND EXISTS (SELECT 1 FROM webhook_destinations dst
+ WHERE dst.id = d.destination_id AND dst.deleted_at IS NULL)
RETURNING `+deliveryCols, deliveryID, destID, orgID))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {