Files
zyt/identity-admin/tests/kefu-http-origin.php
T
2026-11-11 13:53:14 +08:00

95 lines
6.5 KiB
PHP

<?php
declare(strict_types=1);
// No application bootstrap, .env, database, socket or external service is used.
function env(string $key, mixed $default = null): mixed { return $default; }
require dirname(__DIR__) . '/server/vendor/autoload.php';
use app\exception\ApiError;
use app\service\group\{KefuClient, KefuMetadataClient, KefuAuthorizationClient};
$checks = 0;
function check(bool $ok, string $label): void {
global $checks;
$checks++;
if (!$ok) { throw new RuntimeException($label); }
}
function denied(callable $action, int $status = 503): void {
try { $action(); } catch (ApiError $error) { check($error->status === $status, 'Unexpected rejection status'); return; }
throw new RuntimeException('Expected rejection');
}
$origin = 'http://im.zhenyangtang.cn:8369';
$key = str_repeat('ab', 32);
$noTransport = static function (): array { throw new RuntimeException('Constructor reached transport'); };
$clients = [KefuMetadataClient::class, KefuAuthorizationClient::class];
$entry = static function (string $base): string { putenv('IAM_KEFU_BASE_URL=' . $base); return KefuClient::entry(); };
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=');
check($entry($origin) === '', 'Remote HTTP defaults closed');
foreach ($clients as $class) { denied(static fn () => new $class($origin . '/api/v2', $key, $noTransport)); }
foreach (['https://remote.invalid', 'http://localhost:5666', 'http://127.0.0.1:5666', 'http://[::1]:5666'] as $base) {
check($entry($base) === $base . '/auth/group-login', 'HTTPS and loopback entry defaults');
check(!KefuClient::isExplicitHttpOriginAllowed($base), 'No implicit public HTTP flag');
foreach ($clients as $class) { new $class($base . '/api/v2', $key, $noTransport); $checks++; }
}
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=' . $origin);
foreach ([$origin, $origin . '/', $origin . '/apps/kefu/'] as $base) {
check($entry($base) === rtrim($base, '/') . '/auth/group-login', 'Explicit origin preserves existing callback paths');
check(KefuClient::isExplicitHttpOriginAllowed(KefuClient::entry()), 'Explicit origin flag');
}
foreach ([$origin . '.evil', 'http://evil.im.zhenyangtang.cn:8369', 'http://im.zhenyangtang.cn:8370',
'http://im.zhenyangtang.cn', 'http://im.zhenyangtang.cn:80'] as $base) {
check($entry($base) === '', 'Origin comparison is exact');
foreach ($clients as $class) { denied(static fn () => new $class($base . '/api/v2', $key, $noTransport)); }
}
foreach ([$origin . '?x=1', $origin . '#x', 'http://user:pass@im.zhenyangtang.cn:8369',
$origin . '/..', $origin . '/%2f', $origin . '/a//b', $origin . '\\evil', $origin . "/\nx"] as $base) {
check($entry($base) === '', 'Allowlisting does not weaken entry URL shape');
foreach ($clients as $class) { denied(static fn () => new $class($base, $key, $noTransport)); }
}
foreach (['*', 'http://*.zhenyangtang.cn:8369', $origin . '/', $origin . '/api', $origin . '?', $origin . '#',
'http://user:pass@im.zhenyangtang.cn:8369', 'https://im.zhenyangtang.cn:8369', $origin . ',*',
$origin . ',', ',' . $origin, $origin . ",\nhttp://other.invalid", 'http://im.zhenyangtang.cn:',
'http://im.zhenyangtang.cn:0', 'http://im.zhenyangtang.cn:65536', 'http://im.zhenyangtang.cn%3a8369'] as $list) {
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=' . $list);
check($entry($origin) === '', 'Any invalid allowlist item fails closed');
check(!KefuClient::isExplicitHttpOriginAllowed($origin), 'Invalid allowlist has no public flag');
foreach ($clients as $class) { denied(static fn () => new $class($origin . '/api/v2', $key, $noTransport)); }
check($entry('https://remote.invalid') !== '' && $entry('http://127.0.0.1:5666') !== '', 'Invalid HTTP list does not change defaults');
}
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=http://im.zhenyangtang.cn');
check($entry('http://IM.zhenyangtang.cn:80') !== '', 'Host case and effective default port are canonical');
check($entry($origin) === '', 'Default port does not match 8369');
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=http://im.zhenyangtang.cn:80');
check($entry('http://im.zhenyangtang.cn') !== '', 'Explicit port 80 matches omitted default port');
putenv('IAM_KEFU_ALLOWED_HTTP_ORIGINS=http://other.invalid:9000, ' . $origin);
check($entry($origin) !== '', 'Comma-separated explicit origins');
// Exercise all machine endpoints against a synthetic authenticated transport.
$now = time(); $calls = []; $nonces = [];
$transport = static function (string $url, array $headers, string $body) use ($origin, $key, $now, &$calls, &$nonces): array {
$path = substr($url, strlen($origin . '/api/v2'));
check($url === $origin . '/api/v2' . $path && in_array($path, ['/group/access-snapshot', '/group/access-options', '/group/access-update'], true), 'Bound public API endpoint');
$h = []; foreach ($headers as $line) { [$name, $value] = explode(':', $line, 2); $h[strtolower($name)] = trim($value); }
check(hash_equals(hash_hmac('sha256', "POST\n$path\n" . $h['x-group-timestamp'] . "\n" . $h['x-group-nonce'] . "\n" . hash('sha256', $body), hex2bin($key)), $h['x-group-signature']), 'Endpoint-specific request signature');
check(!isset($nonces[$h['x-group-nonce']]) && preg_match('/^[a-f0-9]{32}$/D', $h['x-group-nonce']) === 1, 'Fresh nonce');
$nonces[$h['x-group-nonce']] = true; $calls[] = $path;
$snapshot = $path === '/group/access-snapshot';
$payload = ['version' => 1, 'client_id' => 'kefu', 'generated_at' => $now] + ($snapshot
? ['subjects' => [], 'catalog' => null] : ['error' => ['code' => 403, 'message' => '合成拒绝']]);
$raw = json_encode($payload, JSON_THROW_ON_ERROR);
return ['status' => $snapshot ? 200 : 403, 'body' => $raw, 'headers' => ['X-Group-Response-Signature' =>
hash_hmac('sha256', "response\n" . $h['x-group-nonce'] . "\n" . hash('sha256', $raw), hex2bin($key))]];
};
$metadata = new KefuMetadataClient($origin . '/api/v2', $key, $transport, static fn (): int => $now);
check($metadata->snapshot([], false)['subjects'] === [], 'Allowlisted HTTP metadata verifies response');
$authorization = new KefuAuthorizationClient($origin . '/api/v2', $key, $transport, static fn (): int => $now);
$gid = 'gid_' . str_repeat('1', 32);
denied(static fn () => $authorization->options($gid, 7, 12), 403);
denied(static fn () => $authorization->update($gid, 7, 12, 1, str_repeat('a', 64), 'viewer', null), 403);
check($calls === ['/group/access-snapshot', '/group/access-options', '/group/access-update'], 'All machine endpoints stay fixed');
fwrite(STDOUT, "PASS kefu HTTP origin: {$checks} checks (synthetic transport only).\n");