Files
2026-06-02 22:14:33 +02:00

69 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/CsrfGuard.php';
require_once PLUGIN_ROOT . '/exec/lib/Http.php';
require_once PLUGIN_ROOT . '/exec/lib/Settings.php';
require_once PLUGIN_ROOT . '/exec/lib/Lang.php';
require_once PLUGIN_ROOT . '/exec/lib/DirectAdminUser.php';
require_once PLUGIN_ROOT . '/exec/lib/RuleRepository.php';
require_once PLUGIN_ROOT . '/exec/lib/AuditLog.php';
require_once PLUGIN_ROOT . '/exec/lib/AppContext.php';
test('csrf token is bound to user session action and time', function (): void {
$guard = new CsrfGuard('secret', 'alice', 'session-1');
$issued = $guard->issue('create');
assert_true($guard->validate('create', (string)$issued['ts'], $issued['token'], 3600, 'session-1'));
assert_false((new CsrfGuard('secret', 'bob', 'session-1'))->validate('create', (string)$issued['ts'], $issued['token'], 3600, 'session-1'));
assert_false($guard->validate('delete', (string)$issued['ts'], $issued['token'], 3600, 'session-1'));
assert_false($guard->validate('create', (string)($issued['ts'] - 7200), $issued['token'], 3600, 'session-1'));
assert_false($guard->validate('create', 'bad', $issued['token'], 3600, 'session-1'));
});
test('csrf form fields use plugin scoped names to avoid directadmin token collisions', function (): void {
$settings = Settings::load(TEST_TMP . '/missing-csrf-form.conf');
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = $ctx->csrfField('create');
assert_contains('name="gar_csrf_ts"', $html);
assert_contains('name="gar_csrf_sid"', $html);
assert_contains('name="gar_csrf_token"', $html);
assert_false(str_contains($html, 'name="csrf_token"'));
});
test('http bootstrap populates post data from directadmin cli environment', function (): void {
$oldGet = $_GET;
$oldPost = $_POST;
$oldRequest = $_REQUEST;
$oldServer = $_SERVER;
putenv('REQUEST_METHOD=POST');
putenv('QUERY_STRING=id=abc');
putenv('POST=gar_csrf_ts=123&gar_csrf_sid=sid&gar_csrf_token=token&body=Hello+World');
try {
Http::bootstrapGlobals();
assert_same('POST', Http::method());
assert_same('abc', Http::getString($_GET, 'id'));
assert_same('123', Http::getString($_POST, 'gar_csrf_ts'));
assert_same('token', Http::getString($_POST, 'gar_csrf_token'));
assert_same('Hello World', Http::getString($_POST, 'body'));
} finally {
putenv('REQUEST_METHOD');
putenv('QUERY_STRING');
putenv('POST');
$_GET = $oldGet;
$_POST = $oldPost;
$_REQUEST = $oldRequest;
$_SERVER = $oldServer;
}
});