A free open source IT asset/license management system
Clean up checkout APIs for concurrency
snipef71806b1e0ef
diff --git a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php b/app/Http/Controllers/Accessories/AccessoryCheckoutController.phpindex 4e85fd609d..02ff2c8d6b 100644--- a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php+++ b/app/Http/Controllers/Accessories/AccessoryCheckoutController.php@@ -16,6 +16,7 @@ use Carbon\Carbon;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;+use Illuminate\Support\Facades\DB;class AccessoryCheckoutController extends Controller{@@ -82,18 +83,41 @@ class AccessoryCheckoutController extends Controller$accessory->checkout_qty = $request->input('checkout_qty', 1);- for ($i = 0; $i < $accessory->checkout_qty; $i++) {+ // Concurrency guard. AccessoryCheckoutRequest's+ // number_remaining_after_checkout rule runs on an unlocked read of+ // numRemaining(), so two simultaneous checkout requests could both+ // pass validation, both attach rows, and land the register at -1.+ // Re-fetch the parent row under lockForUpdate INSIDE a transaction,+ // re-check availability against the locked snapshot, and only then+ // write. Mirrors the License checkout locking pattern.+ $overAllocated = false;- $accessory_checkout = new AccessoryCheckout([- 'accessory_id' => $accessory->id,- 'created_at' => Carbon::now(),- 'assigned_to' => $target->id,- 'assigned_type' => $target::class,- 'note' => $request->input('note'),- ]);+ DB::transaction(function () use ($accessory, $request, $target, &$overAllocated): void {+ $locked = Accessory::whereKey($accessory->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $accessory->checkout_qty) {+ $overAllocated = true;++ return;+ }++ for ($i = 0; $i < $accessory->checkout_qty; $i++) {++ $accessory_checkout = new AccessoryCheckout([+ 'accessory_id' => $accessory->id,+ 'created_at' => Carbon::now(),+ 'assigned_to' => $target->id,+ 'assigned_type' => $target::class,+ 'note' => $request->input('note'),+ ]);++ $accessory_checkout->created_by = auth()->id();+ $accessory_checkout->save();+ }+ });- $accessory_checkout->created_by = auth()->id();- $accessory_checkout->save();+ if ($overAllocated) {+ return redirect()->back()->with('error', trans('admin/accessories/message.checkout.unavailable'));}event(new CheckoutableCheckedOut(diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.phpindex 2a9be43ff8..d8947e1e45 100644--- a/app/Http/Controllers/Api/AccessoriesController.php+++ b/app/Http/Controllers/Api/AccessoriesController.php@@ -326,9 +326,25 @@ class AccessoriesController extends Controller$accessory->checkout_qty = $request->input('checkout_qty', 1);$payload = null;+ $overAllocated = false;++ // Concurrency guard. AccessoryCheckoutRequest validated+ // number_remaining_after_checkout >= 0 with an unlocked read of+ // numRemaining(), so two simultaneous checkout requests could both+ // pass validation, both attach rows, and land the register at -1.+ // Re-fetch the parent row under lockForUpdate INSIDE the+ // transaction, re-check availability against the locked snapshot,+ // and only then write. Mirrors the License checkout locking+ // pattern.+ DB::transaction(function () use ($accessory, $request, $target, &$payload, &$overAllocated): void {+ $locked = Accessory::whereKey($accessory->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $accessory->checkout_qty) {+ $overAllocated = true;++ return;+ }- // Keep checkout rows and checkout log/event atomic to avoid ghost assignments.- DB::transaction(function () use ($accessory, $request, $target, &$payload): void {for ($i = 0; $i < $accessory->checkout_qty; $i++) {$accessory_checkout = new AccessoryCheckout([@@ -363,6 +379,10 @@ class AccessoriesController extends Controller));});+ if ($overAllocated) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkout.unavailable')));+ }+return response()->json(Helper::formatStandardApiResponse('success', $payload, trans('admin/accessories/message.checkout.success')));}diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.phpindex 295971067f..3257b86619 100644--- a/app/Http/Controllers/Api/AssetsController.php+++ b/app/Http/Controllers/Api/AssetsController.php@@ -1025,6 +1025,43 @@ class AssetsController extends Controller];}+ // The PATCH/PUT update path accepts assigned_user / assigned_asset /+ // assigned_location for backwards compatibility with older callers,+ // but that meant a role with only assets.edit (and an explicit deny+ // on assets.checkout) could still trigger $asset->checkOut() and+ // record a checkout event, bypassing the permission entirely.+ // Enforce the same authorization the dedicated checkout endpoint+ // requires whenever the update payload asks for a checkout.+ if ($requestedCheckout && ! Gate::allows('checkout', $asset)) {+ return [+ 'success' => false,+ 'asset' => null,+ 'message' => null,+ 'errors' => null,+ 'encrypted_field_warning' => false,+ 'error_response_key' => 'general.unauthorized',+ ];+ }++ // Same as the dedicated checkout endpoint: an asset is only eligible+ // for checkout when it is not currently assigned to anyone and its+ // status is deployable / not archived. Rejecting here blocks+ // (a) reassigning an already-checked-out asset without an+ // intervening checkin (which the pre-fix code allowed and+ // recorded as two consecutive checkout events), and+ // (b) checking out an asset in a Pending / non-deployable status.+ // availableForCheckout() covers both. See App\Models\Asset::availableForCheckout.+ if ($requestedCheckout && ! $asset->availableForCheckout()) {+ return [+ 'success' => false,+ 'asset' => null,+ 'message' => null,+ 'errors' => null,+ 'encrypted_field_warning' => false,+ 'error_response_key' => 'admin/hardware/message.checkout.not_available',+ ];+ }+$updated = DB::transaction(function () use ($asset, $request, $target, $requestedCheckout): bool {if (! $asset->save()) {return false;diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.phpindex e251c8a207..0bfe7bc114 100644--- a/app/Http/Controllers/Api/ComponentsController.php+++ b/app/Http/Controllers/Api/ComponentsController.php@@ -341,9 +341,24 @@ class ComponentsController extends Controllerreturn response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));}- // Keep pivot + action log in one transaction so checkout is all-or-nothing.+ // Concurrency guard. The numRemaining() checks above are+ // unlocked reads, so two simultaneous checkout requests could+ // both pass, both attach a pivot row, and land the register at+ // -1. Re-fetch the parent under lockForUpdate INSIDE the+ // transaction and re-check against the locked snapshot before+ // writing. Mirrors the License checkout locking pattern.+ $overAllocated = false;+try {- DB::transaction(function () use ($component, $request, $asset): void {+ DB::transaction(function () use ($component, $request, $asset, &$overAllocated): void {+ $locked = Component::whereKey($component->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $request->input('assigned_qty')) {+ $overAllocated = true;++ return;+ }+$component->assigned_to = $request->input('assigned_to');$component->assets()->attach($component->id, [@@ -373,6 +388,13 @@ class ComponentsController extends Controllerreturn response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'), 422);}+ if ($overAllocated) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/components/message.checkout.unavailable', [+ 'remaining' => $component->fresh()->numRemaining(),+ 'requested' => $request->input('assigned_qty'),+ ])));+ }+return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.checkout.success')));}diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.phpindex c5db927147..17128748f6 100644--- a/app/Http/Controllers/Api/ConsumablesController.php+++ b/app/Http/Controllers/Api/ConsumablesController.php@@ -336,8 +336,29 @@ class ConsumablesController extends Controller// Update the consumable data$consumable->assigned_to = $request->input('assigned_to');- // Keep pivot writes and checkout log/event atomic to avoid partial checkout state.- DB::transaction(function () use ($consumable, $request, $user): void {+ // Concurrency guard. The unlocked numRemaining() check above is+ // advisory only — two simultaneous checkout requests can both read+ // "1 remaining", both pass the check, both attach a pivot row, and+ // land the register at -1. Re-fetch the parent row under+ // lockForUpdate INSIDE the transaction, re-check availability+ // against the locked snapshot, and only then write. Any concurrent+ // checkout blocks on the row lock until this transaction commits.+ // Mirrors the pattern already used by License checkout (which locks+ // LicenseSeat rows).+ $errorResponse = null;++ DB::transaction(function () use ($consumable, $request, $user, &$errorResponse): void {+ $locked = Consumable::whereKey($consumable->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $consumable->checkout_qty) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.checkout.unavailable', [+ 'requested' => $consumable->checkout_qty,+ 'remaining' => $locked ? $locked->numRemaining() : 0,+ ])));++ return;+ }+for ($i = 0; $i < $consumable->checkout_qty; $i++) {$consumable->users()->attach($consumable->id,[@@ -363,6 +384,10 @@ class ConsumablesController extends Controller));});+ if ($errorResponse) {+ return $errorResponse;+ }+return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.checkout.success')));}diff --git a/app/Http/Controllers/Components/ComponentCheckoutController.php b/app/Http/Controllers/Components/ComponentCheckoutController.phpindex 90c0bc309b..29119e4455 100644--- a/app/Http/Controllers/Components/ComponentCheckoutController.php+++ b/app/Http/Controllers/Components/ComponentCheckoutController.php@@ -11,6 +11,7 @@ use Illuminate\Auth\Access\AuthorizationException;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Validator;class ComponentCheckoutController extends Controller@@ -113,16 +114,40 @@ class ComponentCheckoutController extends Controller$component->checkout_qty = $request->input('assigned_qty');- // Update the component data- $component->asset_id = $request->input('asset_id');- $component->assets()->attach($component->id, [- 'component_id' => $component->id,- 'created_by' => auth()->user()->id,- 'created_at' => date('Y-m-d H:i:s'),- 'assigned_qty' => $component->checkout_qty,- 'asset_id' => $request->input('asset_id'),- 'note' => $request->input('note'),- ]);+ // Concurrency guard. The numRemaining() check above is an unlocked+ // read, so two simultaneous checkout requests could both pass, both+ // attach a pivot row, and land the register at -1. Re-fetch the+ // parent under lockForUpdate INSIDE a transaction, re-check against+ // the locked snapshot, then write. Mirrors the License checkout+ // locking pattern.+ $overAllocated = false;++ DB::transaction(function () use ($component, $request, &$overAllocated): void {+ $locked = Component::whereKey($component->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $component->checkout_qty) {+ $overAllocated = true;++ return;+ }++ $component->asset_id = $request->input('asset_id');+ $component->assets()->attach($component->id, [+ 'component_id' => $component->id,+ 'created_by' => auth()->user()->id,+ 'created_at' => date('Y-m-d H:i:s'),+ 'assigned_qty' => $component->checkout_qty,+ 'asset_id' => $request->input('asset_id'),+ 'note' => $request->input('note'),+ ]);+ });++ if ($overAllocated) {+ return redirect()->back()->withInput()->with('error', trans('admin/components/message.checkout.unavailable', [+ 'remaining' => $component->fresh()->numRemaining(),+ 'requested' => $component->checkout_qty,+ ]));+ }event(new CheckoutableCheckedOut($component,diff --git a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php b/app/Http/Controllers/Consumables/ConsumableCheckoutController.phpindex c5ed4d57ac..f532f0dd05 100644--- a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php+++ b/app/Http/Controllers/Consumables/ConsumableCheckoutController.php@@ -13,6 +13,7 @@ use Illuminate\Auth\Access\AuthorizationException;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;+use Illuminate\Support\Facades\DB;class ConsumableCheckoutController extends Controller{@@ -107,17 +108,42 @@ class ConsumableCheckoutController extends Controller// Update the consumable data$consumable->assigned_to = e($request->input('assigned_to'));+ $consumable->checkout_qty = $quantity;- for ($i = 0; $i < $quantity; $i++) {- $consumable->users()->attach($consumable->id, [- 'consumable_id' => $consumable->id,- 'created_by' => $admin_user->id,- 'assigned_to' => e($request->input('assigned_to')),- 'note' => $request->input('note'),- ]);- }+ // Concurrency guard. The unlocked numRemaining() check above is+ // advisory only — two simultaneous checkout requests could both+ // read "1 remaining", both pass the check, both attach a pivot+ // row, and land the register at -1. Re-fetch the parent row under+ // lockForUpdate INSIDE a transaction, re-check availability+ // against the locked snapshot, and only then write. Mirrors the+ // License checkout locking pattern.+ $overAllocated = false;- $consumable->checkout_qty = $quantity;+ DB::transaction(function () use ($consumable, $request, $admin_user, $quantity, &$overAllocated): void {+ $locked = Consumable::whereKey($consumable->id)->lockForUpdate()->first();++ if (! $locked || $locked->numRemaining() < $quantity) {+ $overAllocated = true;++ return;+ }++ for ($i = 0; $i < $quantity; $i++) {+ $consumable->users()->attach($consumable->id, [+ 'consumable_id' => $consumable->id,+ 'created_by' => $admin_user->id,+ 'assigned_to' => e($request->input('assigned_to')),+ 'note' => $request->input('note'),+ ]);+ }+ });++ if ($overAllocated) {+ return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.checkout.unavailable', [+ 'requested' => $quantity,+ 'remaining' => $consumable->fresh()->numRemaining(),+ ]));+ }event(new CheckoutableCheckedOut($consumable,diff --git a/tests/Feature/Assets/Api/UpdateAssetTest.php b/tests/Feature/Assets/Api/UpdateAssetTest.phpindex 7a02f0895a..80c63e1ac4 100644--- a/tests/Feature/Assets/Api/UpdateAssetTest.php+++ b/tests/Feature/Assets/Api/UpdateAssetTest.php@@ -45,13 +45,19 @@ class UpdateAssetTest extends TestCasepublic function test_all_asset_attributes_are_stored(){$asset = Asset::factory()->create();- $user = User::factory()->editAssets()->create();+ // Needs checkoutAssets too because this test also asserts assigned_user+ // sticks. The PATCH-based assignment path is now gated on the+ // checkout permission (was previously bypassable via edit-only)+ // and requires a deployable status (was previously bypassable too).+ $user = User::factory()->editAssets()->checkoutAssets()->create();$userAssigned = User::factory()->create();$company = Company::factory()->create();$location = Location::factory()->create();$model = AssetModel::factory()->create();$rtdLocation = Location::factory()->create();- $status = Statuslabel::factory()->create();+ // Was Statuslabel::factory()->create() which defaults to deployable=0,+ // so a checkout via PATCH would now (correctly) be refused.+ $status = Statuslabel::factory()->rtd()->create();$supplier = Supplier::factory()->create();$response = $this->actingAsForApi($user)@@ -406,7 +412,10 @@ class UpdateAssetTest extends TestCasepublic function test_checkout_to_user_on_asset_update(){$asset = Asset::factory()->create();- $user = User::factory()->editAssets()->create();+ // Needs both edit + checkout: assigning via PATCH triggers the+ // checkout workflow, which is now gated on the checkout permission+ // (see security fix in Api\AssetsController::applyAssetUpdate).+ $user = User::factory()->editAssets()->checkoutAssets()->create();$assigned_user = User::factory()->create();$response = $this->actingAsForApi($user)@@ -561,7 +570,7 @@ class UpdateAssetTest extends TestCasepublic function test_checkout_to_location_on_asset_update(){$asset = Asset::factory()->create();- $user = User::factory()->editAssets()->create();+ $user = User::factory()->editAssets()->checkoutAssets()->create();$assigned_location = Location::factory()->create();$this->actingAsForApi($user)@@ -600,7 +609,7 @@ class UpdateAssetTest extends TestCasepublic function test_checkout_asset_on_asset_update(){$asset = Asset::factory()->create();- $user = User::factory()->editAssets()->create();+ $user = User::factory()->editAssets()->checkoutAssets()->create();$assigned_asset = Asset::factory()->create();$this->actingAsForApi($user)@@ -724,4 +733,100 @@ class UpdateAssetTest extends TestCase$this->assertEquals('Old Name', $logMeta['name']['old']);$this->assertEquals('New Name', $logMeta['name']['new']);}++ /**+ * Security regression pin: the PATCH endpoint accepted assigned_user /+ * assigned_asset / assigned_location and drove them straight into+ * $asset->checkOut(), which fires CheckoutableCheckedOut and bumps+ * checkout_counter — so a caller with only assets.edit (explicit deny+ * on assets.checkout) could still check assets out and steal custody.+ * Api\AssetsController::applyAssetUpdate() now requires the checkout+ * permission whenever the update payload asks for a checkout.+ */+ public function test_update_denies_checkout_when_actor_lacks_checkout_permission()+ {+ $asset = Asset::factory()->create(['name' => 'Original Name']);+ // Edit only. No checkout permission.+ $editOnly = User::factory()->editAssets()->create();+ $target = User::factory()->create();++ $this->actingAsForApi($editOnly)+ ->patchJson(route('api.assets.update', $asset->id), [+ 'name' => 'Name That Should Roll Back',+ 'assigned_user' => $target->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error')+ ->assertMessagesAre(trans('general.unauthorized'));++ $asset->refresh();++ $this->assertNull($asset->assigned_to, 'edit-only actor must not be able to change custody');+ $this->assertNull($asset->assigned_type);+ $this->assertEquals('Original Name', $asset->name, 'name update should have rolled back with the failed checkout');+ $this->assertDatabaseMissing('action_logs', [+ 'action_type' => 'checkout',+ 'target_type' => User::class,+ 'target_id' => $target->id,+ 'item_type' => Asset::class,+ 'item_id' => $asset->id,+ ]);+ }++ /**+ * Security regression pin: reassigning an already-assigned asset via+ * PATCH used to bypass the "must be currently checked in" workflow+ * check, recording two consecutive checkout events with no intervening+ * checkin. availableForCheckout() rejects any currently-assigned asset,+ * so the second PATCH must fail.+ */+ public function test_update_denies_reassignment_of_already_checked_out_asset()+ {+ $originalHolder = User::factory()->create();+ $newHolder = User::factory()->create();+ $asset = Asset::factory()->create();+ $actor = User::factory()->editAssets()->checkoutAssets()->create();++ // First checkout: succeeds (asset is available).+ $this->actingAsForApi($actor)+ ->patchJson(route('api.assets.update', $asset->id), [+ 'assigned_user' => $originalHolder->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ // Second checkout without a checkin: should be refused.+ $this->actingAsForApi($actor)+ ->patchJson(route('api.assets.update', $asset->id), [+ 'assigned_user' => $newHolder->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error')+ ->assertMessagesAre(trans('admin/hardware/message.checkout.not_available'));++ $this->assertEquals($originalHolder->id, $asset->fresh()->assigned_to, 'custody must not have moved');+ }++ /**+ * Security regression pin: assigning via PATCH used to skip the+ * status_label->deployable check that the dedicated checkout endpoint+ * enforces. A Pending / non-deployable asset must not be checkoutable.+ */+ public function test_update_denies_checkout_when_asset_status_is_not_deployable()+ {+ $pendingStatus = Statuslabel::factory()->pending()->create();+ $asset = Asset::factory()->create(['status_id' => $pendingStatus->id]);+ $actor = User::factory()->editAssets()->checkoutAssets()->create();+ $target = User::factory()->create();++ $this->actingAsForApi($actor)+ ->patchJson(route('api.assets.update', $asset->id), [+ 'assigned_user' => $target->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error')+ ->assertMessagesAre(trans('admin/hardware/message.checkout.not_available'));++ $this->assertNull($asset->fresh()->assigned_to);+ }}diff --git a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.phpindex 8540fd7bfc..cce1b24a80 100644--- a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php+++ b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php@@ -275,4 +275,40 @@ class AccessoryCheckoutTest extends TestCase implements TestsPermissionsRequirem->assertOk()->assertStatusMessageIs('success');}++ /**+ * Security regression pin: sibling to the consumable race test.+ * AccessoryCheckoutRequest validates number_remaining_after_checkout+ * with an unlocked numRemaining() read. Two racing checkouts for a+ * qty=1 accessory both used to pass validation and both attach pivot+ * rows. Fix wraps the writes in DB::transaction with a lockForUpdate+ * re-check. This test pre-drains the pivot to simulate the "someone+ * else grabbed it" moment and asserts we refuse.+ */+ public function test_checkout_refuses_when_inventory_is_already_exhausted(): void+ {+ $target = User::factory()->create();+ $accessory = Accessory::factory()->create(['qty' => 1]);+ $actor = User::factory()->superuser()->create();++ \App\Models\AccessoryCheckout::create([+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $target->id,+ 'assigned_type' => User::class,+ 'created_by' => $actor->id,+ ]);++ $this->assertSame(0, $accessory->fresh()->numRemaining());++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_user' => $target->id,+ 'checkout_to_type' => 'user',+ 'checkout_qty' => 1,+ ])+ ->assertStatusMessageIs('error');++ $this->assertSame(1, $accessory->checkouts()->count(), 'A second pivot row would mean the register went negative');+ $this->assertSame(0, $accessory->fresh()->numRemaining());+ }}diff --git a/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php b/tests/Feature/Checkouts/Api/ComponentCheckoutTest.phpindex a59f013261..2594088559 100644--- a/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php+++ b/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php@@ -212,4 +212,40 @@ class ComponentCheckoutTest extends TestCase implements TestsFullMultipleCompani$this->assertEquals(1, $componentInCompanyA->fresh()->numRemaining());}++ /**+ * Security regression pin: sibling to the consumable/accessory race+ * tests. Two racing checkouts for a qty=1 component both used to see+ * "1 available", both attach pivot rows, register lands at -1. Fix+ * wraps writes in DB::transaction with a lockForUpdate re-check.+ * Pre-drain the pivot to simulate the "someone else grabbed it"+ * moment and assert we refuse.+ */+ public function test_checkout_refuses_when_inventory_is_already_exhausted(): void+ {+ $asset = Asset::factory()->create();+ $component = Component::factory()->create(['qty' => 1]);+ $actor = User::factory()->superuser()->create();++ // Drain via a direct pivot insert.+ $component->assets()->attach($component->id, [+ 'component_id' => $component->id,+ 'assigned_qty' => 1,+ 'created_by' => $actor->id,+ 'asset_id' => $asset->id,+ 'created_at' => Carbon::now(),+ ]);++ $this->assertEquals(0, $component->fresh()->numRemaining());++ $this->actingAsForApi($actor)+ ->postJson(route('api.components.checkout', $component), [+ 'assigned_to' => $asset->id,+ 'assigned_qty' => 1,+ ])+ ->assertStatusMessageIs('error');++ $this->assertEquals(1, $component->assets()->count(), 'A second pivot row would mean the register went negative');+ $this->assertEquals(0, $component->fresh()->numRemaining());+ }}diff --git a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.phpindex c97a2eeeea..811aba0ce9 100644--- a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php+++ b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php@@ -226,4 +226,44 @@ class ConsumableCheckoutTest extends TestCase->assertOk()->assertStatusMessageIs('success');}++ /**+ * Security regression pin: the checkout endpoint used to read+ * numRemaining() outside any transaction/lock. Two racing requests+ * for a qty=1 consumable both saw "1 available", both attached+ * pivot rows, and the register landed at -1. The fix wraps the+ * pivot writes in a DB::transaction that begins with a+ * lockForUpdate re-fetch + re-check of numRemaining. This test+ * simulates the "someone else already grabbed the last one"+ * moment by pre-attaching pivot rows to drain the consumable to+ * zero before the checkout request runs, and asserts the endpoint+ * refuses instead of over-allocating.+ */+ public function test_checkout_refuses_when_inventory_is_already_exhausted(): void+ {+ $target = User::factory()->create();+ $consumable = Consumable::factory()->create(['qty' => 1]);++ // Drain the consumable via a direct pivot insert. Same state a+ // concurrent request would have left mid-transaction.+ $consumable->users()->attach($consumable->id, [+ 'consumable_id' => $consumable->id,+ 'assigned_to' => $target->id,+ 'created_by' => User::factory()->superuser()->create()->id,+ ]);++ $this->assertSame(0, $consumable->fresh()->numRemaining());++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->postJson(route('api.consumables.checkout', $consumable), [+ 'assigned_to' => $target->id,+ 'checkout_qty' => 1,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error');++ // The pre-drained row is the only pivot; no second row got added.+ $this->assertSame(1, $consumable->users()->count(), 'A second pivot row would mean the register went negative');+ $this->assertSame(0, $consumable->fresh()->numRemaining());+ }}