Files
madar/tests/security.php
T
2026-09-05 15:54:33 +03:30

76 lines
4.2 KiB
PHP

<?php
declare(strict_types=1);
use App\Http\HttpException;
use App\Security\InitDataValidator;
use App\Security\RateLimiter;
require dirname(__DIR__) . '/bootstrap/autoload.php';
$tests = 0;
function check(bool $condition, string $name): void
{
global $tests;
if (!$condition) {
throw new RuntimeException('FAIL: ' . $name);
}
$tests++;
echo 'PASS: ' . $name . PHP_EOL;
}
function rejects(callable $fn, string $name, int $status = 401): void
{
try {
$fn();
} catch (HttpException $e) {
check($e->status === $status, $name);
return;
}
throw new RuntimeException('FAIL: accepted ' . $name);
}
function signFixture(array $data, string $token): string
{
ksort($data, SORT_STRING);
$pairs = [];
foreach ($data as $k => $v) {
$pairs[] = $k . '=' . $v;
}
$data['hash'] = hash_hmac('sha256', implode("\n", $pairs), hash_hmac('sha256', $token, 'WebAppData', true));
return http_build_query($data, '', '&', PHP_QUERY_RFC3986);
}
$token = 'TEST_ONLY_NOT_A_REAL_TOKEN';
$now = 1800000000;
$data = ['auth_date' => (string) $now, 'user' => '{"id":279058397,"first_name":"مهدی + & =","allows_write_to_pm":true}', 'start_param' => 'hello+world'];
$signed = signFixture($data, $token);
$validated = InitDataValidator::validate($signed, $token, 300, $now);
check($validated['start_param'] === 'hello+world', 'URL decoding preserves encoded plus');
check(InitDataValidator::user($validated)['first_name'] === 'مهدی + & =', 'Persian user data is preserved');
check(InitDataValidator::validate(str_replace('%20', '+', $signed), $token, 300, $now)['user'] === $data['user'], 'Form-encoded spaces supported');
rejects(fn() => InitDataValidator::validate(str_replace('hello%2Bworld', 'changed', $signed), $token, 300, $now), 'Tampered data');
rejects(fn() => InitDataValidator::validate($signed, 'WRONG', 300, $now), 'Wrong token');
rejects(fn() => InitDataValidator::validate($signed . '&auth_date=' . $now, $token, 300, $now), 'Duplicate key');
rejects(fn() => InitDataValidator::validate($signed . '&%61uth_date=' . $now, $token, 300, $now), 'Encoded duplicate key');
rejects(fn() => InitDataValidator::validate($signed . '&user.name=x', $token, 300, $now), 'PHP key normalization ambiguity');
rejects(fn() => InitDataValidator::validate($signed . '&x=%ZZ', $token, 300, $now), 'Malformed URL encoding');
rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now + 301), 'Expired launch');
rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now - 31), 'Future launch');
rejects(fn() => InitDataValidator::validate(signFixture(['user' => $data['user']], $token), $token, 300, $now), 'Missing auth_date');
rejects(fn() => InitDataValidator::validate(signFixture(['auth_date' => 'abc'], $token), $token, 300, $now), 'Invalid auth_date');
rejects(fn() => InitDataValidator::validate(str_repeat('x', 16385), $token, 300, $now), 'Oversized payload');
rejects(fn() => InitDataValidator::validate('auth_date=1&hash=123', $token, 300, $now), 'Invalid hash format');
rejects(fn() => InitDataValidator::user(['user' => '{"id":-1}']), 'Invalid recipient ID');
rejects(fn() => InitDataValidator::user(['user' => 'not-json']), 'Malformed user JSON');
check(InitDataValidator::user(['user' => '{"id":4503599627370495}'])['id'] === 4503599627370495, '52-bit Eitaa ID preserved');
check(!isset(InitDataValidator::user(['user' => '{"id":12,"extra":"secret"}'])['extra']), 'User response is allowlisted');
// Published HMAC intermediate value is independent of our fixture signer.
check(hash_hmac('sha256', '5768337691:AAGDAe6rjxu1cUgxK4BizYi--Utc3J9v5AU', 'WebAppData') === 'aa492a44bdf019c759defb1698c1d77690189973945491a756051cdc1207a449', 'Documentation HMAC reference vector');
$file = tempnam(sys_get_temp_dir(), 'app-limits-');
try {
(new RateLimiter($file))->hit('user-1', 2, 3600);
(new RateLimiter($file))->hit('user-1', 2, 3600);
rejects(fn() => (new RateLimiter($file))->hit('user-1', 2, 3600), 'Persistent quota blocks third request', 429);
(new RateLimiter($file))->hit('user-2', 2, 3600);
check(count(json_decode(file_get_contents($file), true)) === 2, 'Independent user quotas');
} finally {
unlink($file);
}
echo "\n$tests security checks passed.\n";