Files
2026-09-05 15:54:33 +03:30

101 lines
7.0 KiB
PHP

<?php
declare(strict_types=1);
// Isolated test installation: never loads the real token or contacts Eitaa.
require __DIR__ . '/security.php';
$root = dirname(__DIR__);
$temp = sys_get_temp_dir() . '/app-http-' . bin2hex(random_bytes(6));
mkdir($temp, 0700);
foreach (['storage', 'storage/secrets', 'storage/sessions', 'storage/cache', 'config', 'public'] as $directory) {
mkdir($temp . '/' . $directory, 0700);
}
foreach (['bootstrap', 'app', 'resources'] as $directory) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . '/' . $directory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
mkdir($temp . '/' . $directory, 0700);
foreach ($iterator as $entry) {
$destination = $temp . '/' . substr($entry->getPathname(), strlen($root) + 1);
$entry->isDir() ? mkdir($destination, 0700) : copy($entry->getPathname(), $destination);
}
}
copy($root . '/config/app.php', $temp . '/config/app.php');
mkdir($temp . '/public/assets/brand', 0700, true);
copy($root . '/public/assets/brand/social.svg', $temp . '/public/assets/brand/social.svg');
foreach (['index.php', 'api.php', 'sample.php'] as $file) {
copy($root . '/public/' . $file, $temp . '/public/' . $file);
}
file_put_contents($temp . '/config/local.php', "<?php return ['token' => 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => true];");
file_put_contents($temp . '/storage/secrets/token.txt', 'PRIVATE_FILE_MUST_NOT_BE_SERVED');
$port = random_int(20000, 45000);
$server = proc_open([PHP_BINARY,'-S','127.0.0.1:' . $port,'-t',$temp . '/public'], [['pipe','r'],['file',$temp . '/server.log','a'],['file',$temp . '/server.log','a']], $pipes, $temp, array_merge(getenv(), ['EITAA_APP_TOKEN' => 'TEST_ONLY_NOT_A_REAL_TOKEN']));
if (!is_resource($server)) {
throw new RuntimeException('Cannot start PHP test server.');
}
$curl = curl_init();
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER=>true,CURLOPT_COOKIEFILE=>'',CURLOPT_TIMEOUT=>5]);
$base = 'http://127.0.0.1:' . $port;
function request(string $path, ?array $body = null, ?string $csrf = null, ?string $raw = null): array
{
global $curl, $base;
curl_setopt_array($curl, [CURLOPT_URL=>$base.$path,CURLOPT_HTTPGET=>true,CURLOPT_HTTPHEADER=>[]]);
if ($body !== null || $raw !== null) {
curl_setopt_array($curl, [CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$raw ?? json_encode($body),CURLOPT_HTTPHEADER=>['Content-Type: application/json','X-CSRF-Token: '.($csrf??'')]]);
}
$response = curl_exec($curl);
return [curl_getinfo($curl,CURLINFO_RESPONSE_CODE),$response,json_decode($response ?: '',true)];
}
try {
for ($i=0;$i<30;$i++) {
[$status,$html] = request('/');
if ($status === 200) break;
usleep(100000);
}
check($status===200,'Page loads from isolated installation');
preg_match('/name="csrf-token" content="([a-f0-9]+)"/', $html, $matches);
$csrf = $matches[1] ?? '';
check(strlen($csrf)===64,'CSRF token provided');
check(!str_contains($html,'TEST_ONLY_NOT_A_REAL_TOKEN'),'App token absent from page');
check(request('/api.php')[0]===405,'API rejects GET');
check(request('/api.php',['action'=>'authenticate'])[0]===403,'API rejects missing CSRF');
check(request('/api.php',null,$csrf,'{broken')[0]===400,'API rejects malformed JSON');
check(request('/api.php',null,$csrf,str_repeat('x',20001))[0]===413,'API rejects large request');
check(request('/api.php',['action'=>'sendMessage','text'=>'hello'],$csrf)[0]===401,'Message requires verified session');
$launch = signFixture(['auth_date'=>(string)time(),'user'=>'{"id":12345,"first_name":"تست"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
check(request('/api.php',['action'=>'authenticate','initData'=>$launch.'x'],$csrf)[0]===401,'Forged launch rejected over HTTP');
[$status,,$data]=request('/api.php',['action'=>'authenticate','initData'=>$launch],$csrf);
check($status===200 && $data['user']['id']===12345,'Valid launch creates authenticated session');
check(!isset($data['hash'])&&!isset($data['token']),'Authentication response excludes secrets');
check(request('/api.php',['action'=>'sendMessage','text'=>''],$csrf)[0]===400,'Empty message blocked before network call');
$contact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":12345,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
check(request('/api.php',['action'=>'contact','contactData'=>$contact],$csrf)[0]===200,'Signed contact accepted for current user');
$otherContact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":54321,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
check(request('/api.php',['action'=>'contact','contactData'=>$otherContact],$csrf)[0]===401,'Other user contact rejected');
[$status,,$data]=request('/api.php',['action'=>'logout'],$csrf);
check($status===200&&$data['csrf']!==$csrf,'Logout rotates CSRF');
check(request('/api.php',['action'=>'sendMessage','text'=>'test'],$data['csrf'])[0]===401,'Logout removes authenticated user');
// PHP's development server may fall back to index.php for unknown paths.
[$status,$privateBody] = request('/storage/secrets/token.txt');
check(!str_contains($privateBody, 'PRIVATE_FILE_MUST_NOT_BE_SERVED'), 'Private file never served from document root');
file_put_contents($temp . '/config/local.php', "<?php return ['token' => 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => false];");
check(request('/api.php',['action'=>'authenticate','initData'=>$launch],$data['csrf'])[0]===403, 'Production configuration refuses HTTP');
[$status, $svg] = request('/sample.php');
check($status === 200 && str_contains($svg, '<svg'), 'Postcard template served by thin download entry point');
file_put_contents($temp . '/config/local.php', "<?php return ['session_lifetime' => 0];");
[$status, $html] = request('/');
check($status === 500 && !str_contains($html, 'RuntimeException') && !str_contains($html, $temp), 'Invalid configuration fails without exposing paths or exceptions');
file_put_contents($temp . '/config/local.php', "<?php return ['public_url' => 'https://example.com/demo'];");
[$status, $html] = request('/');
check($status === 200 && str_contains($html, 'https://example.com/demo/assets/brand/social.png'), 'Configured share URL supports subdirectory deployment');
file_put_contents($temp . '/config/local.php', "<?php return ['public_url' => 'https://user:pass@example.com'];");
check(request('/')[0] === 500, 'Share base URL rejects embedded credentials');
echo "\n$tests total security and HTTP checks passed.\n";
} finally {
proc_terminate($server);
fclose($pipes[0]);
proc_close($server);
// Remove only the uniquely generated test fixture, never user data.
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($temp, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $entry) {
$entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname());
}
rmdir($temp);
}