Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/portable.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ jobs:
- run: php tests/windows/bootstrap.php
- run: php tests/windows/bootstrap.php --negative-control
- run: php tests/windows/process.php
- name: Contained WebAPI errors (offline)
timeout-minutes: 2
run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/webapi-errors.php
- name: Portable restart contracts (offline)
timeout-minutes: 2
run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/windows/portable-restart.php
- run: php tests/windows/shell-guard.php
- run: php tests/windows/ready.php
- run: php tests/windows/ready.php vendor/autoload.php --hosted
Expand Down
48 changes: 4 additions & 44 deletions bot.php
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,8 @@ function loadEnv(string $filePath, bool $explicit = false): array
* @param ServerRequestInterface $request The HTTP request object.
* @return Response The HTTP response object.
*/
$webapi = new HttpServer(Loop::get(), async(function (ServerRequestInterface $request) use (&$civ13, &$logger): Response {
$httpErrors = new HttpErrorBoundary($logger, [$hidden_options['http_key']]);
$webapi = new HttpServer(Loop::get(), $httpErrors, async(function (ServerRequestInterface $request) use (&$civ13, &$logger): Response {
/** @var ?Civ13 $civ13 */
if (! $civ13 || ! $civ13 instanceof Civ13) {
$logger->warning('Civ13 instance not found. Please check the server settings.');
Expand All @@ -638,49 +639,8 @@ function loadEnv(string $filePath, bool $explicit = false): array

return $civ13->httpServiceManager->handle($request);
}));
/**
* This code snippet handles the error event of the web API.
* It logs the error message, file, line, and trace, and handles specific error cases.
* If the error message starts with 'Received request with invalid protocol version', it is ignored.
* If the error message starts with 'The response callback', it triggers a restart process.
* The restart process includes sending a message to a specific Discord channel and closing the socket connection.
* After a delay of 5 seconds, the script is restarted by calling the 'restart' function and closing the Discord connection.
*
* @param Exception $e The exception object representing the error.
* @param \Psr\Http\Message\RequestInterface|null $request The HTTP request object associated with the error, if available.
* @param object $civ13 The main object of the application.
* @param object $socket The socket object.
* @param bool $testing Flag indicating if the script is running in testing mode.
*/
$webapi->on('error', async(function (Exception $e, ?\Psr\Http\Message\RequestInterface $request = null) use (&$civ13, &$logger, &$socket) {
if (
str_starts_with($e->getMessage(), 'Received request with invalid protocol version')
) {
return;
} // Ignore this error, it's not important
$error = "[WEBAPI] {$e->getMessage()} [{$e->getFile()}:{$e->getLine()}] ".str_replace('\n', PHP_EOL, $e->getTraceAsString());
$logger->error("[WEBAPI] $error");
if ($request) {
$logger->error('[WEBAPI] Request: '.preg_replace('/(?<=key=)[^&]+/', '********', $request->getRequestTarget()));
}
if (str_starts_with($e->getMessage(), 'The response callback')) {
$logger->info('[WEBAPI] ERROR - RESTART');
/** @var ?Civ13 $civ13 */
if (! $civ13) {
return;
}
if (! getenv('testing') && isset($civ13->channel_ids['staff_bot']) && $channel = $civ13->discord->getChannel($civ13->channel_ids['staff_bot'])) {
$builder = Civ13::createBuilder()
->setContent('Restarting due to error in HttpServer API...')
->addFileFromContent('httpserver_error.txt', preg_replace('/(?<=key=)[^&]+/', '********', $error));
$channel->sendMessage($builder);
}
$socket->close();
if (! isset($civ13->timers['restart'])) {
$civ13->timers['restart'] = Loop::addTimer(5, fn () => $civ13->restart());
}
}
}));
// React handles failed requests with an error response; keep the listener and bot alive.
$webapi->on('error', $httpErrors->report(...));

//$events = ['MESSAGE_UPDATE'];
//$eventLogger = new \EventLogger\EventLogger($discord, $events);
Expand Down
19 changes: 18 additions & 1 deletion src/Civ13/Civ13.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ class Civ13

private string $constructed_file;
private RestartPolicy $restartPolicy;
private bool $portableRestartRequested = false;

private PromiseMiddleware $then;

Expand Down Expand Up @@ -1035,8 +1036,24 @@ private function stopCalendarSync(): void
public function restart(?string $file = null): PromiseInterface
{
if (getenv('CIVILIZATIONBOT_PROFILE')) {
if ($file !== null) { throw new \InvalidArgumentException('Portable restart cannot select an entry point'); }
if ($this->portableRestartRequested) { return resolve(null); }
$state = $this->portable_state_dir;
try {
if ($state === '' || !PortableProfile::absolute($state) || !is_dir($state)) {
throw new \RuntimeException('Portable restart state unavailable');
}
// A launcher stop wins. Its existing timer owns shutdown and marker cleanup.
if (is_file($state.'/stop.request')) { return resolve(null); }
// Publish intent before shutdown: a failed write must leave the bot running.
// An existing reload request already supplies the same one-use intent.
if (!is_file($state.'/reload.request')) { PortableProcess::requestReload($state); }
} catch (\Throwable $error) {
return \React\Promise\reject($error);
}
$this->stop();
return \React\Promise\resolve(null); // Portable supervisor owns relaunch.
$this->portableRestartRequested = true;
return resolve(null); // Only the portable supervisor may spawn the replacement.
}
return $this->restartPolicy->restart($file, fn () => $this->stop(), fn (?string $entry) => OSFunctions::restart($entry ?? $this->constructed_file));
}
Expand Down
94 changes: 94 additions & 0 deletions src/Civ13/HttpErrorBoundary.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

namespace Civ13;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use React\Http\Message\Response;
use React\Promise\PromiseInterface;

/** A failed request must not shut down the HTTP listener or the Discord client. */
final class HttpErrorBoundary
{
/** @param list<string> $secrets Known credentials that must never enter diagnostics. */
public function __construct(private LoggerInterface $logger, private array $secrets = []) {}

public function __invoke(ServerRequestInterface $request, callable $next): ResponseInterface|PromiseInterface
{
try {
$response = $next($request);
if ($response instanceof PromiseInterface) {
return $response->then(
fn ($value) => $this->response($value, $request),
fn (\Throwable $error) => $this->failure($error, $request)
);
}
return $this->response($response, $request);
} catch (\Throwable $error) {
return $this->failure($error, $request);
}
}

private function response(mixed $response, ServerRequestInterface $request): ResponseInterface
{
if (!$response instanceof ResponseInterface) {
return $this->failure(new \UnexpectedValueException('HTTP handler returned '.get_debug_type($response).' instead of ResponseInterface'), $request);
}
return $response;
}

private function failure(\Throwable $error, ServerRequestInterface $request): ResponseInterface
{
$this->report($error, $request);
return new Response(Response::STATUS_INTERNAL_SERVER_ERROR, ['Content-Type' => 'text/plain'], 'Internal Server Error');
}

/** React's error event supplies only the exception, not a request. Never restart here. */
public function report(\Throwable $error, ?ServerRequestInterface $request = null): void
{
if (str_starts_with($error->getMessage(), 'Received request with invalid protocol version')) {
return;
}
// No query, headers, body, or trace arguments: any of these may contain credentials or chat.
$message = '[WEBAPI]';
if ($request !== null) {
$message .= ' '.$this->redact($request->getMethod().' '.$request->getUri()->getPath(), 512);
}
for ($depth = 0; $error !== null && $depth < 8; $error = $error->getPrevious(), ++$depth) {
$message .= "\n".($depth === 0 ? '' : 'Caused by: ').get_class($error).': '.$this->redact($error->getMessage(), 2048);
$message .= ' ['.$this->redact($error->getFile(), 512).':'.$error->getLine().']';
// getTraceAsString() can include function arguments depending on PHP configuration.
foreach (array_slice($error->getTrace(), 0, 20) as $index => $frame) {
$message .= "\n#".$index.' '.$this->redact((string) ($frame['file'] ?? '[internal]'), 512).':'.($frame['line'] ?? 0);
$message .= ' '.$this->redact(($frame['class'] ?? '').($frame['type'] ?? '').($frame['function'] ?? ''), 256).'()';
}
}
try {
$this->logger->error($message);
} catch (\Throwable) {
// A broken log sink must not turn an otherwise contained request into another rejection.
}
}

private function redact(string $value, int $limit): string
{
foreach ($this->secrets as $secret) {
if ($secret !== '') {
$value = str_replace(array_unique([$secret, rawurlencode($secret), urlencode($secret)]), '[redacted]', $value);
}
}
// Drop entire URL/request-target queries, including nested JSON and encoded query keys.
$value = preg_replace('/\?[^\s]*/', '?[redacted]', $value) ?? '[redacted]';
$value = preg_replace('/\b(Bearer|Bot)\s+\S+/i', '$1 [redacted]', $value) ?? '[redacted]';
$credentials = <<<'REGEX'
/\b((?:[a-z0-9_-]*[_-])?(?:key|token|password|secret)|authorization)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/i
REGEX;
$value = preg_replace($credentials, '$1=[redacted]', $value) ?? '[redacted]';
$value = preg_replace('~(https?://)[^/\s@]+@~i', '$1[redacted]@', $value) ?? '[redacted]';
$value = preg_replace('/[\x00-\x1f\x7f]/', ' ', $value) ?? '[redacted]';
return strlen($value) > $limit ? substr($value, 0, $limit).' [truncated]' : $value;
}
}
2 changes: 1 addition & 1 deletion src/Civ13/HttpHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public function handle(ServerRequestInterface $request): HttpResponse

return $this->__processCallback($array['callback'], $request, $array['endpoint']);
} catch (\Throwable $e) {
$this->logger->error("HTTP Server error: An endpoint for `$path` failed with error `{$e->getMessage()}`. Stack Trace:".PHP_EOL.str_replace('#', PHP_EOL.'#', $e->getTraceAsString()));
(new HttpErrorBoundary($this->logger, [$this->key]))->report($e, $request);

return new HttpResponse(HttpResponse::STATUS_INTERNAL_SERVER_ERROR);
}
Expand Down
9 changes: 7 additions & 2 deletions tests/local/library.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,18 @@ class PortableRestartProbe extends Civ13\Civ13 {
public function stop(bool $closeLoop = true): void { $this->stops++; }
}
$portable = (new ReflectionClass(PortableRestartProbe::class))->newInstanceWithoutConstructor();
$state = sys_get_temp_dir().'/local-restart-'.bin2hex(random_bytes(8));
mkdir($state);
$portable->portable_state_dir = $state;
$oldProfile = getenv('CIVILIZATIONBOT_PROFILE');
putenv('CIVILIZATIONBOT_PROFILE=synthetic-local-profile');
try {
// restartPolicy remains deliberately uninitialized: portable must never reach it or OS spawn.
$portable->restart()->then(static fn ($result) => assertLocal($result === null));
assertLocal($portable->stops === 1);
assertLocal($portable->stops === 1 && Civ13\PortableProcess::consumeReload($state));
} finally {
if (is_file($state.'/reload.request')) { unlink($state.'/reload.request'); }
rmdir($state);
$oldProfile === false ? putenv('CIVILIZATIONBOT_PROFILE') : putenv('CIVILIZATIONBOT_PROFILE='.$oldProfile);
}
echo "PASS actual merged portable restart stops without legacy/policy spawn\n";
echo "PASS actual merged portable restart signals supervisor before stopping without legacy/policy spawn\n";
Loading
Loading