From 75b88f55e00a4af66c0d6034faacfbd7f840e28b Mon Sep 17 00:00:00 2001 From: Shengcun Date: Thu, 19 Nov 2026 19:08:39 -0500 Subject: [PATCH] security: book title reaches the calibre check as shell syntax (#1718) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `check_calibre()` builds a shell command by interpolating a book title: ```python cmd = f'calibredb list --search title:="{title}"' subprocess.run(cmd, check=False, shell=True, ...) ``` Titles arrive from `--file` JSON, from positional CLI arguments, and from metadata pulled off the shelfmark page, so a title containing `"` escapes the quoted search term and the rest is re-parsed by `/bin/sh` — e.g. a title of `Dune"; touch /tmp/pwned; echo "` runs the injected command as whoever is running the downloader. Fix: pass the search term as a single argv item and drop `shell=True`. Inside the term, `\` and `"` are escaped, so the title reaches calibre as one value instead of ending the quoted term and turning the remainder into calibre query syntax. The match kind is untouched: it stays `title:"=..."`, an exact-title search, so the same books are found as before and none are re-downloaded. A second commit 93378d1 handles a case the shell form hid: with the argv call, a missing or unexecutable `calibredb` raises instead of answering 127, so it is caught and read as "not in the library" — the same verdict the old code produced — with a warning on stdout rather than an aborted batch. `tests/skills/test_check_calibre.py` asserts the command is an argv list, that the title is one element, that no shell is requested, that the search stays an exact match, and that an unusable binary reads as absent. It is parametrised over a plain title plus six shapes that used to break the quoting (embedded quotes, `$(id)`, backticks, a trailing backslash, a Windows path): ``` $ uv run pytest tests/skills/test_check_calibre.py -q .......... [100%] ``` `uv run pytest tests/skills tests/core -q` -> 3172 passed; `ruff check` and `ruff format --check` are clean. --------- Co-authored-by: Roni Saguey --- skills/shelfmark/download_books.py | 22 +++++- tests/skills/test_check_calibre.py | 120 +++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 tests/skills/test_check_calibre.py diff --git a/skills/shelfmark/download_books.py b/skills/shelfmark/download_books.py index 0b8b02d0..a7df5f27 100755 --- a/skills/shelfmark/download_books.py +++ b/skills/shelfmark/download_books.py @@ -277,12 +277,30 @@ def clear_completed_downloads(page: Page) -> None: page.wait_for_timeout(2000) +def calibre_title_search(title: str) -> str: + """A calibre search expression matching this exact title. + + Calibre has its own query language: a term with spaces or quotes goes in + double quotes, and a quote or backslash inside it is escaped with a + backslash (manual, "Searching calibre"). Without that, a title containing + `"` ends the quoted term and the rest is read as more query syntax. + """ + escaped = title.replace("\\", "\\\\").replace('"', '\\"') + return f'title:"={escaped}"' + + def check_calibre(title: str) -> bool: """Check if a book is already in the calibre database.""" import subprocess - cmd = f'calibredb list --search title:="{title}"' - result = subprocess.run(cmd, check=False, shell=True, capture_output=True, text=True) + cmd = ["calibredb", "list", "--search", calibre_title_search(title)] + try: + result = subprocess.run(cmd, check=False, capture_output=True, text=True) + except OSError as exc: + # calibredb missing, not executable, or unloadable: the old shell call + # answered 127 and its empty output read as "not in the library". + print(f"warning: cannot run calibredb ({exc}); treating the book as absent") + return False output = result.stdout.strip() # calibredb output has header line "id title authors", count non-header lines lines = [l.strip() for l in output.split("\n") if l.strip()] diff --git a/tests/skills/test_check_calibre.py b/tests/skills/test_check_calibre.py new file mode 100644 index 00000000..95641742 --- /dev/null +++ b/tests/skills/test_check_calibre.py @@ -0,0 +1,120 @@ +"""A book title reaches calibredb as data: one argv item and one query term.""" + +import importlib.util +import subprocess +import sys +import types +from pathlib import Path +from unittest.mock import patch + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / "skills" / "shelfmark" / "download_books.py" + + +def _load_module(): + # The script imports playwright at module level; checkout CI installs it, + # a bare test run may not. + if "playwright.sync_api" not in sys.modules: + try: + import playwright.sync_api + except ModuleNotFoundError: + playwright = types.ModuleType("playwright") + sync_api = types.ModuleType("playwright.sync_api") + sync_api.Error = type("Error", (Exception,), {}) + sync_api.sync_playwright = lambda: None + playwright.sync_api = sync_api + sys.modules["playwright"] = playwright + sys.modules["playwright.sync_api"] = sync_api + + spec = importlib.util.spec_from_file_location("shelfmark_download_books", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize( + "title", + [ + "Mistborn", + 'Dune"; touch /tmp/pwned; echo "', + "Neuromancer$(id)", + "Snow Crash`whoami`", + 'The "Ball" and The "Chain"', + r"C:\Books\Dune", + ], +) +def test_title_is_one_argument_and_one_query_term(title): + module = _load_module() + completed = subprocess.CompletedProcess( + args=[], returncode=0, stdout="id title authors\n", stderr="" + ) + + with patch.object(subprocess, "run", return_value=completed) as run: + module.check_calibre(title) + + args, kwargs = run.call_args + command = args[0] + assert isinstance(command, list), "the command must be an argv list" + assert command[:3] == ["calibredb", "list", "--search"] + assert not kwargs.get("shell"), "a shell must not re-parse the title" + + term = command[3] + # `=` keeps it an exact-title search; without it calibre does "contains", + # so "Dune" would match "Dune Messiah" and the book would be skipped. + assert term.startswith('title:"=') and term.endswith('"'), term + inner = term[len('title:"=') : -1] + # Nothing inside the term may end it early: every quote and every + # backslash is escaped, and unescaping gives the title back. + assert _unescape(inner) == title + assert _every_quote_escaped(inner), inner + + +@pytest.mark.parametrize("error", [FileNotFoundError("calibredb"), PermissionError("calibredb")]) +def test_missing_or_unusable_calibredb_reads_as_absent(error, capsys): + """A shell answered 127 and looked like "not in the library"; a missing or + unusable binary must not raise out of the batch.""" + module = _load_module() + with patch.object(subprocess, "run", side_effect=error): + assert module.check_calibre("Dune") is False + assert "cannot run calibredb" in capsys.readouterr().out + + +def _every_quote_escaped(inner: str) -> bool: + i = 0 + while i < len(inner): + if inner[i] == "\\": + i += 2 + continue + if inner[i] == '"': + return False + i += 1 + return True + + +def _unescape(inner: str) -> str: + out = [] + i = 0 + while i < len(inner): + char = inner[i] + if char == "\\": + i += 1 + out.append(inner[i]) + else: + out.append(char) + i += 1 + return "".join(out) + + +def test_plain_title_is_unchanged_by_escaping(): + module = _load_module() + assert module.calibre_title_search("Mistborn") == 'title:"=Mistborn"' + + +def test_search_stays_an_exact_title_match(): + """A contains-search would treat "Dune" as present when only + "Dune Messiah" is in the library, and the download would be skipped.""" + module = _load_module() + term = module.calibre_title_search("Dune") + assert term == 'title:"=Dune"', term + assert not term.startswith('title:"D'), "lost the exact-match marker"