A free open source IT asset/license management system
Fixed FD-57462 - better handle race conditions on kit assignment
snipec36df33fb9d8
diff --git a/app/Services/PredefinedKitCheckoutService.php b/app/Services/PredefinedKitCheckoutService.phpindex 8c191e3e65..99e9d6585b 100644--- a/app/Services/PredefinedKitCheckoutService.php+++ b/app/Services/PredefinedKitCheckoutService.php@@ -3,7 +3,10 @@namespace App\Services;use App\Events\CheckoutableCheckedOut;+use App\Models\Accessory;use App\Models\Asset;+use App\Models\Consumable;+use App\Models\LicenseSeat;use App\Models\PredefinedKit;use App\Models\User;use Illuminate\Foundation\Auth\Access\AuthorizesRequests;@@ -216,10 +219,10 @@ class PredefinedKitCheckoutServiceforeach ($assets_to_add as $asset) {$asset->location_id = $user->location_id;- // Concurrency guard, same shape as Api\AssetsController::checkout.+ // Concurrency guard, same as Api\AssetsController::checkout.// Kit checkout can race with any other checkout of the same asset.- // Re-fetch under lockForUpdate and re-check availability before- // invoking checkOut; a claimed asset gets skipped rather than+ // Re-fetch under lockForUpdate and re-check availability+ // before invoking checkOut. A claimed asset gets skipped rather than// producing a duplicate history row and counter bump.$locked = Asset::whereKey($asset->id)->lockForUpdate()->first();if (! $locked || ! $locked->availableForCheckout()) {@@ -235,33 +238,81 @@ class PredefinedKitCheckoutService}// licensesforeach ($license_seats_to_add as $licenseSeat) {- $licenseSeat->created_by = $admin->id;- $licenseSeat->assigned_to = $user->id;- if ($licenseSeat->save()) {- event(new CheckoutableCheckedOut($licenseSeat, $user, $admin, $note));+ // Concurrency guard, same shape as the asset branch+ // above. getLicenseSeatsToAdd() reads freeSeats before+ // the transaction, so two concurrent kit checkouts+ // can pick the same "free" seat and both save+ // assigned_to on it, producing duplicate+ // CheckoutableCheckedOut history rows and audit-log+ // entries even though only one assignment persists on+ // the seat row. Re-fetch each seat under lockForUpdate+ // and re-check that assigned_to is still null before+ // claiming it. A seat that was claimed by a racing+ // request gets skipped with an operator-visible error+ // so the audit log matches the persisted state.+ $locked = LicenseSeat::whereKey($licenseSeat->id)->lockForUpdate()->first();+ if (!$locked || $locked->assigned_to !== null) {+ $errors[] = trans('admin/kits/general.none_licenses', [+ 'license' => $licenseSeat->license?->name ?? '?',+ 'qty' => 1,+ ]);++ continue;+ }+ $locked->created_by = $admin->id;+ $locked->assigned_to = $user->id;+ if ($locked->save()) {+ event(new CheckoutableCheckedOut($locked, $user, $admin, $note));} else {$errors[] = 'Something went wrong saving a license seat';}}// consumablesforeach ($consumables_to_add as $consumable) {- $consumable->assigned_to = $user->id;- $consumable->users()->attach($consumable->id, [- 'consumable_id' => $consumable->id,+ // Same class of race as the license branch above but+ // count-bounded rather than identity-bounded: two+ // concurrent kit checkouts each read numRemaining()+ // before the transaction and both proceed to attach,+ // producing an oversubscribed pivot. Lock the+ // consumable row and re-count remaining under the+ // lock. Skip with an operator-visible error if the+ // capacity was already consumed by a racing request.+ $requestedQuantity = $consumable->pivot->quantity;+ $locked = Consumable::whereKey($consumable->id)->lockForUpdate()->first();+ if (!$locked || $locked->numRemaining() < $requestedQuantity) {+ $errors[] = trans('admin/kits/general.none_consumables', [+ 'consumable' => $consumable->name,+ 'qty' => $requestedQuantity,+ ]);++ continue;+ }+ $locked->users()->attach($locked->id, [+ 'consumable_id' => $locked->id,'user_id' => $admin->id,'assigned_to' => $user->id,]);- event(new CheckoutableCheckedOut($consumable, $user, $admin, $note));+ event(new CheckoutableCheckedOut($locked, $user, $admin, $note));}// accessoriesforeach ($accessories_to_add as $accessory) {- $accessory->assigned_to = $user->id;- $accessory->users()->attach($accessory->id, [- 'accessory_id' => $accessory->id,+ // Same shape as the consumable branch above.+ $requestedQuantity = $accessory->pivot->quantity;+ $locked = Accessory::whereKey($accessory->id)->lockForUpdate()->first();+ if (!$locked || $locked->numRemaining() < $requestedQuantity) {+ $errors[] = trans('admin/kits/general.none_accessory', [+ 'accessory' => $accessory->name,+ 'qty' => $requestedQuantity,+ ]);++ continue;+ }+ $locked->users()->attach($locked->id, [+ 'accessory_id' => $locked->id,'user_id' => $admin->id,'assigned_to' => $user->id,]);- event(new CheckoutableCheckedOut($accessory, $user, $admin, $note));+ event(new CheckoutableCheckedOut($locked, $user, $admin, $note));}return $errors;diff --git a/tests/Feature/PredefinedKits/PredefinedKitConcurrencyGuardsTest.php b/tests/Feature/PredefinedKits/PredefinedKitConcurrencyGuardsTest.phpnew file mode 100644index 0000000000..38b9e980f3--- /dev/null+++ b/tests/Feature/PredefinedKits/PredefinedKitConcurrencyGuardsTest.php@@ -0,0 +1,170 @@+<?php++namespace Tests\Feature\PredefinedKits;++use App\Models\Accessory;+use App\Models\AccessoryCheckout;+use App\Models\Actionlog;+use App\Models\Consumable;+use App\Models\License;+use App\Models\LicenseSeat;+use App\Models\User;+use App\Services\PredefinedKitCheckoutService;+use Illuminate\Support\Facades\DB;+use ReflectionMethod;+use Tests\TestCase;++class PredefinedKitConcurrencyGuardsTest extends TestCase+{+ public function test_license_seat_race_skips_a_seat_already_claimed_between_read_and_write(): void+ {+ [$actor, $target] = [User::factory()->create(), User::factory()->create()];+ $racingWinner = User::factory()->create();++ $license = License::factory()->create(['seats' => 1]);+ $license->refresh()->load('freeSeats');+ $seat = $license->freeSeats->first();+ $this->assertNotNull($seat, 'License factory must produce a free seat for the test setup.');++ // A racing request has already claimed the same seat AFTER+ // this caller's getLicenseSeatsToAdd() but BEFORE its+ // saveToDb() transaction opens.+ LicenseSeat::whereKey($seat->id)->update(['assigned_to' => $racingWinner->id]);++ $service = new PredefinedKitCheckoutService;+ $errors = $this->invokeSaveToDb($service, $target, $actor, [], [$seat], [], []);++ $this->assertNotEmpty($errors, 'The guard must record an operator-visible error when the seat was claimed by a racing request.');+ $this->assertSame(+ $racingWinner->id,+ LicenseSeat::whereKey($seat->id)->value('assigned_to'),+ 'The seat must retain the racing winner. The stale caller must not overwrite it.',+ );+ $this->assertSame(+ 0,+ Actionlog::query()->where('target_id', $target->id)->where('item_id', $seat->id)->count(),+ 'No CheckoutableCheckedOut action_log row may be written for the caller that lost the race.',+ );+ }++ public function test_consumable_race_skips_a_unit_already_consumed_between_read_and_write(): void+ {+ [$actor, $target] = [User::factory()->create(), User::factory()->create()];+ $racingWinner = User::factory()->create();++ // Single-unit consumable so a racing checkout exhausts capacity.+ $consumable = Consumable::factory()->create(['qty' => 1]);++ // Stale snapshot the caller built pre-transaction: the+ // consumable was reported as having one unit remaining and+ // the kit demands one, so it passed the pre-check.+ $stale = Consumable::query()->find($consumable->id);+ $stale->setRelation('pivot', (object) ['quantity' => 1]);++ // Racing request has consumed the only unit before this+ // caller's transaction opens. Direct pivot insert rather than+ // ->attach() because the kit service's own attach shape has a+ // pre-existing FK-column mismatch that trips SQLite. Simulating+ // the winning state at the row level sidesteps that unrelated+ // bug and keeps the test focused on the guard behavior.+ DB::table('consumables_users')->insert([+ 'consumable_id' => $consumable->id,+ 'assigned_to' => $racingWinner->id,+ 'created_by' => $actor->id,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);++ $service = new PredefinedKitCheckoutService;+ $errors = $this->invokeSaveToDb($service, $target, $actor, [], [], [$stale], []);++ $this->assertNotEmpty($errors, 'The guard must record an error when a racing request has already consumed the unit.');+ $this->assertSame(+ 0,+ $consumable->fresh()->numRemaining(),+ 'Consumable must remain at zero remaining. The guard must not oversubscribe.',+ );+ $this->assertSame(+ 1,+ $consumable->users()->count(),+ 'Only the racing winner may hold a pivot row. The stale caller must not add a second.',+ );+ }++ public function test_accessory_race_skips_a_unit_already_consumed_between_read_and_write(): void+ {+ [$actor, $target] = [User::factory()->create(), User::factory()->create()];+ $racingWinner = User::factory()->create();++ $accessory = Accessory::factory()->create(['qty' => 1]);++ $stale = Accessory::query()->find($accessory->id);+ $stale->setRelation('pivot', (object) ['quantity' => 1]);++ // Racing request has consumed the only unit before this+ // caller's transaction opens. Direct AccessoryCheckout create+ // rather than ->users()->attach() for the same reason as the+ // consumable branch above.+ AccessoryCheckout::create([+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $racingWinner->id,+ 'assigned_type' => User::class,+ 'created_by' => $actor->id,+ 'created_at' => now(),+ ]);++ $service = new PredefinedKitCheckoutService;+ $errors = $this->invokeSaveToDb($service, $target, $actor, [], [], [], [$stale]);++ $this->assertNotEmpty($errors, 'The guard must record an error when a racing request has already consumed the accessory unit.');+ $this->assertSame(+ 0,+ $accessory->fresh()->numRemaining(),+ 'Accessory must remain at zero remaining. The guard must not oversubscribe.',+ );+ $this->assertSame(+ 1,+ AccessoryCheckout::query()->where('accessory_id', $accessory->id)->count(),+ 'Only the racing winner may hold a checkout row. The stale caller must not add a second.',+ );+ }++ /**+ * Call the protected saveToDb() method with a signature that+ * matches what the public checkout() flow produces. Reflection+ * keeps the test aware of the exact contract the guards protect+ * without requiring the wider public flow to run.+ *+ * @param array<int, \App\Models\Asset> $assets+ * @param array<int, LicenseSeat> $seats+ * @param array<int, Consumable> $consumables+ * @param array<int, Accessory> $accessories+ * @return array<int, string>+ */+ private function invokeSaveToDb(+ PredefinedKitCheckoutService $service,+ User $user,+ User $admin,+ array $assets,+ array $seats,+ array $consumables,+ array $accessories,+ ): array {+ $method = new ReflectionMethod($service, 'saveToDb');+ $method->setAccessible(true);++ return $method->invoke(+ $service,+ $user,+ $admin,+ date('Y-m-d H:i:s'),+ '',+ [],+ $assets,+ $seats,+ $consumables,+ $accessories,+ 'concurrency-guard-test',+ );+ }+}