feat: replace token-based impersonation with enterprise-grade header-based system

Replaces the insecure token-in-localStorage approach with a header-based
impersonation system backed by cache sessions and MFA verification.

Key changes:
- New impersonation_sessions audit table (immutable, ULID PK)
- MFA verification required to start impersonation (TOTP/email/backup)
- X-Impersonate-User header + HandleImpersonation middleware
- Per-request auth context swap (admin session never modified)
- IP pinning, sensitive route blocking, no nesting, sliding 60-min TTL
- Activity log auto-tagged with impersonated_by during sessions
- Frontend: sessionStorage, BroadcastChannel sync, countdown timer
- ImpersonateDialog with reason + MFA verification flow
- 26 comprehensive tests covering core, middleware, audit, lifecycle

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-16 02:42:53 +02:00
parent 47cb6b83d4
commit 4df668b5b8
25 changed files with 1813 additions and 269 deletions

View File

@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Services\ImpersonationService;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class HandleImpersonation
{
/**
* Routes that are blocked during impersonation.
* These are prefix-matched against the request path (without api/v1 prefix).
*/
private const SENSITIVE_ROUTE_PREFIXES = [
'auth/password',
'auth/logout',
'auth/mfa',
'auth/trusted-devices',
'me/profile',
'me/change-password',
'me/change-email',
'admin/impersonate',
'verify-email-change',
];
public function __construct(
private readonly ImpersonationService $impersonationService,
) {}
public function handle(Request $request, Closure $next): Response
{
$targetUserId = $request->header('X-Impersonate-User');
if (! $targetUserId) {
return $next($request);
}
/** @var User|null $admin */
$admin = $request->user();
if (! $admin) {
return response()->json(['message' => 'Authentication required.'], 401);
}
// Block sensitive routes during impersonation
if ($this->isSensitiveRoute($request)) {
return response()->json([
'message' => 'This action is not allowed during impersonation.',
], 403);
}
// Validate impersonation session via Redis
$session = $this->impersonationService->validateRequest(
$admin->id,
$targetUserId,
$request->ip(),
);
if (! $session) {
return response()->json([
'message' => 'Impersonation session is invalid or has expired.',
'impersonation_ended' => true,
], 403);
}
// Load the target user
$targetUser = User::find($targetUserId);
if (! $targetUser) {
return response()->json(['message' => 'Target user not found.'], 404);
}
// Store impersonation context in request attributes
$request->attributes->set('impersonator', $admin);
$request->attributes->set('impersonation_session', $session);
// Swap auth context — the rest of the request sees the target user
app('auth')->setUser($targetUser);
// Tag all log entries with impersonation context
Log::shareContext([
'impersonated_by' => $admin->id,
'impersonation_session_id' => $session->id,
]);
// Increment actions count
$this->impersonationService->incrementActionsCount($session);
return $next($request);
}
private function isSensitiveRoute(Request $request): bool
{
// Get path relative to API prefix (strip api/v1/)
$path = $request->path();
$path = preg_replace('#^api/v1/#', '', $path);
foreach (self::SENSITIVE_ROUTE_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix)) {
return true;
}
}
return false;
}
}