feat: P2 RBAC defers — REST API + invitation workflow

Closes the P2 items from /tmp/service/new/01-TZ-rbac §4.1 §4.2.

== User invitation workflow ==

New columns on users: invited_at, invited_by_id (FK self), accepted_at,
invitation_token (sha256 hash, indexed). Migration is idempotent.

User::sendInvitation($invitedBy = auth()->user())
  - generates 64-char random token
  - stores sha256(token) in invitation_token column (never plaintext)
  - marks invited_at = now(), status = inactive
  - queues UserInvitationMail to the user's email with the signed accept URL
  - returns the raw token (for tests / API consumers)

User::findByInvitationToken($rawToken) hashes + lookups.
User::acceptInvitation($password) sets password (hashed cast), clears
invitation_token, marks accepted_at + email_verified_at, status = active.

Web routes (no auth — token IS the credential):
  GET  /invitations/{token}  → password-set form
  POST /invitations/{token}  → validates min:8 + confirmed, accepts

Tokens expire after 7 days (checked against invited_at). Expired and
invalid tokens render dedicated views (invitations/expired.blade.php,
invitations/invalid.blade.php) instead of generic 404 — so the user
knows to ask for a resend.

UserInvitationMail uses Filament's existing markdown layout; subject
includes the tenant display_name.

== REST API ==

Twenty new endpoints under /api/v1/ (Sanctum auth + tenant scoping
via the existing EnsureTokenMatchesTenant middleware). All gated by
ADMIN_USERS_* / ADMIN_ROLES_MANAGE permissions; mechanic-level token
gets 403.

Users:
  GET    /users                                  — paginated + role/status/q filters
  GET    /users/{u}                              — eager-loads roles + overrides + invitedBy
  POST   /users                                  — creates inactive user + sends invitation
  PATCH  /users/{u}                              — update name/email/role/status
  DELETE /users/{u}                              — soft delete
  POST   /users/{u}/activate
  POST   /users/{u}/deactivate                   — also revokes all sessions
  POST   /users/{u}/resend-invitation
  POST   /users/{u}/force-password-reset         — re-sends invitation
  GET    /users/{u}/sessions                     — list active sessions (from sessions table)
  DELETE /users/{u}/sessions                     — revoke all
  DELETE /users/{u}/sessions/{sessionId}         — revoke one
  GET    /users/{u}/roles                        — assigned roles
  POST   /users/{u}/roles                        — assign role
  DELETE /users/{u}/roles/{role}                 — remove role
  GET    /users/{u}/permissions                  — effective: role perms + grants - active denies
  POST   /users/{u}/permission-overrides         — add grant/deny (with optional expires_at)
  DELETE /users/{u}/permission-overrides/{perm}

Roles:
  apiResource roles                              — index/show/store/update/destroy
                                                   (system roles guarded against rename/delete)
  GET    /roles/{r}/permissions
  PUT    /roles/{r}/permissions                  — bulk sync
  GET    /permissions                            — catalog: flat list + grouped + labels + role labels

Authorization is uniform: every controller method calls $this->authorize()
which throws 403 if canDo(perm) is false. canDo() already honors the
overrides + admin bypass + audit log from earlier commits, so the API
behaves identically to the Filament UI.

== Tests ==

InvitationFlowTest (8): token generation + sha256 storage + queued mail,
findByInvitationToken happy/sad path, accept sets password + activates,
GET form renders, POST accepts + redirects, invalid token view,
backdated invited_at → expired view, password too short → validation error.

RbacApiTest (12): admin can list users, mechanic 403, create user
queues invitation, assign+remove role round-trip, effective permissions
endpoint subtracts active denies, add+remove override via API,
role index returns 7 system roles with permission counts (51 for owner),
role sync permissions, system role destroy rejected with 422,
permission catalog endpoint returns all 51 + grouped + labels,
revoke all sessions deletes only target user's rows.

