Skip to content

A free open source IT asset/license management system

Fixed qp3v-6792 - added serial(): Attribute for full coverage of license key masking

sniped020b4b49e6b
diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.php
index 8be6b17919..3df795eaee 100644
--- a/app/Http/Controllers/ReportsController.php
+++ b/app/Http/Controllers/ReportsController.php
@@ -380,20 +380,14 @@ class ReportsController extends Controller
$item_name = '';
}
- // Mask license serial when the current user
- // does not hold viewKeys. A license's serial is
- // the product key, and the licenses / index /
- // export sinks already treat it that way. Without
- // this the Activity report CSV leaks every key
- // for licenses in the caller's scope.
- $itemSerial = null;
- if ($actionlog->item && $actionlog->item->serial) {
- if ($actionlog->item instanceof License && ! Gate::allows('viewKeys', $actionlog->item)) {
- $itemSerial = License::PRODUCT_KEY_MASK;
- } else {
- $itemSerial = $actionlog->item->serial;
- }
- }
+ // License::getSerialAttribute and
+ // Actionlog::getLogMetaAttribute apply the
+ // licenses.keys mask upstream, so the raw
+ // product key never reaches this writer when
+ // the viewer is not permitted.
+ $itemSerial = ($actionlog->item && $actionlog->item->serial)
+ ? $actionlog->item->serial
+ : null;
$row = [
$actionlog->created_at,
diff --git a/app/Http/Transformers/ActionlogsTransformer.php b/app/Http/Transformers/ActionlogsTransformer.php
index 399535b2d7..7198833dcf 100644
--- a/app/Http/Transformers/ActionlogsTransformer.php
+++ b/app/Http/Transformers/ActionlogsTransformer.php
@@ -160,40 +160,14 @@ class ActionlogsTransformer
}
$clean_meta = $this->changedInfo($clean_meta);
-
- // A license serial is the product key. When the current
- // user does not hold licenses.keys / create / edit, the
- // resource / index / export sinks all mask the raw key.
- // The old / new pair in log_meta['serial'] on a license
- // edit would otherwise leak both the previous and new
- // key through the History tab and the activity report.
- if ($actionlog->item instanceof License
- && ! Gate::allows('viewKeys', $actionlog->item)
- && isset($clean_meta['serial'])
- && is_array($clean_meta['serial'])
- ) {
- if (isset($clean_meta['serial']['old'])) {
- $clean_meta['serial']['old'] = License::PRODUCT_KEY_MASK;
- }
- if (isset($clean_meta['serial']['new'])) {
- $clean_meta['serial']['new'] = License::PRODUCT_KEY_MASK;
- }
- }
}
- // A license serial is the product key. When the current user
- // does not hold licenses.keys / create / edit, mask it here the
- // same way LicensesTransformer masks product_key. Without this
- // the /api/v1/licenses/{id}/history and /api/v1/reports/activity
- // sinks leak the raw key through actionlog rows.
- $itemSerial = null;
- if ($actionlog->item && $actionlog->item->serial) {
- if ($actionlog->item instanceof License && ! Gate::allows('viewKeys', $actionlog->item)) {
- $itemSerial = License::PRODUCT_KEY_MASK;
- } else {
- $itemSerial = e($actionlog->item->serial);
- }
- }
+ // License::getSerialAttribute and Actionlog::getLogMetaAttribute
+ // apply the licenses.keys mask upstream, so the raw product key
+ // never reaches this layer when the viewer is not permitted.
+ $itemSerial = ($actionlog->item && $actionlog->item->serial)
+ ? e($actionlog->item->serial)
+ : null;
$array = [
'id' => (int) $actionlog->id,
diff --git a/app/Mail/CheckoutLicenseMail.php b/app/Mail/CheckoutLicenseMail.php
index 415145f43e..e953c19c5f 100644
--- a/app/Mail/CheckoutLicenseMail.php
+++ b/app/Mail/CheckoutLicenseMail.php
@@ -2,7 +2,6 @@
namespace App\Mail;
-use App\Models\Asset;
use App\Models\LicenseSeat;
use App\Models\Setting;
use App\Models\User;
@@ -31,12 +30,6 @@ class CheckoutLicenseMail extends BaseMailable
$this->settings = Setting::getSettings();
$this->target = $checkedOutTo;
$this->firstTimeSending = $firstTimeSending;
-
- if ($this->target instanceof User) {
- $this->target = $this->target->display_name;
- } elseif ($this->target instanceof Asset) {
- $this->target = $this->target->display_name;
- }
}
/**
diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.php
index 7597bc96c9..f27f82386d 100755
--- a/app/Models/Actionlog.php
+++ b/app/Models/Actionlog.php
@@ -11,10 +11,12 @@ use App\Presenters\ActionlogPresenter;
use App\Presenters\Presentable;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
@@ -49,6 +51,41 @@ class Actionlog extends SnipeModel
protected $with = ['adminuser'];
+ /**
+ * Mask the diff blob on read when it carries license-key values the
+ * current user is not permitted to see.
+ */
+ protected function logMeta(): Attribute
+ {
+ return Attribute::get(function ($value) {
+ if ($value === null || $value === '') {
+ return $value;
+ }
+
+ if (!$this->item instanceof License) {
+ return $value;
+ }
+
+ if (Gate::allows('viewKeys', $this->item)) {
+ return $value;
+ }
+
+ $decoded = json_decode($value, true);
+ if (!is_array($decoded) || !isset($decoded['serial']) || !is_array($decoded['serial'])) {
+ return $value;
+ }
+
+ if (array_key_exists('old', $decoded['serial'])) {
+ $decoded['serial']['old'] = License::PRODUCT_KEY_MASK;
+ }
+ if (array_key_exists('new', $decoded['serial'])) {
+ $decoded['serial']['new'] = License::PRODUCT_KEY_MASK;
+ }
+
+ return json_encode($decoded);
+ });
+ }
+
protected $presenter = ActionlogPresenter::class;
use Presentable;
diff --git a/app/Models/License.php b/app/Models/License.php
index bee51ea1ac..ec85a0968b 100755
--- a/app/Models/License.php
+++ b/app/Models/License.php
@@ -59,6 +59,18 @@ class License extends Depreciable implements Importable
*/
public const PRODUCT_KEY_MASK = '------------';
+ /**
+ * Mask the product key on read when the current user does not hold
+ * the licenses.keys gate.
+ */
+ protected function serial(): Attribute
+ {
+ return Attribute::get(fn($value) => $value !== null && !Gate::allows('viewKeys', $this)
+ ? self::PRODUCT_KEY_MASK
+ : $value
+ );
+ }
+
protected $casts = [
'purchase_date' => 'date',
'expiration_date' => 'date',
diff --git a/app/Models/User.php b/app/Models/User.php
index 881aabe1ad..2b3b308d12 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -438,7 +438,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
$normalized = strtolower(trim($filterValue));
$trueTokens = ['1', 'true', 'yes'];
$falseTokens = ['0', 'false', 'no'];
- if (!in_array($normalized, array_merge($trueTokens, $falseTokens), true)) {
+ if (! in_array($normalized, array_merge($trueTokens, $falseTokens), true)) {
return null;
}
$wantMatch = in_array($normalized, $trueTokens, true);
@@ -512,24 +512,24 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
$outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
$query->{$outerBoolean}(function ($nested) use ($pivot, $ids, $includeNull) {
- if (!empty($ids)) {
+ if (! empty($ids)) {
$nested->whereIn('users.id', function ($q) use ($pivot, $ids) {
$q->from($pivot['table'])
- ->whereIn($pivot['table'] . '.' . $pivot['column'], $ids)
- ->select($pivot['table'] . '.user_id');
+ ->whereIn($pivot['table'].'.'.$pivot['column'], $ids)
+ ->select($pivot['table'].'.user_id');
});
}
if ($includeNull) {
$nullMatcher = function ($q) use ($pivot) {
$q->whereNotIn('users.id', function ($sub) use ($pivot) {
- $sub->from($pivot['table'])->select($pivot['table'] . '.user_id');
+ $sub->from($pivot['table'])->select($pivot['table'].'.user_id');
});
};
if (empty($ids)) {
$nullMatcher($nested);
} else {
$nested->orWhereNotIn('users.id', function ($sub) use ($pivot) {
- $sub->from($pivot['table'])->select($pivot['table'] . '.user_id');
+ $sub->from($pivot['table'])->select($pivot['table'].'.user_id');
});
}
}
@@ -539,32 +539,32 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
}
$countBranches = [
- 'assets_count' => fn() => \App\Models\Asset::query()
+ 'assets_count' => fn () => \App\Models\Asset::query()
->whereColumn('assets.assigned_to', 'users.id')
->where('assets.assigned_type', self::class)
->whereNull('assets.deleted_at')
->selectRaw('COUNT(*)'),
- 'accessories_count' => fn() => \Illuminate\Support\Facades\DB::table('accessories_checkout')
+ 'accessories_count' => fn () => \Illuminate\Support\Facades\DB::table('accessories_checkout')
->whereColumn('accessories_checkout.assigned_to', 'users.id')
->where('accessories_checkout.assigned_type', self::class)
->selectRaw('COUNT(*)'),
- 'consumables_count' => fn() => \Illuminate\Support\Facades\DB::table('consumables_users')
+ 'consumables_count' => fn () => \Illuminate\Support\Facades\DB::table('consumables_users')
->whereColumn('consumables_users.assigned_to', 'users.id')
->selectRaw('COUNT(*)'),
- 'licenses_count' => fn() => \Illuminate\Support\Facades\DB::table('license_seats')
+ 'licenses_count' => fn () => \Illuminate\Support\Facades\DB::table('license_seats')
->whereColumn('license_seats.assigned_to', 'users.id')
->selectRaw('COUNT(*)'),
- 'manages_users_count' => fn() => \Illuminate\Support\Facades\DB::table('users as managed_users')
+ 'manages_users_count' => fn () => \Illuminate\Support\Facades\DB::table('users as managed_users')
->whereColumn('managed_users.manager_id', 'users.id')
->whereNull('managed_users.deleted_at')
->selectRaw('COUNT(*)'),
- 'manages_locations_count' => fn() => \Illuminate\Support\Facades\DB::table('locations')
+ 'manages_locations_count' => fn () => \Illuminate\Support\Facades\DB::table('locations')
->whereColumn('locations.manager_id', 'users.id')
->whereNull('locations.deleted_at')
->selectRaw('COUNT(*)'),
];
- if (!array_key_exists($filterKey, $countBranches)) {
+ if (! array_key_exists($filterKey, $countBranches)) {
return null;
}
@@ -943,6 +943,30 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
return $this->checkPermissionSection($section);
}
+ /**
+ * True when the user carries an explicit "-1" on the given
+ * permission section at the user level. Group permissions do not
+ * express "deny", only "grant", so an explicit user-level "-1" is
+ * the only way an operator can shut off a specific action for an
+ * account. Callers that treat a deny as absolute (beating implicit
+ * grants that would otherwise return true via related permissions)
+ * use this to short-circuit before the normal has-access check.
+ */
+ public function isPermissionExplicitlyDenied(string $section): bool
+ {
+ if (! is_string($this->permissions) || $this->permissions === '') {
+ return false;
+ }
+
+ $permissions = json_decode($this->permissions, true);
+
+ if (! is_array($permissions)) {
+ return false;
+ }
+
+ return ($permissions[$section] ?? null) === '-1';
+ }
+
/**
* Checks if the user is a SuperUser
*
diff --git a/app/Policies/LicensePolicy.php b/app/Policies/LicensePolicy.php
index 8258a1a441..79007edbcb 100644
--- a/app/Policies/LicensePolicy.php
+++ b/app/Policies/LicensePolicy.php
@@ -28,6 +28,13 @@ class LicensePolicy extends CheckoutablePermissionsPolicy
*/
public function viewKeys(User $user, ?License $license = null)
{
+ // An explicit "-1" on licenses.keys is an absolute deny that
+ // beats the implicit grants from licenses.create and
+ // licenses.edit below.
+ if ($user->isPermissionExplicitlyDenied('licenses.keys')) {
+ return false;
+ }
+
if ($user->hasAccess('licenses.keys') || $user->hasAccess('licenses.create') || $user->hasAccess('licenses.edit')) {
return true;
}
diff --git a/resources/views/mail/markdown/checkin-license.blade.php b/resources/views/mail/markdown/checkin-license.blade.php
index 2c1c91a50c..dd21f5b37a 100644
--- a/resources/views/mail/markdown/checkin-license.blade.php
+++ b/resources/views/mail/markdown/checkin-license.blade.php
@@ -10,8 +10,8 @@
@if (isset($license->manufacturer))
| **{{ trans('general.manufacturer') }}** | {{ $license->manufacturer->name }} |
@endif
-@if (($target instanceof \App\Models\User && $target->can('view', $license)) ||($target instanceof \App\Models\Asset && $license_seat->user?->can('view', $license)))
-| **Key** | {{ $license->serial }} |
+@if (($target instanceof \App\Models\User && Gate::forUser($target)->allows('viewKeys', $license)) || ($target instanceof \App\Models\Asset && $license_seat->user && Gate::forUser($license_seat->user)->allows('viewKeys', $license)))
+| **Key** | {{ $license->getRawOriginal('serial') }} |
@endif
@if (isset($item->category))
| **{{ trans('general.category') }}** | {{ $license->category->name }} |
diff --git a/resources/views/mail/markdown/checkout-license.blade.php b/resources/views/mail/markdown/checkout-license.blade.php
index 4467ad8296..2da9b3cd8f 100644
--- a/resources/views/mail/markdown/checkout-license.blade.php
+++ b/resources/views/mail/markdown/checkout-license.blade.php
@@ -1,5 +1,5 @@
@component('mail::message')
-# {{ trans('mail.hello').' '.$target.','}}
+# {{ trans('mail.hello').' '.$target->display_name.','}}
{{ $introduction_line }}
@@ -16,8 +16,8 @@
@if (isset($license->category))
| **{{ trans('general.category') }}** | {{ $license->category->name }} |
@endif
-@if (($target instanceof \App\Models\User && $target->can('view', $license)) || ($target instanceof \App\Models\Asset && $license_seat->user?->can('view', $license)))
-| **Key** | {{ $license->serial }} |
+@if (($target instanceof \App\Models\User && Gate::forUser($target)->allows('viewKeys', $license)) || ($target instanceof \App\Models\Asset && $license_seat->user && Gate::forUser($license_seat->user)->allows('viewKeys', $license)))
+| **Key** | {{ $license->getRawOriginal('serial') }} |
@endif
@if ($note)
| **{{ trans('mail.additional_notes') }}** | {{ $note }} |
diff --git a/tests/Feature/Licenses/Api/LicenseHistoryKeyMaskTest.php b/tests/Feature/Licenses/Api/LicenseHistoryKeyMaskTest.php
new file mode 100644
index 0000000000..ffd6bce01c
--- /dev/null
+++ b/tests/Feature/Licenses/Api/LicenseHistoryKeyMaskTest.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace Tests\Feature\Licenses\Api;
+
+use App\Models\License;
+use App\Models\User;
+use Tests\TestCase;
+
+class LicenseHistoryKeyMaskTest extends TestCase
+{
+ public function test_license_history_api_masks_old_and_new_serial_for_viewer_without_viewkeys(): void
+ {
+ $old = 'HISTORY-OLD-KEY-777';
+ $new = 'HISTORY-NEW-KEY-888';
+
+ $license = License::factory()->create(['serial' => $old]);
+ $license->serial = $new;
+ $license->save();
+
+ $viewer = User::factory()->viewLicenses()->create();
+
+ $response = $this->actingAsForApi($viewer)
+ ->getJson(route('api.licenses.history', ['license' => $license->id]))
+ ->assertOk();
+
+ $body = $response->getContent();
+
+ $this->assertStringNotContainsString($old, $body);
+ $this->assertStringNotContainsString($new, $body);
+ $this->assertStringContainsString(License::PRODUCT_KEY_MASK, $body);
+ }
+
+ public function test_license_history_api_shows_real_serial_for_viewkeys_holder(): void
+ {
+ $old = 'HISTORY-REAL-OLD-111';
+ $new = 'HISTORY-REAL-NEW-222';
+
+ $license = License::factory()->create(['serial' => $old]);
+ $license->serial = $new;
+ $license->save();
+
+ $viewer = User::factory()->viewLicenses()->viewKeysLicenses()->create();
+
+ $response = $this->actingAsForApi($viewer)
+ ->getJson(route('api.licenses.history', ['license' => $license->id]))
+ ->assertOk();
+
+ $body = $response->getContent();
+
+ $this->assertStringContainsString($old, $body);
+ $this->assertStringContainsString($new, $body);
+ }
+}
diff --git a/tests/Feature/Licenses/Api/LicenseIndexSerialMaskTest.php b/tests/Feature/Licenses/Api/LicenseIndexSerialMaskTest.php
new file mode 100644
index 0000000000..7ac4bdc871
--- /dev/null
+++ b/tests/Feature/Licenses/Api/LicenseIndexSerialMaskTest.php
@@ -0,0 +1,74 @@
+<?php
+
+namespace Tests\Feature\Licenses\Api;
+
+use App\Models\License;
+use App\Models\User;
+use Tests\TestCase;
+
+class LicenseIndexSerialMaskTest extends TestCase
+{
+ public function test_license_index_api_masks_product_key_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create([
+ 'name' => 'IndexApiLic-'.now()->timestamp,
+ 'serial' => 'INDEX-API-SECRET-999',
+ ]);
+
+ $viewer = User::factory()->viewLicenses()->create();
+
+ $this->actingAsForApi($viewer)
+ ->getJson(route('api.licenses.index', ['search' => $license->name]))
+ ->assertOk()
+ ->assertJsonFragment(['product_key' => License::PRODUCT_KEY_MASK])
+ ->assertJsonMissing(['product_key' => 'INDEX-API-SECRET-999']);
+ }
+
+ public function test_license_index_api_returns_real_product_key_for_viewkeys_holder(): void
+ {
+ $license = License::factory()->create([
+ 'name' => 'IndexApiLic-'.now()->timestamp,
+ 'serial' => 'INDEX-API-REAL-888',
+ ]);
+
+ $viewer = User::factory()->viewLicenses()->viewKeysLicenses()->create();
+
+ $this->actingAsForApi($viewer)
+ ->getJson(route('api.licenses.index', ['search' => $license->name]))
+ ->assertOk()
+ ->assertJsonFragment(['product_key' => 'INDEX-API-REAL-888']);
+ }
+
+ public function test_explicit_deny_on_licenses_keys_beats_implicit_grant_from_create_or_edit(): void
+ {
+ // viewKeys policy allows licenses.keys OR licenses.create OR
+ // licenses.edit by default (so the admin who created the
+ // license can still see the key to edit it). An operator who
+ // sets licenses.keys to -1 is explicitly revoking that
+ // visibility, and the deny must beat the implicit grant.
+ $license = License::factory()->create([
+ 'name' => 'IndexApiLic-'.now()->timestamp,
+ 'serial' => 'EXPLICIT-DENY-SECRET-444',
+ ]);
+
+ $viewer = User::factory()
+ ->viewLicenses()
+ ->state(fn ($state) => [
+ 'permissions' => json_encode(array_merge(
+ json_decode($state['permissions'], true),
+ [
+ 'licenses.create' => '1',
+ 'licenses.edit' => '1',
+ 'licenses.keys' => '-1',
+ ],
+ )),
+ ])
+ ->create();
+
+ $this->actingAsForApi($viewer)
+ ->getJson(route('api.licenses.index', ['search' => $license->name]))
+ ->assertOk()
+ ->assertJsonFragment(['product_key' => License::PRODUCT_KEY_MASK])
+ ->assertJsonMissing(['product_key' => 'EXPLICIT-DENY-SECRET-444']);
+ }
+}
diff --git a/tests/Feature/Licenses/LicenseKeyMaskingSweepTest.php b/tests/Feature/Licenses/LicenseKeyMaskingSweepTest.php
new file mode 100644
index 0000000000..91b24d461d
--- /dev/null
+++ b/tests/Feature/Licenses/LicenseKeyMaskingSweepTest.php
@@ -0,0 +1,137 @@
+<?php
+
+namespace Tests\Feature\Licenses;
+
+use App\Models\Asset;
+use App\Models\License;
+use App\Models\LicenseSeat;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * Covers every surface that displays a license product key, asserting
+ * the mask lands for a viewer without licenses.keys. The accessor
+ * on License::serial is the backstop. These tests pin the behavior
+ * at each sink so a future refactor of a sink (new transformer, new
+ * blade partial, new CSV writer) cannot silently drop the mask.
+ */
+class LicenseKeyMaskingSweepTest extends TestCase
+{
+ public function test_api_show_masks_product_key_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'SHOW-API-SECRET-111']);
+
+ $this->actingAsForApi(User::factory()->viewLicenses()->create())
+ ->getJson(route('api.licenses.show', ['license_id' => $license->id]))
+ ->assertOk()
+ ->assertJsonFragment(['product_key' => License::PRODUCT_KEY_MASK])
+ ->assertJsonMissing(['product_key' => 'SHOW-API-SECRET-111']);
+ }
+
+ public function test_api_user_licenselist_masks_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'USERLIST-SECRET-222']);
+ $recipient = User::factory()->create();
+ LicenseSeat::factory()->create([
+ 'license_id' => $license->id,
+ 'assigned_to' => $recipient->id,
+ ]);
+
+ $body = $this->actingAsForApi(User::factory()->viewLicenses()->viewUsers()->create())
+ ->getJson(route('api.users.licenselist', ['user' => $recipient->id]))
+ ->assertOk()
+ ->getContent();
+
+ $this->assertStringNotContainsString('USERLIST-SECRET-222', $body);
+ }
+
+ public function test_api_asset_licenselist_masks_product_key_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'ASSETLIST-SECRET-333']);
+ $asset = Asset::factory()->create();
+ LicenseSeat::factory()->create([
+ 'license_id' => $license->id,
+ 'assigned_to' => $asset->id,
+ 'asset_id' => $asset->id,
+ ]);
+
+ $body = $this->actingAsForApi(User::factory()->viewAssets()->viewLicenses()->create())
+ ->getJson(route('api.assets.licenselist', ['asset' => $asset->id]))
+ ->assertOk()
+ ->getContent();
+
+ $this->assertStringNotContainsString('ASSETLIST-SECRET-333', $body);
+ }
+
+ public function test_license_checkout_form_masks_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKOUT-FORM-SECRET-444']);
+ LicenseSeat::factory()->create(['license_id' => $license->id]);
+
+ $this->actingAs(User::factory()->viewLicenses()->checkoutLicenses()->create())
+ ->get(route('licenses.checkout', ['license' => $license->id]))
+ ->assertOk()
+ ->assertDontSee('CHECKOUT-FORM-SECRET-444');
+ }
+
+ public function test_license_checkin_form_masks_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKIN-FORM-SECRET-555']);
+ $seat = LicenseSeat::factory()->create([
+ 'license_id' => $license->id,
+ 'assigned_to' => User::factory()->create()->id,
+ ]);
+
+ $this->actingAs(User::factory()->viewLicenses()->checkinLicenses()->create())
+ ->get(route('licenses.checkin', ['licenseSeat' => $seat->id]))
+ ->assertOk()
+ ->assertDontSee('CHECKIN-FORM-SECRET-555');
+ }
+
+ public function test_user_print_page_masks_license_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'USER-PRINT-SECRET-666']);
+ $recipient = User::factory()->create();
+ LicenseSeat::factory()->create([
+ 'license_id' => $license->id,
+ 'assigned_to' => $recipient->id,
+ ]);
+
+ $this->actingAs(User::factory()->viewUsers()->viewLicenses()->create())
+ ->get(route('users.print', ['userId' => $recipient->id]))
+ ->assertOk()
+ ->assertDontSee('USER-PRINT-SECRET-666');
+ }
+
+ public function test_licenses_csv_download_masks_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create([
+ 'name' => 'CsvDownloadLic-'.now()->timestamp,
+ 'serial' => 'LICENSES-CSV-SECRET-777',
+ ]);
+
+ $response = $this->actingAs(User::factory()->viewLicenses()->create())
+ ->get(route('licenses.export'))
+ ->assertOk();
+
+ $body = $response->streamedContent();
+ $this->assertStringContainsString($license->name, $body);
+ $this->assertStringNotContainsString('LICENSES-CSV-SECRET-777', $body);
+ $this->assertStringContainsString(License::PRODUCT_KEY_MASK, $body);
+ }
+
+ public function test_reports_export_licenses_csv_masks_serial_for_viewer_without_viewkeys(): void
+ {
+ $license = License::factory()->create([
+ 'name' => 'ReportLic-'.now()->timestamp,
+ 'serial' => 'REPORTS-LICENSES-SECRET-888',
+ ]);
+
+ $response = $this->actingAs(User::factory()->canViewReports()->viewLicenses()->create())
+ ->get(url('reports/export/licenses'))
+ ->assertOk();
+
+ $body = $response->streamedContent();
+ $this->assertStringNotContainsString('REPORTS-LICENSES-SECRET-888', $body);
+ }
+}
diff --git a/tests/Feature/Licenses/LicenseMailKeyVisibilityTest.php b/tests/Feature/Licenses/LicenseMailKeyVisibilityTest.php
new file mode 100644
index 0000000000..4df6f822b0
--- /dev/null
+++ b/tests/Feature/Licenses/LicenseMailKeyVisibilityTest.php
@@ -0,0 +1,121 @@
+<?php
+
+namespace Tests\Feature\Licenses;
+
+use App\Mail\CheckinLicenseMail;
+use App\Mail\CheckoutLicenseMail;
+use App\Models\License;
+use App\Models\LicenseSeat;
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * Render-time coverage for the license checkin / checkout mail
+ * bodies. The Key row only renders when the recipient user holds
+ * licenses.keys. Omitted entirely for recipients the admin has
+ * deliberately denied, matching the policy that an explicit deny
+ * beats implicit grants from create / edit. These tests pin the
+ * blade conditional so a future redesign of the mail layout cannot
+ * silently reintroduce the raw key for a denied recipient.
+ */
+class LicenseMailKeyVisibilityTest extends TestCase
+{
+ public function test_checkin_mail_body_includes_raw_key_for_recipient_with_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKIN-MAIL-RAW-111']);
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()->viewLicenses()->viewKeysLicenses()->create();
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckinLicenseMail($seat, $recipient, $admin, ''))->render();
+
+ $this->assertStringContainsString('CHECKIN-MAIL-RAW-111', $html);
+ }
+
+ public function test_checkin_mail_body_omits_key_row_for_recipient_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKIN-MAIL-SECRET-222']);
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()->viewLicenses()->create();
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckinLicenseMail($seat, $recipient, $admin, ''))->render();
+
+ $this->assertStringNotContainsString('CHECKIN-MAIL-SECRET-222', $html);
+ $this->assertStringNotContainsString(License::PRODUCT_KEY_MASK, $html);
+ }
+
+ public function test_checkin_mail_body_omits_key_row_when_recipient_has_create_or_edit_but_explicit_deny_on_keys(): void
+ {
+ // Mirrors the real-world shape caught during the GHSA
+ // review. A recipient granted licenses.create and
+ // licenses.edit still has keys explicitly denied, and the
+ // mail must respect that deny.
+ $license = License::factory()->create(['serial' => 'CHECKIN-MAIL-DENY-333']);
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()
+ ->viewLicenses()
+ ->state(fn ($state) => [
+ 'permissions' => json_encode(array_merge(
+ json_decode($state['permissions'], true),
+ [
+ 'licenses.create' => '1',
+ 'licenses.edit' => '1',
+ 'licenses.keys' => '-1',
+ ],
+ )),
+ ])
+ ->create();
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckinLicenseMail($seat, $recipient, $admin, ''))->render();
+
+ $this->assertStringNotContainsString('CHECKIN-MAIL-DENY-333', $html);
+ }
+
+ public function test_checkout_mail_body_includes_raw_key_for_recipient_with_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKOUT-MAIL-RAW-444']);
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()->viewLicenses()->viewKeysLicenses()->create();
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckoutLicenseMail($seat, $recipient, $admin, null, '', true))->render();
+
+ $this->assertStringContainsString('CHECKOUT-MAIL-RAW-444', $html);
+ }
+
+ public function test_checkout_mail_body_omits_key_row_for_recipient_without_viewkeys(): void
+ {
+ $license = License::factory()->create(['serial' => 'CHECKOUT-MAIL-SECRET-555']);
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()->viewLicenses()->create();
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckoutLicenseMail($seat, $recipient, $admin, null, '', true))->render();
+
+ $this->assertStringNotContainsString('CHECKOUT-MAIL-SECRET-555', $html);
+ $this->assertStringNotContainsString(License::PRODUCT_KEY_MASK, $html);
+ }
+
+ public function test_checkout_mail_greeting_still_renders_recipient_display_name(): void
+ {
+ // Regression guard. The previous CheckoutLicenseMail
+ // constructor stringified $target to display_name so the
+ // greeting could do '# Hello '.$target.','. Preserving the
+ // User instance for the Key gate requires the blade to read
+ // $target->display_name instead. This test pins that the
+ // greeting still renders without a type coercion error.
+ $license = License::factory()->create();
+ $seat = LicenseSeat::factory()->create(['license_id' => $license->id]);
+ $recipient = User::factory()->create([
+ 'first_name' => 'Mail',
+ 'last_name' => 'Recipient',
+ ]);
+ $admin = User::factory()->admin()->create();
+
+ $html = (new CheckoutLicenseMail($seat, $recipient, $admin, null, '', true))->render();
+
+ $this->assertStringContainsString($recipient->display_name, $html);
+ }
+}
diff --git a/tests/Feature/Reporting/ActivityReportCsvExportTest.php b/tests/Feature/Reporting/ActivityReportCsvExportTest.php
index af4a50c97e..3fe42b80ff 100644
--- a/tests/Feature/Reporting/ActivityReportCsvExportTest.php
+++ b/tests/Feature/Reporting/ActivityReportCsvExportTest.php
@@ -5,6 +5,7 @@ namespace Tests\Feature\Reporting;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\Component;
+use App\Models\License;
use App\Models\User;
use Tests\TestCase;
@@ -75,6 +76,91 @@ class ActivityReportCsvExportTest extends TestCase
$this->assertStringNotContainsString('ASSET_ROW_SENTINEL', $body);
}
+ public function test_activity_csv_masks_license_serial_and_log_meta_for_viewer_without_viewkeys()
+ {
+ // Regression for GHSA-qp3v-6792-5cpq. The CSV writer previously
+ // emitted the raw action_logs.log_meta JSON into the Changed
+ // column. LicenseObserver records every changed license
+ // attribute including serial, so an edit left old / new product
+ // keys in the row even when the serial column itself was masked.
+ $oldKey = 'OLD-REAL-KEY-AAA111';
+ $newKey = 'NEW-REAL-KEY-BBB222';
+
+ $license = License::factory()->create([
+ 'name' => 'Real License',
+ 'serial' => $oldKey,
+ ]);
+
+ $license->serial = $newKey;
+ $license->save();
+
+ $this->assertDatabaseHas('action_logs', [
+ 'item_type' => License::class,
+ 'item_id' => $license->id,
+ 'action_type' => 'update',
+ ]);
+
+ $csv = $this->actingAs(User::factory()->canViewReports()->viewLicenses()->create())
+ ->post(route('reports.activity.post'))
+ ->assertOk()
+ ->streamedContent();
+
+ // Mask on the item.serial column AND inside the log_meta blob,
+ // both of which previously leaked the raw product key.
+ $this->assertStringNotContainsString($oldKey, $csv);
+ $this->assertStringNotContainsString($newKey, $csv);
+ $this->assertStringContainsString(License::PRODUCT_KEY_MASK, $csv);
+ }
+
+ public function test_activity_csv_shows_license_serial_and_log_meta_for_viewkeys_holder()
+ {
+ // Permitted viewers still see the real product keys so audit
+ // history stays reconstructable. The accessors only mask on
+ // the gate check failing, raw values stay in the DB regardless.
+ $oldKey = 'OLD-REAL-KEY-CCC333';
+ $newKey = 'NEW-REAL-KEY-DDD444';
+
+ $license = License::factory()->create([
+ 'name' => 'Real License',
+ 'serial' => $oldKey,
+ ]);
+
+ $license->serial = $newKey;
+ $license->save();
+
+ $csv = $this->actingAs(User::factory()->canViewReports()->viewLicenses()->viewKeysLicenses()->create())
+ ->post(route('reports.activity.post'))
+ ->assertOk()
+ ->streamedContent();
+
+ $this->assertStringContainsString($oldKey, $csv);
+ $this->assertStringContainsString($newKey, $csv);
+ }
+
+ public function test_action_log_raw_db_still_contains_license_keys_after_masking_fix()
+ {
+ // Audit integrity check. The accessors mask on read only.
+ // getRawOriginal and the underlying column must still carry
+ // the real values so a permitted viewer can reconstruct the
+ // audit trail and so a key-rotation audit remains possible.
+ $oldKey = 'OLD-REAL-KEY-EEE555';
+ $newKey = 'NEW-REAL-KEY-FFF666';
+
+ $license = License::factory()->create(['serial' => $oldKey]);
+ $license->serial = $newKey;
+ $license->save();
+
+ $row = \DB::table('action_logs')
+ ->where('item_type', License::class)
+ ->where('item_id', $license->id)
+ ->where('action_type', 'update')
+ ->first();
+
+ $this->assertNotNull($row);
+ $this->assertStringContainsString($oldKey, $row->log_meta);
+ $this->assertStringContainsString($newKey, $row->log_meta);
+ }
+
public function test_reports_view_holder_csv_export_contains_every_type()
{
// reports.view holders keep the full unfiltered CSV. Guard