fix(quota): make the claim gate atomic, and stop zeroing the storage cache

Two defects in the §9.3 quota path, both invisible to the hermetic suite:

- Audit #4's TOCTOU was real and documented: QuotaCheck and ClaimServer were
  separate statements, so two concurrent claims by one user for two different
  ownerless servers both read count < max_servers and both won. The gate now
  lives inside ClaimServer, in the SAME transaction as the ownership write,
  under pg_advisory_xact_lock(hashtext(user_id)) — the aggregate read, the
  four-dimension re-check (shared with QuotaCheck via one helper so the two
  cannot drift), and the UPDATE are one serialized decision. The loser gets
  ErrQuotaExceeded, which both claim handlers map to the same 403 the
  sequential path gives; the server row is additionally taken FOR UPDATE so
  same-server races still resolve to exactly one winner.

- The server PATCH path called UpdateServerResources(..., 0) for storage even
  though a resources patch cannot change storage. The cached columns are the
  ONLY input to the quota aggregate, so every resource patch silently dropped
  that server's storage contribution from its owner's cap. The handler now
  reads the current spec and passes storage through.

Red-then-green: the new pgint test drives two real concurrent claims against
max_servers=1 (before: both win; now: exactly one win + one gated 403, and the
DB shows one owned row); the hermetic suite pins the 403 mapping and the
storage-preserving cache write.
This commit is contained in:
Lemon-miaow committed 2026-09-23 03:37:59 +08:00
1 parent d829267f1c
commit bb68fefe04
8 files changed
+274 -50

No files matched your search

+7
View File
@@ -15,6 +15,13 @@ var (
ErrNotFound = errors.New("not found")
// ErrConflict means an atomic precondition failed (e.g. claim lost the race).
ErrConflict = errors.New("conflict")
// ErrQuotaExceeded means an ownership write would push the user over a quota
// cap (spec §9.3). ClaimServer — the atomic gate — returns it when a claim
// passes the handler's advisory pre-check but loses the serialized re-check
// (two concurrent claims by one user); handlers map it to a 403
// quota_exceeded, the same answer the pre-check gives, so the CONCURRENT case
// and the SEQUENTIAL case are indistinguishable to the caller.
ErrQuotaExceeded = errors.New("server quota exhausted")
// ErrLinkCodeInvalid means an account-link code is unknown or expired (spec
// §10). It is a client error (the verify endpoint exists; the code is bad), so
// handlers map it to 400, not 404.