A free open source IT asset/license management system
Fixed FD-57823 / vf6q-3mvj - prevent double-firing a request deletion
snipea806e52285ba
diff --git a/app/Http/Controllers/Account/AcceptanceController.php b/app/Http/Controllers/Account/AcceptanceController.phpindex 05ba1348d9..99f683b1a2 100644--- a/app/Http/Controllers/Account/AcceptanceController.php+++ b/app/Http/Controllers/Account/AcceptanceController.php@@ -275,8 +275,17 @@ class AcceptanceController extends Controllerreturn redirect()->back()->with('error', trans('admin/users/message.accept_pdf_write_failed'));}- // Log the acceptance- $acceptance->accept($sig_filename, $item->getEula(), $pdf_filename, $request->input('note'));+ // Log the acceptance. accept() runs a compare-and-set UPDATE+ // under the hood, so if another request already finalized this+ // row, we bail here before any notification, event, or follow-up+ // side effect fires. The PDF file we just wrote is left behind+ // (same disposition as the signature file above) rather than+ // rolled back, since cleaning up on the loser side would race+ // the winner reading the same file. Not ideal, but the alternative+ // is a more complex transactional file store that can roll back on failure.+ if (!$acceptance->accept($sig_filename, $item->getEula(), $pdf_filename, $request->input('note'))) {+ return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted'));+ }// Send the PDF to the signing userif (($request->input('send_copy') === '1') && ($assignedUser->email !== '')) {@@ -301,8 +310,12 @@ class AcceptanceController extends Controller// Item was declined} else {- for ($i = 0; $i < ($acceptance->qty ?? 1); $i++) {- $acceptance->decline($sig_filename, $request->input('note'));+ // decline() does its own compare-and-set and loops the per-unit+ // declinedCheckout side effects internally for qty > 1. If another+ // request already finalized this row, bail before notifications+ // and events fire.+ if (!$acceptance->decline($sig_filename, $request->input('note'))) {+ return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted'));}$acceptance->notify(new AcceptanceItemDeclinedNotification($data));diff --git a/app/Models/Accessory.php b/app/Models/Accessory.phpindex a821007298..564c8dc397 100755--- a/app/Models/Accessory.php+++ b/app/Models/Accessory.php@@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;use Illuminate\Database\Eloquent\Relations\Relation;use Illuminate\Database\Eloquent\SoftDeletes;use Illuminate\Database\Query\Builder;+use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;use Watson\Validating\ValidatingTrait;@@ -457,12 +458,23 @@ class Accessory extends SnipeModel*/public function declinedCheckout(User $declinedBy, $signature){- if (is_null($accessory_checkout = AccessoryCheckout::userAssigned()->where('assigned_to', $declinedBy->id)->where('accessory_id', $this->id)->latest('created_at'))) {- // Redirect to the accessory management page with error- return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist'));+ // ->latest() on a builder is never null, so the previous+ // `is_null($query_builder)` guard was dead code and the subsequent+ // `->limit(1)->delete()` ran unconditionally. Resolve the row first+ // and delete by model so the no-match path is explicit.+ $accessory_checkout = AccessoryCheckout::userAssigned()+ ->where('assigned_to', $declinedBy->id)+ ->where('accessory_id', $this->id)+ ->latest('created_at')+ ->first();++ if ($accessory_checkout === null) {+ Log::warning('No AccessoryCheckout row found to decline for accessory '.$this->id.' and user '.$declinedBy->id);++ return;}- $accessory_checkout->limit(1)->delete();+ $accessory_checkout->delete();}/**diff --git a/app/Models/CheckoutAcceptance.php b/app/Models/CheckoutAcceptance.phpindex b38908028a..9bbae367de 100644--- a/app/Models/CheckoutAcceptance.php+++ b/app/Models/CheckoutAcceptance.php@@ -116,43 +116,76 @@ class CheckoutAcceptance extends Model}/**- * Add a record to the checkout_acceptance table ONLY.- * Do not add stuff here that doesn't have a corresponding column in the- * checkout_acceptances table or you'll get an error.+ * Finalize this acceptance as accepted. Returns false when another+ * request already finalized the row (accepted or declined). The state+ * transition is a compare-and-set UPDATE scoped by whereNull on both+ * timestamps, so overlapping requests cannot both run the side effects.** @param string $signature_filename*/- public function accept($signature_filename, $eula = null, $filename = null, $note = null)+ public function accept($signature_filename, $eula = null, $filename = null, $note = null): bool{- $this->accepted_at = now();- $this->signature_filename = $signature_filename;- $this->stored_eula = $eula;- $this->stored_eula_file = $filename;- $this->note = $note;- $this->save();-- /**- * Update state for the checked out item- */+ $now = now();++ $claimed = static::query()+ ->where('id', $this->id)+ ->whereNull('accepted_at')+ ->whereNull('declined_at')+ ->update([+ 'accepted_at' => $now,+ 'signature_filename' => $signature_filename,+ 'stored_eula' => $eula,+ 'stored_eula_file' => $filename,+ 'note' => $note,+ 'updated_at' => $now,+ ]);++ if ($claimed === 0) {+ return false;+ }++ $this->refresh();+$this->checkoutable->acceptedCheckout($this->assignedTo, $signature_filename, $filename);++ return true;}/**- * Decline the checkout acceptance+ * Finalize this acceptance as declined. Returns false when another+ * request already finalized the row. The qty loop lives here (not in+ * the controller) so the per-unit side effects are tied to a winning+ * state transition.** @param string $signature_filename*/- public function decline($signature_filename, $note = null)+ public function decline($signature_filename, $note = null): bool{- $this->declined_at = now();- $this->note = $note;- $this->signature_filename = $signature_filename;- $this->save();-- /**- * Update state for the checked out item- */- $this->checkoutable->declinedCheckout($this->assignedTo, $signature_filename);+ $now = now();++ $claimed = static::query()+ ->where('id', $this->id)+ ->whereNull('accepted_at')+ ->whereNull('declined_at')+ ->update([+ 'declined_at' => $now,+ 'signature_filename' => $signature_filename,+ 'note' => $note,+ 'updated_at' => $now,+ ]);++ if ($claimed === 0) {+ return false;+ }++ $this->refresh();++ $qty = max((int) ($this->qty ?? 1), 1);+ for ($i = 0; $i < $qty; $i++) {+ $this->checkoutable->declinedCheckout($this->assignedTo, $signature_filename);+ }++ return true;}/**diff --git a/tests/Feature/CheckoutAcceptances/AcceptanceFinalizationRaceTest.php b/tests/Feature/CheckoutAcceptances/AcceptanceFinalizationRaceTest.phpnew file mode 100644index 0000000000..56c78eb0c8--- /dev/null+++ b/tests/Feature/CheckoutAcceptances/AcceptanceFinalizationRaceTest.php@@ -0,0 +1,168 @@+<?php++namespace Tests\Feature\CheckoutAcceptances;++use App\Models\Accessory;+use App\Models\AccessoryCheckout;+use App\Models\Asset;+use App\Models\CheckoutAcceptance;+use App\Models\User;+use PHPUnit\Framework\Attributes\Test;+use Tests\TestCase;++/**+ * Regression tests for the CAND-09 race on acceptance finalization.+ *+ * CheckoutAcceptance::accept() and decline() used to do an unconditional+ * save() followed by the item-specific side effects (deleting an accessory+ * checkout, nulling an asset's assigned_to, etc). Two overlapping requests+ * could both load the acceptance while isPending() was true and both run+ * the side-effect chain. For accessory declines in particular,+ * Accessory::declinedCheckout picks the "latest" AccessoryCheckout row by+ * created_at with no acceptance binding, so the second stale request would+ * delete an older, legitimate assignment.+ *+ * The fix moves accept() and decline() to a compare-and-set UPDATE scoped+ * by whereNull on both timestamps. The first caller wins at the database+ * layer. The second caller's UPDATE affects zero rows, the method returns+ * false, and side effects do not run.+ */+class AcceptanceFinalizationRaceTest extends TestCase+{+ #[Test]+ public function second_decline_on_a_stale_acceptance_does_not_delete_an_unrelated_older_accessory_checkout(): void+ {+ $user = User::factory()->create();+ $accessory = Accessory::factory()->create();++ $older = AccessoryCheckout::factory()->create([+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $user->id,+ 'assigned_type' => User::class,+ 'created_at' => now()->subWeek(),+ ]);++ $newer = AccessoryCheckout::factory()->create([+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $user->id,+ 'assigned_type' => User::class,+ 'created_at' => now(),+ ]);++ $acceptance = CheckoutAcceptance::factory()+ ->pending()+ ->for($accessory, 'checkoutable')+ ->create([+ 'assigned_to_id' => $user->id,+ 'qty' => 1,+ ]);++ $firstInstance = CheckoutAcceptance::find($acceptance->id);+ $secondInstance = CheckoutAcceptance::find($acceptance->id);++ $this->assertTrue($firstInstance->isPending());+ $this->assertTrue($secondInstance->isPending());++ $this->assertTrue($firstInstance->decline(''));++ $this->assertFalse(+ $secondInstance->decline(''),+ 'Second decline on a stale acceptance instance must return false, not run side effects.'+ );++ $this->assertNull(+ AccessoryCheckout::find($newer->id),+ 'Winning decline should have removed the newer AccessoryCheckout (the one tied to this acceptance).'+ );+ $this->assertNotNull(+ AccessoryCheckout::find($older->id),+ 'Older unrelated AccessoryCheckout must survive. Stale second decline must not delete it.'+ );+ }++ #[Test]+ public function second_accept_on_a_stale_acceptance_returns_false(): void+ {+ $user = User::factory()->create();+ $asset = Asset::factory()->assignedToUser($user)->create();++ $acceptance = CheckoutAcceptance::factory()+ ->pending()+ ->for($asset, 'checkoutable')+ ->create(['assigned_to_id' => $user->id]);++ $firstInstance = CheckoutAcceptance::find($acceptance->id);+ $secondInstance = CheckoutAcceptance::find($acceptance->id);++ $this->assertTrue($firstInstance->accept('', null, null, 'first'));+ $this->assertFalse(+ $secondInstance->accept('', null, null, 'second'),+ 'Second accept on a stale instance must return false.'+ );++ $this->assertSame(+ 'first',+ CheckoutAcceptance::find($acceptance->id)->note,+ 'Winning accept note must survive. Stale second accept must not overwrite it.'+ );+ }++ #[Test]+ public function decline_cannot_overwrite_a_previously_accepted_acceptance(): void+ {+ $user = User::factory()->create();+ $asset = Asset::factory()->assignedToUser($user)->create();++ $acceptance = CheckoutAcceptance::factory()+ ->pending()+ ->for($asset, 'checkoutable')+ ->create(['assigned_to_id' => $user->id]);++ $acceptInstance = CheckoutAcceptance::find($acceptance->id);+ $declineInstance = CheckoutAcceptance::find($acceptance->id);++ $this->assertTrue($acceptInstance->accept(''));+ $this->assertFalse(+ $declineInstance->decline(''),+ 'Decline must not succeed after accept has already finalized the row.'+ );++ $fresh = CheckoutAcceptance::find($acceptance->id);+ $this->assertNotNull($fresh->accepted_at);+ $this->assertNull($fresh->declined_at);+ }++ #[Test]+ public function decline_still_runs_qty_side_effects_on_the_winning_caller(): void+ {+ // qty > 1 case. The loop that used to live in the controller has+ // moved inside decline(), so the winning caller still deletes+ // $qty AccessoryCheckout rows.+ $user = User::factory()->create();+ $accessory = Accessory::factory()->create();++ AccessoryCheckout::factory()->count(3)->create([+ 'accessory_id' => $accessory->id,+ 'assigned_to' => $user->id,+ 'assigned_type' => User::class,+ ]);++ $acceptance = CheckoutAcceptance::factory()+ ->pending()+ ->for($accessory, 'checkoutable')+ ->create([+ 'assigned_to_id' => $user->id,+ 'qty' => 3,+ ]);++ $this->assertSame(3, AccessoryCheckout::where('assigned_to', $user->id)->count());++ $this->assertTrue($acceptance->decline(''));++ $this->assertSame(+ 0,+ AccessoryCheckout::where('assigned_to', $user->id)->count(),+ 'qty=3 decline should remove all 3 AccessoryCheckout rows.'+ );+ }+}