-
Notifications
You must be signed in to change notification settings - Fork 0
Backend PR-2: CSRF Token Endpoint & Security Hardening #212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+245
−1
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| <?php | ||
|
|
||
| // SPDX-FileCopyrightText: 2025 SecPal Contributors | ||
| // SPDX-License-Identifier: AGPL-3.0-or-later | ||
|
|
||
| namespace App\Http\Middleware; | ||
|
|
||
| use Closure; | ||
| use Illuminate\Http\Request; | ||
| use Symfony\Component\HttpFoundation\Response; | ||
|
|
||
| /** | ||
| * Security Headers Middleware | ||
| * | ||
| * Adds security-related HTTP headers to all responses to protect against | ||
| * common web vulnerabilities. | ||
| */ | ||
| class SecurityHeaders | ||
| { | ||
| /** | ||
| * Handle an incoming request. | ||
| * | ||
| * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next | ||
| */ | ||
| public function handle(Request $request, Closure $next): Response | ||
| { | ||
| $response = $next($request); | ||
|
|
||
| // Prevent clickjacking attacks by disallowing the page to be framed | ||
| $response->headers->set('X-Frame-Options', 'DENY'); | ||
|
|
||
| // Prevent MIME type sniffing | ||
| $response->headers->set('X-Content-Type-Options', 'nosniff'); | ||
|
|
||
| // Enable browser XSS protection (legacy browsers) | ||
| $response->headers->set('X-XSS-Protection', '1; mode=block'); | ||
|
|
||
| // Control referrer information sent with requests | ||
| $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin'); | ||
|
|
||
| // Only allow HTTPS connections (enforced in production) | ||
| if (config('app.env') === 'production') { | ||
| $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); | ||
| } | ||
|
|
||
| return $response; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| <?php | ||
|
|
||
| // SPDX-FileCopyrightText: 2025 SecPal Contributors | ||
| // SPDX-License-Identifier: AGPL-3.0-or-later | ||
|
|
||
| use App\Models\User; | ||
| use Illuminate\Foundation\Testing\RefreshDatabase; | ||
| use Illuminate\Support\Facades\Hash; | ||
|
|
||
| uses(RefreshDatabase::class); | ||
|
|
||
| describe('CSRF Token Endpoint', function () { | ||
| test('csrf cookie endpoint is accessible', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| $response->assertNoContent(); | ||
| }); | ||
|
|
||
| test('csrf cookie endpoint returns XSRF-TOKEN cookie', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| // XSRF-TOKEN cookie should be set by Laravel | ||
| $response->assertCookie('XSRF-TOKEN'); | ||
| }); | ||
|
|
||
| test('csrf cookie is httpOnly for session cookie', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| // Session cookie should be httpOnly (XSRF-TOKEN is not httpOnly by design - needs to be read by JS) | ||
| $cookies = $response->headers->getCookies(); | ||
| $sessionCookie = collect($cookies)->first(fn ($cookie) => str_contains($cookie->getName(), 'session')); | ||
|
|
||
| expect($sessionCookie)->not->toBeNull() | ||
| ->and($sessionCookie->isHttpOnly())->toBeTrue(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('CSRF Protection for State-Changing Requests', function () { | ||
| test('CSRF middleware is enabled globally', function () { | ||
| // Verify CSRF middleware is configured in Sanctum | ||
| $middleware = config('sanctum.middleware'); | ||
|
|
||
| expect($middleware)->toHaveKey('validate_csrf_token') | ||
| ->and($middleware['validate_csrf_token'])->toBe( | ||
| \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class | ||
| ); | ||
| }); | ||
|
|
||
| test('GET request does not require CSRF token', function () { | ||
| $user = User::factory()->create([ | ||
| 'email' => 'test@example.com', | ||
| 'password' => Hash::make('password123'), | ||
| ]); | ||
|
|
||
| $this->actingAs($user, 'sanctum'); | ||
|
|
||
| // GET request should work without CSRF token | ||
| $response = $this->getJson('/v1/me'); | ||
|
|
||
| // Should succeed (or return appropriate status, not 419) | ||
| expect($response->status())->not->toBe(419); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Session Cookie Configuration', function () { | ||
| test('session cookies have correct security attributes', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| $cookies = $response->headers->getCookies(); | ||
| $sessionCookie = collect($cookies)->first(fn ($cookie) => str_contains($cookie->getName(), 'session')); | ||
|
|
||
| expect($sessionCookie)->not->toBeNull() | ||
| ->and($sessionCookie->isHttpOnly())->toBeTrue() | ||
| ->and($sessionCookie->getSameSite())->toBe('lax'); | ||
|
|
||
| // In production, secure should be true (HTTPS only) | ||
| // In testing, it's false since we don't have HTTPS | ||
| if (config('session.secure')) { | ||
| expect($sessionCookie->isSecure())->toBeTrue(); | ||
| } | ||
| }); | ||
|
|
||
| test('XSRF-TOKEN cookie is not httpOnly to allow JavaScript access', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| $cookies = $response->headers->getCookies(); | ||
| $xsrfCookie = collect($cookies)->first(fn ($cookie) => $cookie->getName() === 'XSRF-TOKEN'); | ||
|
|
||
| expect($xsrfCookie)->not->toBeNull() | ||
| // XSRF-TOKEN must NOT be httpOnly - JS needs to read it | ||
| ->and($xsrfCookie->isHttpOnly())->toBeFalse(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('CSRF Token Refresh Flow', function () { | ||
| test('expired CSRF token can be refreshed', function () { | ||
| $user = User::factory()->create([ | ||
| 'email' => 'test@example.com', | ||
| 'password' => Hash::make('password123'), | ||
| ]); | ||
|
|
||
| // Get initial CSRF token | ||
| $csrfResponse = $this->get('/sanctum/csrf-cookie'); | ||
| $cookies = $csrfResponse->headers->getCookies(); | ||
| $xsrfCookie = collect($cookies)->first(fn ($cookie) => $cookie->getName() === 'XSRF-TOKEN'); | ||
|
|
||
| expect($xsrfCookie)->not->toBeNull(); | ||
|
|
||
| $oldToken = $xsrfCookie->getValue(); | ||
|
|
||
| // Simulate token expiration by getting a new token | ||
| $newCsrfResponse = $this->get('/sanctum/csrf-cookie'); | ||
| $newCookies = $newCsrfResponse->headers->getCookies(); | ||
| $newXsrfCookie = collect($newCookies)->first(fn ($cookie) => $cookie->getName() === 'XSRF-TOKEN'); | ||
|
|
||
| expect($newXsrfCookie)->not->toBeNull(); | ||
|
|
||
| $newToken = $newXsrfCookie->getValue(); | ||
|
|
||
| // Tokens should be different (new token generated) | ||
| // Note: In some cases they might be the same if session hasn't changed | ||
| // The important part is that the endpoint is accessible for refresh | ||
| expect($newToken)->toBeString(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| <?php | ||
|
|
||
| // SPDX-FileCopyrightText: 2025 SecPal Contributors | ||
| // SPDX-License-Identifier: AGPL-3.0-or-later | ||
|
|
||
| use Illuminate\Foundation\Testing\RefreshDatabase; | ||
|
|
||
| uses(RefreshDatabase::class); | ||
|
|
||
| describe('Security Headers Middleware', function () { | ||
| test('X-Frame-Options header is set to DENY', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| expect($response->headers->get('X-Frame-Options'))->toBe('DENY'); | ||
| }); | ||
|
|
||
| test('X-Content-Type-Options header is set to nosniff', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| expect($response->headers->get('X-Content-Type-Options'))->toBe('nosniff'); | ||
| }); | ||
|
|
||
| test('X-XSS-Protection header is set', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| expect($response->headers->get('X-XSS-Protection'))->toBe('1; mode=block'); | ||
| }); | ||
|
|
||
| test('Referrer-Policy header is set', function () { | ||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| expect($response->headers->get('Referrer-Policy'))->toBe('strict-origin-when-cross-origin'); | ||
| }); | ||
|
|
||
| test('Strict-Transport-Security header is not set in non-production', function () { | ||
| if (config('app.env') === 'production') { | ||
| $this->markTestSkipped('This test is for non-production environments only'); | ||
| } | ||
|
|
||
| $response = $this->get('/sanctum/csrf-cookie'); | ||
|
|
||
| expect($response->headers->has('Strict-Transport-Security'))->toBeFalse(); | ||
| }); | ||
|
|
||
| test('all security headers are present on API routes', function () { | ||
| $response = $this->get('/health'); | ||
|
|
||
| expect($response->headers->get('X-Frame-Options'))->toBe('DENY') | ||
| ->and($response->headers->get('X-Content-Type-Options'))->toBe('nosniff') | ||
| ->and($response->headers->get('X-XSS-Protection'))->toBe('1; mode=block') | ||
| ->and($response->headers->get('Referrer-Policy'))->toBe('strict-origin-when-cross-origin'); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.