Suite: 234 passed (659 assertions). Was 214.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-04 22:36:44 +00:00
parent 1d4ac3db38
commit d9180e16b3
14 changed files with 987 additions and 0 deletions
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace Tests\Feature;
use App\Mail\UserInvitationMail;
use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\User;
use App\Services\RbacSeeder;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class InvitationFlowTest extends TestCase
{
use RefreshDatabase;
private Company $company;
protected function setUp(): void
{
parent::setUp();
$plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
$this->company = Company::create([
'plan_id' => $plan->id, 'slug' => 'inv-' . uniqid(),
'name' => 'Inv Co', 'status' => 'active',
]);
app(TenantManager::class)->setCurrent($this->company);
app(RbacSeeder::class)->seedTenantRoles($this->company->id);
}
public function test_send_invitation_generates_token_marks_pending_and_queues_mail(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
$u->refresh();
$this->assertNotEmpty($token);
$this->assertEquals(64, strlen($token));
$this->assertNotNull($u->invited_at);
$this->assertNull($u->accepted_at);
$this->assertEquals('inactive', $u->status);
$this->assertTrue($u->isPendingInvitation());
// Stored token is sha256 hash, not the raw value
$this->assertNotEquals($token, $u->invitation_token);
$this->assertEquals(hash('sha256', $token), $u->invitation_token);
Mail::assertQueued(UserInvitationMail::class, fn ($m) => $m->user->id === $u->id);
}
public function test_find_by_invitation_token_resolves_user(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
$found = User::findByInvitationToken($token);
$this->assertNotNull($found);
$this->assertEquals($u->id, $found->id);
// Wrong token returns null
$this->assertNull(User::findByInvitationToken('not-a-real-token'));
}
public function test_accept_invitation_sets_password_clears_token_activates(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('placeholder'), 'role' => 'mechanic', 'status' => 'inactive']);
$token = $u->sendInvitation();
$u->refresh();
$u->acceptInvitation('NewStrongPass123');
$u->refresh();
$this->assertNull($u->invitation_token);
$this->assertNotNull($u->accepted_at);
$this->assertEquals('active', $u->status);
$this->assertNotNull($u->email_verified_at);
$this->assertTrue(\Hash::check('NewStrongPass123', $u->password));
$this->assertFalse($u->isPendingInvitation());
}
public function test_invitation_url_returns_form_with_token(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
$resp = $this->get("/invitations/{$token}");
$resp->assertStatus(200);
$resp->assertSee($u->name);
$resp->assertSee('Activează contul');
}
public function test_invitation_post_accepts_password_and_redirects(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('placeholder'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
$resp = $this->post("/invitations/{$token}", [
'password' => 'BrandNewPass1',
'password_confirmation' => 'BrandNewPass1',
]);
$resp->assertStatus(302);
$u->refresh();
$this->assertNotNull($u->accepted_at);
$this->assertTrue(\Hash::check('BrandNewPass1', $u->password));
}
public function test_invalid_token_returns_invalid_view(): void
{
$resp = $this->get('/invitations/not-a-real-token');
$resp->assertStatus(200);
$resp->assertSee('Invitație invalidă');
}
public function test_expired_invitation_returns_expired_view(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
// Force expiry by backdating invited_at
$u->forceFill(['invited_at' => now()->subDays(8)])->saveQuietly();
$resp = $this->get("/invitations/{$token}");
$resp->assertStatus(200);
$resp->assertSee('Invitație expirată');
}
public function test_password_too_short_returns_validation_error(): void
{
Mail::fake();
$u = User::create(['name' => 'X', 'email' => 'x@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$token = $u->sendInvitation();
$resp = $this->post("/invitations/{$token}", [
'password' => 'short',
'password_confirmation' => 'short',
]);
$resp->assertSessionHasErrors('password');
$u->refresh();
$this->assertNull($u->accepted_at);
}
}
+203
View File
@@ -0,0 +1,203 @@
<?php
namespace Tests\Feature;
use App\Auth\Permissions;
use App\Mail\UserInvitationMail;
use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\User;
use App\Models\Tenant\UserPermissionOverride;
use App\Services\RbacSeeder;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Laravel\Sanctum\Sanctum;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;
use Tests\TestCase;
class RbacApiTest extends TestCase
{
use RefreshDatabase;
private Company $company;
private User $admin;
private User $mechanic;
protected function setUp(): void
{
parent::setUp();
$plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
$this->company = Company::create([
'plan_id' => $plan->id, 'slug' => 'api-' . uniqid(),
'name' => 'API Co', 'status' => 'active',
]);
app(TenantManager::class)->setCurrent($this->company);
app(RbacSeeder::class)->seedTenantRoles($this->company->id);
app(PermissionRegistrar::class)->setPermissionsTeamId($this->company->id);
$this->admin = User::create(['name' => 'A', 'email' => 'a@e.com', 'password' => bcrypt('x'), 'role' => 'admin', 'status' => 'active']);
$this->admin->syncRoles(['admin']);
$this->mechanic = User::create(['name' => 'M', 'email' => 'm@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$this->mechanic->syncRoles(['mechanic']);
}
public function test_admin_can_list_users_via_api(): void
{
Sanctum::actingAs($this->admin);
$resp = $this->getJson('/api/v1/users');
$resp->assertOk();
$this->assertGreaterThanOrEqual(2, count($resp->json('data')));
}
public function test_mechanic_cannot_list_users_403(): void
{
Sanctum::actingAs($this->mechanic);
$resp = $this->getJson('/api/v1/users');
$resp->assertForbidden();
}
public function test_admin_can_create_user_and_invitation_is_sent(): void
{
Mail::fake();
Sanctum::actingAs($this->admin);
$resp = $this->postJson('/api/v1/users', [
'name' => 'New U', 'email' => 'newu@e.com',
'role' => 'receptionist', 'send_invitation' => true,
]);
$resp->assertCreated();
$this->assertEquals('inactive', $resp->json('data.status')); // inactive until invitation accepted
$this->assertTrue($resp->json('invitation_sent'));
Mail::assertQueued(UserInvitationMail::class);
}
public function test_admin_can_assign_and_remove_roles_via_api(): void
{
Sanctum::actingAs($this->admin);
$resp = $this->postJson("/api/v1/users/{$this->mechanic->id}/roles", ['role' => 'receptionist']);
$resp->assertOk();
$this->mechanic->refresh();
$this->assertTrue($this->mechanic->hasRole('receptionist'));
$resp = $this->deleteJson("/api/v1/users/{$this->mechanic->id}/roles/receptionist");
$resp->assertOk();
$this->mechanic->refresh();
$this->assertFalse($this->mechanic->hasRole('receptionist'));
}
public function test_effective_permissions_endpoint_subtracts_denies(): void
{
Sanctum::actingAs($this->admin);
// Admin has FINANCE_VIEW_OVERVIEW. Add a deny override.
$perm = Permission::where('name', Permissions::FINANCE_VIEW_OVERVIEW)->first();
UserPermissionOverride::create([
'user_id' => $this->admin->id, 'permission_id' => $perm->id,
'mode' => 'deny', 'reason' => 'test', 'granted_at' => now(),
]);
$resp = $this->getJson("/api/v1/users/{$this->admin->id}/permissions");
$resp->assertOk();
$effective = collect($resp->json('data'));
$this->assertFalse($effective->contains(Permissions::FINANCE_VIEW_OVERVIEW));
$denies = collect($resp->json('overrides.denies'));
$this->assertTrue($denies->contains(Permissions::FINANCE_VIEW_OVERVIEW));
}
public function test_add_override_via_api_persists(): void
{
Sanctum::actingAs($this->admin);
$resp = $this->postJson("/api/v1/users/{$this->mechanic->id}/permission-overrides", [
'permission' => Permissions::WORK_ORDERS_VIEW_ALL,
'mode' => 'grant',
'reason' => 'pinch hitter',
'expires_at' => now()->addDays(3)->toIso8601String(),
]);
$resp->assertOk();
$this->mechanic->refresh();
$this->assertEquals(1, $this->mechanic->permissionOverrides()->count());
$this->assertTrue($this->mechanic->canDo(Permissions::WORK_ORDERS_VIEW_ALL));
}
public function test_remove_override_via_api(): void
{
Sanctum::actingAs($this->admin);
$perm = Permission::where('name', Permissions::WORK_ORDERS_VIEW_ALL)->first();
UserPermissionOverride::create(['user_id' => $this->mechanic->id, 'permission_id' => $perm->id, 'mode' => 'grant', 'granted_at' => now()]);
$resp = $this->deleteJson("/api/v1/users/{$this->mechanic->id}/permission-overrides/" . Permissions::WORK_ORDERS_VIEW_ALL);
$resp->assertOk();
$this->assertEquals(0, $this->mechanic->fresh()->permissionOverrides()->count());
}
public function test_role_index_returns_all_roles_with_counts(): void
{
Sanctum::actingAs($this->admin);
$resp = $this->getJson('/api/v1/roles');
$resp->assertOk();
$roles = collect($resp->json('data'));
$this->assertGreaterThanOrEqual(7, $roles->count());
$owner = $roles->firstWhere('name', 'owner');
$this->assertNotNull($owner);
$this->assertEquals(51, $owner['permissions_count']);
}
public function test_role_sync_permissions_updates_role(): void
{
Sanctum::actingAs($this->admin);
$role = \Spatie\Permission\Models\Role::create(['name' => 'custom_role', 'guard_name' => 'web']);
$resp = $this->putJson("/api/v1/roles/{$role->id}/permissions", [
'permissions' => [Permissions::CLIENTS_VIEW_ALL, Permissions::VEHICLES_VIEW_ALL],
]);
$resp->assertOk();
$this->assertEquals(2, $role->fresh()->permissions()->count());
}
public function test_role_destroy_rejects_system_role(): void
{
Sanctum::actingAs($this->admin);
$owner = \Spatie\Permission\Models\Role::where('name', 'owner')->where('company_id', $this->company->id)->first();
$resp = $this->deleteJson("/api/v1/roles/{$owner->id}");
$resp->assertStatus(422);
$this->assertEquals('Cannot delete system role', $resp->json('error'));
}
public function test_permission_catalog_endpoint_returns_full_list_and_groups(): void
{
Sanctum::actingAs($this->admin);
$resp = $this->getJson('/api/v1/permissions');
$resp->assertOk();
$this->assertEquals(51, count($resp->json('data')));
$this->assertArrayHasKey('grouped', $resp->json());
$this->assertArrayHasKey('clients', $resp->json('grouped'));
$this->assertArrayHasKey('roles', $resp->json());
}
public function test_revoke_all_sessions_endpoint(): void
{
Sanctum::actingAs($this->admin);
\DB::table('sessions')->insert([
['id' => 's1', 'user_id' => $this->mechanic->id, 'ip_address' => '1.1.1.1', 'user_agent' => 'X', 'payload' => '', 'last_activity' => time()],
['id' => 's2', 'user_id' => $this->mechanic->id, 'ip_address' => '2.2.2.2', 'user_agent' => 'Y', 'payload' => '', 'last_activity' => time()],
]);
$resp = $this->deleteJson("/api/v1/users/{$this->mechanic->id}/sessions");
$resp->assertOk();
$this->assertEquals(2, $resp->json('revoked_count'));
$this->assertEquals(0, \DB::table('sessions')->where('user_id', $this->mechanic->id)->count());
}
}