fix(security): make session-cookie hardening work under TLS termination

The passive scan flagged 3x MEDIUM 'PHPSESSID missing Secure' and an
admin-login cookie missing HttpOnly. Root cause was not the cookie code
but scheme detection: every call site read $_SERVER['HTTPS'] directly,
which is unset when TLS is terminated in front of PHP-FPM, so the Secure
flag was silently dropped.

Add RequestUtil::isSecure()/baseUrl() as the single scheme detector:
  1. $_SERVER['HTTPS'] (direct TLS)
  2. X-Forwarded-Proto — only from a loopback/private peer, so a remote
     client cannot spoof it
  3. SERVER_PORT == 443
Replace all 8 inline $_SERVER['HTTPS'] idioms (App, AdminAuth, 4x filepond
endpoints, validate-access, admin/acces, SystemController self-ping).

nginx: forward the scheme to php-fpm in all 4 fastcgi blocks
(fastcgi_param HTTPS $https + X-Forwarded-Proto $scheme) and uncomment
server_tokens off. Config validated with nginx -t (real config, alpine
container).

AdminAuth: logout() now clears the session cookie with the same
path/domain/secure/httponly/samesite it was set with, instead of the
legacy positional setcookie() that dropped SameSite.

Tests (+24, 340 total):
  - RequestUtilTest: scheme detection incl. proxy trust boundaries
  - SessionCookieTest: logout emits a hardened deletion cookie
  - PeerTubeIntegrationTest: PeerTube keeps using its absolute instance_url
    and is unaffected by scheme changes (Guzzle MockHandler)
  - NginxConfigTest: pins HTTPS forwarding, HSTS includeSubDomains,
    server_tokens off

