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

+6 -5
View File
@@ -1,4 +1,4 @@
Exported 80 tasks to /home/theophile/repos/xamxam/TODO.md
Exported 81 tasks to /home/theophile/repos/xamxam/TODO.md
rategy: run unusedSymbols report-only (10-14) first to get go/no-go reclaimable-byte data; per-page split (u-x) second, reusing template inventory in docs/css-split-analysis.md.
## In Progress
@@ -6,14 +6,11 @@ rategy: run unusedSymbols report-only (10-14) first to get go/no-go reclaimable-
## Pending
- [ ] #test-env-deploy-code-chown-regression test-env deploy-code --chown regression documented in README --context test-env
- [ ] #history-cleanup-66-commits [!medium] History cleanup: 66 commits squashed to 29 on top of main; pre-squash backup at refs/backup/pre-squash-tip (tree 8649514e) + git bundle /tmp/xamxam-presquash.bundle
- [ ] #security-scan-passive-xamxam-erg-be [!high] Security scan (passive, xamxam.erg.be): verify nginx config drift — live HSTS is 'max-age=63072000; preload;' but repo nginx/xamxam.conf:58 has 'includeSubDomains; preload;'. Repo config is correct; deployed config is stale. Run 'just deploy-nginx' and re-check. --context security
- [ ] #security-scan-scanner-s-cookie [!high] Security scan: scanner's 'Cookie PHPSESSID missing Secure' (3x MEDIUM). Code sets Secure conditionally via $_SERVER['HTTPS'] (App.php:29, AdminAuth.php:73, filepond). Likely scanner probed HTTP, or HTTPS var unset. Verify prod: nginx passes HTTPS/X-Forwarded-Proto to fastcgi so Secure flag is not silently dropped under TLS termination. --context security
- [ ] #security-scan-admin-login [!high] Security scan: admin login cookie missing HttpOnly (scanner MEDIUM #3). AdminAuth::startSession sets httponly=true but login.php path may start session before AdminAuth hardening, or path=/admin scoping drops it. Trace session start order on /admin/login.php and ensure the login-response Set-Cookie carries HttpOnly+Secure+SameSite. --context security
- [ ] #security-scan-low-reduce [!low] Security scan (LOW): reduce CSP script-src 'unsafe-inline'/'unsafe-eval' (nginx/xamxam.conf:59,148,193). Blockers documented: OverType editor init inline block + htmx Function() eval. Path: migrate inline init to external JS with nonce or hashes; check htmx version for CSP-safe build. Low priority (admin already auth-gated). --context security
- [ ] #security-scan-low-server-tokens [!low] Security scan (LOW): server_tokens off is commented out (nginx/xamxam.conf:68) — live Server: nginx disclosure. Uncomment or set in http block; confirm token stripped. --context security
- [ ] #security-scan-info-5 [!low] Security scan (INFO): 5 subdomains exist on shared hosts (www/ftp on 79.99.200.80, mail/wiki on 79.99.201.119, gitlab on 92.222.93.212). Session cookies are host-scoped (no Domain= set), so no cross-subdomain cookie leak — confirmed OK. Action: none unless a wildcard cert/Domain cookie is ever introduced. --context security
- [ ] #security-scan-info-negative [!low] Security scan (INFO, negative result): certificate expiry check — live TLS cert expires 2026-12-02 (~49 days). Let's Encrypt auto-renew should cover it, but confirm certbot renew timer is active/enabled on server. --context deploy
- [ ] #security-scan-meta-passive [!medium] Security scan meta: passive scan revealed repo nginx config != deployed nginx config (HSTS includeSubDomains + Referrer-Policy differ). Add a post-deploy drift check (e.g. curl live headers and diff against nginx/xamxam.conf expected values) so config drift is caught, not discovered by scanners. --context deploy
- [ ] #deploy-the-security-scan-nginx [!high] Deploy the security-scan nginx fixes to production: run 'just deploy-nginx' then verify live headers (HSTS includeSubDomains, Server: without version, PHPSESSID Secure+HttpOnly+SameSite). Repo config is fixed; server is still running the stale config. --context deploy
## Completed
- [x] #audit-all-docs-and [!high] Audit all docs/ and classify accurate vs stale
@@ -78,6 +75,10 @@ rategy: run unusedSymbols report-only (10-14) first to get go/no-go reclaimable-
- [x] #verify-final-tree-identical [!medium] Verify final tree identical to backup
- [x] #decide-fate-of-stray [!low] Remove stray tracked commits.txt (6268-line git log dump) — Removed; no code references it
- [x] #fix-6-pre-existing-phpstan [!medium] Fix 6 pre-existing phpstan errors (AdminAuth, ExportController x2, SystemController, TfeController, validate-file-fragment-shared)
- [x] #security-scan-passive-xamxam-erg-be [!high] Security scan (passive, xamxam.erg.be): verify nginx config drift — live HSTS is 'max-age=63072000; preload;' but repo nginx/xamxam.conf:58 has 'includeSubDomains; preload;'. Repo config is correct; deployed config is stale. Run 'just deploy-nginx' and re-check. --context security
- [x] #security-scan-scanner-s-cookie [!high] Security scan: scanner's 'Cookie PHPSESSID missing Secure' (3x MEDIUM). Code sets Secure conditionally via $_SERVER['HTTPS'] (App.php:29, AdminAuth.php:73, filepond). Likely scanner probed HTTP, or HTTPS var unset. Verify prod: nginx passes HTTPS/X-Forwarded-Proto to fastcgi so Secure flag is not silently dropped under TLS termination. --context security
- [x] #security-scan-admin-login [!high] Security scan: admin login cookie missing HttpOnly (scanner MEDIUM #3). AdminAuth::startSession sets httponly=true but login.php path may start session before AdminAuth hardening, or path=/admin scoping drops it. Trace session start order on /admin/login.php and ensure the login-response Set-Cookie carries HttpOnly+Secure+SameSite. --context security
- [x] #security-scan-low-server-tokens [!low] Security scan (LOW): server_tokens off is commented out (nginx/xamxam.conf:68) — live Server: nginx disclosure. Uncomment or set in http block; confirm token stripped. --context security
## Deferred / Blocked
- [ ] #just-setup-backs-a [!medium] just setup backs a stale setup-dev.sh (clones php-live-reload, legacy admin/data/ dirs) — needs rewrite or removal
+2 -2
View File
@@ -11,8 +11,8 @@ $shareLink = ShareLink::make();
$links = $shareLink->listActive();
$archivedLinks = $shareLink->listArchived();
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$baseUrl = $protocol . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
require_once APP_ROOT . '/src/RequestUtil.php';
$baseUrl = RequestUtil::baseUrl();
// ── Demandes d'accès aux fichiers ─────────────────────────────────────────────
require_once APP_ROOT . '/src/Database.php';
+2 -1
View File
@@ -14,7 +14,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -16,7 +16,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -13,7 +13,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
@@ -13,7 +13,8 @@ require_once __DIR__ . '/../../../../src/FilepondHandler.php';
// ── Start session ────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
+2 -1
View File
@@ -164,8 +164,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sessionToken = $db->createAccessSession($redemption['request_id'], 30);
// Set HttpOnly, Secure, SameSite=Strict cookie (long-lived session)
require_once APP_ROOT . '/src/RequestUtil.php';
$cookieName = 'tfe_access_' . $thesisId;
$cookieSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
$cookieSecure = RequestUtil::isSecure();
setcookie($cookieName, $sessionToken, [
'expires' => time() + 30 * 86400,
+30 -12
View File
@@ -67,6 +67,9 @@ class AdminAuth
return;
}
// Harden session cookie (item #8)
// Secure is always on for admin: the panel is only reachable over
// HTTPS in production, and the cli-server dev exception is scoped to
// the built-in server that cannot do TLS anyway.
session_set_cookie_params([
'lifetime' => self::COOKIE_LIFETIME_SECONDS,
'path' => '/admin',
@@ -77,6 +80,32 @@ class AdminAuth
session_start();
}
/**
* Clear the session cookie with the same attributes used to set it.
*
* A deletion cookie must repeat the original path/domain/secure/httponly
* (and samesite, for consistency) or browsers keep the stale cookie.
*/
private static function clearSessionCookie(): void
{
if (!ini_get('session.use_cookies')) {
return;
}
$p = session_get_cookie_params();
setcookie(
session_name(),
'',
[
'expires' => time() - 86400,
'path' => $p['path'],
'domain' => $p['domain'],
'secure' => $p['secure'],
'httponly' => $p['httponly'],
'samesite' => $p['samesite'],
]
);
}
/**
* Enforce server-side idle + absolute timeouts on an authenticated session.
*
@@ -382,18 +411,7 @@ class AdminAuth
}
self::startSession();
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 86400,
$p['path'],
$p['domain'],
$p['secure'],
$p['httponly']
);
}
self::clearSessionCookie();
session_destroy();
}
}
+2 -1
View File
@@ -24,7 +24,8 @@ class App
self::$booted = true;
}
if (session_status() === PHP_SESSION_NONE) {
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
require_once APP_ROOT . '/src/RequestUtil.php';
$isSecure = RequestUtil::isSecure();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
+4 -2
View File
@@ -510,8 +510,10 @@ class SystemController
'detail' => null,
];
// Site HTTP ping
$siteUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/';
// Site HTTP ping — use the same scheme detection as the rest of the
// app so the self-check follows TLS termination (reverse proxy).
require_once APP_ROOT . '/src/RequestUtil.php';
$siteUrl = RequestUtil::baseUrl() . '/';
$httpResult = $this->localHttpCheck($siteUrl);
$checks['site_http'] = [
'label' => 'Site HTTP',
+9
View File
@@ -37,6 +37,15 @@ class PeerTubeService
/** @var Client|null Shared Guzzle client (lazy-init). */
private static ?Client $httpClient = null;
/**
* Inject an HTTP client (used by integration tests with Guzzle MockHandler).
* Pass null to reset to the lazy default client.
*/
public static function setHttpClient(?Client $client): void
{
self::$httpClient = $client;
}
// -------------------------------------------------------------------------
// DB CRUD
// -------------------------------------------------------------------------
+102
View File
@@ -0,0 +1,102 @@
<?php
/**
* RequestUtil — request-level helpers shared across the app.
*
* Centralises scheme detection so that session cookies, absolute URLs and
* system checks all agree on whether the current request is secure.
*
* Detection order (first match wins):
* 1. $_SERVER['HTTPS'] — set to a truthy value ("on", "1", "https") by
* nginx/apache when the request is served over TLS. This is the
* canonical signal and covers the non-proxied case.
* 2. X-Forwarded-Proto — set by a TLS-terminating reverse proxy in front
* of PHP-FPM. We only trust it when the direct peer is a loopback or
* private address, so a remote client cannot spoof it by sending the
* header itself.
* 3. SERVER_PORT === 443 — last resort for setups that expose the port but
* neither of the above.
*
* Always prefer isSecure() over reading $_SERVER['HTTPS'] inline: under TLS
* termination (the production topology) $_SERVER['HTTPS'] is unset and the
* inline idiom silently drops the session cookie Secure flag.
*/
class RequestUtil
{
/**
* Whether the current request arrived over HTTPS.
*
* @param array<string,mixed>|null $server Override for $_SERVER (tests).
*/
public static function isSecure(?array $server = null): bool
{
$server ??= $_SERVER;
// 1. Direct TLS: nginx sets HTTPS=on. Treat "off"/"" as insecure.
$https = $server['HTTPS'] ?? null;
if ($https !== null && $https !== '' && strtolower((string) $https) !== 'off') {
return true;
}
// 2. Reverse-proxy TLS termination. Only trust the header from a
// trusted (loopback/private) peer — otherwise a client could send
// X-Forwarded-Proto: https over plain HTTP and get Secure cookies
// issued (which is harmless) or, worse, poison cached URLs.
$proto = $server['HTTP_X_FORWARDED_PROTO'] ?? '';
if ($proto !== '' && self::isTrustedProxy($server)) {
$first = strtolower(trim(explode(',', (string) $proto)[0]));
if ($first === 'https') {
return true;
}
}
// 3. Port fallback.
if (($server['SERVER_PORT'] ?? null) == 443) {
return true;
}
return false;
}
/**
* Whether the direct peer (REMOTE_ADDR) is a loopback / private address,
* i.e. a proxy we control rather than an arbitrary internet client.
*
* @param array<string,mixed> $server
*/
public static function isTrustedProxy(array $server): bool
{
$remote = (string) ($server['REMOTE_ADDR'] ?? '');
if ($remote === '') {
return false;
}
// Loopback IPv4/IPv6.
if ($remote === '127.0.0.1' || $remote === '::1') {
return true;
}
// Private ranges (RFC 1918 + link-local + unique-local IPv6).
$isPrivate = filter_var(
$remote,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) === false;
return $isPrivate;
}
/**
* Absolute base URL for the current request (scheme://host), respecting
* proxy TLS termination. Used for links and system self-checks.
*
* @param array<string,mixed>|null $server Override for $_SERVER (tests).
*/
public static function baseUrl(?array $server = null): string
{
$server ??= $_SERVER;
$scheme = self::isSecure($server) ? 'https' : 'http';
$host = $server['HTTP_HOST'] ?? 'localhost';
return $scheme . '://' . $host;
}
}
+10 -2
View File
@@ -64,8 +64,8 @@ server {
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
# Server tokens already disabled in nginx.conf
# server_tokens off;
# Hide nginx version in Server header and error pages.
server_tokens off;
# Max upload size (for thesis files — can include video)
client_max_body_size 8192M;
@@ -157,6 +157,8 @@ server {
# Security parameters (must be <= client_max_body_size)
fastcgi_param PHP_VALUE "upload_max_filesize=8192M \n post_max_size=8192M \n upload_tmp_dir=/var/www/xamxam/storage/tmp/php-uploads";
fastcgi_param HTTPS $https;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
# Timeouts
fastcgi_read_timeout 600;
@@ -177,6 +179,8 @@ server {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
fastcgi_param PHP_VALUE "upload_max_filesize=8192M \n post_max_size=8192M \n upload_tmp_dir=/var/www/xamxam/storage/tmp/php-uploads";
fastcgi_param HTTPS $https;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
}
@@ -200,6 +204,8 @@ server {
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
fastcgi_param PHP_VALUE "upload_max_filesize=8192M \n post_max_size=8192M \n upload_tmp_dir=/var/www/xamxam/storage/tmp/php-uploads";
fastcgi_param HTTPS $https;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
}
@@ -221,6 +227,8 @@ server {
# Security parameters (must be <= client_max_body_size)
fastcgi_param PHP_VALUE "upload_max_filesize=8192M \n post_max_size=8192M \n upload_tmp_dir=/var/www/xamxam/storage/tmp/php-uploads";
fastcgi_param HTTPS $https;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
# Timeouts
fastcgi_read_timeout 600;
+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',
]));
}
}