diff options
| author | fox <fox@fakecake.org> | 2026-10-14 21:41:11 +0300 |
|---|---|---|
| committer | GitLab <noreply@fakecake.org> | 2026-10-14 21:41:11 +0300 |
| commit | fa0e418228ec4ff79ef4b2024beb2491e15d538e (patch) | |
| tree | 906546542b5df2689ee6a0c16b889df82f947580 | |
| parent | c0135cc03916ad22707064e8957dce3f8e067a5d (diff) | |
| parent | 48d7b08a87adec0ce1c114bd5c70c0f6e108a954 (diff) | |
| download | the-epube-fa0e418228ec4ff79ef4b2024beb2491e15d538e.tar.gz the-epube-fa0e418228ec4ff79ef4b2024beb2491e15d538e.tar.xz | |
Merge branch 'dev' into 'master'
Dev See merge request git/the-epube!77
| -rw-r--r-- | .docker/web-nginx/nginx.conf | 2 | ||||
| -rw-r--r-- | classes/Handler/HealthzHandler.php | 24 | ||||
| -rw-r--r-- | classes/Handler/PaginationHandler.php | 40 | ||||
| -rw-r--r-- | classes/Response.php | 4 | ||||
| -rw-r--r-- | tests_integration/PaginationHandlerTest.php | 38 |
5 files changed, 90 insertions, 18 deletions
diff --git a/.docker/web-nginx/nginx.conf b/.docker/web-nginx/nginx.conf index e688a42..91361bb 100644 --- a/.docker/web-nginx/nginx.conf +++ b/.docker/web-nginx/nginx.conf @@ -28,7 +28,7 @@ http { # editor/build junk (.phpstan-tmp/, .phpunit.result.cache, __pycache__ etc.). The dev # compose override bind-mounts the whole project directory into this container, so those # files are otherwise servable (and .phpstan-tmp/*.php would even be passed to php-fpm); - # unanchored on purpose, ${APP_BASE} may be "" (site root) or "/tt-rss". + # unanchored on purpose, ${APP_BASE} may be "" (site root) or "/books". location ~ "/[._]" { deny all; } diff --git a/classes/Handler/HealthzHandler.php b/classes/Handler/HealthzHandler.php index 722422c..f12649b 100644 --- a/classes/Handler/HealthzHandler.php +++ b/classes/Handler/HealthzHandler.php @@ -9,38 +9,40 @@ use Request; use RequestHandlerInterface; use Response; +/** + * Public k8s healthcheck endpoint. Intentionally does NOT implement + * AuthRequired. Because it is unauthenticated, it must not leak any + * internals (DSNs, paths, driver errors) — failure details go to the + * PHP error log, the HTTP response only carries 200/503. + */ class HealthzHandler implements RequestHandlerInterface { public function handle(Request $request): Response { - $status = "ok"; - $errors = []; + $healthy = true; // Test Calibre SQLite database try { $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); $caldb->query("SELECT 1 FROM books LIMIT 1"); } catch (\PDOException $e) { - $status = "degraded"; - $errors["calibre_db"] = "Connection failed: " . $e->getMessage(); + $healthy = false; + error_log("healthz: calibre db check failed: " . $e->getMessage()); } // Test main database (via ORM/Db) try { Db::pdo()->query("SELECT 1"); } catch (\PDOException $e) { - $status = "degraded"; - $errors["main_db"] = "Connection failed: " . $e->getMessage(); + $healthy = false; + error_log("healthz: main db check failed: " . $e->getMessage()); } $response = (new Response()) ->withHeader("Content-Type", "application/json") - ->withBody(json_encode([ - "status" => $status, - "errors" => $errors, - ])); + ->withBody(json_encode(["status" => $healthy ? "ok" : "error"])); - if ($status === "degraded") { + if (!$healthy) { $response = $response->withStatus(503); } diff --git a/classes/Handler/PaginationHandler.php b/classes/Handler/PaginationHandler.php index 3c0555b..de22037 100644 --- a/classes/Handler/PaginationHandler.php +++ b/classes/Handler/PaginationHandler.php @@ -3,13 +3,35 @@ namespace Handler; use AuthRequired; +use Config; use ORM; +use PDO; use Request; use RequestHandlerInterface; use Response; class PaginationHandler implements RequestHandlerInterface, AuthRequired { + /** + * Upper bound for stored location payloads. Observed real-world max in + * production is ~3 MB for large books; 16 MiB keeps generous headroom + * while still bounding unbounded storage growth. + */ + private const MAX_PAYLOAD_SIZE = 16 * 1024 * 1024; + + /** + * Verify the id refers to an actual library entry in the Calibre DB. + * The frontend keys pagination by the EPUB 'data' row id, but accept + * a 'books' row id as well for robustness/backwards compatibility. + */ + private function bookExists(int $bookid): bool + { + $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + $sth = $caldb->prepare("SELECT 1 FROM data WHERE id = ? UNION SELECT 1 FROM books WHERE id = ? LIMIT 1"); + $sth->execute([$bookid, $bookid]); + return (bool)$sth->fetch(); + } + private function handleGet(int $bookid): Response { if ($bookid) { @@ -29,7 +51,23 @@ class PaginationHandler implements RequestHandlerInterface, AuthRequired private function handleStore(int $bookid, ?string $payload): Response { - if ($bookid && $payload) { + // Payload is later served back verbatim with a JSON content type, + // so only accept well-formed JSON arrays (epub.js location format) + // instead of storing arbitrary attacker-controlled bytes. + if ($payload !== null && strlen($payload) <= self::MAX_PAYLOAD_SIZE) { + $decoded = json_decode($payload, true); + if (is_array($decoded)) { + // Normalize (strips surrounding whitespace etc.) while keeping + // the round-trip as byte-faithful as possible. + $payload = json_encode($decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } else { + $payload = null; + } + } else { + $payload = null; + } + + if ($bookid && $payload && $this->bookExists($bookid)) { $pag = ORM::for_table('epube_pagination') ->where('bookid', $bookid) ->find_one(); diff --git a/classes/Response.php b/classes/Response.php index ea5e93d..e45814b 100644 --- a/classes/Response.php +++ b/classes/Response.php @@ -6,7 +6,7 @@ class Response /** @var array<string, string> */ private array $headers = []; private string $body = ''; - private string $contentType = "text/json"; + private string $contentType = "application/json"; public function withStatus(int $code, string $reasonPhrase = ''): self { @@ -50,6 +50,8 @@ class Response if (!$contentTypeFound) header("Content-type: {$this->contentType}"); + header("X-Content-Type-Options: nosniff"); + http_response_code($this->status); echo $this->body; } diff --git a/tests_integration/PaginationHandlerTest.php b/tests_integration/PaginationHandlerTest.php index 4674e1e..503178c 100644 --- a/tests_integration/PaginationHandlerTest.php +++ b/tests_integration/PaginationHandlerTest.php @@ -69,7 +69,8 @@ final class PaginationHandlerTest extends ApiTestCase ]); $this->assertEquals(200, $status); - $bookid = 99998; + // Real Calibre 'data' row id from the fixture metadata.db + $bookid = 5; $this->deletePagination($bookid); $payload = '{"page":12,"cfi":"epubcfi(/6/14[]/4:123)"}'; @@ -100,7 +101,8 @@ final class PaginationHandlerTest extends ApiTestCase ]); $this->assertEquals(200, $status); - $bookid = 99997; + // Real Calibre 'data' row id from the fixture metadata.db + $bookid = 6; $this->deletePagination($bookid); // Create initial record @@ -155,7 +157,7 @@ final class PaginationHandlerTest extends ApiTestCase ]); $this->assertEquals(200, $status); - $bookid = 99996; + $bookid = 8; $this->deletePagination($bookid); [$status, $body] = $this->post($this->apiUrl, [ @@ -172,6 +174,33 @@ final class PaginationHandlerTest extends ApiTestCase $this->assertNull($record); } + public function test_storepagination_rejects_nonexistent_book(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + // Valid payload, but no such row in Calibre books/data tables + $bookid = 99990; + $this->deletePagination($bookid); + + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'storepagination', + 'id' => $bookid, + 'payload' => '{"page":1}', + ]); + + $this->assertEquals(200, $status); + + // Verify no record was created for a book that does not exist + $record = $this->getPagination($bookid); + $this->assertNull($record); + } + // ── getpagination ──────────────────────────────────────────────────────── public function test_getpagination_returns_stored_data(): void @@ -184,7 +213,8 @@ final class PaginationHandlerTest extends ApiTestCase ]); $this->assertEquals(200, $status); - $bookid = 99995; + // Real Calibre 'data' row id from the fixture metadata.db + $bookid = 9; $this->deletePagination($bookid); $payload = '{"page":42,"cfi":"epubcfi(/6/30[]/4:789)"}'; |