PeerTube uses an absolute instance_url from the DB and never derives URLs
from the request, so the integration is unchanged — the regression tests
lock that invariant in.
This commit is contained in:
Pontoporeia committed 2026-10-14 10:31:23 +02:00
1 parent e1f9cc9a9a
commit 554fc57455
17 files changed
+652 -29

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
<?php
use PHPUnit\Framework\TestCase;
/**
* NginxConfigTest — regression guard for the passive-scan hardening.
*
* The scan found live responses where:
* - HSTS lacked includeSubDomains (config drift),
* - PHP did not know the request was HTTPS (Secure cookie flag dropped),
* - the nginx version was disclosed via the Server header.
*
* The PHP-side fixes only work if nginx forwards the scheme to PHP-FPM and
* hides its version. These assertions pin the config so a later edit can't
* silently undo them.
*
* Full syntax validation still runs server-side via `nginx -t` in
* scripts/deploy-server.sh.
*/
class NginxConfigTest extends TestCase
{
private string $conf;
protected function setUp(): void
{
$path = APP_ROOT . '/../nginx/xamxam.conf';
$this->assertFileExists($path);
$this->conf = (string) file_get_contents($path);
}
public function testServerTokensDisabled(): void
{
$this->assertMatchesRegularExpression(
'/^\s*server_tokens\s+off;/m',
$this->conf,
'server_tokens must be active (not commented) to hide the nginx version'
);
}
public function testHstsIncludesSubdomainsAndPreload(): void
{
$this->assertMatchesRegularExpression(
'/add_header\s+Strict-Transport-Security\s+"max-age=\d+;\s*includeSubDomains;\s*preload;"/',
$this->conf,
'HSTS must include includeSubDomains; preload'
);
}
/**
* Every php-fpm location must forward HTTPS + the original scheme, or
* RequestUtil falls back to insecure and cookies lose the Secure flag.
*/
public function testEveryPhpLocationForwardsHttpsSignal(): void
{
$phpValueCount = preg_match_all('/fastcgi_param\s+PHP_VALUE\s+"upload_max_filesize/m', $this->conf);
$httpsCount = preg_match_all('/fastcgi_param\s+HTTPS\s+\$https;/m', $this->conf);
$protoCount = preg_match_all('/fastcgi_param\s+HTTP_X_FORWARDED_PROTO\s+\$scheme;/m', $this->conf);
$this->assertGreaterThan(0, $phpValueCount, 'expected php-fpm locations');
$this->assertSame(
$phpValueCount,
$httpsCount,
"every php-fpm block must set fastcgi_param HTTPS (\$phpValue=$phpValueCount, https=$httpsCount)"
);
$this->assertSame(
$phpValueCount,
$protoCount,
"every php-fpm block must set X-Forwarded-Proto (\$phpValue=$phpValueCount, proto=$protoCount)"
);
}
/**
* The admin location must keep its CSP and noindex header, and must not
* inherit a broken frame-ancestors from the parent.
*/
public function testAdminLocationKeepsSecurityHeaders(): void
{
$this->assertMatchesRegularExpression(
'#location\s+\^~\s+/admin/\s*\{.*?add_header\s+Content-Security-Policy#s',
$this->conf,
'admin location must define its own CSP'
);
$this->assertStringContainsString('X-Robots-Tag "noindex, nofollow"', $this->conf);
}
}
+136
View File
@@ -0,0 +1,136 @@
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* PeerTubeIntegrationTest — regression guard for the HTTPS/scheme changes.
*
* The session-cookie hardening (RequestUtil::isSecure) changed how the app
* detects the request scheme. PeerTube must be unaffected: the service talks
* to an *absolute* instance_url stored in peertube_settings, and must never
* derive or rewrite that URL from $_SERVER.
*
* These tests pin the exact URLs PeerTubeService builds, so a future refactor
* that starts routing PeerTube through request-derived base URLs fails loudly.
*
* Uses Guzzle's MockHandler so no network is touched.
*/
class PeerTubeIntegrationTest extends TestCase
{
private Database $db;
private MockHandler $mock;
protected function setUp(): void
{
$this->db = TestDatabase::getInstance();
$this->db->getPDO()->exec('DELETE FROM peertube_settings');
$this->db->getPDO()->exec('INSERT INTO peertube_settings (id) VALUES (1)');
// TestDatabase is a shared singleton — reset the feature flag we toggle.
$this->db->getPDO()
->exec("DELETE FROM site_settings WHERE key = 'peertube_upload_enabled'");
$this->mock = new MockHandler();
$stack = HandlerStack::create($this->mock);
PeerTubeService::setHttpClient(new Client([
'handler' => $stack,
'http_errors' => false,
'allow_redirects' => false,
]));
}
protected function tearDown(): void
{
PeerTubeService::setHttpClient(null);
$this->db->getPDO()
->exec("DELETE FROM site_settings WHERE key = 'peertube_upload_enabled'");
}
/** Queue an OAuth client + token handshake, then return the request index. */
private function queueAuth(string $instanceUrl): void
{
$this->mock->append(new Response(200, [], json_encode([
'client_id' => 'cid',
'client_secret' => 'csec',
])));
$this->mock->append(new Response(200, [], json_encode([
'access_token' => 'tok',
])));
}
/**
* Settings are stored and read back verbatim — instance_url is absolute,
* independent of any request context.
*/
public function testInstanceUrlStoredVerbatim(): void
{
PeerTubeService::updateSettings($this->db, [
'instance_url' => 'https://video.erg.be/',
'channel_name' => 'tfe@video.erg.be',
'privacy' => 2,
]);
$s = PeerTubeService::getSettings($this->db);
$this->assertSame('https://video.erg.be', $s['instance_url'], 'trailing slash trimmed');
$this->assertSame('tfe@video.erg.be', $s['channel_name']);
$this->assertSame(2, $s['privacy']);
}
/**
* probeAuth() must hit the absolute instance_url, not a request-derived
* host. Changing HTTPS detection must not alter these URLs.
*/
public function testProbeAuthUsesAbsoluteInstanceUrl(): void
{
$s = [
'instance_url' => 'https://video.erg.be',
'username' => 'user',
'password' => 'pass',
];
$this->queueAuth('https://video.erg.be');
$result = PeerTubeService::probeAuth($s);
$this->assertTrue($result['ok'], $result['error']);
// Last request in the handshake is the token exchange; it must target
// the absolute configured instance URL.
$this->assertSame(
'https://video.erg.be/api/v1/users/token',
(string) $this->mock->getLastRequest()->getUri()
);
}
/**
* An HTTP instance_url must be preserved as-is. If URL handling ever
* started "upgrading" to https based on request scheme, this fails.
*/
public function testHttpInstanceUrlPreservedWhenConfigured(): void
{
PeerTubeService::updateSettings($this->db, [
'instance_url' => 'http://localhost:9000',
'channel_name' => 'chan',
]);
$s = PeerTubeService::getSettings($this->db);
$this->assertSame('http://localhost:9000', $s['instance_url']);
}
/**
* isEnabled() is a pure feature-flag read and must not depend on request
* scheme or HTTPS detection.
*/
public function testFeatureFlagIndependentOfRequestScheme(): void
{
$this->assertFalse(PeerTubeService::isEnabled($this->db));
$this->db->getPDO()
->prepare("INSERT OR REPLACE INTO site_settings (key, value) VALUES ('peertube_upload_enabled', '1')")
->execute();
$this->assertTrue(PeerTubeService::isEnabled($this->db));
}
}
+138
View File
@@ -0,0 +1,138 @@
<?php
use PHPUnit\Framework\TestCase;
/**
* RequestUtilTest — scheme detection under direct TLS and reverse-proxy
* TLS termination.
*
* Regression context: production terminates TLS in front of PHP-FPM, so
* $_SERVER['HTTPS'] is unset. The previous inline idiom
* (empty($_SERVER['HTTPS']) && ... !== 'off') silently returned false and
* session cookies lost their Secure flag. These tests lock in the
* proxy-aware behaviour.
*/
class RequestUtilTest extends TestCase
{
public function testDirectTlsIsSecure(): void
{
$this->assertTrue(RequestUtil::isSecure(['HTTPS' => 'on']));
$this->assertTrue(RequestUtil::isSecure(['HTTPS' => '1']));
$this->assertTrue(RequestUtil::isSecure(['HTTPS' => 'https']));
$this->assertTrue(RequestUtil::isSecure(['HTTPS' => 'ON']));
}
public function testExplicitHttpsOffIsInsecure(): void
{
$this->assertFalse(RequestUtil::isSecure(['HTTPS' => 'off']));
$this->assertFalse(RequestUtil::isSecure(['HTTPS' => 'OFF']));
$this->assertFalse(RequestUtil::isSecure(['HTTPS' => '']));
}
public function testPlainHttpWithLoopbackPeerIsInsecure(): void
{
// No HTTPS var, no proxy header, port 80 → plain HTTP.
$this->assertFalse(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'SERVER_PORT' => '80',
]));
}
public function testForwardedProtoHttpsFromTrustedProxyIsSecure(): void
{
// The production topology: nginx terminates TLS and forwards to
// PHP-FPM on loopback, setting X-Forwarded-Proto.
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
}
public function testForwardedProtoHttpsFromPrivateProxyIsSecure(): void
{
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '10.0.0.5',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '192.168.1.10',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '::1',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
}
public function testForwardedProtoIgnoredFromUntrustedPeer(): void
{
// A remote client sending the header over plain HTTP must NOT be
// treated as secure — otherwise the header is trivially spoofable.
$this->assertFalse(RequestUtil::isSecure([
'REMOTE_ADDR' => '203.0.113.42',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
}
public function testForwardedProtoListUsesFirstValue(): void
{
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'https, http',
]));
$this->assertFalse(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'http, https',
]));
}
public function testForwardedProtoHttpValueIsInsecure(): void
{
$this->assertFalse(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'http',
]));
}
public function testServerPortFallback(): void
{
$this->assertTrue(RequestUtil::isSecure(['SERVER_PORT' => 443]));
$this->assertTrue(RequestUtil::isSecure(['SERVER_PORT' => '443']));
$this->assertFalse(RequestUtil::isSecure(['SERVER_PORT' => 8080]));
}
public function testDirectTlsBeatsUntrustedProxyHeader(): void
{
// HTTPS=on is authoritative even if a bogus proxy header says http.
$this->assertTrue(RequestUtil::isSecure([
'HTTPS' => 'on',
'REMOTE_ADDR' => '203.0.113.42',
'HTTP_X_FORWARDED_PROTO' => 'http',
]));
}
public function testBaseUrlRespectsProxyTermination(): void
{
$this->assertSame('https://xamxam.erg.be', RequestUtil::baseUrl([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'https',
'HTTP_HOST' => 'xamxam.erg.be',
]));
}
public function testBaseUrlFallsBackToLocalhost(): void
{
$this->assertSame('http://localhost', RequestUtil::baseUrl([]));
}
public function testIsTrustedProxyClassification(): void
{
$this->assertTrue(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => '127.0.0.1']));
$this->assertTrue(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => '::1']));
$this->assertTrue(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => '172.16.0.1']));
$this->assertTrue(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => 'fd00::1']));
$this->assertFalse(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => '8.8.8.8']));
$this->assertFalse(RequestUtil::isTrustedProxy(['REMOTE_ADDR' => '']));
$this->assertFalse(RequestUtil::isTrustedProxy([]));
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
use PHPUnit\Framework\TestCase;
/**
* SessionCookieTest — regression guard for the session cookie hardening that
* the passive security scan flagged (PHPSESSID missing Secure / HttpOnly).
*
* Root cause was two-fold:
* 1. Scheme detection used $_SERVER['HTTPS'] directly, which is unset under
* reverse-proxy TLS termination → Secure silently dropped.
* 2. AdminAuth::logout() emitted a deletion cookie without SameSite (and with
* the legacy positional signature), so the stale cookie could linger.
*
* Uses xdebug_get_headers() to inspect the emitted Set-Cookie header.
*/
class SessionCookieTest extends TestCase
{
protected function setUp(): void
{
if (!function_exists('xdebug_get_headers')) {
$this->markTestSkipped('xdebug required to inspect headers');
}
// Reset any session left over from another test.
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION = [];
session_destroy();
}
if (!headers_sent()) {
header_remove();
}
}
protected function tearDown(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION = [];
session_destroy();
}
}
/** Every Set-Cookie emitted must carry Secure+HttpOnly+SameSite. */
private function assertHardenedSetCookie(string $header): void
{
$this->assertStringContainsStringIgnoringCase('HttpOnly', $header, $header);
$this->assertStringContainsStringIgnoringCase('Secure', $header, $header);
$this->assertStringContainsStringIgnoringCase('SameSite', $header, $header);
}
/** Start an admin session exactly the way the panel does. */
private function startAdminSession(): void
{
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
// Simulate production: TLS terminated by a trusted proxy, so
// $_SERVER['HTTPS'] is absent and only X-Forwarded-Proto is set.
unset($_SERVER['HTTPS']);
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
// AdminAuth::startSession() is private; logout() calls it first.
// Seed the session directly with the same params it applies.
session_set_cookie_params([
'lifetime' => 604800,
'path' => '/admin',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
session_start();
$_SESSION['admin_authenticated'] = true;
}
public function testLogoutEmitsHardenedDeletionCookie(): void
{
$this->startAdminSession();
header_remove();
AdminAuth::logout();
$headers = xdebug_get_headers();
$cookies = array_values(array_filter(
$headers,
static fn (string $h): bool => stripos($h, 'Set-Cookie:') === 0
&& stripos($h, 'PHPSESSID') !== false
));
$this->assertNotEmpty($cookies, 'logout must clear the session cookie');
foreach ($cookies as $header) {
$this->assertHardenedSetCookie($header);
// Deletion requires an expiry in the past.
$this->assertMatchesRegularExpression('/expires=.*(1981|1970)/i', $header, $header);
}
}
public function testLogoutIsNoOpWhenNoSession(): void
{
// No active session — logout() must return quietly, not fatal.
$this->assertSame(PHP_SESSION_NONE, session_status());
AdminAuth::logout();
$this->assertSame(PHP_SESSION_NONE, session_status());
}
/**
* The Secure flag must be driven by RequestUtil (proxy-aware), not by the
* raw $_SERVER['HTTPS'] idiom that regressed in production.
*/
public function testSecureDetectionUnderProxyTermination(): void
{
$this->assertTrue(RequestUtil::isSecure([
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
$this->assertFalse(RequestUtil::isSecure([
'REMOTE_ADDR' => '203.0.113.7',
'HTTP_X_FORWARDED_PROTO' => 'https',
]));
}
}