Skip to content

fix: prevent double-activation of machine tokens via atomic CAS - #197

Open
gusye1234 wants to merge 2 commits into
mainfrom
fix/150-machine-token-toctou
Open

fix: prevent double-activation of machine tokens via atomic CAS#197
gusye1234 wants to merge 2 commits into
mainfrom
fix/150-machine-token-toctou

Conversation

@gusye1234

Copy link
Copy Markdown
Contributor

Summary

  • Adds status = 'pending' condition to the UPDATE WHERE clause in activateMachineToken() so only one concurrent request can succeed
  • Route handler now checks the return value and returns 409 if the token was already activated by another request

Changes

  • src/shared/src/db/queries/machine-token.ts: UPDATE now uses atomic compare-and-swap, returns success boolean
  • src/web/src/app/api/machine-tokens/activate/route.ts: Checks activation result, returns 409 on race conflict

Test plan

  • Activate a pending token → should succeed (200)
  • Activate same token again → should return 409
  • Simulate concurrent activation (two requests) → only one should succeed

Closes #150

Adds status='pending' condition to the UPDATE WHERE clause so only one
concurrent request can activate a token. Returns success/failure to the
route handler which now returns 409 on conflict.

Closes #150
@gusye1234
gusye1234 requested a review from a team as a code owner May 28, 2026 09:31
The function now returns a boolean indicating success, so the test mock
must return true for the happy-path tests.

@gusye1234 gusye1234 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — PR #197: prevent double-activation of machine tokens via atomic CAS

Solid fix for a TOCTOU race condition. The approach is textbook CAS:

  1. The WHERE clause now includes eq(machineToken.status, "pending") — two concurrent activations can't both succeed because only the first UPDATE will match a row.
  2. .returning() + boolean return makes the caller aware of whether activation actually happened.
  3. 409 response for already-activated tokens is the correct HTTP semantic (Conflict).
  4. Tests properly updated to expect true from the mock.

Checklist:

  • Functionality: eliminates race window for double-activation
  • Edge cases: concurrent requests handled atomically
  • Security: prevents duplicate token activation and associated side-effects
  • Code quality: minimal, clear changes
  • Tests: CI green, mock return values updated

LGTM — ready to merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TOCTOU race in machine token activation allows double-activation

1 participant