infra icon indicating copy to clipboard operation
infra copied to clipboard

Fix TOCTOU race in template deletion causing FK violation

Open beran-t opened this issue 8 months ago • 0 comments

Bug

There is a TOCTOU (Time-of-Check-Time-of-Use) race condition in the DELETE /templates/{templateID} handler. When a Sandbox.create(snapshotId) runs concurrently with template deletion, the following sequence causes an FK constraint violation (snapshots_envs_base_env_id):

  1. Delete handler calls ExistsTemplateSnapshots() — no snapshots found
  2. Concurrently, Sandbox.create(snapshotId) resolves the template env, setting BaseTemplateID
  3. Delete handler calls DeleteTemplate() — deletes the env row
  4. The new sandbox later pauses and UpsertSnapshot tries to INSERT with base_env_id pointing to the deleted env — FK violation

Fix

Two-pronged approach:

1. Atomic delete with row locking (template_delete.go)

  • Wrap ExistsTemplateSnapshots + DeleteTemplate in a single DB transaction (following the existing WithTx pattern from template_tags.go)
  • Acquire SELECT ... FOR UPDATE on the env row at the start of the transaction, which blocks concurrent UpsertSnapshot FK checks until the transaction commits
  • This eliminates the TOCTOU window between the snapshot check and the delete

2. Graceful FK violation handling (pause_instance.go)

  • If UpsertSnapshot fails with an FK violation (base template was deleted after the sandbox was created but before it paused), return a typed BaseTemplateDeletedError instead of propagating a raw constraint violation
  • Reported as a non-critical telemetry error since this is a legitimate race outcome

Files changed

File Change
packages/api/internal/handlers/template_delete.go Wrap guard checks + deletion in a DB transaction with SELECT ... FOR UPDATE on the env row
packages/api/internal/orchestrator/pause_instance.go Add BaseTemplateDeletedError type; catch FK violations from UpsertSnapshot and return descriptive error
packages/db/queries/templates/lock_env_for_update.sql New SQL query: SELECT id FROM envs WHERE id = @env_id FOR UPDATE
packages/db/queries/lock_env_for_update.sql.go Generated Go code for the LockEnvForUpdate query

Reproduction

Racing Sandbox.create(snapshotId) against Sandbox.deleteSnapshot(snapshotId) reproduces the FK violation on nearly every first attempt.

Test plan

  • [ ] Verify template deletion still works correctly when no sandboxes reference the template
  • [ ] Verify template deletion returns 400 when paused sandboxes exist
  • [ ] Verify concurrent Sandbox.create(snapshotId) + template deletion no longer causes FK violation
  • [ ] Verify sandbox pause returns BaseTemplateDeletedError (not raw FK violation) when the base template was deleted
  • [ ] Run make generate/db to confirm the generated SQL code matches

beran-t avatar Mar 25 '26 15:03 beran-t