A free open source IT asset/license management system
Better handle incomplete checkouts for non-users
snipe1a4b5b67ca87
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.phpindex 42acd36ee4..92592d36e2 100644--- a/app/Http/Controllers/Api/AccessoriesController.php+++ b/app/Http/Controllers/Api/AccessoriesController.php@@ -18,7 +18,6 @@ use App\Http\Transformers\SelectlistTransformer;use App\Models\Accessory;use App\Models\AccessoryCheckout;use App\Models\Company;-use App\Models\Setting;use App\Models\User;use Carbon\Carbon;use DomainException;@@ -415,7 +414,7 @@ class AccessoriesController extends Controller$this->authorize('checkout', $accessory);$target = $this->determineCheckoutTarget();- if ((Setting::getSettings()->full_multiple_companies_support == '1') && (! $target->companies()->where('companies.id', $accessory->company_id)->exists())) {+ if (! $accessory->canCheckoutTo($target)) {return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));}diff --git a/app/Http/Requests/AccessoryCheckoutRequest.php b/app/Http/Requests/AccessoryCheckoutRequest.phpindex 6f5283f4a7..76d38df989 100644--- a/app/Http/Requests/AccessoryCheckoutRequest.php+++ b/app/Http/Requests/AccessoryCheckoutRequest.php@@ -2,12 +2,15 @@namespace App\Http\Requests;+use App\Http\Requests\Traits\InfersCheckoutToType;use App\Models\Accessory;use Illuminate\Contracts\Validation\ValidationRule;use Illuminate\Support\Facades\Gate;class AccessoryCheckoutRequest extends ImageUploadRequest{+ use InfersCheckoutToType;+/*** Determine if the user is authorized to make this request.*/@@ -18,6 +21,9 @@ class AccessoryCheckoutRequest extends ImageUploadRequestpublic function prepareForValidation(): void{+ parent::prepareForValidation();++ $this->inferCheckoutToType();if ($this->accessory) {@@ -44,9 +50,9 @@ class AccessoryCheckoutRequest extends ImageUploadRequestreturn array_merge([- 'assigned_user' => 'required_without_all:assigned_asset,assigned_location|nullable|exists_undeleted:users,id',- 'assigned_asset' => 'required_without_all:assigned_user,assigned_location|nullable|exists_undeleted:assets,id',- 'assigned_location' => 'required_without_all:assigned_user,assigned_asset|nullable|exists_undeleted:locations,id',+ 'assigned_user' => 'required_without_all:assigned_asset,assigned_location|prohibits:assigned_asset,assigned_location|nullable|exists_undeleted:users,id',+ 'assigned_asset' => 'required_without_all:assigned_user,assigned_location|prohibits:assigned_user,assigned_location|nullable|exists_undeleted:assets,id',+ 'assigned_location' => 'required_without_all:assigned_user,assigned_asset|prohibits:assigned_user,assigned_asset|nullable|exists_undeleted:locations,id','number_remaining_after_checkout' => ['min:0',diff --git a/app/Http/Requests/AssetCheckoutRequest.php b/app/Http/Requests/AssetCheckoutRequest.phpindex 0ff976c6ac..2dfb4c2f7b 100644--- a/app/Http/Requests/AssetCheckoutRequest.php+++ b/app/Http/Requests/AssetCheckoutRequest.php@@ -2,10 +2,13 @@namespace App\Http\Requests;+use App\Http\Requests\Traits\InfersCheckoutToType;use App\Models\Setting;class AssetCheckoutRequest extends Request{+ use InfersCheckoutToType;+/*** Determine if the user is authorized to make this request.*@@ -16,6 +19,11 @@ class AssetCheckoutRequest extends Requestreturn true;}+ public function prepareForValidation(): void+ {+ $this->inferCheckoutToType();+ }+/*** Get the validation rules that apply to the request.*@@ -30,9 +38,9 @@ class AssetCheckoutRequest extends Request// controllers below cannot bind live inventory to trashed users,// assets, or locations. Applied at request-validation time so a// bad request bounces with 422 before any controller mutation.- 'assigned_user' => 'numeric|nullable|required_without_all:assigned_asset,assigned_location|exists_undeleted:users,id',- 'assigned_asset' => 'numeric|nullable|required_without_all:assigned_user,assigned_location|exists_undeleted:assets,id',- 'assigned_location' => 'numeric|nullable|required_without_all:assigned_user,assigned_asset|exists_undeleted:locations,id',+ 'assigned_user' => 'numeric|nullable|required_without_all:assigned_asset,assigned_location|prohibits:assigned_asset,assigned_location|exists_undeleted:users,id',+ 'assigned_asset' => 'numeric|nullable|required_without_all:assigned_user,assigned_location|prohibits:assigned_user,assigned_location|exists_undeleted:assets,id',+ 'assigned_location' => 'numeric|nullable|required_without_all:assigned_user,assigned_asset|prohibits:assigned_user,assigned_asset|exists_undeleted:locations,id','status_id' => 'nullable|exists:status_labels,id,deployable,1','checkout_to_type' => 'required|in:asset,location,user','checkout_at' => [diff --git a/app/Http/Requests/Traits/InfersCheckoutToType.php b/app/Http/Requests/Traits/InfersCheckoutToType.phpnew file mode 100644index 0000000000..1052538d20--- /dev/null+++ b/app/Http/Requests/Traits/InfersCheckoutToType.php@@ -0,0 +1,29 @@+<?php++namespace App\Http\Requests\Traits;++trait InfersCheckoutToType+{+ /**+ * When the client omits checkout_to_type, infer it from whichever+ * assigned_* target field was populated. Ambiguous requests (more than+ * one assigned_* field filled) are left alone so validation can catch+ * them downstream.+ */+ protected function inferCheckoutToType(): void+ {+ if ($this->filled('checkout_to_type')) {+ return;+ }++ $filledTargets = array_keys(array_filter([+ 'location' => $this->filled('assigned_location'),+ 'asset' => $this->filled('assigned_asset'),+ 'user' => $this->filled('assigned_user'),+ ]));++ if (count($filledTargets) === 1) {+ $this->merge(['checkout_to_type' => $filledTargets[0]]);+ }+ }+}diff --git a/phpmd.baseline.xml b/phpmd.baseline.xmlindex 9cc9357779..dc2602a15a 100644--- a/phpmd.baseline.xml+++ b/phpmd.baseline.xml@@ -98,5 +98,6 @@<violation rule="PHPMD\Rule\UnusedFormalParameter" file="app/Rules/UniqueUndeleted.php"/><violation rule="PHPMD\Rule\UnusedFormalParameter" file="app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php"/><violation rule="PHPMD\Rule\UnusedFormalParameter" file="app/Rules/ValidJson.php"/>+ <violation rule="PHPMD\Rule\UnusedFormalParameter" file="app/SyncAdapters/SyncAdapter.php"/><violation rule="PHPMD\Rule\UnusedFormalParameter" file="app/View/Label.php"/></phpmd-baseline>diff --git a/phpstan-baseline.neon b/phpstan-baseline.neonindex 49d583ffee..7869ce54b1 100644--- a/phpstan-baseline.neon+++ b/phpstan-baseline.neon@@ -1788,6 +1788,12 @@ parameters:count: 1path: app/Http/Controllers/Api/ProfileController.php+ -+ message: '#^Access to an undefined property App\\Models\\Statuslabel\:\:\$color\.$#'+ identifier: property.notFound+ count: 3+ path: app/Http/Controllers/Api/StatuslabelsController.php+-message: '#^Access to an undefined property Illuminate\\Pagination\\LengthAwarePaginator\<int, App\\Models\\Statuslabel\>\:\:\$use_text\.$#'identifier: property.notFound@@ -3348,6 +3354,12 @@ parameters:count: 1path: app/Http/Controllers/SetupController.php+ -+ message: '#^Access to an undefined property App\\Models\\Statuslabel\:\:\$color\.$#'+ identifier: property.notFound+ count: 2+ path: app/Http/Controllers/StatuslabelsController.php+-message: '#^Access to an undefined property App\\Models\\Statuslabel\:\:\$created_by\.$#'identifier: property.notFound@@ -3990,6 +4002,12 @@ parameters:count: 3path: app/Http/Transformers/PredefinedKitsTransformer.php+ -+ message: '#^Access to an undefined property App\\Models\\Statuslabel\:\:\$color\.$#'+ identifier: property.notFound+ count: 1+ path: app/Http/Transformers/StatuslabelsTransformer.php+-message: '#^Access to an undefined property App\\Models\\Supplier\:\:\$accessories_count\.$#'identifier: property.notFound@@ -8556,12 +8574,6 @@ parameters:count: 2path: app/Notifications/CheckoutAccessoryNotification.php- -- message: '#^Access to an undefined property App\\Notifications\\CheckoutAssetNotification\:\:\$settings\.$#'- identifier: property.notFound- count: 5- path: app/Notifications/CheckoutAssetNotification.php--message: '#^Ternary operator condition is always true\.$#'identifier: ternary.alwaysTruediff --git a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.phpindex cce1b24a80..63fb9cbc88 100644--- a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php+++ b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php@@ -5,14 +5,19 @@ namespace Tests\Feature\Checkouts\Api;use App\Mail\CheckoutAccessoryMail;use App\Models\Accessory;use App\Models\Actionlog;+use App\Models\Asset;use App\Models\Company;+use App\Models\Location;use App\Models\User;use Illuminate\Support\Facades\Mail;use Tests\Concerns\TestsPermissionsRequirement;+use Tests\Support\MakesWatsonValidationLoud;use Tests\TestCase;class AccessoryCheckoutTest extends TestCase implements TestsPermissionsRequirement{+ use MakesWatsonValidationLoud;+public function test_requires_permission(){$this->actingAsForApi(User::factory()->create())@@ -124,6 +129,87 @@ class AccessoryCheckoutTest extends TestCase implements TestsPermissionsRequirem$this->assertHasTheseActionLogs($accessory, ['create', 'checkout']);}+ public function test_accessory_checkout_infers_user_target_when_checkout_to_type_omitted()+ {+ $accessory = Accessory::factory()->create();+ $user = User::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAccessories()->create())+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_user' => $user->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', User::class)+ ->where('assigned_to', $user->id)+ ->count()+ );+ }++ public function test_accessory_checkout_infers_asset_target_when_checkout_to_type_omitted()+ {+ $accessory = Accessory::factory()->create();+ $asset = Asset::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAccessories()->create())+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_asset' => $asset->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Asset::class)+ ->where('assigned_to', $asset->id)+ ->count()+ );+ }++ public function test_accessory_checkout_infers_location_target_when_checkout_to_type_omitted()+ {+ $accessory = Accessory::factory()->create();+ $location = Location::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAccessories()->create())+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $location->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Location::class)+ ->where('assigned_to', $location->id)+ ->count()+ );+ }++ public function test_accessory_checkout_rejects_multiple_target_fields()+ {+ $accessory = Accessory::factory()->create();+ $user = User::factory()->create();+ $location = Location::factory()->create();++ $response = $this->actingAsForApi(User::factory()->checkoutAccessories()->create())+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_user' => $user->id,+ 'assigned_location' => $location->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error');++ $this->assertArrayHasKey('assigned_user', $response->json('messages'));+ $this->assertSame(0, $accessory->checkouts()->count());+ }+public function test_accessory_cannot_be_checked_out_to_invalid_user(){$accessory = Accessory::factory()->create();@@ -276,6 +362,179 @@ class AccessoryCheckoutTest extends TestCase implements TestsPermissionsRequirem->assertStatusMessageIs('success');}+ /**+ * Regression: AccessoriesController's FMCS check called $target->companies()+ * unconditionally, which only exists on User. Checking an accessory out to+ * a Location or Asset target under FMCS crashed with BadMethodCallException+ * (500). Fix swapped the User-only pivot lookup for $accessory->canCheckoutTo(),+ * matching what the web controller and AssetsController already use.+ */+ public function test_accessory_can_be_checked_out_to_location_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ $company = Company::factory()->create();+ $accessory = Accessory::factory()->for($company)->create();+ $location = Location::factory()->create(['company_id' => $company->id]);+ $actor = User::factory()->superuser()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $location->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Location::class)+ ->where('assigned_to', $location->id)+ ->count()+ );+ }++ public function test_accessory_can_be_checked_out_to_asset_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ $company = Company::factory()->create();+ $accessory = Accessory::factory()->for($company)->create();+ $targetAsset = Asset::factory()->for($company)->create();+ $actor = User::factory()->superuser()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_asset' => $targetAsset->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Asset::class)+ ->where('assigned_to', $targetAsset->id)+ ->count()+ );+ }++ public function test_accessory_cannot_be_checked_out_to_location_in_different_company_when_fmcs_scoped_locations_enabled()+ {+ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $accessory = Accessory::factory()->for($companyA)->create();+ $locationInB = Location::factory()->create(['company_id' => $companyB->id]);+ $actor = User::factory()->superuser()->create();++ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $locationInB->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error')+ ->assertMessagesAre(trans('general.error_user_company'));++ $this->assertSame(0, $accessory->checkouts()->count());+ }++ public function test_accessory_cannot_be_checked_out_to_asset_in_different_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $accessory = Accessory::factory()->for($companyA)->create();+ $assetInB = Asset::factory()->for($companyB)->create();+ $actor = User::factory()->superuser()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_asset' => $assetInB->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error')+ ->assertMessagesAre(trans('general.error_user_company'));++ $this->assertSame(0, $accessory->checkouts()->count());+ }++ public function test_accessory_can_be_checked_out_to_cross_company_location_when_fmcs_location_scoping_is_off()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $accessory = Accessory::factory()->for($companyA)->create();+ $locationInB = Location::factory()->create(['company_id' => $companyB->id]);+ $actor = User::factory()->superuser()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $locationInB->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Location::class)+ ->where('assigned_to', $locationInB->id)+ ->count()+ );+ }++ public function test_accessory_can_be_checked_out_to_child_company_location_under_scoped_fmcs()+ {+ $parent = Company::factory()->create();+ $child = Company::factory()->childOf($parent)->create();+ $accessory = Accessory::factory()->for($parent)->create();+ $locationInChild = Location::factory()->create(['company_id' => $child->id]);+ $actor = User::factory()->superuser()->create();++ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $locationInChild->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Location::class)+ ->where('assigned_to', $locationInChild->id)+ ->count()+ );+ }++ public function test_accessory_can_be_checked_out_to_null_company_location_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $accessory = Accessory::factory()->for($company)->create();+ $locationWithNoCompany = Location::factory()->create(['company_id' => null]);+ $actor = User::factory()->superuser()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.accessories.checkout', $accessory), [+ 'assigned_location' => $locationWithNoCompany->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $this->assertSame(+ 1,+ $accessory->checkouts()+ ->where('assigned_type', Location::class)+ ->where('assigned_to', $locationWithNoCompany->id)+ ->count()+ );+ }+/*** Security regression pin: sibling to the consumable race test.* AccessoryCheckoutRequest validates number_remaining_after_checkoutdiff --git a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php b/tests/Feature/Checkouts/Api/AssetCheckoutTest.phpindex a488e4bf54..ce975084ee 100644--- a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php+++ b/tests/Feature/Checkouts/Api/AssetCheckoutTest.php@@ -12,10 +12,13 @@ use Illuminate\Support\Carbon;use Illuminate\Support\Facades\Event;use Notification;use PHPUnit\Framework\Attributes\DataProvider;+use Tests\Support\MakesWatsonValidationLoud;use Tests\TestCase;class AssetCheckoutTest extends TestCase{+ use MakesWatsonValidationLoud;+protected function setUp(): void{parent::setUp();@@ -99,6 +102,75 @@ class AssetCheckoutTest extends TestCaseEvent::assertNotDispatched(CheckoutableCheckedOut::class);}+ public function test_asset_checkout_infers_user_target_when_checkout_to_type_omitted()+ {+ $asset = Asset::factory()->create();+ $user = User::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAssets()->create())+ ->postJson(route('api.asset.checkout', $asset), [+ 'assigned_user' => $user->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $asset->refresh();+ $this->assertTrue($asset->assignedTo()->is($user));+ }++ public function test_asset_checkout_infers_asset_target_when_checkout_to_type_omitted()+ {+ $asset = Asset::factory()->create();+ $target = Asset::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAssets()->create())+ ->postJson(route('api.asset.checkout', $asset), [+ 'assigned_asset' => $target->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $asset->refresh();+ $this->assertTrue($asset->assignedTo()->is($target));+ }++ public function test_asset_checkout_infers_location_target_when_checkout_to_type_omitted()+ {+ $asset = Asset::factory()->create();+ $location = Location::factory()->create();++ $this->actingAsForApi(User::factory()->checkoutAssets()->create())+ ->postJson(route('api.asset.checkout', $asset), [+ 'assigned_location' => $location->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $asset->refresh();+ $this->assertTrue($asset->assignedTo()->is($location));+ }++ public function test_asset_checkout_rejects_multiple_target_fields()+ {+ $asset = Asset::factory()->create();+ $user = User::factory()->create();+ $location = Location::factory()->create();++ $response = $this->actingAsForApi(User::factory()->checkoutAssets()->create())+ ->postJson(route('api.asset.checkout', $asset), [+ 'assigned_user' => $user->id,+ 'assigned_location' => $location->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error');++ $this->assertArrayHasKey('assigned_user', $response->json('messages'));++ $asset->refresh();+ $this->assertNull($asset->assigned_to);+ $this->assertNull($asset->assigned_type);+ }+public function test_cannot_checkout_across_companies_when_full_company_support_enabled(){$this->settings->enableMultipleFullCompanySupport();diff --git a/tests/Support/MakesWatsonValidationLoud.php b/tests/Support/MakesWatsonValidationLoud.phpnew file mode 100644index 0000000000..c7176988e1--- /dev/null+++ b/tests/Support/MakesWatsonValidationLoud.php@@ -0,0 +1,35 @@+<?php++namespace Tests\Support;++use Illuminate\Support\Facades\Event;++/**+ * Watson's ValidatingTrait silently returns false from save() when+ * validation fails, and Laravel's Factory::create() does not check that+ * return. A factory whose save quietly failed hands back a model with no+ * primary key, and the test crashes hundreds of lines later with a+ * mysterious "missing route parameter" or "unknown attribute" error.+ *+ * Opt in on a specific test class when factory ordering under strict+ * FMCS (or any similarly restrictive setting) is likely to bite, so the+ * failure surfaces at the exact save() with the failing field named.+ *+ * Not applied globally: enabling this suite-wide would break tests that+ * intentionally rely on silent-false save (e.g. asset_tag collision+ * regression tests) and tests that route Watson exceptions through the+ * app's normal error-response path (importers, some FMCS scoping paths).+ */+trait MakesWatsonValidationLoud+{+ protected function setUpMakesWatsonValidationLoud(): void+ {+ Event::listen('eloquent.validated: *', function ($eventName, array $payload) {+ [$model, $status] = $payload;++ if ($status === 'failed' && method_exists($model, 'throwValidationException')) {+ $model->throwValidationException();+ }+ });+ }+}