diff --git a/docs/ingame-verification.md b/docs/ingame-verification.md index 9bb1acce..1056751b 100644 --- a/docs/ingame-verification.md +++ b/docs/ingame-verification.md @@ -5,9 +5,11 @@ Players can link their BYOND key to Discord without editing their BYOND profile. 1. In Discord, the player runs `/approveme` **without** a ckey. CivilizationBot replies privately with a single-use code such as `ABCD-EFGH`, valid for 10 minutes. 2. In any Civ13 server, the player opens the OOC tab, clicks **Verify Discord** and types the code. -3. The game sends `ckey` + `code` to its own bot as the `discord_verify` webhook method - (`/webhook//discord_verify?key=&data={"ckey","code"}`) and shows the - JSON `{ok, message}` answer to the player. +3. The game POSTs `{"ckey","code"}` as JSON to its own bot at `/discord_verify` + (for example `/webhook//discord_verify`) with the webhook key in the `X-Webhook-Key` + header, and shows the JSON `{ok, message}` answer to the player. Neither the key nor the code is + ever part of a URL, so proxies and access logs never see them; a key in the query string is refused. + The game only sends this to a loopback (`127.0.0.1`/`localhost`) or `https://` address. BYOND has already signed the player in, so the game proves the ckey and the private code proves the Discord account. Bans, investigations, existing links, the BYOND account age rule and the @@ -20,15 +22,18 @@ out of in-game verification for ten minutes. Codes are kept in memory only. - **CivilizationBot** (primary, writes the verified list) redeems the code itself. - **VZGCivilizationBot** (desktop profile with the read-only hosted verifier) cannot register anyone. It forwards the request to the primary bot's `POST /verified/ingame` endpoint next to the hosted - verified list (`verification_source.url` + `/ingame`), signed with `X-Ingame-Verify-Time` and - `X-Ingame-Verify-Signature` (HMAC-SHA256 of `time + "\n" + body` with the shared secret), then passes the primary bot's answer back to the game. The link reaches the desktop game through + verified list (`verification_source.url` + `/ingame`), sealed with the shared secret + (`InGameVerification::seal`: AES-256-GCM under an HKDF key), then passes the primary bot's answer + back to the game. The answer is sealed too and bound to the request it answers. The link reaches the desktop game through the normal hosted verified-list refresh and access-file sync. Both bots need the same random secret as `INGAME_VERIFY_TOKEN`: in the primary bot's `.env` and in the desktop profile's environment file. Without it the primary bot refuses relays (403) and the -desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent, so -the plain-HTTP `http://civ13.com:55555` source is acceptable: a captured request expires after 60 seconds -and its code is single use. Anyone holding the secret could link any ckey to a Discord user with a live -code, so keep it out of logs and chat. +desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent and +the ckey and code are encrypted end to end, so someone watching the plain-HTTP `http://civ13.com:55555` +source sees neither and cannot redeem the code for their own account; a changed byte, the wrong +direction, a stale (over 60 seconds) or swapped message is refused. An `https://` source works too. +Anyone holding the secret could link any ckey to a Discord user with a live code, so keep it out of +logs and chat. `/approveme` is re-registered on every start so existing installs get the optional ckey. diff --git a/src/Civ13/HttpHandler.php b/src/Civ13/HttpHandler.php index 84877793..48a9075c 100644 --- a/src/Civ13/HttpHandler.php +++ b/src/Civ13/HttpHandler.php @@ -599,7 +599,12 @@ public function __isWhitelisted(ServerRequestInterface $request, string $ip): bo // Native webhook_send places its secret beside method/data, not inside JSON. $outerKey = $request->getQueryParams()['key'] ?? null; if (str_starts_with($request->getUri()->getPath(), '/webhook/')) { - // A trusted network address is not authentication of a game event. + // A trusted network address is not authentication of a game event. Newer game requests + // (in-game verification) send the key in the X-Webhook-Key header, never in the URL. + $headerKey = $request->getHeaderLine('X-Webhook-Key'); + if ($this->key !== '' && $headerKey !== '' && hash_equals($this->key, $headerKey)) { + return true; + } return $this->key !== '' && is_string($outerKey) && hash_equals($this->key, $outerKey); } if ($this->key) { diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index ba640166..4fe1342f 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -351,19 +351,25 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam } /** - * In-game verification (Civ13 code/modules/client/discord_verify.dm): the game sends the - * player's ckey and the code they typed. The primary bot redeems it; a desktop bot with a - * read-only verifier relays it to the primary bot. Once authenticated the answer is always - * 200 JSON {ok, message}, which the game shows to the player. + * In-game verification (Civ13 code/modules/client/discord_verify.dm): the game POSTs the + * player's ckey and the code they typed as JSON, with the webhook key in the X-Webhook-Key + * header, so neither secret is ever part of a URL. The primary bot redeems it; a desktop bot + * with a read-only verifier relays it, encrypted, to the primary bot. Once authenticated the + * answer is always 200 JSON {ok, message}, which the game shows to the player. */ public function handleDiscordVerifyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse { $secret = $this->civ13->options['http_key'] ?? ''; - $key = $request->getQueryParams()['key'] ?? null; - if (!is_string($secret) || $secret === '' || !is_string($key) || !hash_equals($secret, $key) || $gameserver->legacy_relay) { + $key = $request->getHeaderLine('X-Webhook-Key'); + if (!is_string($secret) || $secret === '' || $key === '' || !hash_equals($secret, $key) || $gameserver->legacy_relay) { return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); } - if (!$data = self::inGameVerifyRequest(self::decodeParamData($request))) { + if ($request->getMethod() !== 'POST') { + return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); + } + $body = (string) $request->getBody(); + $data = strlen($body) <= 1024 ? json_decode($body, true, 4) : null; + if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } if (!$this->civ13->verifier->readOnly) { @@ -374,7 +380,11 @@ public function handleDiscordVerifyWebhook(ServerRequestInterface $request, Game return HttpResponse::json(\React\Async\await($this->relayInGameVerification($data['ckey'], $data['code']))); } - /** Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN (HMAC-signed, see below). */ + /** + * Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN. + * Request and answer are sealed with it ({@see InGameVerification::seal()}), so the code is + * never readable on the wire even over plain HTTP, and the answer is bound to its request. + */ public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpResponse { $secret = $this->civ13->options['ingame_verify_key'] ?? ''; @@ -384,19 +394,20 @@ public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpRe if ($request->getMethod() !== 'POST') { return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); } - $body = (string) $request->getBody(); - if (strlen($body) > 1024 || !self::inGameRelaySignatureValid($secret, $request->getHeaderLine('X-Ingame-Verify-Time'), $body, $request->getHeaderLine('X-Ingame-Verify-Signature'))) { + $opened = InGameVerification::open($secret, 'request', (string) $request->getBody()); + if ($opened === null) { return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); } - $data = json_decode($body, true, 4); - if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) { + if (!$data = self::inGameVerifyRequest($opened['payload'])) { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } + $answer = $this->civ13->verifier->redeemInGame($data['ckey'], $data['code']); - return HttpResponse::json($this->civ13->verifier->redeemInGame($data['ckey'], $data['code'])); + return HttpResponse::plaintext(InGameVerification::seal($secret, 'response', $answer, $opened['nonce'])) + ->withHeader('Content-Type', 'application/json'); } - /** Desktop bot: forwards to the primary bot. Resolves {ok, message}; never rejects. */ + /** Desktop bot: forwards to the primary bot, sealed both ways. Resolves {ok, message}; never rejects. */ public function relayInGameVerification(string $ckey, string $code): PromiseInterface { $url = InGameVerification::relayUrl($this->civ13->verifier->verify_url); @@ -404,18 +415,18 @@ public function relayInGameVerification(string $ckey, string $code): PromiseInte if ($url === null || !is_string($key) || $key === '') { return \React\Promise\resolve(['ok' => false, 'message' => 'Verifying from this server is not set up yet. Use /approveme in Discord instead.']); } - - $body = json_encode(['ckey' => $ckey, 'code' => $code], JSON_THROW_ON_ERROR); - $time = (string) time(); + $body = InGameVerification::seal($key, 'request', ['ckey' => $ckey, 'code' => $code]); + $nonce = InGameVerification::nonceOf($body); return $this->civ13->browser->withTimeout(10.0)->withRejectErrorResponse(false)->post( $url, - ['Content-Type' => 'application/json', 'X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => self::inGameRelaySignature($key, $time, $body)], + ['Content-Type' => 'application/json'], $body - )->then(function (ResponseInterface $response): array { - $body = json_decode((string) $response->getBody(), true, 4); - if ($response->getStatusCode() === 200 && is_array($body) && is_bool($body['ok'] ?? null) && is_string($body['message'] ?? null)) { - return ['ok' => $body['ok'], 'message' => mb_substr($body['message'], 0, 400)]; + )->then(function (ResponseInterface $response) use ($key, $nonce): array { + $opened = $response->getStatusCode() === 200 ? InGameVerification::open($key, 'response', (string) $response->getBody(), $nonce) : null; + $answer = $opened['payload'] ?? null; + if (is_array($answer) && is_bool($answer['ok'] ?? null) && is_string($answer['message'] ?? null)) { + return ['ok' => $answer['ok'], 'message' => mb_substr($answer['message'], 0, 400)]; } $this->logger->warning('In-game verification relay refused', ['status' => $response->getStatusCode()]); @@ -427,24 +438,6 @@ public function relayInGameVerification(string $ckey, string $code): PromiseInte }); } - /** - * The relay may cross plain HTTP, so the shared secret never travels: the desktop bot signs - * time + body with it. A captured request is useless after a minute, and its code is single use. - */ - public static function inGameRelaySignature(string $secret, string $time, string $body): string - { - return hash_hmac('sha256', $time."\n".$body, $secret); - } - - public static function inGameRelaySignatureValid(string $secret, string $time, string $body, string $signature, ?int $now = null): bool - { - if ($secret === '' || preg_match('/^[0-9]{1,12}$/D', $time) !== 1 || abs(($now ?? time()) - (int) $time) > 60 || preg_match('/^[0-9a-f]{64}$/D', $signature) !== 1) { - return false; - } - - return hash_equals(self::inGameRelaySignature($secret, $time, $body), $signature); - } - /** {ckey, code} from the game or a relay, or null. The game sends a BYOND ckey: lower-case letters and digits. */ public static function inGameVerifyRequest(array $data): ?array { diff --git a/src/Civ13/InGameVerification.php b/src/Civ13/InGameVerification.php index f7b083f1..3610b819 100644 --- a/src/Civ13/InGameVerification.php +++ b/src/Civ13/InGameVerification.php @@ -21,10 +21,11 @@ * already knows their BYOND key (BYOND signed them in), so the code proves the * Discord side and the game proves the ckey; no BYOND profile token is needed. * - * The game sends `ckey` + `code` to its own bot (`/webhook//discord_verify`). - * The primary bot redeems it here. A desktop bot with a read-only verifier cannot - * register anyone, so it forwards the same request to the primary bot's - * `/verified/ingame` relay endpoint and hands the answer back to the game. + * The game POSTs `ckey` + `code` to its own bot (`/webhook//discord_verify`, + * key in a header, nothing secret in the URL). The primary bot redeems it here. A desktop + * bot with a read-only verifier cannot register anyone, so it forwards the request, sealed + * with INGAME_VERIFY_TOKEN ({@see seal()}), to the primary bot's `/verified/ingame` relay + * endpoint and hands the sealed answer back to the game. * * Codes live only in memory: a bot restart simply asks players for a new code. */ @@ -162,6 +163,66 @@ public static function relayUrl(string $verify_url): ?string return rtrim($verify_url, '/').'/ingame'; } + public const SEAL_WINDOW = 60; // seconds a sealed relay message stays valid + private const NONCE_BYTES = 12; + private const TAG_BYTES = 16; + + /** + * Relay messages between a desktop bot and the primary bot are sealed with AES-256-GCM + * (OpenSSL, already required by the portable profile) under a key derived from INGAME_VERIFY_TOKEN: the code is never readable + * on the wire, a changed byte is rejected, and each message carries its direction and time. + * An answer also carries the nonce of the request it answers, so it can't be swapped. + */ + public static function seal(string $secret, string $direction, array $payload, ?string $answers = null, ?int $now = null): string + { + $nonce = random_bytes(self::NONCE_BYTES); + $plain = json_encode(['d' => $direction, 't' => $now ?? time(), 'r' => $answers, 'p' => $payload], JSON_THROW_ON_ERROR); + $tag = ''; + $cipher = openssl_encrypt($plain, 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, $tag, '', self::TAG_BYTES); + if (!is_string($cipher)) { + throw new \RuntimeException('Could not seal the relay message'); + } + + return json_encode(['v' => 1, 'n' => base64_encode($nonce), 'c' => base64_encode($cipher.$tag)], JSON_THROW_ON_ERROR); + } + + /** @return array{payload: array, nonce: string}|null null for anything forged, stale, mismatched or malformed */ + public static function open(string $secret, string $direction, string $body, ?string $answers = null, ?int $now = null): ?array + { + if ($secret === '' || strlen($body) > 4096) { + return null; + } + $outer = json_decode($body, true, 3); + if (!is_array($outer) || ($outer['v'] ?? null) !== 1 || !is_string($outer['n'] ?? null) || !is_string($outer['c'] ?? null)) { + return null; + } + $nonce = base64_decode($outer['n'], true); + $cipher = base64_decode($outer['c'], true); + if (!is_string($nonce) || strlen($nonce) !== self::NONCE_BYTES || !is_string($cipher) || strlen($cipher) < self::TAG_BYTES) { + return null; + } + $plain = openssl_decrypt(substr($cipher, 0, -self::TAG_BYTES), 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, substr($cipher, -self::TAG_BYTES)); + $inner = is_string($plain) ? json_decode($plain, true, 6) : null; + if (!is_array($inner) || ($inner['d'] ?? null) !== $direction || !is_int($inner['t'] ?? null) + || abs(($now ?? time()) - $inner['t']) > self::SEAL_WINDOW || !is_array($inner['p'] ?? null) + || ($inner['r'] ?? null) !== $answers) { + return null; + } + + return ['payload' => $inner['p'], 'nonce' => $outer['n']]; + } + + /** The base64 nonce of a sealed message, which its answer must name. */ + public static function nonceOf(string $sealed): string + { + return (string) (json_decode($sealed, true, 3)['n'] ?? ''); + } + + private static function sealKey(string $secret): string + { + return hash_hkdf('sha256', $secret, 32, 'civ13 in-game verification relay v1'); + } + /** The player-facing reply to `/approveme` without a ckey. */ public static function codeMessage(string $code): string { diff --git a/tests/local/ingame-verification.php b/tests/local/ingame-verification.php index b168eaf7..22169ab8 100644 --- a/tests/local/ingame-verification.php +++ b/tests/local/ingame-verification.php @@ -85,42 +85,98 @@ function verifier(bool $readOnly): FakeVerifier foreach ([['ckey' => 'Alice', 'code' => 'x'], ['ckey' => 'alice'], ['ckey' => 'alice', 'code' => ''], ['ckey' => 'alice', 'code' => str_repeat('A', 33)], ['ckey' => 'a b', 'code' => 'x'], ['ckey' => ['alice'], 'code' => 'x']] as $bad) { check(HttpServiceManager::inGameVerifyRequest($bad) === null, 'invalid request rejected: '.json_encode($bad)); } +final class LogSpy extends Monolog\Handler\AbstractProcessingHandler +{ + public string $text = ''; + protected function write(Monolog\LogRecord $record): void { $this->text .= $record->message.' '.json_encode($record->context).PHP_EOL; } +} +$spy = new LogSpy(); function manager(Verifier $verifier, string $relayKey): HttpServiceManager { + global $spy; $civ13 = inert(Civ13::class); $civ13->options = ['http_key' => 'webhook-key', 'ingame_verify_key' => $relayKey]; $civ13->verifier = $verifier; $manager = inert(HttpServiceManager::class); setProp($manager, 'civ13', $civ13); - $manager->logger = new Logger('test', [new NullHandler()]); + $manager->logger = new Logger('test', [$spy]); return $manager; } -function relayRequest(string $key, string $body, string $method = 'POST', ?int $time = null): ServerRequest +function relayRequest(string $body, string $method = 'POST'): ServerRequest { - $time = (string) ($time ?? time()); - return new ServerRequest($method, 'http://civ13.com:55555/verified/ingame', $key === '' ? [] : ['X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => HttpServiceManager::inGameRelaySignature($key, $time, $body)], $body); + return new ServerRequest($method, 'http://civ13.com:55555/verified/ingame', ['Content-Type' => 'application/json'], $body); } $v = verifier(false); $code = $v->inGame->issue(ALICE); $m = manager($v, 'relay-secret'); +$payload = ['ckey' => 'alice', 'code' => $code]; +$sealed = InGameVerification::seal('relay-secret', 'request', $payload); +check(! str_contains($sealed, $code) && ! str_contains($sealed, str_replace('-', '', $code)) && ! str_contains($sealed, 'alice') && ! str_contains($sealed, 'relay-secret'), 'the sealed relay body shows neither the code, the ckey nor the secret'); +check(InGameVerification::open('relay-secret', 'request', $sealed)['payload'] === $payload, 'seal round trip'); +check(InGameVerification::open('other-secret', 'request', $sealed) === null, 'a wrong secret cannot open it'); +check(InGameVerification::open('relay-secret', 'response', $sealed) === null, 'a request cannot pose as an answer'); +check(InGameVerification::open('relay-secret', 'request', $sealed, null, time() + 120) === null, 'a stale message is refused'); +$outer = json_decode($sealed, true); +$cipher = base64_decode($outer['c']); +$cipher[20] = chr(ord($cipher[20]) ^ 1); +check(InGameVerification::open('relay-secret', 'request', json_encode(['v' => 1, 'n' => $outer['n'], 'c' => base64_encode($cipher)])) === null, 'a changed byte is refused'); +check(InGameVerification::open('relay-secret', 'request', '') === null && InGameVerification::open('', 'request', $sealed) === null && InGameVerification::open('relay-secret', 'request', '{"v":1}') === null, 'malformed or keyless input is refused'); +check($m->handleInGameVerifyRelay(relayRequest(json_encode($payload)))->getStatusCode() === 403, 'an unsealed relay is refused'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('wrong', 'request', $payload)))->getStatusCode() === 403, 'relay rejects a wrong secret'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('relay-secret', 'request', $payload, null, time() - 120)))->getStatusCode() === 403, 'stale relays are refused'); +check(manager($v, '')->handleInGameVerifyRelay(relayRequest($sealed))->getStatusCode() === 403, 'relay off without INGAME_VERIFY_TOKEN'); +check(manager(verifier(true), 'relay-secret')->handleInGameVerifyRelay(relayRequest($sealed))->getStatusCode() === 403, 'a read-only bot never accepts relays'); +check($m->handleInGameVerifyRelay(relayRequest($sealed, 'GET'))->getStatusCode() === 405, 'relay is POST only'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('relay-secret', 'request', ['ckey' => 'alice'])))->getStatusCode() === 400, 'relay validates the payload'); +$response = $m->handleInGameVerifyRelay(relayRequest($sealed)); +$answerBody = (string) $response->getBody(); +check(! str_contains($answerBody, 'linked'), 'the answer is sealed too'); +check(InGameVerification::open('relay-secret', 'response', $answerBody, InGameVerification::nonceOf(InGameVerification::seal('relay-secret', 'request', $payload))) === null, 'an answer only opens for the request it answers'); +$answer = InGameVerification::open('relay-secret', 'response', $answerBody, InGameVerification::nonceOf($sealed)); +check($response->getStatusCode() === 200 && $answer['payload']['ok'] === true && $v->processed === [['alice', ALICE]], 'relay redeems on the primary bot'); + +// Game webhook: key only in the X-Webhook-Key header, ckey and code only in a POST body. +$gameserver = inert(\Civ13\GameServer::class); +setProp($gameserver, 'legacy_relay', false); +function gameRequest(array $headers, string $body, string $method = 'POST', string $query = ''): ServerRequest +{ + return new ServerRequest($method, 'http://127.0.0.1:55555/webhook/nomads/discord_verify'.$query, $headers, $body); +} +$v = verifier(false); +$code = $v->inGame->issue(ALICE); +$m = manager($v, ''); $body = json_encode(['ckey' => 'alice', 'code' => $code]); -check($m->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay needs the key'); -check($m->handleInGameVerifyRelay(relayRequest('wrong', $body))->getStatusCode() === 403, 'relay rejects a wrong key'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'POST', time() - 120))->getStatusCode() === 403, 'stale signatures are refused'); -$tampered = relayRequest('relay-secret', $body); -check($m->handleInGameVerifyRelay(new ServerRequest('POST', 'http://civ13.com:55555/verified/ingame', ['X-Ingame-Verify-Time' => $tampered->getHeaderLine('X-Ingame-Verify-Time'), 'X-Ingame-Verify-Signature' => $tampered->getHeaderLine('X-Ingame-Verify-Signature')], json_encode(['ckey' => 'admin', 'code' => $code])))->getStatusCode() === 403, 'a signature does not cover another ckey'); -check(! str_contains(json_encode($tampered->getHeaders()), 'relay-secret'), 'the secret itself is never sent'); -check(manager($v, '')->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay off without INGAME_VERIFY_TOKEN'); -check(manager(verifier(true), 'relay-secret')->handleInGameVerifyRelay(relayRequest('relay-secret', $body))->getStatusCode() === 403, 'a read-only bot never accepts relays'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'GET'))->getStatusCode() === 405, 'relay is POST only'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', '{"ckey":"alice"}'))->getStatusCode() === 400, 'relay validates the body'); -$response = $m->handleInGameVerifyRelay(relayRequest('relay-secret', $body)); -$answer = json_decode((string) $response->getBody(), true); -check($response->getStatusCode() === 200 && $answer['ok'] === true && $v->processed === [['alice', ALICE]], 'relay redeems on the primary bot'); +check($m->handleDiscordVerifyWebhook(gameRequest([], $body), $gameserver)->getStatusCode() === 403, 'game request needs the key header'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'wrong'], $body), $gameserver)->getStatusCode() === 403, 'game request rejects a wrong key'); +check($m->handleDiscordVerifyWebhook(gameRequest([], $body, 'POST', '?key=webhook-key'), $gameserver)->getStatusCode() === 403, 'a key in the URL is not accepted'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], '', 'GET', '?key=webhook-key&method=discord_verify&data='.urlencode($body)), $gameserver)->getStatusCode() === 405, 'the old query-string request is refused'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], '{"ckey":"alice"}'), $gameserver)->getStatusCode() === 400, 'game request validates the body'); +check($v->processed === [], 'nothing redeemed by refused requests'); +$response = $m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], $body), $gameserver); +check($response->getStatusCode() === 200 && json_decode((string) $response->getBody(), true)['ok'] === true && $v->processed === [['alice', ALICE]], 'game request redeems with header key and JSON body'); +$handler = inert(\Civ13\HttpHandler::class); +setProp($handler, 'key', 'webhook-key'); +check($handler->__isWhitelisted(gameRequest(['X-Webhook-Key' => 'webhook-key'], $body), '203.0.113.9'), 'the router accepts the header key on webhook paths'); +check(! $handler->__isWhitelisted(gameRequest(['X-Webhook-Key' => 'nope'], $body), '203.0.113.9'), 'the router refuses a wrong header key'); // A desktop bot without a relay key answers the game without any network call. $relayed = null; manager(verifier(true), '')->relayInGameVerification('alice', 'ABCD-EFGH')->then(static function (array $r) use (&$relayed): void { $relayed = $r; }); check(is_array($relayed) && $relayed['ok'] === false && str_contains($relayed['message'], 'not set up'), 'unconfigured relay answers plainly'); +// Logs: nothing above wrote a code, a ckey's code, a key or a relay secret. +foreach (array_merge([$code, str_replace('-', '', $code), 'webhook-key', 'relay-secret'], array_map(static fn (string $c): string => str_replace('-', '', $c), [$first, $second, $late, $good])) as $secret) { + check(! str_contains($spy->text, $secret), 'secret kept out of the logs: '.$secret); +} + +// And no log call in the verification paths names the code, the key, the body or the secret. +$source = file_get_contents(__DIR__.'/../../src/Civ13/HttpServiceManager.php'); +$from = strpos($source, 'public function handleDiscordVerifyWebhook'); +$section = substr($source, $from, strpos($source, 'public static function inGameVerifyRequest') - $from); +preg_match_all('/logger->\w+\((.*?)\);/s', $section, $calls); +check(count($calls[1]) >= 2, 'log calls found in the verification paths'); +foreach ($calls[1] as $call) { + check(preg_match('/\$(code|key|secret|body|data|payload|request)\b/', $call) !== 1, 'log call carries no secret: '.$call); +} + echo "ingame-verification: $checks checks passed\n";