A free open source IT asset/license management system
Tighter scoping on reporting permissions
snipe397de5a5e884
diff --git a/app/Models/CheckoutRequest.php b/app/Models/CheckoutRequest.phpindex 174c931d89..8809f79dbc 100644--- a/app/Models/CheckoutRequest.php+++ b/app/Models/CheckoutRequest.php@@ -245,6 +245,25 @@ class CheckoutRequest extends Modelreturn $this->itemRequested()->name;}+ /**+ * Accessor mirror of name() so property-style access (`->name`) doesn't+ * fall through Eloquent's __get to `getRelationValue('name')`, which+ * treats the plain name() method as a candidate relation and throws+ * `LogicException: name must return a relationship instance` when it+ * gets a string back. `hasGetMutator('name')` fires first and returns+ * this accessor's value before relation resolution ever runs.+ *+ * The specific symptom is `CalendarEventsTransformer::titleFor()` which+ * coalesces `$source->display_name ?? $source->name ?? ...` for any+ * source without a Presentable presenter (CheckoutRequest doesn't have+ * one); pre-accessor, that crashed the calendar API for any install+ * with a reservation-shape CheckoutRequest on the calendar.+ */+ public function getNameAttribute(): ?string+ {+ return $this->name();+ }+public function fulfilledBy(): BelongsTo{return $this->belongsTo(User::class, 'fulfilled_by', 'id');diff --git a/app/Models/Company.php b/app/Models/Company.phpindex 97bad3a238..14ecc5f2e8 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -383,12 +383,23 @@ final class Company extends SnipeModel$userCompanyIds = self::getCurrentUserCompanyIds();- // Empty pivot = unrestricted (legacy no-company users). The pivot- // is the sole source of truth for membership now that the- // company_user table migration has run; the old scalar- // users.company_id column is not consulted here.+ // Empty-pivot actor: route through null_company_is_floater to match+ // the query scope's behavior for pivotless callers. Previously this+ // branch returned true unconditionally, which let empty-pivot users+ // act on rows their list queries would have hidden — the actual+ // GHSA-8hq6-r8cw-gqwh bypass. This mirrors+ // scopeCompanyablesDirectly()'s empty-pivot branches for+ // companyable-table queries:+ // - Floater on: unrestricted (matches `return $query`).+ // - Floater off: null-company items only (matches `whereNull($column)`).+ // Company targets never reach here — the tables-without-company_id+ // early exit above returns true regardless of actor state.if (empty($userCompanyIds)) {- return true;+ if (Setting::getSettings()->null_company_is_floater) {+ return true;+ }++ return is_null($companyable->company_id ?? null);}$companyable_company_id = ($companyable instanceof Company)@@ -655,13 +666,40 @@ final class Company extends SnipeModelreturn $query->whereNull($table.$column);}- // action_logs: a NULL company_id means the logged object (AssetModel, Company, etc.)- // has no company_id column of its own. Those are global objects, visible to all users,- // so their log entries should not be hidden by the company filter.+ // action_logs: a NULL company_id means the logged object's table has no+ // company_id column. For most of those (AssetModel, Category, Manufacturer,+ // Statuslabel, Location, etc.) the row is admin-authored global config+ // that is safe to show cross-company. But User is also a table without a+ // scalar company_id column (users belong to companies via the company_user+ // pivot), and User-item action_logs carry PII in their log_meta diff+ // (email, phone, employee_num, notes, address, jobtitle, etc.) written by+ // UserObserver on every profile edit. Treating those as globally visible+ // leaks cross-company PII, per GHSA-mch3-g6rh-gj22.+ //+ // Split by item_type: non-User rows keep the existing "null is safe" rule;+ // User-item rows only fall through when the viewer shares at least one+ // company with the target user via the company_user pivot (same visibility+ // rule the users list itself applies under FMCS).if ($query->getModel()->getTable() === 'action_logs') {- return $query->where(function ($q) use ($table, $column, $companyIds) {+ $userClass = User::class;++ return $query->where(function ($q) use ($table, $column, $companyIds, $userClass) {$q->whereIn($table.$column, $companyIds)- ->orWhereNull($table.$column);+ ->orWhere(function ($null) use ($table, $column, $companyIds, $userClass) {+ $null->whereNull($table.$column)+ ->where(function ($check) use ($companyIds, $userClass) {+ // Non-User item (or null item_type): safe global config, existing behavior.+ $check->where('action_logs.item_type', '!=', $userClass)+ ->orWhereNull('action_logs.item_type')+ // User-item: viewer must share a company with the target user via pivot.+ ->orWhere(function ($userItem) use ($companyIds, $userClass) {+ $userItem->where('action_logs.item_type', $userClass)+ ->whereIn('action_logs.item_id', function ($sub) use ($companyIds) {+ $sub->select('user_id')->from('company_user')->whereIn('company_id', $companyIds);+ });+ });+ });+ });});}diff --git a/tests/Feature/ActionLogs/ActionlogFmcsUserItemScopeTest.php b/tests/Feature/ActionLogs/ActionlogFmcsUserItemScopeTest.phpnew file mode 100644index 0000000000..000192630e--- /dev/null+++ b/tests/Feature/ActionLogs/ActionlogFmcsUserItemScopeTest.php@@ -0,0 +1,234 @@+<?php++namespace Tests\Feature\ActionLogs;++use App\Models\Actionlog;+use App\Models\Category;+use App\Models\Company;+use App\Models\User;+use Tests\TestCase;++/**+ * Regression coverage for GHSA-mch3-g6rh-gj22.+ *+ * User-item action_logs (item_type = App\Models\User) land with+ * company_id = NULL because the users table has no scalar company_id+ * column (users belong to companies via the company_user pivot). Before+ * the fix, CompanyableScope treated ALL null-company action_logs as+ * globally visible, on the assumption that null-company meant "global+ * config record" (AssetModel, Manufacturer, Category, Statuslabel,+ * etc.). That assumption was wrong for User-item rows, which carry PII+ * in their log_meta diff (email, phone, employee_num, notes, address,+ * jobtitle, ...) written by UserObserver on every profile edit.+ *+ * Result: any FMCS-scoped user with reports.view (or the more granular+ * users.view for a specific target) could read the entire activity+ * trail of every user in every other company on the install.+ *+ * Fix (Company::scopeCompanyablesDirectly): null-company action_logs+ * are now split by item_type.+ *+ * - Non-User items keep the existing "null is safe" rule. Global+ * config action_logs (Category create/edit, Manufacturer create,+ * etc.) remain cross-company visible as they were.+ * - User-item rows require the viewer to share at least one company+ * with the target user via the company_user pivot, matching the+ * same visibility rule the users list itself applies under FMCS.+ */+class ActionlogFmcsUserItemScopeTest extends TestCase+{+ private function makeUserInCompanies(Company ...$companies): User+ {+ // Users use the company_user pivot for membership; there is no+ // scalar users.company_id column, so ->for() / ->hasAttached()+ // factory helpers don't work here. Save through the+ // company->users() relation the same way HttpCrossCompanyLeakTest+ // does, then attach any extra companies afterwards.+ $first = array_shift($companies);+ $user = $first->users()->save(User::factory()->make());+ foreach ($companies as $additional) {+ $user->companies()->attach($additional->id);+ }++ return $user;+ }++ private function makeViewerInCompany(Company $company, array $permissionKeys = ['users.view']): User+ {+ $permissions = [];+ foreach ($permissionKeys as $key) {+ $permissions[$key] = '1';+ }++ return $company->users()->save(+ User::factory()->make(['permissions' => json_encode($permissions)])+ );+ }++ private function seedUserItemActionLog(User $targetUser): Actionlog+ {+ // The write path stays as-is: User-item rows land with+ // company_id = NULL by design (there is no single company_id+ // to assign for a user who may belong to N companies). Force+ // the shape here rather than triggering an observer, so the+ // test doesn't depend on which action_type happens to fire.+ return Actionlog::factory()->create([+ 'item_type' => User::class,+ 'item_id' => $targetUser->id,+ 'company_id' => null,+ ]);+ }++ public function test_strict_fmcs_hides_cross_company_user_action_log(): void+ {+ // The reporter's exact scenario. CompanyA viewer with users.view+ // must not see a User-item action_log for a CompanyB-only user.+ $this->settings->enableMultipleFullCompanySupport();+ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $viewer = $this->makeViewerInCompany($companyA);+ $targetInB = $this->makeUserInCompanies($companyB);++ $log = $this->seedUserItemActionLog($targetInB);++ $this->actingAs($viewer);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertNotContains(+ $log->id,+ $visibleIds,+ 'Cross-company User-item action_log leaked to a strict-FMCS viewer.'+ );+ }++ public function test_strict_fmcs_shows_same_company_user_action_log(): void+ {+ // Positive regression: don't over-hide. Same-company viewer with+ // users.view must still see the target user's activity trail.+ $this->settings->enableMultipleFullCompanySupport();+ $company = Company::factory()->create();++ $viewer = $this->makeViewerInCompany($company);+ $targetInSame = $this->makeUserInCompanies($company);++ $log = $this->seedUserItemActionLog($targetInSame);++ $this->actingAs($viewer);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertContains(+ $log->id,+ $visibleIds,+ 'Same-company User-item action_log was hidden from a viewer who shares a company with the target.'+ );+ }++ public function test_strict_fmcs_shows_action_log_when_viewer_shares_one_of_targets_companies(): void+ {+ // Multi-company overlap. Viewer in {A, B}, target in {B} only.+ // Any shared company should make the row visible.+ $this->settings->enableMultipleFullCompanySupport();+ [$companyA, $companyB, $companyC] = Company::factory()->count(3)->create();++ $viewer = $this->makeViewerInCompany($companyA);+ $viewer->companies()->attach($companyB->id);++ $target = $this->makeUserInCompanies($companyB);+ $log = $this->seedUserItemActionLog($target);++ // Also seed a User in C to confirm C's user isn't leaked.+ $unrelated = $this->makeUserInCompanies($companyC);+ $unrelatedLog = $this->seedUserItemActionLog($unrelated);++ $this->actingAs($viewer);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertContains($log->id, $visibleIds, 'Shared-company target action_log should be visible.');+ $this->assertNotContains($unrelatedLog->id, $visibleIds, 'Non-overlapping target action_log should be hidden.');+ }++ public function test_floater_mode_still_hides_cross_company_user_action_log(): void+ {+ // Floater mode makes null-company ITEMS visible to company-scoped+ // callers, but that policy is about admin-authored config records+ // that happen to have no company_id. User rows are null-company+ // for a different reason (pivot-based membership), so the floater+ // relaxation must not turn User-item PII into a cross-company+ // leak.+ $this->settings->enableFloaterMode();+ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $viewer = $this->makeViewerInCompany($companyA);+ $target = $this->makeUserInCompanies($companyB);++ $log = $this->seedUserItemActionLog($target);++ $this->actingAs($viewer);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertNotContains(+ $log->id,+ $visibleIds,+ 'Floater mode leaked a cross-company User-item action_log; the pivot-share rule should still gate it.'+ );+ }++ public function test_non_user_null_company_action_log_still_visible_cross_company(): void+ {+ // Regression guard: the fix must not change existing behavior for+ // legit global-config null-company rows (Category / Manufacturer /+ // Statuslabel / etc). Category is used here as a representative;+ // its table has no company_id column so its action_logs land with+ // company_id = NULL, same shape as the User case, but is+ // administrator-authored config rather than user PII.+ $this->settings->enableMultipleFullCompanySupport();+ $companyA = Company::factory()->create();++ $viewer = $this->makeViewerInCompany($companyA);++ $category = Category::factory()->create();+ $log = Actionlog::factory()->create([+ 'item_type' => Category::class,+ 'item_id' => $category->id,+ 'company_id' => null,+ ]);++ $this->actingAs($viewer);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertContains(+ $log->id,+ $visibleIds,+ 'Non-User null-company action_log (safe global config) should still be visible cross-company under FMCS. Regression check.'+ );+ }++ public function test_superuser_sees_every_user_item_action_log_regardless_of_company(): void+ {+ // Superusers bypass FMCS entirely (Company::scopeCompanyables+ // short-circuits at the top). This just pins that the User-item+ // gate we added does not accidentally start hiding rows from+ // superusers.+ $this->settings->enableMultipleFullCompanySupport();+ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $superuser = User::factory()->superuser()->create();+ $targetInA = $this->makeUserInCompanies($companyA);+ $targetInB = $this->makeUserInCompanies($companyB);++ $logA = $this->seedUserItemActionLog($targetInA);+ $logB = $this->seedUserItemActionLog($targetInB);++ $this->actingAs($superuser);++ $visibleIds = Actionlog::query()->pluck('id')->all();++ $this->assertContains($logA->id, $visibleIds);+ $this->assertContains($logB->id, $visibleIds);+ }+}diff --git a/tests/Feature/Fmcs/EmptyPivotAccessTest.php b/tests/Feature/Fmcs/EmptyPivotAccessTest.phpnew file mode 100644index 0000000000..a0b6d15be6--- /dev/null+++ b/tests/Feature/Fmcs/EmptyPivotAccessTest.php@@ -0,0 +1,231 @@+<?php++namespace Tests\Feature\Fmcs;++use App\Models\Accessory;+use App\Models\Asset;+use App\Models\Company;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\License;+use App\Models\User;+use Tests\TestCase;++/**+ * Regression coverage for GHSA-8hq6-r8cw-gqwh.+ *+ * Company::isCurrentUserHasAccess() historically returned true+ * unconditionally for any actor whose company_user pivot was empty. The+ * intent was to preserve legacy behavior for pre-FMCS users who never+ * had a company_id set (or, post-migration, no pivot rows), but the+ * effect was that any non-superuser with role permissions could be+ * created with no pivot rows and get UNRESTRICTED per-target access to+ * every companyable in every tenant on the install — a full FMCS bypass+ * for that actor.+ *+ * The query-scope side of the code already handled empty-pivot actors+ * correctly:+ * - Strict mode: empty pivot sees only null-company items (nothing,+ * effectively, since production items usually have a company_id).+ * - Floater mode: empty pivot is treated as "floater" and sees all+ * items (documented behavior at snipe-it.readme.io/docs/multi-tenancy-ish).+ *+ * The fix aligns isCurrentUserHasAccess() branch-for-branch with the+ * query scope for companyable items, so per-target policy checks match+ * list visibility:+ * - Floater ON: allowed (mirrors `return $query`).+ * - Floater OFF: allowed only for null-company items (mirrors+ * `whereNull($column)`).+ *+ * Scope note: Company targets are NOT covered here. The tables-without-+ * a-company_id-column early exit at the top of isCurrentUserHasAccess()+ * short-circuits every Company / Location / etc. target to `return true`+ * for every actor (empty pivot or not, superuser or not). That predates+ * this GHSA and is a separate surface; tightening it belongs in its own+ * advisory / fix.+ *+ * These tests exercise the direct API surface. FMCS query-scope tests+ * are in tests/Feature/Fmcs/HttpCrossCompanyLeakTest.php and its+ * siblings; that suite continues to gate list visibility. This file+ * gates per-target authorization, which is the branch the GHSA hit.+ */+class EmptyPivotAccessTest extends TestCase+{+ private User $emptyPivotActor;++ private Company $companyA;++ private Company $companyB;++ protected function setUp(): void+ {+ parent::setUp();++ [$this->companyA, $this->companyB] = Company::factory()->count(2)->create();++ // The actor's pivot is deliberately left empty. Role permissions+ // are broad enough that the SnipePermissionsPolicy would grant+ // authorization on any item; the FMCS gate we're testing is what+ // stops them from acting on cross-tenant rows.+ $this->emptyPivotActor = User::factory()->create();+ $this->emptyPivotActor->companies()->sync([]);++ $this->actingAs($this->emptyPivotActor);+ }++ private function assertAccess(bool $expected, $target, string $context): void+ {+ $actual = Company::isCurrentUserHasAccess($target);+ $this->assertSame(+ $expected,+ $actual,+ $context.' (expected '.($expected ? 'ALLOWED' : 'BLOCKED').', got '.($actual ? 'ALLOWED' : 'BLOCKED').')'+ );+ }++ // -----------------------------------------------------------------+ // FMCS OFF baseline. Empty-pivot access must not regress here, since+ // the whole gate collapses to "everyone sees everything" without FMCS.+ // -----------------------------------------------------------------++ public function test_fmcs_off_empty_pivot_can_access_any_asset(): void+ {+ $this->settings->disableMultipleFullCompanySupport();+ $companyBAsset = Asset::factory()->for($this->companyB)->create();++ $this->assertAccess(true, $companyBAsset, 'FMCS off, empty pivot, cross-company Asset');+ }++ // -----------------------------------------------------------------+ // FMCS on, STRICT (floater off).+ //+ // Empty pivot actor must NOT be able to act on any company's rows,+ // and must NOT be able to act on Company targets at all. Their only+ // legitimate access surface is null-company items.+ // -----------------------------------------------------------------++ public function test_strict_empty_pivot_cannot_access_asset_in_any_company(): void+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $asset = Asset::factory()->for($this->companyB)->create();++ $this->assertAccess(false, $asset, 'Strict FMCS, empty pivot, Asset in company B — cross-tenant leak (GHSA-8hq6-r8cw-gqwh).');+ }++ public function test_strict_empty_pivot_cannot_access_accessory_in_any_company(): void+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $accessory = Accessory::factory()->for($this->companyB)->create();++ $this->assertAccess(false, $accessory, 'Strict FMCS, empty pivot, Accessory in company B');+ }++ public function test_strict_empty_pivot_cannot_access_consumable_in_any_company(): void+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $consumable = Consumable::factory()->for($this->companyB)->create();++ $this->assertAccess(false, $consumable, 'Strict FMCS, empty pivot, Consumable in company B');+ }++ public function test_strict_empty_pivot_cannot_access_component_in_any_company(): void+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $component = Component::factory()->for($this->companyB)->create();++ $this->assertAccess(false, $component, 'Strict FMCS, empty pivot, Component in company B');+ }++ public function test_strict_empty_pivot_cannot_access_license_in_any_company(): void+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $license = License::factory()->for($this->companyB)->create();++ $this->assertAccess(false, $license, 'Strict FMCS, empty pivot, License in company B');+ }++ public function test_strict_empty_pivot_can_still_access_null_company_asset(): void+ {+ // Positive regression: strict mode is not "block everything".+ // Null-company items are the one legitimate surface an empty-+ // pivot actor is intended to see (matches the query scope's+ // `whereNull($column)` branch for empty pivot in strict).+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ $nullAsset = Asset::factory()->create(['company_id' => null]);++ $this->assertAccess(true, $nullAsset, 'Strict FMCS, empty pivot, null-company Asset should be visible.');+ }++ // -----------------------------------------------------------------+ // FMCS on, FLOATER MODE.+ //+ // In floater mode empty-pivot actors ARE unrestricted for items+ // (mirrors `return $query` in the query scope). This is documented+ // behavior at snipe-it.readme.io/docs/multi-tenancy-ish — a "floater"+ // actor is intentionally not company-scoped.+ // -----------------------------------------------------------------++ public function test_floater_empty_pivot_can_access_asset_in_any_company(): void+ {+ $this->settings->enableFloaterMode();+ $asset = Asset::factory()->for($this->companyB)->create();++ $this->assertAccess(true, $asset, 'Floater FMCS, empty pivot, cross-company Asset should be accessible (matches query scope).');+ }++ public function test_floater_empty_pivot_can_access_accessory_in_any_company(): void+ {+ $this->settings->enableFloaterMode();+ $accessory = Accessory::factory()->for($this->companyB)->create();++ $this->assertAccess(true, $accessory, 'Floater FMCS, empty pivot, cross-company Accessory');+ }++ public function test_floater_empty_pivot_can_access_null_company_asset(): void+ {+ $this->settings->enableFloaterMode();+ $nullAsset = Asset::factory()->create(['company_id' => null]);++ $this->assertAccess(true, $nullAsset, 'Floater FMCS, empty pivot, null-company Asset');+ }++ // -----------------------------------------------------------------+ // Regression guards: superuser and non-empty pivot behavior must be+ // untouched by the empty-pivot fix.+ // -----------------------------------------------------------------++ public function test_superuser_with_empty_pivot_still_bypasses_fmcs(): void+ {+ $superuser = User::factory()->superuser()->create();+ $superuser->companies()->sync([]);+ $this->actingAs($superuser);++ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $asset = Asset::factory()->for($this->companyB)->create();++ $this->assertAccess(true, $asset, 'Superusers bypass FMCS unconditionally, empty pivot or not.');+ }++ public function test_non_empty_pivot_actor_still_scoped_to_their_companies(): void+ {+ $companyAActor = $this->companyA->users()->save(User::factory()->make());+ $this->actingAs($companyAActor);++ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $inCompanyAsset = Asset::factory()->for($this->companyA)->create();+ $crossCompanyAsset = Asset::factory()->for($this->companyB)->create();++ $this->assertAccess(true, $inCompanyAsset, 'Company A actor, in-company Asset');+ $this->assertAccess(false, $crossCompanyAsset, 'Company A actor, cross-company Asset');+ }+}diff --git a/tests/Unit/Models/CheckoutRequestTest.php b/tests/Unit/Models/CheckoutRequestTest.phpindex 7eceafadfd..c95aafdfb0 100644--- a/tests/Unit/Models/CheckoutRequestTest.php+++ b/tests/Unit/Models/CheckoutRequestTest.php@@ -72,4 +72,25 @@ class CheckoutRequestTest extends TestCase$this->assertDatabaseMissing('checkout_requests', ['id' => $checkoutRequest->id]);}++ public function test_name_property_access_does_not_trigger_relation_resolution()+ {+ // Regression: CalendarEventsTransformer::titleFor() falls through+ // to `$source->display_name ?? $source->name ?? ...` when the+ // source has no Presentable presenter. CheckoutRequest defines a+ // plain name() method that returns the requestable's display+ // string. Without an accessor, Eloquent's __get('name') routes+ // through getRelationValue('name') → getRelationshipFromMethod()+ // which calls name(), gets a string back instead of a Relation,+ // and throws `LogicException: name must return a relationship+ // instance`, taking down the calendar API for any install that+ // has a reservation-shape CheckoutRequest.+ $checkoutRequest = CheckoutRequest::factory()->forAsset()->create();++ $this->assertSame(+ $checkoutRequest->name(),+ $checkoutRequest->name,+ 'Property access `->name` must return the accessor value, not throw when Eloquent misinterprets name() as a relation.'+ );+ }}