A free open source IT asset/license management system
Handle TOCTOU in Accessory/Consumable/Component
snipec9114c251cf6
diff --git a/app/Models/Traits/AdjustsQuantity.php b/app/Models/Traits/AdjustsQuantity.phpindex 467af7a422..fc5105c70c 100644--- a/app/Models/Traits/AdjustsQuantity.php+++ b/app/Models/Traits/AdjustsQuantity.php@@ -95,17 +95,34 @@ trait AdjustsQuantitypublic function adjustQuantity(int $delta, string $note, ?int $orderItemId = null, ?string $filename = null): void{$column = $this->getAdjustableQuantityColumn();- $current = (int) ($this->{$column} ?? 0);- $inUse = max(0, (int) $this->currentlyInUseCount());- $floor = $inUse;- if ($current + $delta < $floor) {- throw new DomainException(- "Adjustment would take on-hand quantity ({$current}) below the {$inUse} unit(s) currently in use (delta={$delta})"- );- }+ DB::transaction(function () use ($delta, $column, $note, $orderItemId, $filename) {+ // TOCTOU-safe path: SELECT ... FOR UPDATE on this row so+ // concurrent adjusters serialize. Read + floor-check ++ // decrement all live under the same lock, otherwise two+ // requests each read the same pre-decrement quantity, each+ // pass the floor check independently, and each apply their+ // delta - aggregate effect drives on-hand below in-use even+ // though each request looked valid on its own. The pattern+ // matches the pessimistic lock LicenseCheckoutController+ // already uses on seat checkout for the same reason.+ $locked = static::query()->lockForUpdate()->find($this->id);+ if ($locked === null) {+ // Row went away between the caller loading it and the+ // trait entering the transaction. Rare (would require+ // a concurrent forceDelete) but bail cleanly rather+ // than hit a null-deref two lines below.+ throw new DomainException("Row {$this->id} not found during adjustQuantity lock");+ }+ $current = (int) ($locked->{$column} ?? 0);+ $inUse = max(0, (int) $locked->currentlyInUseCount());++ if ($current + $delta < $inUse) {+ throw new DomainException(+ "Adjustment would take on-hand quantity ({$current}) below the {$inUse} unit(s) currently in use (delta={$delta})"+ );+ }- DB::transaction(function () use ($delta, $column, $current, $note, $orderItemId, $filename) {// Use the query builder directly (not $this->increment) so// the model's `updated` event doesn't fire. Firing it would// write a second "update" action_log entry (with log_meta of@@ -116,11 +133,11 @@ trait AdjustsQuantity// submissions (delta = 0) skip the round-trip.if ($delta > 0) {$this->newQuery()->where('id', $this->id)->increment($column, $delta);- $this->{$column} = (int) $this->{$column} + $delta;+ $this->{$column} = $current + $delta;$this->syncOriginalAttribute($column);} elseif ($delta < 0) {$this->newQuery()->where('id', $this->id)->decrement($column, abs($delta));- $this->{$column} = (int) $this->{$column} + $delta;+ $this->{$column} = $current + $delta;$this->syncOriginalAttribute($column);}@@ -132,12 +149,12 @@ trait AdjustsQuantity$log->order_item_id = $orderItemId;$log->quantity = $delta;// Feed the history-tab's "changed" column so QuantityAdjust- // entries render "qty: 5 → 8" the same way an update-type- // log renders a name change. Only populated on non-zero- // deltas — audit-only (delta = 0) submissions carry their- // reason in `note` and leaving log_meta null keeps the- // "changed" column empty for them (no field actually- // changed, so nothing to diff).+ // entries render qty diffs the same way an update-type log+ // renders a name change. Only populated on non-zero deltas+ // - audit-only (delta = 0) submissions carry their reason+ // in `note` and leaving log_meta null keeps the "changed"+ // column empty for them (no field actually changed, so+ // nothing to diff).if ($delta !== 0) {$log->log_meta = json_encode([$column => ['old' => $current, 'new' => $current + $delta],diff --git a/tests/Feature/InventoryAdjust/AdjustQuantityRaceConditionTest.php b/tests/Feature/InventoryAdjust/AdjustQuantityRaceConditionTest.phpnew file mode 100644index 0000000000..5dcee78145--- /dev/null+++ b/tests/Feature/InventoryAdjust/AdjustQuantityRaceConditionTest.php@@ -0,0 +1,151 @@+<?php++namespace Tests\Feature\InventoryAdjust;++use App\Models\Accessory;+use App\Models\Component;+use App\Models\Consumable;+use DomainException;+use Illuminate\Support\Facades\DB;+use PHPUnit\Framework\Attributes\DataProvider;+use Tests\TestCase;++/**+ * Regression coverage for the TOCTOU race in AdjustsQuantity::adjustQuantity()+ * that GHSA-3wf3-jcpq-265f reported.+ *+ * Pre-fix, the read of $current + the read of currentlyInUseCount() + the+ * floor invariant check all ran OUTSIDE the DB::transaction, and only the+ * increment/decrement itself ran inside. Two concurrent adjusters each+ * observed the same pre-decrement quantity, each independently passed the+ * floor check, each atomically applied their own delta, and the aggregate+ * effect drove on-hand below in-use even though every individual request+ * looked valid on its own.+ *+ * The fix moves the whole read + check + write sequence inside the+ * transaction and takes a pessimistic row lock (SELECT ... FOR UPDATE)+ * so concurrent adjusters serialize instead of interleaving.+ *+ * SQLite (which the test suite uses in memory) does not enforce row locks+ * the same way MySQL/MariaDB does, so a real concurrent-request test+ * cannot deterministically reproduce the race here. Instead we assert on+ * the code-path indicators the lock adds: the SELECT query must carry+ * `for update`, and it must be emitted INSIDE the same transaction as the+ * UPDATE. Those two invariants together are what closes the race on any+ * ACID engine that honors row locks.+ */+class AdjustQuantityRaceConditionTest extends TestCase+{+ /**+ * @return array<string, array{class-string}>+ */+ public static function inventoryModelProvider(): array+ {+ return [+ 'accessory' => [Accessory::class],+ 'consumable' => [Consumable::class],+ 'component' => [Component::class],+ ];+ }++ #[DataProvider('inventoryModelProvider')]+ public function test_adjust_quantity_takes_pessimistic_row_lock(string $modelClass): void+ {+ // SQLite's Laravel grammar strips the FOR UPDATE clause on+ // compile (Illuminate\Database\Query\Grammars\SQLiteGrammar::compileLock+ // returns ''), so the emitted SQL doesn't carry the lock text+ // even though the builder had lockForUpdate() applied. Skip on+ // SQLite; MySQL/MariaDB/Postgres runs (CI) will exercise this.+ $this->markIncompleteIfSqlite('SQLite grammar drops FOR UPDATE on compile, cannot observe the lock in the query log.');++ $item = $modelClass::factory()->create(['qty' => 10]);++ DB::enableQueryLog();+ DB::flushQueryLog();++ $item->adjustQuantity(1, 'lock probe');++ $queries = DB::getQueryLog();+ DB::disableQueryLog();++ // Look for a SELECT on the item's table carrying `for update`.+ // Case-insensitive match handles driver variance in how the SQL+ // is echoed back (Laravel normalizes to lowercase but grammars+ // differ).+ $selectForUpdate = collect($queries)->first(+ fn ($q) => stripos($q['query'], 'select') === 0+ && stripos($q['query'], (new $modelClass)->getTable()) !== false+ && stripos($q['query'], 'for update') !== false+ );++ $this->assertNotNull(+ $selectForUpdate,+ "adjustQuantity() on {$modelClass} must issue a SELECT ... FOR UPDATE on the item row to serialize concurrent adjusters. GHSA-3wf3-jcpq-265f regression."+ );+ }++ #[DataProvider('inventoryModelProvider')]+ public function test_adjust_quantity_lock_and_write_share_a_transaction(string $modelClass): void+ {+ // The lock is only meaningful if it holds through the write. If+ // the SELECT ... FOR UPDATE ran outside the transaction that+ // does the increment/decrement, the lock would release before+ // the write and the race would reappear.+ //+ // Laravel's query log does not include BEGIN/COMMIT (those are+ // PDO-driver-level commands, not routed through the query+ // builder), so we sample DB::transactionLevel() live at every+ // query-fire via DB::listen. transactionLevel() > 0 at the+ // moment the locking SELECT fires AND at the moment the UPDATE+ // fires, plus both being emitted before the level returns to 0,+ // proves the lock's transaction covers the write.+ //+ // Same SQLite constraint as the sibling test: the compiled SQL+ // doesn't carry `for update` on SQLite, so we can't reliably+ // pick the locking SELECT apart from the count-checkouts SELECT+ // in the log.+ $this->markIncompleteIfSqlite('SQLite grammar drops FOR UPDATE on compile, cannot identify the locking SELECT.');++ $item = $modelClass::factory()->create(['qty' => 10]);+ $table = $item->getTable();++ $observed = [];+ DB::listen(function ($event) use (&$observed, $table) {+ $sql = strtolower($event->sql);+ $isLockingSelect = str_starts_with($sql, 'select')+ && str_contains($sql, $table)+ && str_contains($sql, 'for update');+ $isTableUpdate = str_starts_with($sql, 'update')+ && str_contains($sql, $table);+ if ($isLockingSelect || $isTableUpdate) {+ $observed[] = [+ 'kind' => $isLockingSelect ? 'lock' : 'update',+ 'txLevel' => DB::transactionLevel(),+ ];+ }+ });++ $item->adjustQuantity(-1, 'lock probe');++ $lock = collect($observed)->firstWhere('kind', 'lock');+ $update = collect($observed)->firstWhere('kind', 'update');++ $this->assertNotNull($lock, 'Expected a locking SELECT ... FOR UPDATE on the item row');+ $this->assertNotNull($update, 'Expected an UPDATE on the item row');+ $this->assertGreaterThan(0, $lock['txLevel'], 'Locking SELECT must fire inside an open transaction');+ $this->assertGreaterThan(0, $update['txLevel'], 'UPDATE must fire inside an open transaction');+ }++ #[DataProvider('inventoryModelProvider')]+ public function test_floor_check_still_rejects_below_zero_adjustment(string $modelClass): void+ {+ // Existing regression: a single adjuster that would drop qty+ // below zero (or below in-use) still throws. The fix moved this+ // check inside the transaction; make sure the check itself did+ // not regress in the process.+ $item = $modelClass::factory()->create(['qty' => 3]);++ $this->expectException(DomainException::class);+ $item->adjustQuantity(-5, 'would go negative');+ }+}