Steuerkram/tests/54_SessionCookieHardeningTest.php

60 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
use Steuerkram\Auth;
class SessionCookieHardeningTest extends TestCase
{
protected string $testName = 'Test 54: Session-Cookie-Härtung (HttpOnly, SameSite, Secure)';
public function run(): void
{
$httpsBackup = $_SERVER['HTTPS'] ?? null;
$forwardBackup = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null;
unset($_SERVER['HTTPS'], $_SERVER['HTTP_X_FORWARDED_PROTO']);
putenv('SESSION_COOKIE_SECURE');
// Auth::cookieParams() berechnet die Cookie-Attribute ohne Seiteneffekt (kein echter
// session_start()). Ein echter Sessionstart würde hier scheitern, da der Test-Runner
// bereits Ergebnisse per echo ausgibt – PHP behandelt Header/Session-Cookies danach
// als "bereits gesendet". cookieParams() prüft dieselbe Logik ohne dieses Problem.
try {
// Plain HTTP ohne Override: httponly/samesite immer gesetzt, secure aus
$params = Auth::cookieParams();
$this->assert($params['httponly'] === true, 'HttpOnly-Flag ist gesetzt');
$this->assertEquals('Lax', $params['samesite'], 'SameSite steht auf Lax');
$this->assert($params['secure'] === false, 'Secure ist bei Plain-HTTP ohne Override deaktiviert');
// Erzwungenes Secure per Env, unabhängig vom Request
putenv('SESSION_COOKIE_SECURE=1');
$params = Auth::cookieParams();
$this->assert($params['secure'] === true, 'SESSION_COOKIE_SECURE=1 erzwingt Secure-Flag');
// Override hat Vorrang vor erkanntem HTTPS-Request
putenv('SESSION_COOKIE_SECURE=0');
$_SERVER['HTTPS'] = 'on';
$params = Auth::cookieParams();
$this->assert($params['secure'] === false, 'SESSION_COOKIE_SECURE=0 deaktiviert Secure trotz HTTPS-Request');
// Ohne Override: Reverse-Proxy-Header aktiviert Secure automatisch
putenv('SESSION_COOKIE_SECURE');
unset($_SERVER['HTTPS']);
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$params = Auth::cookieParams();
$this->assert($params['secure'] === true, 'X-Forwarded-Proto: https aktiviert Secure automatisch');
} finally {
putenv('SESSION_COOKIE_SECURE');
if ($httpsBackup === null) {
unset($_SERVER['HTTPS']);
} else {
$_SERVER['HTTPS'] = $httpsBackup;
}
if ($forwardBackup === null) {
unset($_SERVER['HTTP_X_FORWARDED_PROTO']);
} else {
$_SERVER['HTTP_X_FORWARDED_PROTO'] = $forwardBackup;
}
}
}
}