From cfd6d7a8dfedf098b5af7451d0bab3489c38d841 Mon Sep 17 00:00:00 2001 From: MelekTaus Date: Thu, 15 Oct 2026 23:05:32 +0200 Subject: [PATCH] Lock the server down before the editor goes public (#427) The editor is about to be opened to strangers: a post on Reddit and a guest access (#428). nginx served the whole workspace and ran every PHP file in it, the API let anybody guess passwords as fast as they liked, and one account could fill the disk. - nginx (shared web stack, outside this repo, backup in /root/config-backup-20261015/) hands out only the two pages, dist/, public/brand/, the uploads by kind and ending, and api/index.php. Everything else under /feuerwerk/ is a 404. - PHP behind it has display_errors off and no X-Powered-By. Plain HTTP forwards to HTTPS, the API refuses it. - Headers: a Content-Security-Policy without inline code or eval, nosniff, frame-ancestors, HSTS, Referrer-, Permissions-, COOP, CORP. - vite.config.ts writes the same policy into the built pages, so CI runs the whole suite under it. Pixi gets by without eval through pixi.js/unsafe-eval. The page CSS left its inline style for a file. - The harness fails a module for anything the policy refuses, from Chrome's log and from the page's securitypolicyviolation event. - LoginThrottle: five wrong passwords from one address within 15 minutes, and it gets 429 until 15 minutes after the last of them. The address is the last X-Forwarded-For entry, the Brandmauer's own. - Quota: 1 GB per account for uploads, projects and snapshots. Only a write that grows the account is refused (413). Admins have no limit. - A write whose Sec-Fetch-Site says another site is refused (403). - The session cookie carries Secure, nginx passes HTTPS on. - showFailure puts the message in as text, not as HTML. - Every PHP script outside api/ stops unless it runs on the command line. - The video worker sees the checkout read-only and can only write data/videos. No capabilities, 2 GB and 256 processes at most. - tests/php/rights.test.php runs the API under php -S on a scratch directory and asks every route as signed out, owner, stranger and admin. A route named in api/index.php but missing in the matrix fails it. limits.test.php covers the brake and the quota. Findings: - tmp/ was readable from outside, with 79 copies of project files. Closed on 15.10. at 20:02 with chmod 750. The log back to 11.10. shows only our own requests. - Port 8080 is bound on 0.0.0.0, so the LAN could reach nginx past the Brandmauer. Left as it is: the web stack is not this project's. - npm audit finds nothing in what is shipped. Dev tools (vitest, brace-expansion, source-map-js) have advisories, not touched here. Tests: check 313 files / 4843 tests. PHP limits 21, rights 60, accounts 56, snapshots 15, releases 20, files 46 (videos 50/51, no ffmpeg in the web container). e2e on stein2, atx was off: 34+38+41 197/198, the one red check (a click in 41) passes with 41 alone, 27/27. 67 misses frames at 1080p on stein2 with and without this. Path list from outside: 10 served, 26 refused. ZAP baseline against the live site: nothing High or Medium under /feuerwerk/. Counter-checks: rights.test.php without the cross-site guard, the quota, the brake, the admin check of users, or with an undocumented route fails each time. A policy without wasm-unsafe-eval fails e2e 41 with the harness's own CSP line. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 6 +- .gitignore | 1 + api/index.php | 140 +++++++++++++-- api/lib/LoginThrottle.php | 119 +++++++++++++ api/lib/Quota.php | 77 +++++++++ src/core/store/AuthStore.ts | 8 + src/core/store/HttpAuthStore.ts | 16 +- src/editor/auth/loginRules.ts | 4 + src/page.ts | 9 +- tests/core/auth.test.ts | 23 ++- tests/php/accounts.test.php | 5 + tests/php/files.test.php | 5 + tests/php/limits.test.php | 126 ++++++++++++++ tests/php/releases.test.php | 5 + tests/php/rights.test.php | 296 ++++++++++++++++++++++++++++++++ tests/php/snapshots.test.php | 5 + tests/php/videos.test.php | 5 + tools/ci/serve.sh | 3 + tools/lib/harness.mjs | 21 ++- tools/make-user.php | 5 + tools/migrate-file-owners.php | 5 + tools/video-worker.php | 5 + tools/video/compose.yml | 14 +- vite.config.ts | 37 +++- web/index.html | 5 +- web/page.css | 15 ++ web/play.html | 5 +- 27 files changed, 928 insertions(+), 37 deletions(-) create mode 100644 api/lib/LoginThrottle.php create mode 100644 api/lib/Quota.php create mode 100644 tests/php/limits.test.php create mode 100644 tests/php/rights.test.php create mode 100644 web/page.css diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index f0e05c03..e616f898 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -35,8 +35,8 @@ jobs: env: GM_TEST_WORKERS: 2 - # The API's own rules (#180, #179, #231, #266). Not part of check.sh: the host the editor is built - # on has no PHP, the image does. + # The API's own rules (#180, #179, #231, #266, #427). Not part of check.sh: the host the editor is + # built on has no PHP, the image does. rights.test.php runs the API itself under `php -S`. - name: PHP tests run: | php tests/php/accounts.test.php @@ -44,6 +44,8 @@ jobs: php tests/php/releases.test.php php tests/php/files.test.php php tests/php/videos.test.php + php tests/php/limits.test.php + php tests/php/rights.test.php suite: runs-on: feuerwerk-wsl diff --git a/.gitignore b/.gitignore index b3b65338..b3910ef7 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ /data/e2e-password.txt /data/e2e-admin-password.txt /data/sessions/ +/data/sign-ins/ /data/snapshots/ /data/releases/ /data/users.json diff --git a/api/index.php b/api/index.php index 9e6e8b28..82a3ddfc 100644 --- a/api/index.php +++ b/api/index.php @@ -8,12 +8,23 @@ declare(strict_types=1); * site's nginx configuration does not pass PATH_INFO to PHP. * * GET ?r=auth/session → {user, role} (both null while nobody is signed in) - * POST ?r=auth/login {username,password} → {user, role} | 401 + * POST ?r=auth/login {username,password} → {user, role} | 401 | 429 * POST ?r=auth/logout → 204 - * POST ?r=auth/password {currentPassword,newPassword} → 204 | 401 | 422 + * POST ?r=auth/password {currentPassword,newPassword} → 204 | 401 | 422 | 429 * (the only auth route that needs a session; ends the account's * other logins, keeps the one asking) * + * Five wrong passwords from one address within 15 minutes, and it gets 429 with `Retry-After` for + * the next 15 (see LoginThrottle, #427). + * + * A request that changes something (anything but GET) is refused with 403 when the browser says it + * comes from another site, `Sec-Fetch-Site` being `cross-site` or `same-site`: the session cookie is + * SameSite=Lax, and every subdomain of the site counts as the same site to it. Tools send no such + * header and their own cookie. + * + * An account takes up at most 1 GB with its uploads, projects and snapshots (see Quota); a write that + * would make it larger is refused with 413. Administrators have no limit. + * * Everything below needs a signed-in user (401 otherwise), and projects belong to one: a project * of somebody else answers like one that is not there – unless the one asking is an administrator * (#179), who reads and saves it like their own; a save keeps its owner. Deleting a project is @@ -99,9 +110,11 @@ require __DIR__ . '/lib/Auth.php'; require __DIR__ . '/lib/FileUsage.php'; require __DIR__ . '/lib/HashedFileStore.php'; // before the font, sound and texture stores built on it require __DIR__ . '/lib/FontStore.php'; +require __DIR__ . '/lib/LoginThrottle.php'; require __DIR__ . '/lib/OriginalName.php'; require __DIR__ . '/lib/PixelStore.php'; require __DIR__ . '/lib/PluginStore.php'; +require __DIR__ . '/lib/Quota.php'; require __DIR__ . '/lib/ReleaseStore.php'; require __DIR__ . '/lib/Response.php'; require __DIR__ . '/lib/SessionStore.php'; @@ -134,6 +147,20 @@ const MAX_SOUND_BYTES = 256 * 1024 * 1024; */ const MAX_VIDEO_BYTES = 2048 * 1024 * 1024; +/** + * Where everything the API keeps lies, and how much of it an account may fill. The rights test + * (tests/php/rights.test.php) runs the API under `php -S` on a scratch directory with a small quota; + * behind nginx neither can be moved. + */ +define('DATA_DIR', testSetting('FEUERWERK_DATA') ?? dirname(__DIR__) . '/data'); +define('QUOTA_BYTES', (int) (testSetting('FEUERWERK_QUOTA_BYTES') ?? Quota::BYTES)); + +function testSetting(string $name): ?string +{ + $value = PHP_SAPI === 'cli-server' ? getenv($name) : false; + return is_string($value) && $value !== '' ? $value : null; +} + set_error_handler(static function (int $severity, string $message, string $file, int $line): bool { // PHP calls the handler for a call silenced with `@` as well, only with less reported: that // warning was expected and is answered where it happens (an unreadable image is a 422). @@ -147,6 +174,7 @@ set_error_handler(static function (int $severity, string $message, string $file, function routeAuth(array $parts, string $method, Auth $auth): never { $what = $parts[1] ?? ''; + $throttle = new LoginThrottle(DATA_DIR . '/sign-ins'); if ($what === 'session') { if ($method !== 'GET') { @@ -163,8 +191,10 @@ function routeAuth(array $parts, string $method, Auth $auth): never Response::error('Method not allowed', 405); } $body = Response::body(); + refuseWhileThrottled($throttle); $user = $auth->logIn((string) ($body['username'] ?? ''), (string) ($body['password'] ?? '')); if ($user === null) { + countFailure($throttle); // One message for both halves: which of the two was wrong is the attacker's question. Response::error('Wrong user name or password', 401); } @@ -183,7 +213,10 @@ function routeAuth(array $parts, string $method, Auth $auth): never if (!UserStore::isValidPassword($new)) { Response::error('The new password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422); } + // Guessing the current password from an open tab is guessing all the same. + refuseWhileThrottled($throttle); if (!$auth->changePassword($user, (string) ($body['currentPassword'] ?? ''), $new)) { + countFailure($throttle); Response::error('Wrong password', 401); } Response::noContent(); @@ -200,10 +233,47 @@ function routeAuth(array $parts, string $method, Auth $auth): never Response::error('Not found', 404); } -/** @param list $parts */ -function routeProjects(array $parts, string $method, string $owner, bool $seesAll): never +/** The address a request came from: nginx puts the one the Brandmauer saw there (#427). */ +function clientAddress(): string { - $store = new Store(dirname(__DIR__) . '/data/projects', $owner, $seesAll); + return (string) ($_SERVER['REMOTE_ADDR'] ?? ''); +} + +function countFailure(LoginThrottle $throttle): void +{ + $throttle->fail(clientAddress()); + // Now and then, so the folder holds the addresses of the last quarter of an hour and no more. + if (random_int(1, 20) === 1) { + $throttle->prune(); + } +} + +function refuseWhileThrottled(LoginThrottle $throttle): void +{ + $wait = $throttle->waitFor(clientAddress()); + if ($wait === 0) { + return; + } + header('Retry-After: ' . $wait); + Response::error('Too many failed sign-ins. Try again in ' . (int) ceil($wait / 60) . ' minutes', 429); +} + +/** + * Bytes a project takes up as stored, 0 for one that is not there. + */ +function projectBytes(string $id): int +{ + $path = DATA_DIR . "/projects/{$id}.json"; + return is_file($path) ? (int) filesize($path) : 0; +} + +/** + * @param list $parts + * @param Closure(int):void $fits answers 413 when that many more bytes do not fit the quota + */ +function routeProjects(array $parts, string $method, string $owner, bool $seesAll, Closure $fits): never +{ + $store = new Store(DATA_DIR . '/projects', $owner, $seesAll); if (count($parts) === 1) { if ($method === 'GET') { @@ -215,6 +285,8 @@ function routeProjects(array $parts, string $method, string $owner, bool $seesAl if ($name === '' || mb_strlen($name) > 120) { Response::error('Project name must be 1–120 characters', 422); } + // What an empty project takes up, give or take its name. + $fits(1024); Response::json($store->create($name), 201); } Response::error('Method not allowed', 405); @@ -225,11 +297,11 @@ function routeProjects(array $parts, string $method, string $owner, bool $seesAl Response::error('Invalid project id', 400); } - $snapshots = new SnapshotStore(dirname(__DIR__) . '/data/snapshots'); + $snapshots = new SnapshotStore(DATA_DIR . '/snapshots'); if (($parts[2] ?? null) === 'snapshots') { - routeSnapshots($parts, $method, $store, $snapshots, $id); + routeSnapshots($parts, $method, $store, $snapshots, $id, $fits); } - $releases = new ReleaseStore(dirname(__DIR__) . '/data/releases'); + $releases = new ReleaseStore(DATA_DIR . '/releases'); if (($parts[2] ?? null) === 'release' && count($parts) === 3) { routeRelease($method, $store, $releases, $id); } @@ -250,6 +322,11 @@ function routeProjects(array $parts, string $method, string $owner, bool $seesAl if (!isset($body['revision']) || !is_int($body['revision']) || !is_array($body['project'] ?? null)) { Response::error('Body must contain integer "revision" and object "project"', 422); } + // Asked after whether the project is there for them: a 413 would tell a stranger it is. + if ($store->load($id) === null) { + Response::error('Project not found', 404); + } + $fits((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) - projectBytes($id)); try { $result = $store->save($id, $body['revision'], $body['project']); } catch (StaleRevisionException $e) { @@ -282,9 +359,13 @@ function routeProjects(array $parts, string $method, string $owner, bool $seesAl * The snapshots of one project (#231). Whoever may load the project may see, make, restore and * delete its snapshots; for everybody else the project, and with it this route, is not there. * + * A snapshot copies the project, and so does restoring one (the stand it replaces is kept), so both + * count against the quota with the project's size. + * * @param list $parts + * @param Closure(int):void $fits */ -function routeSnapshots(array $parts, string $method, Store $store, SnapshotStore $snapshots, string $id): never +function routeSnapshots(array $parts, string $method, Store $store, SnapshotStore $snapshots, string $id, Closure $fits): never { $doc = $store->load($id); if ($doc === null) { @@ -297,6 +378,7 @@ function routeSnapshots(array $parts, string $method, Store $store, SnapshotStor } if ($method === 'POST') { $name = snapshotName(Response::body()); + $fits(projectBytes($id)); Response::json($snapshots->create($id, $doc, $name === '' ? gmdate('Y-m-d H:i') . ' UTC' : $name), 201); } Response::error('Method not allowed', 405); @@ -329,6 +411,7 @@ function routeSnapshots(array $parts, string $method, Store $store, SnapshotStor if (!isset($body['revision']) || !is_int($body['revision'])) { Response::error('Body must contain integer "revision"', 422); } + $fits(projectBytes($id)); // The same guard a save has: a tab that is behind must not throw away what another one saved. if ($body['revision'] !== $doc['revision']) { Response::error('Project was modified elsewhere', 409, ['revision' => $doc['revision']]); @@ -379,7 +462,7 @@ function routeReleases(array $parts, string $method): never if ($method !== 'GET' || count($parts) !== 2) { Response::error('Not found', 404); } - $release = (new ReleaseStore(dirname(__DIR__) . '/data/releases'))->load($parts[1]); + $release = (new ReleaseStore(DATA_DIR . '/releases'))->load($parts[1]); if ($release === null) { Response::error('Game not found', 404); } @@ -401,7 +484,7 @@ function snapshotName(array $body): string function routeUsers(array $parts, string $method, Auth $auth, UserStore $users): never { $actor = $auth->requireAdmin(); - $projects = new Store(dirname(__DIR__) . '/data/projects', $actor, true); + $projects = new Store(DATA_DIR . '/projects', $actor, true); $shown = static function (string $name) use ($users): array { foreach ($users->accounts() as $account) { if (strcasecmp($account['username'], $name) === 0) { @@ -519,6 +602,7 @@ function routeUsers(array $parts, string $method, Auth $auth, UserStore $users): * * @param list $parts * @param class-string $invalid what the store throws for bytes it cannot take + * @param Closure(int):void $fits */ function routeFiles( array $parts, @@ -530,6 +614,7 @@ function routeFiles( int $maxBytes, string $noun, string $invalid, + Closure $fits, ): never { if (count($parts) === 1) { if ($method === 'GET') { @@ -538,6 +623,7 @@ function routeFiles( if ($method === 'POST') { $tooLarge = "{$noun} must be at most " . ($maxBytes / 1024 / 1024) . ' MB'; $name = (string) ($_GET['name'] ?? ''); + $fits((int) ($_SERVER['CONTENT_LENGTH'] ?? 0)); try { // A video is too big for memory and goes from the request straight to disk. if ($store instanceof VideoStore) { @@ -586,7 +672,7 @@ function routeFiles( if (!$store->exists($file)) { Response::error("{$noun} not found", 404); } - $uses = (new FileUsage(dirname(__DIR__) . '/data'))->of($file); + $uses = (new FileUsage(DATA_DIR))->of($file); if ($uses !== []) { Response::error(FileUsage::refusal($uses, $user, $isAdmin), 409); } @@ -603,7 +689,7 @@ function routePixels(array $parts, string $method): never if (count($parts) !== 1 || $method !== 'POST') { Response::error('Method not allowed', 405); } - $store = new PixelStore(dirname(__DIR__) . '/data/pixels'); + $store = new PixelStore(DATA_DIR . '/pixels'); $bytes = Response::rawBody(); if (strlen($bytes) > PixelStore::MAX_BYTES) { Response::error('A cel is at most ' . PixelStore::MAX_BYTES . ' bytes', 413); @@ -618,7 +704,7 @@ function routePixels(array $parts, string $method): never /** @param list $parts */ function routePlugins(array $parts, string $method): never { - $store = new PluginStore(dirname(__DIR__) . '/data/plugins'); + $store = new PluginStore(DATA_DIR . '/plugins'); if (count($parts) === 1) { if ($method !== 'GET') { @@ -650,6 +736,11 @@ try { $route = trim((string) ($_GET['r'] ?? ''), '/'); $parts = $route === '' ? [] : explode('/', $route); + $site = (string) ($_SERVER['HTTP_SEC_FETCH_SITE'] ?? ''); + if ($method !== 'GET' && $method !== 'HEAD' && ($site === 'cross-site' || $site === 'same-site')) { + Response::error('Requests from other sites are refused', 403); + } + $maxBody = ($parts[0] ?? '') === 'videos' ? MAX_VIDEO_BYTES : MAX_BODY_BYTES; if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > $maxBody) { Response::error('Request body too large', 413); @@ -668,8 +759,8 @@ try { Response::error('Not found', 404); } - $users = new UserStore(dirname(__DIR__) . '/data/users.json'); - $auth = new Auth($users, new SessionStore(dirname(__DIR__) . '/data/sessions')); + $users = new UserStore(DATA_DIR . '/users.json'); + $auth = new Auth($users, new SessionStore(DATA_DIR . '/sessions')); if ($parts[0] === 'auth') { routeAuth($parts, $method, $auth); } @@ -683,10 +774,19 @@ try { // dropped in by a stranger. $user = $auth->require(); $isAdmin = $auth->role($user) === 'admin'; - $data = dirname(__DIR__) . '/data'; + $data = DATA_DIR; + $fits = static function (int $adding) use ($user, $isAdmin, $users): void { + if ($isAdmin) { + return; + } + $refusal = (new Quota(DATA_DIR, QUOTA_BYTES))->refusal($user, $users->folderOf($user), $adding); + if ($refusal !== null) { + Response::error($refusal, 413); + } + }; match ($parts[0]) { - 'projects' => routeProjects($parts, $method, $user, $isAdmin), + 'projects' => routeProjects($parts, $method, $user, $isAdmin, $fits), 'textures' => routeFiles( $parts, $method, @@ -697,6 +797,7 @@ try { MAX_TEXTURE_BYTES, 'Image', InvalidImageException::class, + $fits, ), 'fonts' => routeFiles( $parts, @@ -708,6 +809,7 @@ try { MAX_FONT_BYTES, 'Font', InvalidFontException::class, + $fits, ), 'sounds' => routeFiles( $parts, @@ -719,6 +821,7 @@ try { MAX_SOUND_BYTES, 'Sound', InvalidSoundException::class, + $fits, ), 'videos' => routeFiles( $parts, @@ -730,6 +833,7 @@ try { MAX_VIDEO_BYTES, 'Video', InvalidVideoException::class, + $fits, ), 'pixels' => routePixels($parts, $method), 'plugins' => routePlugins($parts, $method), diff --git a/api/lib/LoginThrottle.php b/api/lib/LoginThrottle.php new file mode 100644 index 00000000..e1952350 --- /dev/null +++ b/api/lib/LoginThrottle.php @@ -0,0 +1,119 @@ + $failures when the recent failures were + */ + public static function wait(array $failures, int $now): int + { + $times = self::recent($failures, $now); + sort($times); + $until = 0; + for ($i = self::MAX_FAILURES - 1; $i < count($times); $i++) { + if ($times[$i] - $times[$i - self::MAX_FAILURES + 1] < self::WINDOW_SECONDS) { + $until = $times[$i] + self::WINDOW_SECONDS; + } + } + return max(0, $until - $now); + } + + /** Seconds until `$address` may try again, 0 when it may now. */ + public function waitFor(string $address): int + { + $path = $this->path($address); + $raw = is_file($path) ? file_get_contents($path) : false; + return self::wait($raw === false ? [] : self::decode($raw), $this->now()); + } + + /** Counts a failed attempt of `$address` and answers the wait that follows from it. */ + public function fail(string $address): int + { + if (!is_dir($this->dir) && !mkdir($this->dir, 0775, true) && !is_dir($this->dir)) { + throw new RuntimeException('Cannot create the directory of failed sign-ins'); + } + $path = $this->path($address); + $handle = fopen($path, 'c+'); + if ($handle === false) { + throw new RuntimeException('Cannot count a failed sign-in'); + } + try { + chmod($path, AtomicFile::HIDDEN); + flock($handle, LOCK_EX); + $now = $this->now(); + $failures = self::recent(self::decode((string) stream_get_contents($handle)), $now); + $failures[] = $now; + ftruncate($handle, 0); + rewind($handle); + fwrite($handle, (string) json_encode(['failures' => $failures])); + fflush($handle); + return self::wait($failures, $now); + } finally { + flock($handle, LOCK_UN); + fclose($handle); + } + } + + /** Removes the files of addresses whose failures are all too old to matter. */ + public function prune(): int + { + $removed = 0; + foreach (glob($this->dir . '/*.json') ?: [] as $path) { + if ((int) filemtime($path) < $this->now() - 2 * self::WINDOW_SECONDS && unlink($path)) { + $removed++; + } + } + return $removed; + } + + /** + * The failures that can still matter: five of them lie within one window, and the lock lasts one + * window after the last, so nothing older than two windows can. + * + * @param list $failures + * @return list + */ + private static function recent(array $failures, int $now): array + { + return array_values(array_filter($failures, static fn(int $at): bool => $at > $now - 2 * self::WINDOW_SECONDS)); + } + + /** @return list */ + private static function decode(string $raw): array + { + $data = json_decode($raw, true); + $failures = is_array($data) && is_array($data['failures'] ?? null) ? $data['failures'] : []; + return array_values(array_map('intval', array_filter($failures, 'is_int'))); + } + + private function path(string $address): string + { + return $this->dir . '/' . hash('sha256', $address) . '.json'; + } + + private function now(): int + { + return $this->clock === null ? time() : ($this->clock)(); + } +} diff --git a/api/lib/Quota.php b/api/lib/Quota.php new file mode 100644 index 00000000..3c69b7ee --- /dev/null +++ b/api/lib/Quota.php @@ -0,0 +1,77 @@ +data}/{$kind}/{$folder}"); + } + } + $projects = new Store("{$this->data}/projects", $owner); + foreach ($projects->listOf($owner) as $project) { + $bytes += (int) @filesize("{$this->data}/projects/{$project['id']}.json"); + $bytes += self::sizeOf("{$this->data}/snapshots/{$project['id']}"); + } + return $bytes; + } + + /** Why `$adding` more bytes do not fit, or null when they do (or add nothing). */ + public function refusal(string $owner, string $folder, int $adding): ?string + { + if ($adding <= 0) { + return null; + } + $used = $this->usage($owner, $folder); + if ($used + $adding <= $this->limit) { + return null; + } + return sprintf( + 'Not enough space: this account uses %s of its %s', + self::megabytes($used), + self::megabytes($this->limit), + ); + } + + private static function megabytes(int $bytes): string + { + return number_format($bytes / 1024 / 1024, $bytes < 10 * 1024 * 1024 ? 1 : 0, '.', '') . ' MB'; + } + + private static function sizeOf(string $dir): int + { + if (!is_dir($dir)) { + return 0; + } + $bytes = 0; + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)); + foreach ($files as $file) { + if ($file->isFile()) { + $bytes += $file->getSize(); + } + } + return $bytes; + } +} diff --git a/src/core/store/AuthStore.ts b/src/core/store/AuthStore.ts index 802ee19b..762e50f7 100644 --- a/src/core/store/AuthStore.ts +++ b/src/core/store/AuthStore.ts @@ -37,3 +37,11 @@ export class WrongCredentialsError extends Error { this.name = 'WrongCredentialsError'; } } + +/** Thrown while the server turns sign-ins away after too many wrong ones (#427); says for how long. */ +export class TooManyAttemptsError extends Error { + constructor(message = 'Too many failed sign-ins. Try again later') { + super(message); + this.name = 'TooManyAttemptsError'; + } +} diff --git a/src/core/store/HttpAuthStore.ts b/src/core/store/HttpAuthStore.ts index 4e813940..ec01bcbb 100644 --- a/src/core/store/HttpAuthStore.ts +++ b/src/core/store/HttpAuthStore.ts @@ -1,14 +1,24 @@ -import { type AuthStore, roleOf, type SignedIn, WrongCredentialsError } from './AuthStore'; +import { + type AuthStore, + roleOf, + type SignedIn, + TooManyAttemptsError, + WrongCredentialsError, +} from './AuthStore'; import { apiRequest, jsonBody } from './http'; /** * A wrong password is the expected answer of a login screen, not a breakdown: it gets its own type * so the screen can say one thing about it and another about a server that is down. Changing the * password answers the same way when the current one was wrong; a 422 (too short) carries the - * server's wording and stays generic. + * server's wording and stays generic. So does the brake after too many wrong ones (429), which + * says how long it lasts. */ function wrongCredentials(status: number, data: unknown): Error | undefined { - return status === 401 ? new WrongCredentialsError((data as { error?: string } | null)?.error) : undefined; + const message = (data as { error?: string } | null)?.error; + if (status === 401) return new WrongCredentialsError(message); + if (status === 429) return new TooManyAttemptsError(message); + return undefined; } export class HttpAuthStore implements AuthStore { diff --git a/src/editor/auth/loginRules.ts b/src/editor/auth/loginRules.ts index 921962da..1e606c83 100644 --- a/src/editor/auth/loginRules.ts +++ b/src/editor/auth/loginRules.ts @@ -1,3 +1,5 @@ +import { TooManyAttemptsError } from '../../core/store/AuthStore'; + /** * What a login form may complain about before anything is sent. Kept apart from the screen so it * can be read without a browser: the screen only shows what this returns. @@ -11,6 +13,7 @@ export function loginProblem(username: string, password: string): string | null /** The message a failed attempt puts under the form. */ export function loginError(error: unknown, wrongCredentials: boolean): string { if (wrongCredentials) return 'Wrong user name or password'; + if (error instanceof TooManyAttemptsError) return error.message; return `Could not sign in: ${error instanceof Error ? error.message : String(error)}`; } @@ -34,5 +37,6 @@ export function passwordProblem(current: string, next: string, repeat: string): /** The message a refused change puts under the form. */ export function passwordError(error: unknown, wrongCredentials: boolean): string { if (wrongCredentials) return 'Wrong current password'; + if (error instanceof TooManyAttemptsError) return error.message; return `Could not change the password: ${error instanceof Error ? error.message : String(error)}`; } diff --git a/src/page.ts b/src/page.ts index ba3f8710..5cc274c8 100644 --- a/src/page.ts +++ b/src/page.ts @@ -1,4 +1,7 @@ import { Application, Container } from 'pixi.js'; +// Pixi writes its uniform uploads as generated code; this swaps them for plain ones, so the pages run +// under a Content-Security-Policy without `unsafe-eval` (#427). +import 'pixi.js/unsafe-eval'; import { initPixelGrid, initRenderLoop, initUI, loadEditorFonts, Theme, tieBreakFor, VStack } from './ui'; import { fixedPageSize, type PageSize, placePage } from './ui/pageSize'; import { moveOldStoredKeys } from './core/site'; @@ -75,7 +78,11 @@ function pinCanvas(canvas: HTMLCanvasElement, size: PageSize): void { window.addEventListener('resize', place); } +/** Shows what went wrong as text: a message may carry a project's or a file's name. */ export function showFailure(error: unknown): void { console.error(error); - document.body.innerHTML = `
${String(error)}
`; + const text = document.createElement('pre'); + text.textContent = String(error); + Object.assign(text.style, { color: '#e0553f', padding: '16px', font: '13px monospace' }); + document.body.replaceChildren(text); } diff --git a/tests/core/auth.test.ts b/tests/core/auth.test.ts index 69463efa..0444f9a1 100644 --- a/tests/core/auth.test.ts +++ b/tests/core/auth.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { WrongCredentialsError } from '../../src/core/store/AuthStore'; +import { TooManyAttemptsError, WrongCredentialsError } from '../../src/core/store/AuthStore'; import { HttpAuthStore } from '../../src/core/store/HttpAuthStore'; import { loginError, @@ -81,6 +81,21 @@ describe('HttpAuthStore', () => { await expect(failure).rejects.toThrow(/418/); }); + // #427: five wrong passwords and the address waits. That is neither a wrong pair nor a breakdown, + // and the server's sentence says how long. + it('tells the brake after too many wrong passwords apart, with the server’s wording', async () => { + const said = 'Too many failed sign-ins. Try again in 15 minutes'; + stubFetch(JSON.stringify({ error: said }), { status: 429, headers: { 'Retry-After': '900' } }); + const login = new HttpAuthStore('/api').logIn('user', 'secret'); + await expect(login).rejects.toBeInstanceOf(TooManyAttemptsError); + await expect(login).rejects.toThrow(said); + + stubFetch(JSON.stringify({ error: said }), { status: 429 }); + await expect(new HttpAuthStore('/api').changePassword('old', 'a-new-one')).rejects.toBeInstanceOf( + TooManyAttemptsError, + ); + }); + it('signs out without a body', async () => { const mock = stubFetch(null, { status: 204 }); await expect(new HttpAuthStore('/api').logOut()).resolves.toBeUndefined(); @@ -128,6 +143,12 @@ describe('the rules of the sign-in form', () => { 'Could not sign in: Server unavailable (503)', ); }); + + it('passes on how long the brake lasts, without a prefix', () => { + const said = 'Too many failed sign-ins. Try again in 15 minutes'; + expect(loginError(new TooManyAttemptsError(said), false)).toBe(said); + expect(passwordError(new TooManyAttemptsError(said), false)).toBe(said); + }); }); describe('the rules of the change-password form', () => { diff --git a/tests/php/accounts.test.php b/tests/php/accounts.test.php index d5229ed5..110b897a 100644 --- a/tests/php/accounts.test.php +++ b/tests/php/accounts.test.php @@ -1,6 +1,11 @@ waitFor('203.0.113.7') === 0); +for ($i = 1; $i < LoginThrottle::MAX_FAILURES; $i++) { + $throttle->fail('203.0.113.7'); + $now += 10; +} +check('four failures still let it try', $throttle->waitFor('203.0.113.7') === 0, $throttle->waitFor('203.0.113.7')); +$wait = $throttle->fail('203.0.113.7'); +check('the fifth locks it for the whole window', $wait === $window, $wait); +check('and asking says so', $throttle->waitFor('203.0.113.7') === $window); +check('another address is not touched', $throttle->waitFor('198.51.100.1') === 0); + +$now += $window - 1; +check('one second before the end it still waits', $throttle->waitFor('203.0.113.7') === 1, $throttle->waitFor('203.0.113.7')); +$now += 1; +check('15 minutes after the last failure it may try again', $throttle->waitFor('203.0.113.7') === 0); +$throttle->fail('203.0.113.7'); +check('and the old failures no longer count', $throttle->waitFor('203.0.113.7') === 0); + +// Failures spread wider than the window never add up to five. +$now += $window; +for ($i = 0; $i < 10; $i++) { + $throttle->fail('192.0.2.9'); + $now += (int) ($window / 4) + 1; +} +check('failures spread over more than 15 minutes never lock', $throttle->waitFor('192.0.2.9') === 0); + +check( + 'the rule as a function: five within the window wait for the rest of it', + LoginThrottle::wait([100, 200, 300, 400, 500], 600) === 500 + $window - 600, +); +check('four do not', LoginThrottle::wait([100, 200, 300, 400], 600) === 0); +check( + 'nor five of which the first is a whole window before the last', + LoginThrottle::wait([500 - $window, 200, 300, 400, 500], 600) === 0, +); + +$files = glob("{$dir}/sign-ins/*.json") ?: []; +check('one file per address that failed, named by its hash', count($files) === 2 &&!str_contains(implode('', $files), '203.0.113.7'), $files); +check('which the web server may not read', (fileperms($files[0]) & 0o007) === 0); + +touch($files[0], $now - 2 * $window - 1); +check('pruning drops an address whose failures are all old', $throttle->prune() >= 1 && !is_file($files[0])); + +// --- Quota ----------------------------------------------------------------------------------------- + +$data = "{$dir}/data"; +mkdir("{$data}/projects", 0775, true); +$users = new UserStore("{$data}/users.json"); +$users->put('ann', 'password1'); +$folder = $users->folderOf('ann', true); +mkdir("{$data}/sounds/{$folder}", 0775, true); +file_put_contents("{$data}/sounds/{$folder}/" . str_repeat('a', 64) . '.wav', str_repeat("\0", 3000)); +mkdir("{$data}/videos/{$folder}", 0775, true); +file_put_contents("{$data}/videos/{$folder}/" . str_repeat('b', 64) . '.mp4', str_repeat("\0", 2000)); +$doc = (new Store("{$data}/projects", 'ann'))->create('Mine'); +$projectBytes = filesize("{$data}/projects/{$doc['id']}.json"); +mkdir("{$data}/snapshots/{$doc['id']}", 0775, true); +file_put_contents("{$data}/snapshots/{$doc['id']}/s1.json", str_repeat('x', 500)); +// Somebody else's things do not count, nor do the files that belong to nobody. +$theirs = (new Store("{$data}/projects", 'bob'))->create('Theirs'); +file_put_contents("{$data}/sounds/" . str_repeat('c', 64) . '.wav', str_repeat("\0", 9000)); + +$quota = new Quota($data, 10_000); +$used = $quota->usage('ann', $folder); +check('usage adds the uploads, the projects and their snapshots', $used === 3000 + 2000 + $projectBytes + 500, [$used, $projectBytes]); +check('what fits is let through', $quota->refusal('ann', $folder, 10_000 - $used) === null); +$refusal = $quota->refusal('ann', $folder, 10_000 - $used + 1); +check('one byte more is refused, saying how full the account is', is_string($refusal) && str_contains($refusal, 'Not enough space'), $refusal); +check('a write that makes nothing larger always fits', (new Quota($data, 1))->refusal('ann', $folder, 0) === null); +check( + 'an account without uploads counts its projects only', + $quota->usage('bob', '') === filesize("{$data}/projects/{$theirs['id']}.json"), + $quota->usage('bob', ''), +); +check('the limit is 1 GB unless a test says otherwise', Quota::BYTES === 1024 * 1024 * 1024); + +exec('rm -rf ' . escapeshellarg($dir)); + +echo $failed === 0 ? "ALL PASSED – {$passed} checks\n" : "{$failed} FAILED, {$passed} passed\n"; +exit($failed === 0 ? 0 : 1); diff --git a/tests/php/releases.test.php b/tests/php/releases.test.php index cdc465b9..b5655b52 100644 --- a/tests/php/releases.test.php +++ b/tests/php/releases.test.php @@ -1,6 +1,11 @@ put('alice', 'password-alice', 'user'); +$users->put('bob', 'password-bob', 'user'); +$users->put('root', 'password-root', 'admin'); +$users->put('carol', 'password-carol', 'user'); + +$probe = stream_socket_server('tcp://127.0.0.1:0'); +$port = (int) substr((string) stream_socket_get_name($probe, false), strrpos((string) stream_socket_get_name($probe, false), ':') + 1); +fclose($probe); +$server = proc_open( + [PHP_BINARY, '-S', "127.0.0.1:{$port}", '-t', "{$base}/www"], + [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['file', "{$base}/server.log", 'w']], + $pipes, + null, + ['FEUERWERK_DATA' => $data, 'FEUERWERK_QUOTA_BYTES' => (string) QUOTA] + getenv(), +); +register_shutdown_function(static function () use ($server, $base): void { + proc_terminate($server); + exec('rm -rf ' . escapeshellarg($base)); +}); + +/** + * One request against the API. + * + * @param array $headers + * @return array{status:int,body:mixed,headers:list} + */ +function call(string $method, string $route, ?string $cookie = null, mixed $body = null, array $headers = []): array +{ + global $port; + $lines = []; + if ($cookie !== null) { + $lines[] = "Cookie: feuerwerk_session={$cookie}"; + } + foreach ($headers as $name => $value) { + $lines[] = "{$name}: {$value}"; + } + $content = ''; + if (is_string($body)) { + $content = $body; + $lines[] = 'Content-Type: application/octet-stream'; + } elseif ($body !== null) { + $content = (string) json_encode($body); + $lines[] = 'Content-Type: application/json'; + } + $context = stream_context_create(['http' => [ + 'method' => $method, + 'header' => implode("\r\n", $lines), + 'content' => $content, + 'ignore_errors' => true, + 'timeout' => 20, + ]]); + [$path, $query] = array_pad(explode('&', $route, 2), 2, null); + $url = "http://127.0.0.1:{$port}/feuerwerk/api/index.php?r=" . $path . ($query === null ? '' : "&{$query}"); + $text = @file_get_contents($url, false, $context); + $received = $http_response_header ?? []; + preg_match('#^HTTP/\S+ (\d{3})#', $received[0] ?? '', $status); + return [ + 'status' => (int) ($status[1] ?? 0), + 'body' => $text === false || $text === '' ? null : json_decode($text, true), + 'headers' => $received, + ]; +} + +function signIn(string $name, string $password): string +{ + $answer = call('POST', 'auth/login', null, ['username' => $name, 'password' => $password]); + foreach ($answer['headers'] as $line) { + if (preg_match('/^Set-Cookie: feuerwerk_session=([^;]+)/i', $line, $match)) { + return $match[1]; + } + } + throw new RuntimeException("{$name} could not sign in: " . json_encode($answer)); +} + +$up = false; +for ($i = 0; $i < 50 && !$up; $i++) { + usleep(100_000); + $up = call('GET', 'auth/session')['status'] === 200; +} +check('the API comes up on its scratch directory', $up, @file_get_contents("{$base}/server.log")); +if (!$up) { + exit(1); +} + +/** A PNG of one pixel: the smallest image the texture store takes. */ +$png = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='); +$wav = static fn(int $bytes, string $tag): string => 'RIFF' . pack('V', 36) . 'WAVE' . str_repeat("\0", $bytes) . $tag; + +$alice = signIn('alice', 'password-alice'); +$bob = signIn('bob', 'password-bob'); +$admin = signIn('root', 'password-root'); + +// What the matrix asks about: a project of alice's that uses an image of hers, with a snapshot and a +// release, and a sound of hers that nothing uses. +$project = call('POST', 'projects', $alice, ['name' => 'Alice'])['body']; +$texture = call('POST', 'textures&name=a.png', $alice, $png)['body']['file'] ?? ''; +$sound = call('POST', 'sounds&name=a.wav', $alice, $wav(32, 'alice'))['body']['file'] ?? ''; +$saved = call('PUT', "projects/{$project['id']}", $alice, [ + 'revision' => 1, + 'project' => ['id' => $project['id'], 'name' => 'Alice', 'assets' => [['id' => 't', 'file' => $texture]]], +]); +$snapshot = call('POST', "projects/{$project['id']}/snapshots", $alice, ['name' => 'One'])['body']; +$release = call('POST', "projects/{$project['id']}/release", $alice)['body']; +check( + 'alice has her project, image, sound, snapshot and release', + $saved['status'] === 200 && $texture !== '' && $sound !== '' && isset($snapshot['id'], $release['token']), + [$saved['status'], $texture, $sound, $snapshot, $release], +); +$folder = explode('/', $texture)[0]; +$p = $project['id']; +$s = $snapshot['id']; +$missing = $folder . '/' . str_repeat('0', 64); + +/** + * Method, route, body, the route as the header comment of api/index.php names it, and the status + * expected from [signed out, alice who owns it, bob who does not, an administrator]; null where + * asking would destroy what the next rows need. + * + * @var list + */ +$matrix = [ + ['GET', 'auth/session', null, 'GET auth/session', [200, 200, 200, 200]], + ['POST', 'auth/login', ['username' => 'carol', 'password' => 'password-carol'], 'POST auth/login', [200, 200, 200, 200]], + ['POST', 'auth/logout', null, 'POST auth/logout', [204, null, null, null]], + ['POST', 'auth/password', ['currentPassword' => 'x', 'newPassword' => ''], 'POST auth/password', [401, 422, 422, 422]], + + ['GET', 'users', null, 'GET users', [401, 403, 403, 200]], + ['POST', 'users', ['username' => '', 'password' => '', 'role' => 'user'], 'POST users', [401, 403, 403, 422]], + ['PATCH', 'users/alice', [], 'PATCH users/{}', [401, 403, 403, 200]], + ['DELETE', 'users/nobody', null, 'DELETE users/{}', [401, 403, 403, 404]], + + ['GET', 'projects', null, 'GET projects', [401, 200, 200, 200]], + ['POST', 'projects', ['name' => ''], 'POST projects', [401, 422, 422, 422]], + ['GET', "projects/{$p}", null, 'GET projects/{}', [401, 200, 404, 200]], + ['PUT', "projects/{$p}", ['revision' => 999, 'project' => []], 'PUT projects/{}', [401, 409, 404, 409]], + ['DELETE', "projects/{$p}", null, 'DELETE projects/{}', [401, null, 404, 403]], + ['GET', "projects/{$p}/snapshots", null, 'GET projects/{}/snapshots', [401, 200, 404, 200]], + ['POST', "projects/{$p}/snapshots", [], 'POST projects/{}/snapshots', [401, 201, 404, 201]], + ['DELETE', "projects/{$p}/snapshots/{$s}", null, 'DELETE projects/{}/snapshots/{}', [401, null, 404, null]], + ['POST', "projects/{$p}/snapshots/{$s}/restore", ['revision' => -1], 'POST projects/{}/snapshots/{}/restore', [401, 409, 404, 409]], + ['GET', "projects/{$p}/release", null, 'GET projects/{}/release', [401, 200, 404, 200]], + ['POST', "projects/{$p}/release", null, 'POST projects/{}/release', [401, 200, 404, 200]], + ['DELETE', "projects/{$p}/release", null, 'DELETE projects/{}/release', [401, null, 404, null]], + ['GET', "releases/{$release['token']}", null, 'GET releases/{}', [200, 200, 200, 200]], + + ['GET', 'textures', null, 'GET textures', [401, 200, 200, 200]], + ['POST', 'textures&name=b.png', $png, 'POST textures', [401, 201, 201, 201]], + ['DELETE', "textures/{$texture}", null, 'DELETE textures/{}', [401, 409, 403, 409]], + ['GET', 'fonts', null, 'GET fonts', [401, 200, 200, 200]], + ['POST', 'fonts&name=x.ttf', 'not a font at all', 'POST fonts', [401, 422, 422, 422]], + ['DELETE', "fonts/{$missing}.ttf", null, 'DELETE fonts/{}', [401, 404, 403, 404]], + ['GET', 'sounds', null, 'GET sounds', [401, 200, 200, 200]], + ['POST', 'sounds&name=b.wav', $wav(32, 'b'), 'POST sounds', [401, 201, 201, 201]], + ['DELETE', "sounds/{$sound}", null, 'DELETE sounds/{}', [401, null, 403, null]], + ['GET', 'videos', null, 'GET videos', [401, 200, 200, 200]], + ['POST', 'videos&name=x.mov&convert=0', 'not a video at all', 'POST videos', [401, 422, 422, 422]], + ['POST', "videos/{$missing}.mp4/convert", null, 'POST videos/{}/convert', [401, 404, 403, 404]], + ['DELETE', "videos/{$missing}.mp4", null, 'DELETE videos/{}', [401, 404, 403, 404]], + ['POST', 'pixels', 'not a cel', 'POST pixels', [401, 422, 422, 422]], + ['GET', 'plugins', null, 'GET plugins', [401, 200, 200, 200]], + ['GET', 'plugins/nothing.js', null, 'GET plugins/{}', [401, 404, 404, 404]], +]; + +$actors = ['signed out' => null, 'alice' => $alice, 'bob' => $bob, 'an administrator' => $admin]; +foreach ($matrix as [$method, $route, $body, $documented, $expected]) { + $got = []; + $want = []; + foreach (array_values($actors) as $i => $cookie) { + if ($expected[$i] === null) { + continue; + } + $got[] = call($method, $route, $cookie, $body)['status']; + $want[] = $expected[$i]; + } + check("{$documented}: " . implode(' / ', array_map( + static fn(string $who, ?int $status): string => "{$who} " . ($status ?? '-'), + array_keys($actors), + $expected, + )), $got === $want, $got); +} + +// Every route the API documents is asked about above. +preg_match_all('/^\s*\*\s+(GET|POST|PUT|PATCH|DELETE)\s+\?r=([^\s&\[]+)/m', (string) file_get_contents("{$root}/api/index.php"), $found, PREG_SET_ORDER); +$documentedRoutes = array_values(array_unique(array_map( + static fn(array $m): string => $m[1] . ' ' . preg_replace('/\{[^}]*\}/', '{}', $m[2]), + $found, +))); +$asked = array_unique(array_column($matrix, 3)); +$unasked = array_values(array_diff($documentedRoutes, $asked)); +check('every route of the API is in the matrix', count($documentedRoutes) > 30 && $unasked === [], $unasked ?: count($documentedRoutes)); +check('and the matrix asks about no route the API does not name', array_values(array_diff($asked, $documentedRoutes)) === [], array_values(array_diff($asked, $documentedRoutes))); + +// --- Paths, depth and unknown routes -------------------------------------------------------------- + +check('an unknown route is 401 signed out', call('GET', 'nothing')['status'] === 401); +check('and 404 signed in', call('GET', 'nothing', $alice)['status'] === 404); +check('a path that climbs out of a store is refused for a user', call('DELETE', 'textures/../users.json', $bob)['status'] === 403); +check('and not found for an administrator', call('DELETE', 'textures/../users.json', $admin)['status'] === 404); +check('a project id that climbs out is no project id', call('GET', 'projects/..%2Fusers', $alice)['status'] === 400); +check('a route deeper than its kind allows is not there', call('GET', "projects/{$p}/snapshots/{$s}/restore/more", $alice)['status'] === 404); +check('the accounts file is still there', is_file("{$data}/users.json")); + +// --- Requests from other sites -------------------------------------------------------------------- + +check( + 'a write from another site is refused before anything else', + call('POST', 'projects', $alice, ['name' => 'x'], ['Sec-Fetch-Site' => 'cross-site'])['status'] === 403, +); +check( + 'so is one from a sibling subdomain', + call('POST', 'auth/login', null, ['username' => 'alice', 'password' => 'password-alice'], ['Sec-Fetch-Site' => 'same-site'])['status'] === 403, +); +check( + 'the editor’s own page passes', + call('POST', 'projects', $alice, ['name' => ''], ['Sec-Fetch-Site' => 'same-origin'])['status'] === 422, +); +check('reading from another site is no write', call('GET', 'projects', $alice, null, ['Sec-Fetch-Site' => 'cross-site'])['status'] === 200); + +// --- Quota ---------------------------------------------------------------------------------------- + +$large = $wav(QUOTA, 'large'); +$refused = call('POST', 'sounds&name=large.wav', $alice, $large); +check( + 'an upload past the quota is refused with 413, saying how full the account is', + $refused['status'] === 413 && str_contains((string) ($refused['body']['error'] ?? ''), 'Not enough space'), + $refused, +); +check('an administrator has no quota', call('POST', 'sounds&name=large.wav', $admin, $large)['status'] === 201); +$big = ['id' => $p, 'name' => 'Alice', 'assets' => [], 'pad' => str_repeat('x', QUOTA)]; +check('so is a save that would grow a project past it', call('PUT', "projects/{$p}", $alice, ['revision' => 2, 'project' => $big])['status'] === 413); +check('a save that keeps it small goes through', call('PUT', "projects/{$p}", $alice, ['revision' => 2, 'project' => ['name' => 'Alice']])['status'] === 200); + +// --- Sign-ins: the brake ------------------------------------------------------------------------- + +$gone = signIn('carol', 'password-carol'); +check('signing out ends that session', call('POST', 'auth/logout', $gone)['status'] === 204 && call('GET', 'projects', $gone)['status'] === 401); +$wrong = []; +for ($i = 0; $i < 5; $i++) { + $wrong[] = call('POST', 'auth/login', null, ['username' => 'bob', 'password' => 'guess'])['status']; +} +check('five wrong passwords are five 401', $wrong === [401, 401, 401, 401, 401], $wrong); +$locked = call('POST', 'auth/login', null, ['username' => 'bob', 'password' => 'password-bob']); +$retry = preg_grep('/^Retry-After: \d+$/i', $locked['headers']); +check('then even the right one waits, with 429 and Retry-After', $locked['status'] === 429 && $retry !== [], $locked); +check('the session of somebody already signed in goes on', call('GET', 'projects', $alice)['status'] === 200); + +echo $failed === 0 ? "ALL PASSED – {$passed} checks\n" : "{$failed} FAILED, {$passed} passed\n"; +exit($failed === 0 ? 0 : 1); diff --git a/tests/php/snapshots.test.php b/tests/php/snapshots.test.php index 8b2cd1b4..a8a8d2f7 100644 --- a/tests/php/snapshots.test.php +++ b/tests/php/snapshots.test.php @@ -1,6 +1,11 @@ console.warn('[csp] ' + e.violatedDirective + ' refused ' + (e.blockedURI || 'inline')), true);`, + }); cdp.on((msg) => { - if (msg.method === 'Runtime.consoleAPICalled') - consoleLog.push(msg.params.args.map((a) => a.value ?? a.description).join(' ')); + if (msg.method === 'Runtime.consoleAPICalled') { + const text = msg.params.args.map((a) => a.value ?? a.description).join(' '); + consoleLog.push(text); + if (text.startsWith('[csp] ')) refused.push(text); + } if (msg.method === 'Runtime.exceptionThrown') consoleLog.push( 'EXCEPTION ' + (msg.params.exceptionDetails.exception?.description ?? msg.params.exceptionDetails.text), ); + if (msg.method === 'Log.entryAdded' && /Content Security Policy/i.test(msg.params.entry.text)) + refused.push(msg.params.entry.text); }); await body(makeTools({ cdp, projectId, baseUrl, consoleLog, check, shotPrefix })); ws.close(); @@ -652,6 +665,10 @@ export async function runChecks(options, body) { stopBrowser(); }); } + // Reported only when it happens, so a passing run keeps its count of checks; and also after a step + // that threw, which a refusal is the likeliest cause of. + if (refused.length) + check('the pages stay within their Content-Security-Policy', false, [...new Set(refused)].slice(0, 3)); if (consoleLog.length) console.log('--- console ---\n' + consoleLog.slice(0, 20).join('\n')); reportedSummary = true; console.log(failures ? `${failures} FAILED` : `ALL PASSED – ${checkCount} checks`); diff --git a/tools/make-user.php b/tools/make-user.php index 795c269e..2173e815 100644 --- a/tools/make-user.php +++ b/tools/make-user.php @@ -1,6 +1,11 @@ [ + { + tag: 'meta', + attrs: { 'http-equiv': 'Content-Security-Policy', content: CONTENT_SECURITY_POLICY }, + injectTo: 'head-prepend', + }, + ], + }; +} + /** * Editor plugins are loaded from `data/plugins/`, which is not in the repository; the ones that * ship with it live in `plugins/` and are put there on every build. A file of the same name is @@ -46,7 +81,7 @@ export default defineConfig({ root: 'web', base: `${SITE_PATH}dist/`, publicDir: false, - plugins: [publishPages(), shipPlugins()], + plugins: [contentSecurityPolicy(), publishPages(), shipPlugins()], build: { outDir: '../dist', emptyOutDir: true, diff --git a/web/index.html b/web/index.html index 00aa46fa..f6bef589 100644 --- a/web/index.html +++ b/web/index.html @@ -7,10 +7,7 @@ - + diff --git a/web/page.css b/web/page.css new file mode 100644 index 00000000..e7dc99b0 --- /dev/null +++ b/web/page.css @@ -0,0 +1,15 @@ +html, +body { + margin: 0; + padding: 0; + width: 100%; + height: 100%; + overflow: hidden; + background: #1b1d22; +} +canvas { + display: block; + width: 100%; + height: 100%; + touch-action: none; +} diff --git a/web/play.html b/web/play.html index 5a1c93c9..8c16b53a 100644 --- a/web/play.html +++ b/web/play.html @@ -4,10 +4,7 @@ Game - +