From 2e94a107e4b3612f39af6a821dc53cd66c4b98d2 Mon Sep 17 00:00:00 2001 From: "bert.hausmans" Date: Wed, 6 May 2026 00:24:01 +0200 Subject: [PATCH] refactor(auth): consolidate to single cookie post single-SPA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dual-cookie machinery (crewli_app_token + crewli_portal_token, Origin-based resolution) was load-bearing only when the second SPA existed. apps/portal/ was deleted in WS-3 PR-B1; the resolver code has been carrying dead branches since then. Collapse to one cookie. Cookie name retained as crewli_app_token — no session breakage on deploy. crewli_portal_token is fully purged from the server-side. CookieBearerToken middleware: - COOKIE_NAMES array → single COOKIE_NAME constant - resolveCookieName method (Origin/Referer parsing, host+port matching against frontend_app_url/frontend_portal_url) → removed - Body collapses to: skip if Authorization header present; else read crewli_app_token cookie and inject Bearer header SetAuthCookie trait: - COOKIE_MAP / resolveCookieName / originMatches → removed - makeAuthCookie / forgetAuthCookie now take only $token; the cookie name is the trait's private constant Five callers updated to drop the resolveCookieName($request) line and the cookie-name argument: LoginController (3 sites), MfaVerifyController (1 site), AuthRefreshController (1 site), LogoutController (1 site), InvitationController (1 site — caller list in the prompt missed this one but the same pattern applies). frontend_portal_url config key retained (per Phase A directive Q1): EmailChangeController, PasswordResetController, PersonController are non-auth consumers that build per-app URL maps for outbound emails. The map structure is now functionally redundant (production resolves all FRONTEND_* env vars to the same host) but stays structurally intact. Refactor tracked as TECH-FRONTEND-URL-CONSOLIDATE in the upcoming docs commit. HttpOnlyCookieAuthTest: - Removed 4 dual-cookie tests (login_sets_portal_cookie_for_portal_origin, app_cookie_does_not_authenticate_portal_requests, portal_cookie_does_not_authenticate_app_requests, correct_cookie_authenticates_with_matching_origin) - Renamed login_sets_app_cookie_for_unknown_origin → login_sets_app_cookie_regardless_of_origin; expanded to four Origin variants (none, app, unknown, foreign) — pins the new origin-agnostic contract - Removed Origin headers from request calls in remaining tests (now meaningless) Backend test count: 1491 → 1487 (-4 deleted, dual-cookie tests encoding the obsolete contract). Pint clean. Larastan clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../Api/V1/Auth/MfaVerifyController.php | 7 +- .../Api/V1/AuthRefreshController.php | 3 +- .../Api/V1/InvitationController.php | 4 +- .../Controllers/Api/V1/LoginController.php | 10 +- .../Controllers/Api/V1/LogoutController.php | 4 +- .../Api/V1/Traits/SetAuthCookie.php | 49 +--------- api/app/Http/Middleware/CookieBearerToken.php | 65 ++----------- .../Security/HttpOnlyCookieAuthTest.php | 92 ++++++------------- 8 files changed, 49 insertions(+), 185 deletions(-) diff --git a/api/app/Http/Controllers/Api/V1/Auth/MfaVerifyController.php b/api/app/Http/Controllers/Api/V1/Auth/MfaVerifyController.php index d7d8ce54..87a0c4d1 100644 --- a/api/app/Http/Controllers/Api/V1/Auth/MfaVerifyController.php +++ b/api/app/Http/Controllers/Api/V1/Auth/MfaVerifyController.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace App\Http\Controllers\Api\V1\Auth; +use App\Enums\MfaMethod; use App\Http\Controllers\Api\V1\Traits\SetAuthCookie; use App\Http\Controllers\Controller; use App\Http\Requests\Api\V1\Auth\MfaEmailSendRequest; use App\Http\Requests\Api\V1\Auth\MfaVerifyRequest; use App\Http\Resources\Api\V1\MeResource; -use App\Enums\MfaMethod; use App\Models\User; use App\Services\MfaService; use Illuminate\Http\JsonResponse; @@ -58,19 +58,18 @@ final class MfaVerifyController extends Controller ]); $token = $user->createToken('auth-token')->plainTextToken; - $cookieName = $this->resolveCookieName($request); return $this->success([ 'user' => new MeResource($user), ], 'MFA verification successful') - ->withCookie($this->makeAuthCookie($cookieName, $token)); + ->withCookie($this->makeAuthCookie($token)); } public function sendEmailCode(MfaEmailSendRequest $request): JsonResponse { $sessionToken = $request->validated('mfa_session_token'); - $cacheKey = 'mfa_session:' . $sessionToken; + $cacheKey = 'mfa_session:'.$sessionToken; $session = Cache::get($cacheKey); if (! $session) { diff --git a/api/app/Http/Controllers/Api/V1/AuthRefreshController.php b/api/app/Http/Controllers/Api/V1/AuthRefreshController.php index 70cd6d11..65d99b40 100644 --- a/api/app/Http/Controllers/Api/V1/AuthRefreshController.php +++ b/api/app/Http/Controllers/Api/V1/AuthRefreshController.php @@ -24,7 +24,6 @@ final class AuthRefreshController extends Controller // Create a new token $newToken = $user->createToken('auth-token')->plainTextToken; - $cookieName = $this->resolveCookieName($request); $user->load(['organisations', 'roles', 'permissions']); @@ -34,6 +33,6 @@ final class AuthRefreshController extends Controller ]); return $this->success(new MeResource($user), 'Token refreshed') - ->withCookie($this->makeAuthCookie($cookieName, $newToken)); + ->withCookie($this->makeAuthCookie($newToken)); } } diff --git a/api/app/Http/Controllers/Api/V1/InvitationController.php b/api/app/Http/Controllers/Api/V1/InvitationController.php index e0eff145..13d777d1 100644 --- a/api/app/Http/Controllers/Api/V1/InvitationController.php +++ b/api/app/Http/Controllers/Api/V1/InvitationController.php @@ -18,6 +18,7 @@ use Illuminate\Support\Facades\Gate; final class InvitationController extends Controller { use SetAuthCookie; + public function __construct( private readonly InvitationService $invitationService, ) {} @@ -65,7 +66,6 @@ final class InvitationController extends Controller ); $sanctumToken = $user->createToken('auth-token')->plainTextToken; - $cookieName = $this->resolveCookieName($request); return $this->success([ 'user' => [ @@ -76,7 +76,7 @@ final class InvitationController extends Controller 'email' => $user->email, ], ], 'Uitnodiging geaccepteerd') - ->withCookie($this->makeAuthCookie($cookieName, $sanctumToken)); + ->withCookie($this->makeAuthCookie($sanctumToken)); } public function revoke(Organisation $organisation, UserInvitation $invitation): JsonResponse diff --git a/api/app/Http/Controllers/Api/V1/LoginController.php b/api/app/Http/Controllers/Api/V1/LoginController.php index c790f57b..1d31775c 100644 --- a/api/app/Http/Controllers/Api/V1/LoginController.php +++ b/api/app/Http/Controllers/Api/V1/LoginController.php @@ -65,13 +65,11 @@ final class LoginController extends Controller // Return MFA challenge — NO auth token, NO auth cookie. // Expire the auth cookie to invalidate any stale browser session. - $cookieName = $this->resolveCookieName($request); - return response()->json([ 'success' => true, 'mfa_required' => true, ...$mfaSession, - ])->withCookie($this->forgetAuthCookie($cookieName)); + ])->withCookie($this->forgetAuthCookie()); } // MFA required by policy but not yet set up — issue token with flag @@ -80,11 +78,10 @@ final class LoginController extends Controller $data = $response->getData(true); $data['mfa_setup_required'] = true; - $cookieName = $this->resolveCookieName($request); $token = $user->createToken('auth-token')->plainTextToken; return response()->json($data) - ->withCookie($this->makeAuthCookie($cookieName, $token)); + ->withCookie($this->makeAuthCookie($token)); } // No MFA — issue token as normal @@ -101,11 +98,10 @@ final class LoginController extends Controller ]); $token = $user->createToken('auth-token')->plainTextToken; - $cookieName = $this->resolveCookieName($request); return $this->success([ 'user' => new MeResource($user), ], 'Login successful') - ->withCookie($this->makeAuthCookie($cookieName, $token)); + ->withCookie($this->makeAuthCookie($token)); } } diff --git a/api/app/Http/Controllers/Api/V1/LogoutController.php b/api/app/Http/Controllers/Api/V1/LogoutController.php index 73889296..d1ff3d3e 100644 --- a/api/app/Http/Controllers/Api/V1/LogoutController.php +++ b/api/app/Http/Controllers/Api/V1/LogoutController.php @@ -17,9 +17,7 @@ final class LogoutController extends Controller { $request->user()->currentAccessToken()->delete(); - $cookieName = $this->resolveCookieName($request); - return $this->success(null, 'Logged out successfully') - ->withCookie($this->forgetAuthCookie($cookieName)); + ->withCookie($this->forgetAuthCookie()); } } diff --git a/api/app/Http/Controllers/Api/V1/Traits/SetAuthCookie.php b/api/app/Http/Controllers/Api/V1/Traits/SetAuthCookie.php index 84f86088..a575a818 100644 --- a/api/app/Http/Controllers/Api/V1/Traits/SetAuthCookie.php +++ b/api/app/Http/Controllers/Api/V1/Traits/SetAuthCookie.php @@ -4,42 +4,18 @@ declare(strict_types=1); namespace App\Http\Controllers\Api\V1\Traits; -use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Cookie; trait SetAuthCookie { - private const COOKIE_MAP = [ - 'app' => 'crewli_app_token', - 'portal' => 'crewli_portal_token', - ]; + private const COOKIE_NAME = 'crewli_app_token'; private const COOKIE_TTL_MINUTES = 60 * 24 * 7; // 7 days - protected function resolveCookieName(Request $request): string - { - $origin = $request->headers->get('Origin') - ?? $request->headers->get('Referer') - ?? ''; - - $appUrl = config('app.frontend_app_url', 'http://localhost:5174'); - $portalUrl = config('app.frontend_portal_url', 'http://localhost:5175'); - - if ($this->originMatches($origin, $appUrl)) { - return self::COOKIE_MAP['app']; - } - - if ($this->originMatches($origin, $portalUrl)) { - return self::COOKIE_MAP['portal']; - } - - return self::COOKIE_MAP['app']; - } - - protected function makeAuthCookie(string $cookieName, string $token): Cookie + protected function makeAuthCookie(string $token): Cookie { return new Cookie( - name: $cookieName, + name: self::COOKIE_NAME, value: $token, expire: now()->addMinutes(self::COOKIE_TTL_MINUTES), path: '/', @@ -50,10 +26,10 @@ trait SetAuthCookie ); } - protected function forgetAuthCookie(string $cookieName): Cookie + protected function forgetAuthCookie(): Cookie { return new Cookie( - name: $cookieName, + name: self::COOKIE_NAME, value: '', expire: now()->subMinute(), path: '/', @@ -63,19 +39,4 @@ trait SetAuthCookie sameSite: 'Strict', ); } - - private function originMatches(string $origin, string $configuredUrl): bool - { - if ($origin === '' || $configuredUrl === '') { - return false; - } - - // Parse to compare host+port, ignoring trailing slashes and paths - $originHost = parse_url($origin, PHP_URL_HOST); - $originPort = parse_url($origin, PHP_URL_PORT); - $configHost = parse_url($configuredUrl, PHP_URL_HOST); - $configPort = parse_url($configuredUrl, PHP_URL_PORT); - - return $originHost === $configHost && $originPort === $configPort; - } } diff --git a/api/app/Http/Middleware/CookieBearerToken.php b/api/app/Http/Middleware/CookieBearerToken.php index 805e2ff8..9ed50860 100644 --- a/api/app/Http/Middleware/CookieBearerToken.php +++ b/api/app/Http/Middleware/CookieBearerToken.php @@ -10,74 +10,21 @@ use Symfony\Component\HttpFoundation\Response; final class CookieBearerToken { - private const COOKIE_NAMES = [ - 'crewli_app_token', - 'crewli_portal_token', - ]; + private const COOKIE_NAME = 'crewli_app_token'; public function handle(Request $request, Closure $next): Response { - // Skip if an Authorization header is already present + // Skip if an Authorization header is already present (e.g. portal-token + // Bearer flow for artists/suppliers, or server-to-server callers). if ($request->hasHeader('Authorization')) { return $next($request); } - // Resolve the cookie name for the requesting app via Origin header. - // This prevents cross-app cookie leakage on localhost where the - // browser sends all cookies regardless of port. - $cookieName = $this->resolveCookieName($request); - - if ($cookieName) { - $token = $request->cookie($cookieName); - if ($token) { - $request->headers->set('Authorization', 'Bearer ' . $token); - } + $token = $request->cookie(self::COOKIE_NAME); + if ($token) { + $request->headers->set('Authorization', 'Bearer '.$token); } return $next($request); } - - private function resolveCookieName(Request $request): ?string - { - $origin = $request->headers->get('Origin') - ?? $request->headers->get('Referer') - ?? ''; - - if ($origin === '') { - // No Origin — fall back to first available cookie (e.g. server-to-server) - foreach (self::COOKIE_NAMES as $name) { - if ($request->cookie($name)) { - return $name; - } - } - - return null; - } - - $originHost = parse_url($origin, PHP_URL_HOST); - $originPort = parse_url($origin, PHP_URL_PORT); - - $map = [ - 'app' => [config('app.frontend_app_url', 'http://localhost:5174'), 'crewli_app_token'], - 'portal' => [config('app.frontend_portal_url', 'http://localhost:5175'), 'crewli_portal_token'], - ]; - - foreach ($map as [$configuredUrl, $cookieName]) { - $configHost = parse_url($configuredUrl, PHP_URL_HOST); - $configPort = parse_url($configuredUrl, PHP_URL_PORT); - - if ($originHost === $configHost && $originPort === $configPort) { - return $cookieName; - } - } - - // Origin didn't match any configured frontend — fall back to first available - foreach (self::COOKIE_NAMES as $name) { - if ($request->cookie($name)) { - return $name; - } - } - - return null; - } } diff --git a/api/tests/Feature/Security/HttpOnlyCookieAuthTest.php b/api/tests/Feature/Security/HttpOnlyCookieAuthTest.php index 636a0227..db2118e5 100644 --- a/api/tests/Feature/Security/HttpOnlyCookieAuthTest.php +++ b/api/tests/Feature/Security/HttpOnlyCookieAuthTest.php @@ -7,7 +7,6 @@ namespace Tests\Feature\Security; use App\Models\User; use Database\Seeders\RoleSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; -use Laravel\Sanctum\Sanctum; use Tests\TestCase; final class HttpOnlyCookieAuthTest extends TestCase @@ -45,7 +44,7 @@ final class HttpOnlyCookieAuthTest extends TestCase $response = $this->postJson('/api/v1/auth/login', [ 'email' => $user->email, 'password' => 'password', - ], ['Origin' => 'http://localhost:5174']); + ]); $response->assertOk(); $response->assertCookie('crewli_app_token'); @@ -58,7 +57,7 @@ final class HttpOnlyCookieAuthTest extends TestCase $response = $this->postJson('/api/v1/auth/login', [ 'email' => $user->email, 'password' => 'password', - ], ['Origin' => 'http://localhost:5174']); + ]); $cookie = $this->findCookie($response, 'crewli_app_token'); $this->assertNotNull($cookie, 'Cookie crewli_app_token not found'); @@ -72,37 +71,41 @@ final class HttpOnlyCookieAuthTest extends TestCase $response = $this->postJson('/api/v1/auth/login', [ 'email' => $user->email, 'password' => 'password', - ], ['Origin' => 'http://localhost:5174']); + ]); $cookie = $this->findCookie($response, 'crewli_app_token'); $this->assertNotNull($cookie); $this->assertEquals('strict', strtolower($cookie->getSameSite())); } - public function test_login_sets_app_cookie_for_unknown_origin(): void + public function test_login_sets_app_cookie_regardless_of_origin(): void { - $user = User::factory()->create(); + // Post-WS-3 PR-B2b: there is no per-app cookie resolution. Whatever + // Origin (or no Origin) the request carries, the auth cookie issued + // is always crewli_app_token. The request body alone determines auth. + $cases = [ + 'no Origin header' => [], + 'app Origin' => ['Origin' => 'http://localhost:5174'], + 'unknown Origin' => ['Origin' => 'http://localhost:9999'], + 'foreign Origin' => ['Origin' => 'https://elsewhere.example.com'], + ]; - $response = $this->postJson('/api/v1/auth/login', [ - 'email' => $user->email, - 'password' => 'password', - ], ['Origin' => 'http://localhost:9999']); + foreach ($cases as $label => $headers) { + $user = User::factory()->create(); - $response->assertOk(); - $response->assertCookie('crewli_app_token'); - } + $response = $this->postJson('/api/v1/auth/login', [ + 'email' => $user->email, + 'password' => 'password', + ], $headers); - public function test_login_sets_portal_cookie_for_portal_origin(): void - { - $user = User::factory()->create(); + $response->assertOk(); - $response = $this->postJson('/api/v1/auth/login', [ - 'email' => $user->email, - 'password' => 'password', - ], ['Origin' => 'http://localhost:5175']); - - $response->assertOk(); - $response->assertCookie('crewli_portal_token'); + $cookie = $this->findCookie($response, 'crewli_app_token'); + $this->assertNotNull( + $cookie, + "crewli_app_token must be set for case: {$label}", + ); + } } // --- Middleware Tests --- @@ -142,7 +145,7 @@ final class HttpOnlyCookieAuthTest extends TestCase $token = $user->createToken('auth-token')->plainTextToken; $response = $this->withUnencryptedCookie('crewli_app_token', $token) - ->postJson('/api/v1/auth/logout', [], ['Origin' => 'http://localhost:5174']); + ->postJson('/api/v1/auth/logout'); $response->assertOk(); @@ -161,7 +164,7 @@ final class HttpOnlyCookieAuthTest extends TestCase $token = $accessToken->plainTextToken; $response = $this->withUnencryptedCookie('crewli_app_token', $token) - ->postJson('/api/v1/auth/refresh', [], ['Origin' => 'http://localhost:5174']); + ->postJson('/api/v1/auth/refresh'); $response->assertOk(); $response->assertCookie('crewli_app_token'); @@ -192,45 +195,6 @@ final class HttpOnlyCookieAuthTest extends TestCase $response->assertUnauthorized(); } - // --- Cross-App Isolation Tests --- - - public function test_app_cookie_does_not_authenticate_portal_requests(): void - { - $user = User::factory()->create(); - $token = $user->createToken('auth-token')->plainTextToken; - - // App cookie is set, but request comes from portal origin — - // middleware should only read crewli_portal_token, not crewli_app_token - $response = $this->withUnencryptedCookie('crewli_app_token', $token) - ->getJson('/api/v1/auth/me', ['Origin' => 'http://localhost:5175']); - - $response->assertUnauthorized(); - } - - public function test_portal_cookie_does_not_authenticate_app_requests(): void - { - $user = User::factory()->create(); - $token = $user->createToken('auth-token')->plainTextToken; - - $response = $this->withUnencryptedCookie('crewli_portal_token', $token) - ->getJson('/api/v1/auth/me', ['Origin' => 'http://localhost:5174']); - - $response->assertUnauthorized(); - } - - public function test_correct_cookie_authenticates_with_matching_origin(): void - { - $user = User::factory()->create(); - $token = $user->createToken('auth-token')->plainTextToken; - - // Portal cookie + portal origin = authenticated - $response = $this->withUnencryptedCookie('crewli_portal_token', $token) - ->getJson('/api/v1/auth/me', ['Origin' => 'http://localhost:5175']); - - $response->assertOk(); - $response->assertJsonPath('data.id', $user->id); - } - // --- Helper --- private function findCookie($response, string $name): ?\Symfony\Component\HttpFoundation\Cookie