Skip to content

A free open source IT asset/license management system

Added/updated tests

snipeeb7e95d2d813
diff --git a/tests/Feature/Components/Api/ComponentAssetsTest.php b/tests/Feature/Components/Api/ComponentAssetsTest.php
index 02edcecb2e..26349e6226 100644
--- a/tests/Feature/Components/Api/ComponentAssetsTest.php
+++ b/tests/Feature/Components/Api/ComponentAssetsTest.php
@@ -19,6 +19,19 @@ class ComponentAssetsTest extends TestCase
->assertForbidden();
}
+ public function test_components_viewer_without_asset_view_can_load_assigned_tab()
+ {
+ // The component show page's default "Assigned" tab hits
+ // this endpoint. A components-only viewer must be allowed
+ // through or the show page they can already reach 403s on
+ // first paint.
+ $component = Component::factory()->create();
+
+ $this->actingAsForApi(User::factory()->viewComponents()->create())
+ ->getJson(route('api.components.assets', $component))
+ ->assertOk();
+ }
+
public function test_can_search_assets_assigned_to_specific_component()
{
$component = Component::factory()->create();
diff --git a/tests/Feature/Dashboard/Api/ActivityWidgetTest.php b/tests/Feature/Dashboard/Api/ActivityWidgetTest.php
new file mode 100644
index 0000000000..ae828bb38d
--- /dev/null
+++ b/tests/Feature/Dashboard/Api/ActivityWidgetTest.php
@@ -0,0 +1,127 @@
+<?php
+
+namespace Tests\Feature\Dashboard\Api;
+
+use App\Models\Accessory;
+use App\Models\Actionlog;
+use App\Models\Asset;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * Purpose-built endpoint that backs the dashboard Recent Activity
+ * widget. See Api\DashboardController for the auth + query-surface
+ * rationale. Split from the general-purpose api.activity.index so
+ * scoped viewers do not gain filter / search / sort probes against
+ * activity attributes the widget does not surface.
+ */
+class ActivityWidgetTest extends TestCase
+{
+ public function test_user_without_any_view_permission_is_forbidden()
+ {
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.dashboard.activity'))
+ ->assertForbidden();
+ }
+
+ public function test_scoped_viewer_sees_only_activity_for_viewable_types()
+ {
+ $asset = Asset::factory()->create();
+ $accessory = Accessory::factory()->create();
+
+ Actionlog::factory()->create([
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ 'action_type' => 'checkout',
+ 'note' => 'ASSET_ROW_SENTINEL',
+ ]);
+ Actionlog::factory()->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessory->id,
+ 'action_type' => 'checkout',
+ 'note' => 'ACCESSORY_ROW_SENTINEL',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $body = $this->getJson(route('api.dashboard.activity'))
+ ->assertOk()
+ ->getContent();
+
+ $this->assertStringContainsString('ACCESSORY_ROW_SENTINEL', $body);
+ $this->assertStringNotContainsString('ASSET_ROW_SENTINEL', $body);
+ }
+
+ public function test_activity_view_holder_sees_every_type_without_filtering()
+ {
+ // Give the caller viewAccessories (so they pass the widget's
+ // canViewUsersAndCheckoutables entry gate) plus canViewReports
+ // (which resolves Gate::allows('activity.view') to true). The
+ // activity.view branch skips the viewable-type filter, so an
+ // Asset row should appear even though this user cannot view
+ // assets directly.
+ $asset = Asset::factory()->create();
+
+ Actionlog::factory()->create([
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ 'action_type' => 'checkout',
+ 'note' => 'ASSET_ROW_SENTINEL',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->canViewReports()->create());
+
+ $this->getJson(route('api.dashboard.activity'))
+ ->assertOk()
+ ->assertSee('ASSET_ROW_SENTINEL');
+ }
+
+ public function test_limit_caps_at_fifty_regardless_of_query_string()
+ {
+ Actionlog::factory()->count(60)->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => Accessory::factory()->create()->id,
+ 'action_type' => 'checkout',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $rows = $this->getJson(route('api.dashboard.activity', ['limit' => 500]))
+ ->assertOk()
+ ->json('rows');
+
+ $this->assertLessThanOrEqual(50, count($rows));
+ }
+
+ public function test_search_and_filter_params_do_not_narrow_the_result_set()
+ {
+ // Probe attempt: scoped viewer trying to run a note-text search
+ // through the dashboard endpoint. The widget does not need it,
+ // so the endpoint ignores it. Same-caller results should be
+ // identical with and without the probe.
+ $accessory = Accessory::factory()->create();
+ Actionlog::factory()->count(3)->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessory->id,
+ 'action_type' => 'checkout',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $unfiltered = $this->getJson(route('api.dashboard.activity'))
+ ->assertOk()
+ ->json('total');
+ $withProbe = $this->getJson(route('api.dashboard.activity', [
+ 'search' => 'never-matches-anything',
+ 'filter' => 'never-matches-anything',
+ 'action_type' => 'delete',
+ 'created_by' => 999_999,
+ ]))
+ ->assertOk()
+ ->json('total');
+
+ $this->assertSame($unfiltered, $withProbe);
+ }
+}
diff --git a/tests/Feature/Dashboard/Api/CategoriesWidgetTest.php b/tests/Feature/Dashboard/Api/CategoriesWidgetTest.php
new file mode 100644
index 0000000000..c1453e1944
--- /dev/null
+++ b/tests/Feature/Dashboard/Api/CategoriesWidgetTest.php
@@ -0,0 +1,108 @@
+<?php
+
+namespace Tests\Feature\Dashboard\Api;
+
+use App\Models\Accessory;
+use App\Models\Category;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * Narrow endpoint backing the dashboard Categories summary widget.
+ * See Api\DashboardController for the auth + payload rationale that
+ * splits this from the general-purpose api.categories.index.
+ */
+class CategoriesWidgetTest extends TestCase
+{
+ public function test_user_without_any_view_permission_is_forbidden()
+ {
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.dashboard.categories'))
+ ->assertForbidden();
+ }
+
+ public function test_scoped_viewer_sees_only_matching_category_types()
+ {
+ Category::factory()->create(['name' => 'Asset Cat', 'category_type' => 'asset']);
+ Category::factory()->create(['name' => 'Accessory Cat', 'category_type' => 'accessory']);
+ Category::factory()->create(['name' => 'License Cat', 'category_type' => 'license']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $rows = $this->getJson(route('api.dashboard.categories'))
+ ->assertOk()
+ ->json('rows');
+ $names = collect($rows)->pluck('name')->all();
+
+ $this->assertContains('Accessory Cat', $names);
+ $this->assertNotContains('Asset Cat', $names);
+ $this->assertNotContains('License Cat', $names);
+ }
+
+ public function test_scoped_viewer_only_gets_count_columns_for_viewable_types()
+ {
+ Category::factory()->create(['category_type' => 'accessory']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.categories'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertArrayHasKey('accessories_count', $row);
+ $this->assertArrayNotHasKey('assets_count', $row);
+ $this->assertArrayNotHasKey('consumables_count', $row);
+ $this->assertArrayNotHasKey('components_count', $row);
+ $this->assertArrayNotHasKey('licenses_count', $row);
+ }
+
+ public function test_row_carries_available_actions_view_flag()
+ {
+ Category::factory()->create(['category_type' => 'accessory']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.categories'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertFalse($row['available_actions']['view']);
+ }
+
+ public function test_search_and_filter_params_are_ignored()
+ {
+ Category::factory()->count(3)->create(['category_type' => 'accessory']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $unfilteredTotal = $this->getJson(route('api.dashboard.categories'))
+ ->assertOk()
+ ->json('total');
+ $probeTotal = $this->getJson(route('api.dashboard.categories', [
+ 'search' => 'never-matches-anything',
+ 'filter' => 'never-matches-anything',
+ 'name' => 'never-matches-anything',
+ 'created_by' => 999_999,
+ ]))
+ ->assertOk()
+ ->json('total');
+
+ $this->assertSame($unfilteredTotal, $probeTotal);
+ }
+
+ public function test_limit_caps_at_fifty()
+ {
+ Accessory::factory()->count(0)->create();
+ Category::factory()->count(60)->create(['category_type' => 'accessory']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $rows = $this->getJson(route('api.dashboard.categories', ['limit' => 500]))
+ ->assertOk()
+ ->json('rows');
+
+ $this->assertLessThanOrEqual(50, count($rows));
+ }
+}
diff --git a/tests/Feature/Dashboard/Api/CompaniesWidgetTest.php b/tests/Feature/Dashboard/Api/CompaniesWidgetTest.php
new file mode 100644
index 0000000000..6569daa955
--- /dev/null
+++ b/tests/Feature/Dashboard/Api/CompaniesWidgetTest.php
@@ -0,0 +1,97 @@
+<?php
+
+namespace Tests\Feature\Dashboard\Api;
+
+use App\Models\Company;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * Narrow endpoint backing the dashboard Companies summary widget.
+ * See Api\DashboardController for the auth + payload rationale that
+ * splits this from the general-purpose api.companies.index.
+ */
+class CompaniesWidgetTest extends TestCase
+{
+ public function test_user_without_any_view_permission_is_forbidden()
+ {
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.dashboard.companies'))
+ ->assertForbidden();
+ }
+
+ public function test_scoped_viewer_only_gets_count_columns_for_viewable_types()
+ {
+ Company::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.companies'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertArrayHasKey('accessories_count', $row);
+ $this->assertArrayNotHasKey('assets_count', $row);
+ $this->assertArrayNotHasKey('consumables_count', $row);
+ $this->assertArrayNotHasKey('components_count', $row);
+ $this->assertArrayNotHasKey('licenses_count', $row);
+ $this->assertArrayNotHasKey('users_count', $row);
+ }
+
+ public function test_row_carries_available_actions_view_flag_and_no_extra_fields()
+ {
+ Company::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.companies'))
+ ->assertOk()
+ ->json('rows.0');
+
+ // Widget-shape whitelist. Anything beyond these fields is a
+ // widening that leaks past what the widget renders. Extend
+ // this list intentionally when adding a widget column, not
+ // accidentally by extending the transformer.
+ $allowed = ['id', 'name', 'available_actions', 'accessories_count'];
+ $this->assertSame(sort($allowed) ? $allowed : $allowed, array_values(collect(array_keys($row))->sort()->values()->all()));
+ $this->assertFalse($row['available_actions']['view']);
+ }
+
+ public function test_admin_sees_view_flag_true()
+ {
+ Company::factory()->create();
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $row = $this->getJson(route('api.dashboard.companies'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertTrue($row['available_actions']['view']);
+ }
+
+ public function test_search_and_filter_params_are_ignored()
+ {
+ Company::factory()->count(3)->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $unfilteredTotal = $this->getJson(route('api.dashboard.companies'))
+ ->assertOk()
+ ->json('total');
+ $probeTotal = $this->getJson(route('api.dashboard.companies', [
+ 'search' => 'never-matches',
+ 'filter' => 'never-matches',
+ 'name' => 'never-matches',
+ 'email' => 'never-matches',
+ 'created_by' => 999_999,
+ 'tag_color' => '#ffffff',
+ ]))
+ ->assertOk()
+ ->json('total');
+
+ $this->assertSame($unfilteredTotal, $probeTotal);
+ }
+}
diff --git a/tests/Feature/Dashboard/Api/LocationsWidgetTest.php b/tests/Feature/Dashboard/Api/LocationsWidgetTest.php
new file mode 100644
index 0000000000..055feae547
--- /dev/null
+++ b/tests/Feature/Dashboard/Api/LocationsWidgetTest.php
@@ -0,0 +1,91 @@
+<?php
+
+namespace Tests\Feature\Dashboard\Api;
+
+use App\Models\Location;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * Narrow endpoint backing the dashboard Locations summary widget.
+ * See Api\DashboardController for the auth + payload rationale that
+ * splits this from the general-purpose api.locations.index.
+ */
+class LocationsWidgetTest extends TestCase
+{
+ public function test_user_without_any_view_permission_is_forbidden()
+ {
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.dashboard.locations'))
+ ->assertForbidden();
+ }
+
+ public function test_scoped_viewer_only_gets_count_columns_for_viewable_types()
+ {
+ Location::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.locations'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertArrayHasKey('accessories_count', $row);
+ $this->assertArrayNotHasKey('assets_count', $row);
+ $this->assertArrayNotHasKey('assigned_assets_count', $row);
+ $this->assertArrayNotHasKey('consumables_count', $row);
+ $this->assertArrayNotHasKey('components_count', $row);
+ $this->assertArrayNotHasKey('users_count', $row);
+ }
+
+ public function test_asset_viewer_gets_both_asset_count_columns()
+ {
+ Location::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAssets()->create());
+
+ $row = $this->getJson(route('api.dashboard.locations'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertArrayHasKey('assets_count', $row);
+ $this->assertArrayHasKey('assigned_assets_count', $row);
+ }
+
+ public function test_row_carries_available_actions_view_flag()
+ {
+ Location::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $row = $this->getJson(route('api.dashboard.locations'))
+ ->assertOk()
+ ->json('rows.0');
+
+ $this->assertFalse($row['available_actions']['view']);
+ }
+
+ public function test_search_and_filter_params_are_ignored()
+ {
+ Location::factory()->count(3)->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $unfilteredTotal = $this->getJson(route('api.dashboard.locations'))
+ ->assertOk()
+ ->json('total');
+ $probeTotal = $this->getJson(route('api.dashboard.locations', [
+ 'search' => 'never-matches',
+ 'filter' => 'never-matches',
+ 'name' => 'never-matches',
+ 'city' => 'never-matches',
+ 'created_by' => 999_999,
+ ]))
+ ->assertOk()
+ ->json('total');
+
+ $this->assertSame($unfilteredTotal, $probeTotal);
+ }
+}
diff --git a/tests/Feature/DashboardTest.php b/tests/Feature/DashboardTest.php
index 8a214d432b..734162329d 100644
--- a/tests/Feature/DashboardTest.php
+++ b/tests/Feature/DashboardTest.php
@@ -12,14 +12,60 @@ use Tests\TestCase;
class DashboardTest extends TestCase
{
- public function test_users_without_admin_access_are_redirected()
+ public function test_users_with_no_visibility_are_redirected_to_own_assets(): void
{
+ // A regular user with no view grants on any HasCalendarEvents
+ // adopter fails the canViewUsersAndCheckoutables gate and
+ // still lands on their own /account/view-assets page, matching
+ // the pre-widening behavior for people with no read access.
$this->actingAs(User::factory()->create())
->get(route('home'))
->assertRedirect(route('view-assets'));
}
- public function test_counts_are_loaded_correctly_for_admins()
+ public function test_admin_sees_dashboard_with_top_boxes(): void
+ {
+ Asset::factory()->count(2)->create();
+
+ $response = $this->actingAs(User::factory()->admin()->create())
+ ->get(route('home'))
+ ->assertOk()
+ ->assertViewIs('dashboard');
+
+ // Top-boxes row carries the counts array cells. The license
+ // box uses number_format($counts['license']) so a rendered
+ // dashboard for an admin includes the localized formatted
+ // count. Non-admin coverage below asserts these are absent.
+ $response->assertSee(trans('general.assets'), false);
+ $response->assertSee(trans('general.licenses'), false);
+ }
+
+ public function test_non_admin_with_view_asset_sees_dashboard_without_top_boxes(): void
+ {
+ // A user with `assets.view` passes canViewUsersAndCheckoutables
+ // (Asset is a HasCalendarEvents source) and gets the widget
+ // section of the dashboard. The top-boxes row and the empty-
+ // inventory shortcut both live behind the admin-only wrapper
+ // and must not render.
+ $viewer = User::factory()->viewAssets()->create();
+
+ $response = $this->actingAs($viewer)
+ ->get(route('home'))
+ ->assertOk()
+ ->assertViewIs('dashboard');
+
+ // The top-box row wraps each cell in a "dashboard small-box"
+ // div. Absence of that class in the rendered HTML proves the
+ // admin-only region did not render.
+ $response->assertDontSee('dashboard small-box', false);
+
+ // The empty-inventory shortcut headline (only appears for
+ // admins on empty installs) must also be absent for
+ // non-admins regardless of inventory state.
+ $response->assertDontSee(trans('general.dashboard_empty'), false);
+ }
+
+ public function test_counts_are_loaded_correctly_for_admins(): void
{
Asset::factory()->count(2)->create();
Accessory::factory()->count(2)->create();
diff --git a/tests/Feature/DashboardWidgetVisibilityTest.php b/tests/Feature/DashboardWidgetVisibilityTest.php
new file mode 100644
index 0000000000..151252b88c
--- /dev/null
+++ b/tests/Feature/DashboardWidgetVisibilityTest.php
@@ -0,0 +1,246 @@
+<?php
+
+namespace Tests\Feature;
+
+use App\Models\Accessory;
+use App\Models\Actionlog;
+use App\Models\Asset;
+use App\Models\Category;
+use App\Models\Company;
+use App\Models\License;
+use App\Models\Location;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * The dashboard is reachable by any user who passes
+ * canViewUsersAndCheckoutables (can view at least one
+ * HasCalendarEvents source). Each widget's API endpoint has to
+ * accept those callers too, or the widget renders an ugly "Could
+ * not load results, 403" toast. This test covers the widening on
+ * Api\CompaniesController@index, Api\LocationsController@index,
+ * Api\CategoriesController@index, and Api\ReportsController@index
+ * (recent activity).
+ *
+ * Transitive-visibility reasoning: a user who can view any inventory
+ * type inherently knows about the companies / locations / categories
+ * those items belong to (they're attributes on every asset,
+ * accessory, etc). CompanyableScope and FMCS location scoping filter
+ * responses naturally.
+ *
+ * Recent activity has an additional server-side per-type filter for
+ * scoped viewers so an accessory-only user's feed only carries
+ * actionlogs on types they can view.
+ */
+class DashboardWidgetVisibilityTest extends TestCase
+{
+ public function test_scoped_viewer_can_reach_companies_widget(): void
+ {
+ Company::factory()->count(2)->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $this->getJson(route('api.dashboard.companies'))->assertOk();
+ }
+
+ public function test_scoped_viewer_can_reach_locations_widget(): void
+ {
+ Location::factory()->count(2)->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $this->getJson(route('api.dashboard.locations'))->assertOk();
+ }
+
+ public function test_scoped_viewer_can_reach_categories_widget(): void
+ {
+ Category::factory()->count(2)->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $this->getJson(route('api.dashboard.categories'))->assertOk();
+ }
+
+ public function test_scoped_viewer_still_forbidden_on_general_index_endpoints(): void
+ {
+ // The dashboard now hits purpose-built api.dashboard.* twins.
+ // A scoped viewer must still get 403 on the general-purpose
+ // per-domain indexes, whose query surface exposes far more
+ // than the widget renders. Regression guard for the widen
+ // that used to live on these endpoints.
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $this->getJson(route('api.companies.index'))->assertForbidden();
+ $this->getJson(route('api.locations.index'))->assertForbidden();
+ $this->getJson(route('api.categories.index'))->assertForbidden();
+ $this->getJson(route('api.activity.index'))->assertForbidden();
+ }
+
+ public function test_permissionless_user_still_forbidden_on_each_widget_endpoint(): void
+ {
+ // A base user without any view grants still fails
+ // canViewUsersAndCheckoutables and gets 403 on each widget
+ // endpoint. Keeps the coarse gate meaningful.
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.dashboard.companies'))->assertForbidden();
+ $this->getJson(route('api.dashboard.locations'))->assertForbidden();
+ $this->getJson(route('api.dashboard.categories'))->assertForbidden();
+ $this->getJson(route('api.dashboard.activity'))->assertForbidden();
+ }
+
+ public function test_scoped_activity_viewer_only_sees_actionlogs_on_types_they_can_view(): void
+ {
+ // Seed one actionlog per relevant type. A user with only
+ // accessories.view should see the Accessory row and nothing
+ // else through the dashboard's recent-activity feed.
+ $asset = Asset::factory()->create();
+ $accessory = Accessory::factory()->create();
+ $license = License::factory()->create();
+
+ Actionlog::factory()->create([
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ 'action_type' => 'checkout',
+ 'note' => 'SENTINEL_ASSET_ROW',
+ ]);
+ Actionlog::factory()->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessory->id,
+ 'action_type' => 'checkout',
+ 'note' => 'SENTINEL_ACCESSORY_ROW',
+ ]);
+ Actionlog::factory()->create([
+ 'item_type' => License::class,
+ 'item_id' => $license->id,
+ 'action_type' => 'checkout',
+ 'note' => 'SENTINEL_LICENSE_ROW',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $response = $this->getJson(route('api.dashboard.activity'))->assertOk();
+ $body = $response->getContent();
+
+ $this->assertStringContainsString('SENTINEL_ACCESSORY_ROW', $body);
+ $this->assertStringNotContainsString('SENTINEL_ASSET_ROW', $body);
+ $this->assertStringNotContainsString('SENTINEL_LICENSE_ROW', $body);
+ }
+
+ public function test_scoped_viewer_sees_available_actions_view_false_on_lookup_rows(): void
+ {
+ // Row-level view flag drives the dashboard formatter's
+ // decision to render the name as plain text (no link) so a
+ // scoped viewer clicking through does not 403 on the show
+ // controller they cannot reach. Same shape on Categories,
+ // Locations, and Companies transformers. Category needs to
+ // be an accessory-typed one so it survives the category_type
+ // filter the API applies for scoped viewers.
+ Category::factory()->create(['category_type' => 'accessory']);
+ Location::factory()->create();
+ Company::factory()->create();
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $categoryRow = $this->getJson(route('api.dashboard.categories'))->assertOk()->json('rows.0');
+ $locationRow = $this->getJson(route('api.dashboard.locations'))->assertOk()->json('rows.0');
+ $companyRow = $this->getJson(route('api.dashboard.companies'))->assertOk()->json('rows.0');
+
+ $this->assertFalse($categoryRow['available_actions']['view']);
+ $this->assertFalse($locationRow['available_actions']['view']);
+ $this->assertFalse($companyRow['available_actions']['view']);
+ }
+
+ public function test_scoped_categories_filter_excludes_types_the_viewer_cannot_view(): void
+ {
+ // Accessory-only viewer should see accessory-typed categories
+ // but not asset / license / consumable / component ones. The
+ // filter widens back out to unfiltered when the caller has
+ // explicit categories.view.
+ Category::factory()->create(['name' => 'Asset Cat', 'category_type' => 'asset']);
+ Category::factory()->create(['name' => 'Accessory Cat', 'category_type' => 'accessory']);
+ Category::factory()->create(['name' => 'License Cat', 'category_type' => 'license']);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $rows = $this->getJson(route('api.dashboard.categories'))->assertOk()->json('rows');
+ $names = collect($rows)->pluck('name')->all();
+
+ $this->assertContains('Accessory Cat', $names);
+ $this->assertNotContains('Asset Cat', $names);
+ $this->assertNotContains('License Cat', $names);
+ }
+
+ public function test_activity_row_carries_viewable_flag_per_item(): void
+ {
+ // Recent-activity's polymorphicItemFormatter renders name +
+ // link when the caller can view the record, plain text when
+ // they cannot. The flag flows through the transformer as
+ // item.viewable / target.viewable on each row so a scoped
+ // viewer's dashboard clicks do not 403.
+ $accessory = Accessory::factory()->create();
+
+ Actionlog::factory()->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessory->id,
+ 'action_type' => 'checkout',
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $rows = $this->getJson(route('api.dashboard.activity'))->assertOk()->json('rows');
+ $accessoryRows = collect($rows)->filter(fn ($r) => ($r['item']['type'] ?? null) === 'accessory')->values()->all();
+ $this->assertNotEmpty($accessoryRows, 'accessory row must survive the scoped-viewer filter');
+ foreach ($accessoryRows as $row) {
+ $this->assertTrue($row['item']['viewable']);
+ }
+ }
+
+ public function test_admin_sees_available_actions_view_true_on_lookup_rows(): void
+ {
+ Category::factory()->create();
+ Location::factory()->create();
+ Company::factory()->create();
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $categoryRow = $this->getJson(route('api.dashboard.categories'))->assertOk()->json('rows.0');
+ $locationRow = $this->getJson(route('api.dashboard.locations'))->assertOk()->json('rows.0');
+ $companyRow = $this->getJson(route('api.dashboard.companies'))->assertOk()->json('rows.0');
+
+ $this->assertTrue($categoryRow['available_actions']['view']);
+ $this->assertTrue($locationRow['available_actions']['view']);
+ $this->assertTrue($companyRow['available_actions']['view']);
+ }
+
+ public function test_full_activity_view_still_sees_every_row(): void
+ {
+ // Superuser (implicit activity.view via hasAccess('admin'))
+ // must still see the full unfiltered feed. Regression guard
+ // for the widened gate.
+ $asset = Asset::factory()->create();
+ $accessory = Accessory::factory()->create();
+
+ Actionlog::factory()->create([
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ 'action_type' => 'checkout',
+ 'note' => 'FULL_ASSET_ROW',
+ ]);
+ Actionlog::factory()->create([
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessory->id,
+ 'action_type' => 'checkout',
+ 'note' => 'FULL_ACCESSORY_ROW',
+ ]);
+
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $response = $this->getJson(route('api.activity.index'))->assertOk();
+ $body = $response->getContent();
+
+ $this->assertStringContainsString('FULL_ASSET_ROW', $body);
+ $this->assertStringContainsString('FULL_ACCESSORY_ROW', $body);
+ }
+}
diff --git a/tests/Feature/Helpers/CheckLowInventoryTest.php b/tests/Feature/Helpers/CheckLowInventoryTest.php
index 87f26293d3..33b8801b95 100644
--- a/tests/Feature/Helpers/CheckLowInventoryTest.php
+++ b/tests/Feature/Helpers/CheckLowInventoryTest.php
@@ -149,6 +149,66 @@ class CheckLowInventoryTest extends TestCase
);
}
+ /**
+ * Components are checked out with a per-pivot-row assigned_qty. A
+ * component with qty=10, min_amt=2, and a single pivot row that
+ * shipped 10 units has 0 remaining and must be flagged as low. The
+ * pre-fix implementation used withCount() on the assets relation,
+ * which counted 1 (one pivot row) instead of 10 (sum of
+ * assigned_qty), calling remaining=9 and skipping the alert. Pin
+ * both the flagged-membership and the reported remaining value so
+ * this can't regress silently.
+ */
+ public function test_component_fully_assigned_in_one_pivot_row_reports_correct_remaining()
+ {
+ $this->settings->set(['alert_threshold' => 0]);
+
+ $component = Component::factory()->create(['qty' => 10, 'min_amt' => 2]);
+ $asset = Asset::factory()->create();
+
+ $component->assets()->attach($asset->id, [
+ 'assigned_qty' => 10,
+ 'created_at' => now(),
+ 'created_by' => User::factory()->create()->id,
+ ]);
+
+ $rows = collect(Helper::checkLowInventory())->where('type', 'components')->keyBy('id');
+
+ $this->assertTrue($rows->has($component->id));
+ $this->assertSame(0, (int) $rows[$component->id]['remaining']);
+ }
+
+ /**
+ * Sums across multiple pivot rows too: 4 + 3 = 7 units shipped, so
+ * a qty=10 component reports remaining=3, not 8 (row-count) or
+ * some other artifact.
+ */
+ public function test_component_partially_assigned_across_pivots_sums_assigned_qty()
+ {
+ $this->settings->set(['alert_threshold' => 0]);
+
+ $component = Component::factory()->create(['qty' => 10, 'min_amt' => 5]);
+ $assetA = Asset::factory()->create();
+ $assetB = Asset::factory()->create();
+ $actor = User::factory()->create();
+
+ $component->assets()->attach($assetA->id, [
+ 'assigned_qty' => 4,
+ 'created_at' => now(),
+ 'created_by' => $actor->id,
+ ]);
+ $component->assets()->attach($assetB->id, [
+ 'assigned_qty' => 3,
+ 'created_at' => now(),
+ 'created_by' => $actor->id,
+ ]);
+
+ $rows = collect(Helper::checkLowInventory())->where('type', 'components')->keyBy('id');
+
+ $this->assertTrue($rows->has($component->id));
+ $this->assertSame(3, (int) $rows[$component->id]['remaining']);
+ }
+
/**
* The AssetModel branch counts RTD (Ready to Deploy, unassigned) assets
* via the availableAssets() scope, so this test creates exactly min_amt
diff --git a/tests/Feature/Livewire/NeedsAttentionTest.php b/tests/Feature/Livewire/NeedsAttentionTest.php
index ba36b9c38c..c4b65b5b7f 100644
--- a/tests/Feature/Livewire/NeedsAttentionTest.php
+++ b/tests/Feature/Livewire/NeedsAttentionTest.php
@@ -19,12 +19,16 @@ use Tests\TestCase;
* Coverage for the dashboard's Needs Attention Livewire widget.
* Focuses on:
*
- * - boot() authorization: hasAccess('admin') gate refuses
- * unauthenticated + non-admin users so a snapshot-replay POST
- * can't leak counts they'd never see in the parent view.
+ * - boot() authorization: canViewUsersAndCheckoutables gate
+ * refuses users who can't view any HasCalendarEvents source so
+ * a snapshot-replay POST can't leak counts they'd never see in
+ * the parent view.
* - Placeholder shape: renders a skeleton with the same title +
* list-group chrome so hydration doesn't visibly shift the row.
* - Count accuracy: each of the eight counts reflects seeded data.
+ * - Per-type scoping: a caller with a narrow view grant (e.g.
+ * accessories.view only) gets zero for the counts covering
+ * types they can't see, instead of a leaked global count.
* - FMCS scoping: a company-scoped admin sees only the counts
* matching rows in their own company, not cross-company totals.
*/
@@ -32,10 +36,10 @@ class NeedsAttentionTest extends TestCase implements TestsFullMultipleCompaniesS
{
public function test_requires_permission(): void
{
- // Livewire's test helper intercepts HttpExceptions raised in
- // boot() and surfaces them as test failures rather than a
- // response status, so call boot() directly. Non-admin user
- // must trip the abort_unless.
+ // A user with zero view grants fails canViewUsersAndCheckoutables
+ // and boot() aborts with 403. Livewire's test helper intercepts
+ // HttpExceptions raised in boot() and surfaces them as test
+ // failures rather than a response status, so call boot() directly.
$this->actingAs(User::factory()->create());
try {
@@ -46,18 +50,51 @@ class NeedsAttentionTest extends TestCase implements TestsFullMultipleCompaniesS
}
}
+ public function test_boot_permits_users_who_can_view_any_source(): void
+ {
+ // A non-admin who can view at least one HasCalendarEvents
+ // source (Asset here via viewAssets()) passes the widened
+ // gate. boot() should return silently.
+ $this->actingAs(User::factory()->viewAssets()->create());
+
+ (new NeedsAttention)->boot();
+
+ // Reaching this line means boot() didn't throw.
+ $this->assertTrue(true);
+ }
+
public function test_boot_permits_admin(): void
{
- // Superuser passes hasAccess('admin'). boot() should return
- // silently (no throw).
+ // Superuser trivially passes canViewUsersAndCheckoutables.
$this->actingAs(User::factory()->superuser()->create());
(new NeedsAttention)->boot();
- // Reaching this line means boot() didn't throw.
$this->assertTrue(true);
}
+ public function test_counts_return_zero_for_types_the_caller_cannot_view(): void
+ {
+ // Seed data that would populate every asset / license /
+ // maintenance count. A user with only accessories.view
+ // should see zero for all of them, since none of those
+ // seeds belong to a type they can view.
+ $farFuture = now()->addYears(5)->format('Y-m-d');
+
+ Asset::factory()->count(3)->create(['next_audit_date' => now()->subDays(5)])
+ ->each(fn ($asset) => $asset->forceFill(['asset_eol_date' => $farFuture])->save());
+ License::factory()->count(2)->create(['expiration_date' => now()->addDays(10)->format('Y-m-d')]);
+
+ Livewire::withoutLazyLoading();
+ Livewire::actingAs(User::factory()->viewAccessories()->create())
+ ->test(NeedsAttention::class)
+ ->assertSet('overdueAudits', 0)
+ ->assertSet('assetsPastEol', 0)
+ ->assertSet('licensesExpiringSoon', 0)
+ ->assertSet('overdueMaintenances', 0)
+ ->assertSet('usersOffboardingSoon', 0);
+ }
+
public function test_the_component_renders_for_admin(): void
{
Livewire::withoutLazyLoading();
diff --git a/tests/Feature/LowStockApiVisibilityTest.php b/tests/Feature/LowStockApiVisibilityTest.php
new file mode 100644
index 0000000000..6da0279bfb
--- /dev/null
+++ b/tests/Feature/LowStockApiVisibilityTest.php
@@ -0,0 +1,60 @@
+<?php
+
+namespace Tests\Feature;
+
+use App\Models\Accessory;
+use App\Models\Consumable;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * The dashboard's Low Stock widget hits /api/v1/low-stock. Before
+ * this filter, the endpoint returned rows for every source model
+ * (consumable / accessory / component / model / license) to any
+ * viewer who could see at least one of them. A viewer with only
+ * accessories.view would see consumable + component + license rows
+ * they can't otherwise reach through the app.
+ *
+ * The controller now filters rows by per-type view permission before
+ * pagination, so the widget's contents match what the caller could
+ * see if they clicked through to the underlying index.
+ */
+class LowStockApiVisibilityTest extends TestCase
+{
+ public function test_accessory_only_viewer_does_not_see_consumable_low_stock_rows(): void
+ {
+ // A low-stock accessory the caller CAN see.
+ Accessory::factory()->create([
+ 'name' => 'Low Accessory',
+ 'qty' => 1,
+ 'min_amt' => 5,
+ ]);
+
+ // A low-stock consumable the caller CANNOT see.
+ Consumable::factory()->create([
+ 'name' => 'Low Consumable',
+ 'qty' => 1,
+ 'min_amt' => 5,
+ ]);
+
+ Passport::actingAs(User::factory()->viewAccessories()->create());
+
+ $response = $this->getJson(route('api.low-stock.index'))
+ ->assertOk();
+
+ $rows = $response->json('rows');
+ $names = collect($rows)->pluck('item.name')->all();
+
+ $this->assertContains('Low Accessory', $names);
+ $this->assertNotContains('Low Consumable', $names);
+ }
+
+ public function test_viewer_with_no_source_permissions_is_forbidden(): void
+ {
+ Passport::actingAs(User::factory()->create());
+
+ $this->getJson(route('api.low-stock.index'))
+ ->assertForbidden();
+ }
+}
diff --git a/tests/Feature/Reporting/UnacceptedAssetReportTest.php b/tests/Feature/Reporting/UnacceptedAssetReportTest.php
index b16c6ecf62..37ea4d7ab1 100644
--- a/tests/Feature/Reporting/UnacceptedAssetReportTest.php
+++ b/tests/Feature/Reporting/UnacceptedAssetReportTest.php
@@ -20,4 +20,32 @@ class UnacceptedAssetReportTest extends TestCase
->get(route('reports/unaccepted_assets'))
->assertOk();
}
+
+ public function test_checkoutable_viewer_can_reach_report_without_reports_view_permission()
+ {
+ // Dashboard's Needs Attention widget links every checkoutable
+ // viewer to this report. Without the widened gate the link
+ // 403s for scoped viewers, which is what this test guards
+ // against. See getAssetAcceptanceReport() in ReportsController.
+ $this->actingAs(User::factory()->viewComponents()->create())
+ ->get(route('reports/unaccepted_assets'))
+ ->assertOk();
+ }
+
+ public function test_mutating_endpoints_still_require_reports_view_for_scoped_viewer()
+ {
+ // The GET report page was widened to accept checkoutable
+ // viewers, but the CSV export (postAssetAcceptanceReport),
+ // sent-reminder, and delete-acceptance endpoints all still
+ // authorize reports.view directly. A scoped viewer arriving
+ // via the Needs Attention widget sees a read-only list. The
+ // blade hides the mutating buttons because
+ // $canManageAcceptances is false, but the underlying route
+ // gates are what actually enforce it and are pinned here.
+ $viewer = User::factory()->viewComponents()->create();
+
+ $this->actingAs($viewer)
+ ->post(route('reports/export/unaccepted_assets'))
+ ->assertForbidden();
+ }
}
diff --git a/tests/Feature/StatusLabels/Api/DashboardPieChartAuthTest.php b/tests/Feature/StatusLabels/Api/DashboardPieChartAuthTest.php
new file mode 100644
index 0000000000..0b5249d479
--- /dev/null
+++ b/tests/Feature/StatusLabels/Api/DashboardPieChartAuthTest.php
@@ -0,0 +1,65 @@
+<?php
+
+namespace Tests\Feature\StatusLabels\Api;
+
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * The dashboard's Assets-by-Status pie chart fetches its data from
+ * api.statuslabels.assets.byname and api.statuslabels.assets.bytype.
+ * Both endpoints used to require statuslabels.view, which broke the
+ * chart for asset viewers who don't also have status-label admin
+ * permission. The chart payload is aggregate asset counts bucketed
+ * by status, so an asset viewer already has read on the underlying
+ * data. These tests pin the widened gate so a future refactor
+ * doesn't quietly re-narrow it and break the dashboard again.
+ */
+class DashboardPieChartAuthTest extends TestCase
+{
+ public function test_asset_viewer_can_reach_pie_chart_by_name_endpoint()
+ {
+ $this->actingAsForApi(User::factory()->viewAssets()->create())
+ ->getJson(route('api.statuslabels.assets.byname'))
+ ->assertOk();
+ }
+
+ public function test_asset_viewer_can_reach_pie_chart_by_meta_status_endpoint()
+ {
+ $this->actingAsForApi(User::factory()->viewAssets()->create())
+ ->getJson(route('api.statuslabels.assets.bytype'))
+ ->assertOk();
+ }
+
+ public function test_status_label_viewer_without_asset_view_can_still_reach_pie_chart_by_name()
+ {
+ $this->actingAsForApi(User::factory()->create([
+ 'permissions' => json_encode(['statuslabels.view' => '1']),
+ ]))
+ ->getJson(route('api.statuslabels.assets.byname'))
+ ->assertOk();
+ }
+
+ public function test_status_label_viewer_without_asset_view_can_still_reach_pie_chart_by_meta_status()
+ {
+ $this->actingAsForApi(User::factory()->create([
+ 'permissions' => json_encode(['statuslabels.view' => '1']),
+ ]))
+ ->getJson(route('api.statuslabels.assets.bytype'))
+ ->assertOk();
+ }
+
+ public function test_user_with_no_relevant_permissions_is_forbidden_from_pie_chart_by_name()
+ {
+ $this->actingAsForApi(User::factory()->create())
+ ->getJson(route('api.statuslabels.assets.byname'))
+ ->assertForbidden();
+ }
+
+ public function test_user_with_no_relevant_permissions_is_forbidden_from_pie_chart_by_meta_status()
+ {
+ $this->actingAsForApi(User::factory()->create())
+ ->getJson(route('api.statuslabels.assets.bytype'))
+ ->assertForbidden();
+ }
+}