Skip to content

A free open source IT asset/license management system

Log group changes in SCIM

snipefe69c4ec2f49
diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.php
index 8730e9a9c9..92aed607f1 100644
--- a/app/Console/Commands/LdapSync.php
+++ b/app/Console/Commands/LdapSync.php
@@ -404,6 +404,7 @@ class LdapSync extends Command
// Check if the relationship already exists
if (! $user->groups()->where('group_id', $ldap_default_group)->exists()) {
$user->groups()->attach($ldap_default_group);
+ $user->logGroupAttached((int) $ldap_default_group);
}
}
diff --git a/app/Http/Controllers/Api/UsersController.php b/app/Http/Controllers/Api/UsersController.php
index 2f4aba2667..4e8f2b18e7 100644
--- a/app/Http/Controllers/Api/UsersController.php
+++ b/app/Http/Controllers/Api/UsersController.php
@@ -563,7 +563,7 @@ class UsersController extends Controller
}
if (($request->has('groups')) && (auth()->user()->isSuperUser())) {
- $user->groups()->sync($request->input('groups'));
+ $user->syncGroupsWithLogging((array) $request->input('groups'));
}
$user->syncCompaniesWithLogging($permittedCompanyIds);
@@ -736,7 +736,7 @@ class UsersController extends Controller
}
// Sync the groups since the user is a superuser and the groups pass validation
- $user->groups()->sync($request->input('groups'));
+ $user->syncGroupsWithLogging((array) $request->input('groups'));
}
// company_ids (new format) = full replacement sync, with
diff --git a/app/Http/Controllers/Users/BulkUsersController.php b/app/Http/Controllers/Users/BulkUsersController.php
index 572a70af95..1d4bebbff6 100644
--- a/app/Http/Controllers/Users/BulkUsersController.php
+++ b/app/Http/Controllers/Users/BulkUsersController.php
@@ -342,7 +342,7 @@ class BulkUsersController extends Controller
}
if ($canEditAuth && $request->filled('groups') && auth()->user()->isSuperUser()) {
- $user->groups()->sync($request->input('groups'));
+ $user->syncGroupsWithLogging((array) $request->input('groups'));
}
}
diff --git a/app/Http/Controllers/Users/UsersController.php b/app/Http/Controllers/Users/UsersController.php
index c3e00405de..15386adf35 100755
--- a/app/Http/Controllers/Users/UsersController.php
+++ b/app/Http/Controllers/Users/UsersController.php
@@ -178,7 +178,7 @@ class UsersController extends Controller
}
if (auth()->user()->isSuperUser() && auth()->user()->can('editableOnDemo')) {
- $user->groups()->sync($request->input('groups'));
+ $user->syncGroupsWithLogging((array) $request->input('groups'));
}
return Helper::getRedirectOption($request, $user->id, 'Users')
@@ -334,10 +334,11 @@ class UsersController extends Controller
));
}
- // Only save groups if the user is a superuser
- if (auth()->user()->isSuperUser()) {
- $user->groups()->sync($request->input('groups'));
- }
+ // Group sync lives in the post-save block below so
+ // UserObserver::updating() has already written its
+ // Actionlog row for this edit session, and
+ // syncGroupsWithLogging() can merge the group diff into
+ // that same row instead of producing two log entries.
}
// Update the location of any assets checked out to this user
@@ -352,6 +353,12 @@ class UsersController extends Controller
if ($user->save()) {
$user->syncCompaniesPreservingInvisibleTo(auth()->user(), $companyIds);
+ if (auth()->user()->isSuperUser()
+ && auth()->user()->can('canEditAuthFields', $user)
+ && auth()->user()->can('editableOnDemo')) {
+ $user->syncGroupsWithLogging((array) $request->input('groups'));
+ }
+
// Redirect to the user page
return Helper::getRedirectOption($request, $user->id, 'Users')
->with('success', trans('admin/users/message.success.update'));
diff --git a/app/Http/Transformers/ActionlogsTransformer.php b/app/Http/Transformers/ActionlogsTransformer.php
index c763a571d0..158a4744e0 100644
--- a/app/Http/Transformers/ActionlogsTransformer.php
+++ b/app/Http/Transformers/ActionlogsTransformer.php
@@ -398,6 +398,33 @@ class ActionlogsTransformer
$clean_meta[trans('general.companies')] = $clean_meta['companies'];
unset($clean_meta['companies']);
}
+ if (array_key_exists('groups', $clean_meta)) {
+ // groups meta is a list of {id, name} snapshots taken at
+ // write time. The name is the load-bearing bit: it
+ // preserves what the group was called at the moment the
+ // change happened, so a later rename or delete doesn't
+ // rewrite history. clean_field() ran e(json_encode()) on
+ // the arrays, so we have to htmlspecialchars_decode the
+ // JSON string before json_decode can read the escaped
+ // quotes back. The companies handler above sidesteps this
+ // because its ids are plain integers with no quoted
+ // strings inside the JSON.
+ $renderGroupSnapshot = function ($rawValue): string {
+ $entries = json_decode(htmlspecialchars_decode((string) $rawValue, ENT_QUOTES), true);
+ if (empty($entries) || ! is_array($entries)) {
+ return trans('general.unassigned');
+ }
+
+ return collect($entries)
+ ->map(fn ($entry) => is_array($entry) && isset($entry['name']) ? e($entry['name']) : trans('general.deleted'))
+ ->join(', ');
+ };
+
+ $clean_meta['groups']['old'] = $renderGroupSnapshot($clean_meta['groups']['old']);
+ $clean_meta['groups']['new'] = $renderGroupSnapshot($clean_meta['groups']['new']);
+ $clean_meta[trans('general.groups')] = $clean_meta['groups'];
+ unset($clean_meta['groups']);
+ }
if (array_key_exists('supplier_id', $clean_meta)) {
$oldSupplier = $supplier->find($clean_meta['supplier_id']['old']);
diff --git a/app/Models/SnipeSCIMConfig.php b/app/Models/SnipeSCIMConfig.php
index 68410bf3d6..d09325ba85 100644
--- a/app/Models/SnipeSCIMConfig.php
+++ b/app/Models/SnipeSCIMConfig.php
@@ -315,7 +315,117 @@ class SnipeMutableCollection extends MutableCollection
request()->attributes->set('scim_in_flight_resource', $object);
}
+ // Snapshot ONLY the user ids referenced in the SCIM payload,
+ // not the whole membership, so a PATCH against a group with
+ // 50k members doesn't load 50k rows just to log a single-add.
+ // See PatchGroupMembersTest for the shape guard.
+ $requestedUserIds = $this->userIdsFromMemberPayload($value);
+ $previouslyAttachedIds = $this->pivotFilterToAttached($object, $requestedUserIds);
+
parent::add($value, $object);
+
+ $this->logGroupMembershipChangesForIds(
+ $object,
+ attachedIds: array_values(array_diff($requestedUserIds, $previouslyAttachedIds)),
+ detachedIds: [],
+ );
+ }
+
+ public function remove($value, Model &$object, ?Path $path = null)
+ {
+ // Two shapes: filter-path form ("members[value eq 5]") targets
+ // one user id, list-value form targets an explicit list. Both
+ // reduce to a small requestedUserIds set that we pre-check
+ // against the pivot so we log only real detachments.
+ if ($path?->getValuePathFilter()?->getComparisonExpression() !== null) {
+ $requestedUserIds = [(int) $path->getValuePathFilter()->getComparisonExpression()->compareValue];
+ } else {
+ $requestedUserIds = $this->userIdsFromMemberPayload($value);
+ }
+ $previouslyAttachedIds = $this->pivotFilterToAttached($object, $requestedUserIds);
+
+ parent::remove($value, $object, $path);
+
+ $this->logGroupMembershipChangesForIds(
+ $object,
+ attachedIds: [],
+ detachedIds: $previouslyAttachedIds,
+ );
+ }
+
+ /**
+ * Flatten the SCIM `members` payload down to a plain list of
+ * integer user ids. Skips entries missing a `value` field so the
+ * validation error in add() stays the one thrown by the guard
+ * above, not a silent misclassification here.
+ *
+ * @return array<int, int>
+ */
+ private function userIdsFromMemberPayload($value): array
+ {
+ $ids = [];
+ foreach ((array) $value as $entry) {
+ if (is_array($entry) && isset($entry['value'])) {
+ $ids[] = (int) $entry['value'];
+ }
+ }
+
+ return array_values(array_unique($ids));
+ }
+
+ /**
+ * Return the subset of $requestedUserIds that are currently on
+ * the pivot for this group. Cheap: one indexed lookup on
+ * (group_id, user_id in (…)) instead of a full-membership scan.
+ *
+ * Returns [] when the parent relation is not user-shaped
+ * (defensive guard for future MutableCollection usage against
+ * non-Group parents).
+ *
+ * @param array<int, int> $requestedUserIds
+ * @return array<int, int>
+ */
+ private function pivotFilterToAttached(Model $object, array $requestedUserIds): array
+ {
+ if (! ($object instanceof Group || $object instanceof SCIMGroup) || $requestedUserIds === []) {
+ return [];
+ }
+
+ return $object->users()
+ ->whereIn('users.id', $requestedUserIds)
+ ->pluck('users.id')
+ ->map(fn ($id) => (int) $id)
+ ->all();
+ }
+
+ /**
+ * Write per-user Actionlogs for the attach / detach delta the
+ * caller computed. Delegates to User::logGroupAttached() /
+ * logGroupDetached() so the log_meta shape matches
+ * User::syncGroupsWithLogging(), letting the history UI render
+ * SCIM-driven changes with the same formatter as Web / API edits.
+ *
+ * @param array<int, int> $attachedIds
+ * @param array<int, int> $detachedIds
+ */
+ private function logGroupMembershipChangesForIds(Model $object, array $attachedIds, array $detachedIds): void
+ {
+ if (! ($object instanceof Group || $object instanceof SCIMGroup)) {
+ return;
+ }
+
+ foreach ($attachedIds as $userId) {
+ $user = User::find($userId);
+ if ($user !== null) {
+ $user->logGroupAttached((int) $object->id);
+ }
+ }
+ foreach ($detachedIds as $userId) {
+ $user = User::find($userId);
+ if ($user !== null) {
+ $user->logGroupDetached((int) $object->id);
+ }
+ }
}
}
diff --git a/app/Models/User.php b/app/Models/User.php
index 5e98160a5b..14de9742fd 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -836,6 +836,148 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
$logAction->logaction('update');
}
+ /**
+ * Sync group pivot membership and log the change if the set of groups changed.
+ *
+ * Same as syncCompaniesWithLogging(): if UserObserver::updating()
+ * already wrote an Actionlog for this edit session (via
+ * $this->currentUpdateLogId), the group diff is merged into that
+ * existing row so a single edit produces one log entry, not two.
+ * Otherwise a standalone Actionlog is written.
+ */
+ public function syncGroupsWithLogging(array $groupIds): void
+ {
+ // Same defensive coercion as the company version: reduce any
+ // callable payload shape (API JSON, form input, bulk edit,
+ // future LDAP importer) to a flat, unique list of positive int
+ // ids before it hits ->sync(). Prevents "Array to string
+ // conversion" tripping on nested arrays and drops junk shapes
+ // (null, booleans, unparseable strings) silently.
+ $groupIds = array_values(array_unique(array_filter(
+ array_map('intval', array_filter($groupIds, 'is_scalar'))
+ )));
+
+ $oldSnapshot = $this->currentGroupSnapshot();
+ $this->groups()->sync($groupIds);
+ $newSnapshot = $this->currentGroupSnapshot();
+
+ $this->recordGroupsChange($oldSnapshot, $newSnapshot);
+ }
+
+ /**
+ * Log the attachment of a single group to this user. Called from
+ * paths that mutate the pivot without going through
+ * syncGroupsWithLogging() (SCIM SnipeMutableCollection::add(),
+ * LdapSync attaching the LDAP default group, future sync adapters
+ * that propagate group membership).
+ *
+ * The caller has already run ->attach() (or the equivalent). This
+ * method's job is to record the delta if it was a real add. When
+ * the group was already attached before the call, we no-op so
+ * repeat-attach patterns don't produce noise.
+ */
+ public function logGroupAttached(int $groupId): void
+ {
+ $newSnapshot = $this->currentGroupSnapshot();
+ if (! collect($newSnapshot)->contains('id', $groupId)) {
+ // The caller's ->attach() didn't produce a real add (e.g.
+ // duplicate insert silently ignored, race with another
+ // process, group id doesn't exist). Nothing to log.
+ return;
+ }
+
+ $oldSnapshot = array_values(array_filter(
+ $newSnapshot,
+ fn ($entry) => $entry['id'] !== $groupId,
+ ));
+
+ $this->recordGroupsChange($oldSnapshot, $newSnapshot);
+ }
+
+ /**
+ * Log the detachment of a single group. Companion to
+ * logGroupAttached(). Called from SCIM's
+ * SnipeMutableCollection::remove() and any other path that runs
+ * ->detach() on a single group without going through
+ * syncGroupsWithLogging().
+ */
+ public function logGroupDetached(int $groupId): void
+ {
+ $newSnapshot = $this->currentGroupSnapshot();
+ if (collect($newSnapshot)->contains('id', $groupId)) {
+ // Detach didn't remove the group (never was attached, or
+ // still present for some other reason). Nothing to log.
+ return;
+ }
+
+ // Look up the detached group's current name so the log records
+ // it verbatim, not the id alone. If the group row is somehow
+ // gone by the time we look (deleted in the same request),
+ // record the id with a placeholder rather than skipping the
+ // log entirely, so the pivot mutation is still visible.
+ $detached = Group::find($groupId);
+ $oldSnapshot = $newSnapshot;
+ $oldSnapshot[] = ['id' => $groupId, 'name' => $detached?->name ?? ('#'.$groupId)];
+ usort($oldSnapshot, fn ($a, $b) => $a['id'] <=> $b['id']);
+
+ $this->recordGroupsChange($oldSnapshot, $newSnapshot);
+ }
+
+ /**
+ * Current pivot state as an ordered list of {id, name} pairs.
+ * The name is snapshotted at log-write time so the history entry
+ * preserves what the group was called when the change happened,
+ * regardless of later renames or deletes.
+ *
+ * @return array<int, array{id: int, name: string}>
+ */
+ private function currentGroupSnapshot(): array
+ {
+ return $this->groups()
+ ->orderBy('permission_groups.id')
+ ->get(['permission_groups.id', 'permission_groups.name'])
+ ->map(fn ($group) => ['id' => (int) $group->id, 'name' => (string) $group->name])
+ ->all();
+ }
+
+ /**
+ * Write (or merge into) an Actionlog for a groups pivot change.
+ * Merges into $this->currentUpdateLogId when the observer already
+ * opened a log row for this edit session so field + group
+ * changes stay in one log entry. Otherwise writes a standalone
+ * 'update' Actionlog row.
+ *
+ * @param array<int, array{id: int, name: string}> $oldSnapshot
+ * @param array<int, array{id: int, name: string}> $newSnapshot
+ */
+ private function recordGroupsChange(array $oldSnapshot, array $newSnapshot): void
+ {
+ if ($oldSnapshot === $newSnapshot) {
+ return;
+ }
+
+ $groupChange = ['groups' => ['old' => $oldSnapshot, 'new' => $newSnapshot]];
+
+ if ($this->currentUpdateLogId && ($existing = Actionlog::find($this->currentUpdateLogId))) {
+ $meta = json_decode($existing->log_meta ?? '{}', true) ?: [];
+ $existing->log_meta = json_encode(array_merge($meta, $groupChange));
+ $existing->save();
+ $this->currentUpdateLogId = null;
+
+ return;
+ }
+
+ $logAction = new Actionlog;
+ $logAction->item_type = static::class;
+ $logAction->item_id = $this->id;
+ $logAction->target_type = static::class;
+ $logAction->target_id = $this->id;
+ $logAction->created_at = date('Y-m-d H:i:s');
+ $logAction->created_by = auth()->id();
+ $logAction->log_meta = json_encode($groupChange);
+ $logAction->logaction('update');
+ }
+
/**
* FMCS-safe wrapper around syncCompaniesWithLogging() for the user
* update path. Folds the target's memberships in companies the
diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php
index d7ec6bb2ba..a3418783fe 100644
--- a/app/Observers/UserObserver.php
+++ b/app/Observers/UserObserver.php
@@ -15,9 +15,13 @@ class UserObserver
public function updating(User $user)
{
- // ONLY allow these fields to be stored
- // NOTE: company_id is intentionally excluded — company membership changes are logged
- // via User::syncCompaniesWithLogging() against the pivot table instead.
+ // ONLY allow these fields to be stored.
+ // NOTE: company_id and permission-group pivot changes are intentionally
+ // excluded here. Company membership is logged via
+ // User::syncCompaniesWithLogging(). Permission-group membership is
+ // logged via User::syncGroupsWithLogging(). Both helpers merge their
+ // diff into this row via $user->currentUpdateLogId when the group
+ // sync runs in the same edit session as a field change.
$allowed_fields = [
'email',
'activated',
diff --git a/tests/Feature/Scim/ScimGroupMembershipLoggingTest.php b/tests/Feature/Scim/ScimGroupMembershipLoggingTest.php
new file mode 100644
index 0000000000..e715b7c957
--- /dev/null
+++ b/tests/Feature/Scim/ScimGroupMembershipLoggingTest.php
@@ -0,0 +1,163 @@
+<?php
+
+namespace Tests\Feature\Scim;
+
+use App\Models\Actionlog;
+use App\Models\Group;
+use App\Models\User;
+use Laravel\Passport\Passport;
+use Tests\TestCase;
+
+/**
+ * Coverage for SCIM-driven group membership logging. SCIM PATCHes
+ * against /scim/v2/Groups mutate the users_groups pivot from the
+ * Group side via SnipeMutableCollection::add() / ::remove(), never
+ * through User::syncGroupsWithLogging(). Without a per-user log the
+ * Activity Report would silently omit every IdP-driven role change.
+ */
+class ScimGroupMembershipLoggingTest extends TestCase
+{
+ public function test_scim_add_member_logs_group_change_on_the_user()
+ {
+ $group = Group::factory()->create(['name' => 'Engineering']);
+ $newMember = User::factory()->create();
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->patchJson('/scim/v2/Groups/'.$group->id, [
+ 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],
+ 'Operations' => [
+ [
+ 'op' => 'add',
+ 'path' => 'members',
+ 'value' => [['value' => (string) $newMember->id]],
+ ],
+ ],
+ ])->assertOk();
+
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $newMember->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $this->assertNotNull($log, 'SCIM add member must produce a per-user Actionlog');
+
+ $meta = json_decode($log->log_meta, true);
+ $this->assertArrayHasKey('groups', $meta);
+ $this->assertSame(
+ [['id' => $group->id, 'name' => 'Engineering']],
+ $meta['groups']['new'],
+ 'SCIM add must snapshot the group name at write time',
+ );
+ $this->assertSame([], $meta['groups']['old']);
+ }
+
+ public function test_scim_remove_member_via_filter_path_logs_group_change_on_the_user()
+ {
+ $group = Group::factory()->create(['name' => 'Engineering']);
+ $departing = User::factory()->create();
+ $group->users()->attach($departing->id);
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->patchJson('/scim/v2/Groups/'.$group->id, [
+ 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],
+ 'Operations' => [
+ [
+ 'op' => 'remove',
+ 'path' => 'members[value eq "'.$departing->id.'"]',
+ ],
+ ],
+ ])->assertOk();
+
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $departing->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $this->assertNotNull($log, 'SCIM remove member must produce a per-user Actionlog');
+
+ $meta = json_decode($log->log_meta, true);
+ $this->assertArrayHasKey('groups', $meta);
+ $this->assertSame(
+ [['id' => $group->id, 'name' => 'Engineering']],
+ $meta['groups']['old'],
+ 'SCIM remove must snapshot the group name at write time',
+ );
+ $this->assertSame([], $meta['groups']['new']);
+ }
+
+ public function test_scim_add_of_already_attached_member_does_not_log_a_change()
+ {
+ // Azure Entra sometimes re-sends a member the group already
+ // has (e.g. reconciliation runs). The pivot's
+ // syncWithoutDetaching is a no-op there, and the log path
+ // must match, otherwise the Activity Report fills with
+ // spurious "no change" entries.
+ $group = Group::factory()->create();
+ $member = User::factory()->create();
+ $group->users()->attach($member->id);
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $preLogCount = Actionlog::where('item_type', User::class)
+ ->where('item_id', $member->id)
+ ->count();
+
+ $this->patchJson('/scim/v2/Groups/'.$group->id, [
+ 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],
+ 'Operations' => [
+ [
+ 'op' => 'add',
+ 'path' => 'members',
+ 'value' => [['value' => (string) $member->id]],
+ ],
+ ],
+ ])->assertOk();
+
+ $postLogCount = Actionlog::where('item_type', User::class)
+ ->where('item_id', $member->id)
+ ->count();
+
+ $this->assertSame($preLogCount, $postLogCount, 'No-op re-add must not produce a log entry');
+ }
+
+ public function test_scim_bulk_add_produces_one_log_per_newly_attached_user()
+ {
+ // Multi-member add in one operation. Each newly-attached
+ // user gets their own per-user log so the Activity Report
+ // for each of them shows the group change independently.
+ $group = Group::factory()->create();
+ [$memberA, $memberB, $memberC] = User::factory()->count(3)->create();
+ Passport::actingAs(User::factory()->superuser()->create());
+
+ $this->patchJson('/scim/v2/Groups/'.$group->id, [
+ 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],
+ 'Operations' => [
+ [
+ 'op' => 'add',
+ 'path' => 'members',
+ 'value' => [
+ ['value' => (string) $memberA->id],
+ ['value' => (string) $memberB->id],
+ ['value' => (string) $memberC->id],
+ ],
+ ],
+ ],
+ ])->assertOk();
+
+ foreach ([$memberA, $memberB, $memberC] as $user) {
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $this->assertNotNull($log, "User {$user->id} must have a group log entry");
+ $meta = json_decode($log->log_meta, true);
+ $this->assertSame(
+ [['id' => $group->id, 'name' => $group->name]],
+ $meta['groups']['new'],
+ );
+ }
+ }
+}
diff --git a/tests/Feature/Users/UserGroupLoggingTest.php b/tests/Feature/Users/UserGroupLoggingTest.php
new file mode 100644
index 0000000000..b13d8c6aec
--- /dev/null
+++ b/tests/Feature/Users/UserGroupLoggingTest.php
@@ -0,0 +1,287 @@
+<?php
+
+namespace Tests\Feature\Users;
+
+use App\Models\Actionlog;
+use App\Models\Group;
+use App\Models\User;
+use Tests\TestCase;
+
+class UserGroupLoggingTest extends TestCase
+{
+ public function test_field_and_group_changes_produce_single_log_entry()
+ {
+ [$groupA, $groupB] = Group::factory()->count(2)->create();
+
+ $user = User::factory()->create(['jobtitle' => 'Engineer']);
+ $user->groups()->sync([$groupA->id]);
+
+ $actor = User::factory()->superuser()->create();
+
+ $existingLogIds = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->pluck('id');
+
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'jobtitle' => 'Senior Engineer',
+ 'groups' => [$groupB->id],
+ ])
+ ->assertOk();
+
+ $newLogs = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->whereNotIn('id', $existingLogIds)
+ ->get();
+
+ $this->assertCount(1, $newLogs, 'Field and group changes should produce exactly one log entry');
+
+ $meta = json_decode($newLogs->first()->log_meta, true);
+ $this->assertArrayHasKey('jobtitle', $meta, 'Log should include field change');
+ $this->assertArrayHasKey('groups', $meta, 'Log should include group change in same entry');
+ }
+
+ public function test_group_only_change_produces_standalone_log_entry()
+ {
+ [$groupA, $groupB] = Group::factory()->count(2)->create();
+
+ $user = User::factory()->create();
+ $user->groups()->sync([$groupA->id]);
+
+ $actor = User::factory()->superuser()->create();
+
+ $existingLogIds = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->pluck('id');
+
+ // Patch with no field changes. Only groups differs.
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'groups' => [$groupB->id],
+ ])
+ ->assertOk();
+
+ $newLogs = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->whereNotIn('id', $existingLogIds)
+ ->get();
+
+ $this->assertCount(1, $newLogs, 'Group-only change should produce one log entry');
+
+ $meta = json_decode($newLogs->first()->log_meta, true);
+ $this->assertArrayHasKey('groups', $meta, 'Log should record group change');
+ }
+
+ public function test_log_entry_records_old_and_new_group_snapshots_with_names()
+ {
+ [$groupA, $groupB, $groupC] = Group::factory()->count(3)
+ ->sequence(['name' => 'Alpha'], ['name' => 'Bravo'], ['name' => 'Charlie'])
+ ->create();
+
+ $user = User::factory()->create();
+ $user->groups()->sync([$groupA->id, $groupB->id]);
+
+ $actor = User::factory()->superuser()->create();
+
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'groups' => [$groupC->id],
+ ])
+ ->assertOk();
+
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $meta = json_decode($log->log_meta, true);
+
+ $this->assertEqualsCanonicalizing(
+ [
+ ['id' => $groupA->id, 'name' => 'Alpha'],
+ ['id' => $groupB->id, 'name' => 'Bravo'],
+ ],
+ $meta['groups']['old'],
+ 'Log old snapshot should carry the pre-change group ids AND their names',
+ );
+ $this->assertEqualsCanonicalizing(
+ [
+ ['id' => $groupC->id, 'name' => 'Charlie'],
+ ],
+ $meta['groups']['new'],
+ 'Log new snapshot should carry the post-change group ids AND their names',
+ );
+ }
+
+ public function test_transformer_renders_snapshot_names_not_unassigned_placeholders()
+ {
+ // Regression: clean_field() runs e(json_encode()) on array
+ // values, HTML-escaping the quotes inside our snapshot JSON.
+ // Without htmlspecialchars_decode before json_decode, the
+ // groups handler saw an empty array and rendered "Unassigned"
+ // for both old and new, hiding the actual change.
+ [$groupA, $groupB] = Group::factory()->count(2)
+ ->sequence(['name' => 'Sales'], ['name' => 'Ops'])
+ ->create();
+ $user = User::factory()->create();
+ $user->syncGroupsWithLogging([$groupA->id]);
+ $user->syncGroupsWithLogging([$groupB->id]);
+
+ $log = \App\Models\Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $transformed = (new \App\Http\Transformers\ActionlogsTransformer)->transformActionlog($log, \App\Models\Setting::getSettings());
+
+ $meta = $transformed['log_meta'];
+ $groupsKey = trans('general.groups');
+ $this->assertArrayHasKey($groupsKey, $meta, 'Transformer must relabel groups meta under the general.groups translation key');
+ $this->assertSame('Sales', $meta[$groupsKey]['old'], 'Old snapshot must render the historical group name, not "Unassigned"');
+ $this->assertSame('Ops', $meta[$groupsKey]['new'], 'New snapshot must render the current group name, not "Unassigned"');
+ }
+
+ public function test_group_name_in_log_is_preserved_across_a_rename()
+ {
+ // The whole point of snapshotting names at write time: the
+ // history entry has to read "Alpha" forever, even after the
+ // group gets renamed to "Renamed Alpha" later.
+ $group = Group::factory()->create(['name' => 'Alpha']);
+
+ $user = User::factory()->create();
+ $actor = User::factory()->superuser()->create();
+
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'groups' => [$group->id],
+ ])
+ ->assertOk();
+
+ $group->update(['name' => 'Renamed Alpha']);
+
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $meta = json_decode($log->log_meta, true);
+ $this->assertSame('Alpha', $meta['groups']['new'][0]['name']);
+ }
+
+ public function test_no_change_to_groups_does_not_create_extra_log_entry()
+ {
+ $group = Group::factory()->create();
+
+ $user = User::factory()->create();
+ $user->groups()->sync([$group->id]);
+
+ $actor = User::factory()->superuser()->create();
+
+ $existingLogIds = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->pluck('id');
+
+ // Send the same groups, no field changes either.
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'groups' => [$group->id],
+ ])
+ ->assertOk();
+
+ $newLogs = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->whereNotIn('id', $existingLogIds)
+ ->count();
+
+ $this->assertEquals(0, $newLogs, 'No changes should produce no new log entries');
+ }
+
+ public function test_non_superuser_edit_does_not_change_or_log_groups()
+ {
+ // Group membership on the API is gated to superusers. A
+ // non-superuser editor whose payload includes a groups key
+ // must not mutate the pivot AND must not produce a groups
+ // log entry, even when other allowed fields are changing.
+ $group = Group::factory()->create();
+ $otherGroup = Group::factory()->create();
+
+ $user = User::factory()->editUsers()->create(['jobtitle' => 'Engineer']);
+ $user->groups()->sync([$group->id]);
+
+ $actor = User::factory()->editUsers()->create();
+
+ $this->actingAsForApi($actor)
+ ->patchJson(route('api.users.update', $user), [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'username' => $user->username,
+ 'jobtitle' => 'Senior Engineer',
+ 'groups' => [$otherGroup->id],
+ ])
+ ->assertOk();
+
+ $this->assertEquals(
+ [$group->id],
+ $user->groups()->pluck('permission_groups.id')->toArray(),
+ 'Non-superuser must not mutate group pivot',
+ );
+
+ $log = Actionlog::where('item_type', User::class)
+ ->where('item_id', $user->id)
+ ->where('action_type', 'update')
+ ->latest('id')
+ ->first();
+
+ $meta = json_decode($log->log_meta ?? '{}', true);
+ $this->assertArrayNotHasKey('groups', $meta, 'Non-superuser edit must not log a group change');
+ }
+
+ /**
+ * Regression guard mirroring the company version. Same hostile
+ * shapes: nested array, string-coerceable id, string that
+ * intvals to zero, null, boolean, plus real ints. sync() must
+ * never see the non-scalars.
+ */
+ public function test_sync_coerces_non_scalar_group_ids()
+ {
+ [$groupA, $groupB] = Group::factory()->count(2)->create();
+
+ $user = User::factory()->create();
+
+ $user->syncGroupsWithLogging([
+ $groupA->id,
+ [$groupB->id, 999],
+ (string) $groupB->id,
+ 'not-a-number',
+ null,
+ true,
+ $groupA->id,
+ ]);
+
+ $this->assertEqualsCanonicalizing(
+ [$groupA->id, $groupB->id],
+ $user->groups()->pluck('permission_groups.id')->toArray(),
+ 'Only the scalar-coerceable real group ids should end up on the pivot'
+ );
+ }
+}