diff --git a/static/cx-core/.gitignore b/static/cx-core/.gitignore new file mode 100644 index 000000000..7a60b85e1 --- /dev/null +++ b/static/cx-core/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/static/cx-core/README.md b/static/cx-core/README.md new file mode 100644 index 000000000..a66576f87 --- /dev/null +++ b/static/cx-core/README.md @@ -0,0 +1,70 @@ +# cx-core: content-exchange core (read side) + +An in-box REST service for granular content exchange between boxes (K2Go and IIAB). +It lists, exports, imports and deletes content per item across Kolibri, Kiwix and +Calibre. It is client-agnostic: dash-node (K2Go) or the IIAB Console reach it over its +REST API. See `controller/docs/ADR-content-exchange.md` for the frozen Pillar 0 +contracts (identity, manifest, adapter port, core REST API). + +This directory is the first slice: the READ side of Pillar 1, with the Kiwix adapter. + +## What is here + +- `cx_core/model.py`: app-agnostic content model (identity, dedup, manifest item). +- `cx_core/ports.py`: the inner contract, the app-adapter port (read methods). +- `cx_core/adapters/kiwix.py`: the first adapter, read side (ZIM header UUID + listing). +- `cx_core/registry.py`: loads an adapter only when its app is installed. +- `cx_core/router.py`: pure `/v1` route dispatch (unit-testable without a socket). +- `cx_core/server.py` + `__main__.py`: a thin stdlib `http.server` wrapper, localhost only. + +No third-party dependency: the core runs on any of AMD64 / ARM64 / ARM32 with just the +system Python 3 (>= 3.7). This keeps it portable to the Pi and to the proot host on a +phone, where a package install is not guaranteed. + +## Run + +``` +cd static/cx-core +python -m cx_core +``` + +Environment (defaults match the box layout): + +- `CX_HOST` (default `127.0.0.1`), `CX_PORT` (default `9500`). +- `CX_ZIMS_DIR` (default `/library/zims/content/`): where the ZIM files live. + +## Endpoints (read side) + +- `GET /v1/apps`: installed content apps that have a loaded adapter. +- `GET /v1/content[?app=]`: every item this box has, with identity + size. Filterable. +- `GET /v1/content/{app}/{localRef}`: one item detail. + +Each item carries two identity handles: `localRef` (the app's own handle for +export / delete) and `dedup` (the cross-box "already have this?" key). For Kiwix both +are read, not computed: `dedup.build` is the ZIM header UUID. + +## Test + +``` +cd static/cx-core +python -m unittest discover -s tests -t . +``` + +The tests cover the pure logic with no device: ZIM header UUID parsing, filename +decomposition, soft-key normalization, the manifest JSON shape, and route dispatch. + +## Not in this slice + +Export, import, delete, the dedup-check endpoint, the Kolibri and Calibre adapters, the +offline-disk and network carriers, strict-mode hashing, and the manager UI. The adapter +boundary is kept clean so Kolibri and Calibre slot in next. + +Deployment (D1d: an Ansible-role baseline plus a dash-node-style live self-update) is +not built here; this slice only has to be runnable. Live on-device verification needs a +box and is a follow-up. + +The registry resolves installed apps once at startup (a snapshot). Reacting to a module +being installed or removed at runtime is a deferred design item: it must consume the +install system's single source of truth (ModuleRegistry / install events), not re-derive +installed-state per request. A second owner of "what is installed" is the design trap this +avoids. diff --git a/static/cx-core/cx_core/__init__.py b/static/cx-core/cx_core/__init__.py new file mode 100644 index 000000000..38741f1fa --- /dev/null +++ b/static/cx-core/cx_core/__init__.py @@ -0,0 +1,7 @@ +"""Content-exchange core: an in-box REST service for granular content exchange. + +See controller/docs/ADR-content-exchange.md for the frozen Pillar 0 contracts. +This package holds the read side of Pillar 1 (list + identity + size). +""" + +__version__ = "0.1.0" diff --git a/static/cx-core/cx_core/__main__.py b/static/cx-core/cx_core/__main__.py new file mode 100644 index 000000000..0665e7922 --- /dev/null +++ b/static/cx-core/cx_core/__main__.py @@ -0,0 +1,14 @@ +"""Entry point: ``python -m cx_core``. Reads config from the environment and serves.""" + +from __future__ import annotations + +from .config import Config +from .server import serve + + +def main() -> None: + serve(Config.from_env()) + + +if __name__ == "__main__": + main() diff --git a/static/cx-core/cx_core/adapters/__init__.py b/static/cx-core/cx_core/adapters/__init__.py new file mode 100644 index 000000000..0875e26d4 --- /dev/null +++ b/static/cx-core/cx_core/adapters/__init__.py @@ -0,0 +1 @@ +"""Per-app content adapters. One module per app; each implements ports.ContentAdapter.""" diff --git a/static/cx-core/cx_core/adapters/calibre.py b/static/cx-core/cx_core/adapters/calibre.py new file mode 100644 index 000000000..42f256443 --- /dev/null +++ b/static/cx-core/cx_core/adapters/calibre.py @@ -0,0 +1,223 @@ +"""Calibre adapter (read side). + +Calibre-Web is not a book store: one record can be any media (epub, pdf, image, video, +audio) and can carry several formats, so there is no ISBN key. Identity is split: +- localRef = books.uuid: the box's own handle to this exact item, authoritative-local, + generated once by Calibre when the item is added (for export / delete). +- dedup = a SOFT, advisory key from metadata Calibre already has (zero compute): normalized + title + authors + formats + byte-size, plus an external identifier when present. idKind is + soft: "you may already have this", never an automatic skip or delete. + +The adapter reads metadata.db in readonly (the sockets/books.query.ts pattern). The schema +(books.uuid, data.format / data.uncompressed_size, identifiers) is confirmed on the box. +""" + +from __future__ import annotations + +import os +import os +import shutil +import sqlite3 +import tarfile +import tempfile +from typing import List, Optional + +from ..export import resolve_within, tar_stream +from ..importing import safe_extract_tar, single_child_dir +from ..model import ABSENT, SAME_VERSION, SOFT, Dedup, Identity, ManifestItem, normalize_text +from ..ports import ContentAdapter, ExportStream +from .calibreweb import CalibreWebClient, resolve_calibre_credentials + +# One row per book, with its authors, formats, total byte-size and one external id if any. +_BOOKS_SQL = """ +SELECT b.uuid, + b.title, + (SELECT GROUP_CONCAT(a.name, ' & ') + FROM authors a + JOIN books_authors_link bal ON bal.author = a.id + WHERE bal.book = b.id) AS authors, + (SELECT GROUP_CONCAT(d.format, ',') FROM data d WHERE d.book = b.id) AS formats, + (SELECT COALESCE(SUM(d.uncompressed_size), 0) FROM data d WHERE d.book = b.id) AS bytes, + (SELECT i.val FROM identifiers i WHERE i.book = b.id ORDER BY i.type LIMIT 1) AS ext_id +FROM books b +{where} +ORDER BY b.sort +""" + + +def build_book_item( + uuid: str, title: Optional[str], authors: Optional[str], + formats: Optional[str], size_bytes: int, ext_id: Optional[str], +) -> ManifestItem: + """Build the manifest item for one Calibre record. Pure.""" + formats_list = sorted(f for f in (formats or "").split(",") if f) + line = { + "title": normalize_text(title or ""), + "authors": normalize_text(authors or ""), + "formats": formats_list, + "bytes": size_bytes, + } + return ManifestItem( + app="calibre", + kind="book", + title=title or uuid, + bytes=size_bytes, + identity=Identity( + local_ref=uuid, + # build carries a stronger hint (an external id) when Calibre has one; the key + # stays soft either way, because arbitrary media has no authoritative cross-box id. + dedup=Dedup(line=line, build=ext_id or None, version=None, id_kind=SOFT), + ), + ) + + +def _content_files(book_dir: str, formats: set) -> List[str]: + """The book's content files to upload. When the manifest lists formats, pick files with + those extensions; otherwise take every file except the Calibre sidecars (cover, opf).""" + out: List[str] = [] + try: + names = sorted(os.listdir(book_dir)) + except OSError: + return out + for name in names: + full = os.path.join(book_dir, name) + if not os.path.isfile(full): + continue + ext = os.path.splitext(name)[1].lstrip(".").lower() + if formats: + if ext in formats: + out.append(full) + elif name.lower() != "metadata.opf" and not name.lower().startswith("cover."): + out.append(full) + return out + + +class CalibreAdapter(ContentAdapter): + app = "calibre" + id_kind = SOFT # arbitrary media has no authoritative cross-box id; verdicts are advisory + + def __init__( + self, db_path: str, + calibre_url: str = "http://127.0.0.1:8083", + credentials_file: str = "/library/dashboard/credentials.json", + staging_dir: str = "/library/.cx-staging", + ): + self._db = db_path + # The Calibre library root is the directory that holds metadata.db; each book's + # files live under //. + self._lib_root = os.path.dirname(db_path) + self._url = calibre_url + self._credentials_file = credentials_file + self._staging_dir = staging_dir + + def is_installed(self) -> bool: + return os.path.exists(self._db) + + def check(self, dedup: dict) -> str: + # Soft: there is no authoritative cross-box id for arbitrary media, so the verdict is + # advisory. Match on the normalized title + authors of the soft key; present -> "you + # may already have this" (SAME_VERSION), else ABSENT. Never an automatic skip. + line = dedup.get("line") or {} + title, authors = line.get("title"), line.get("authors") + for item in self.list(): + local = item.identity.dedup.line + if local.get("title") == title and local.get("authors") == authors: + return SAME_VERSION + return ABSENT + + def import_item(self, entry: dict, payload_path: str) -> dict: + # The payload is the tar of the book's own directory. Extract it safely, then add each + # content-format file through Calibre-Web's upload (calibredb is not installed). + # Soft identity: a re-import can create a duplicate record, so the front checks first. + if not os.path.isfile(payload_path): + return {"ok": False, "reason": "payload not found"} + formats = {f.lower() for f in ((entry.get("identity") or {}).get("dedup", {}).get("line", {}).get("formats") or [])} + os.makedirs(self._staging_dir, exist_ok=True) + work = tempfile.mkdtemp(prefix="cximport-", dir=self._staging_dir) + try: + try: + safe_extract_tar(payload_path, work) + except (ValueError, tarfile.TarError) as exc: + return {"ok": False, "reason": f"bad archive: {exc}"} + files = _content_files(single_child_dir(work) or work, formats) + if not files: + return {"ok": False, "reason": "no book files in archive"} + uploaded = self._upload_files(files) + if uploaded == 0: + return {"ok": False, "reason": "calibre upload failed"} + return {"ok": True, "app": "calibre", "localRef": (entry.get("identity") or {}).get("localRef"), "uploaded": uploaded} + finally: + shutil.rmtree(work, ignore_errors=True) + + def _upload_files(self, files: List[str]) -> int: + """Log into Calibre-Web and upload each file. A seam, so a test need not run a live + Calibre-Web. Returns the number uploaded.""" + user, password = resolve_calibre_credentials(self._credentials_file) + client = CalibreWebClient(self._url, user, password) + if not client.login(): + return 0 + done = 0 + for path in files: + if client.upload(path, os.path.basename(path)): + done += 1 + return done + + def _book_path(self, uuid: str) -> Optional[str]: + """The relative on-disk directory for a book uuid, from metadata.db. None if absent.""" + if not uuid or not os.path.exists(self._db): + return None + try: + con = sqlite3.connect(f"file:{self._db}?mode=ro", uri=True) + except sqlite3.Error: + return None + try: + row = con.execute("SELECT path FROM books WHERE uuid = ?", (uuid,)).fetchone() + except sqlite3.Error: + return None + finally: + con.close() + return row[0] if row and row[0] else None + + def open_export(self, local_ref: str) -> Optional[ExportStream]: + # Export the book's own directory (its format files, cover and opf), the layout + # Calibre itself reads back. books.path comes from the DB, so a containment guard + # keeps a crafted path from escaping the library root. + rel = self._book_path(local_ref) + if rel is None: + return None + book_dir = resolve_within(self._lib_root, rel) + if book_dir is None or not os.path.isdir(book_dir): + return None + return ExportStream( + filename=f"{local_ref}.tar", + content_type="application/x-tar", + chunks=tar_stream(book_dir, arcname=local_ref), + ) + + def _query(self, only_uuid: Optional[str]) -> List[ManifestItem]: + if not os.path.exists(self._db): + return [] + sql = _BOOKS_SQL.format(where="WHERE b.uuid = ?" if only_uuid else "") + params = (only_uuid,) if only_uuid else () + try: + con = sqlite3.connect(f"file:{self._db}?mode=ro", uri=True) + except sqlite3.Error: + return [] + try: + rows = con.execute(sql, params).fetchall() + except sqlite3.Error: + return [] + finally: + con.close() + return [build_book_item(r[0], r[1], r[2], r[3], r[4], r[5]) for r in rows] + + def list(self) -> List[ManifestItem]: + return self._query(None) + + def get(self, local_ref: str) -> Optional[ManifestItem]: + # localRef is a books.uuid used only as a bound SQL parameter (never a path), so a + # single scoped query is enough; no path-containment guard applies here. + if not local_ref: + return None + items = self._query(local_ref) + return items[0] if items else None diff --git a/static/cx-core/cx_core/adapters/calibreweb.py b/static/cx-core/cx_core/adapters/calibreweb.py new file mode 100644 index 000000000..732c64ab7 --- /dev/null +++ b/static/cx-core/cx_core/adapters/calibreweb.py @@ -0,0 +1,159 @@ +"""Calibre-Web HTTP access (add a book), isolated from the adapter. + +calibredb is not installed on the box, so a book is added through Calibre-Web's own upload +endpoint, exactly as dash-node does (sockets/books.exec.ts): log in for a session + CSRF +token, then POST the file to /upload as multipart (field "btn-upload"). Delegating to +Calibre-Web keeps it the one owner of its library. + +Credentials come from the same store dash-node uses: the env override first, then the +operator's credentials.json, then the Ansible factory default. This module never prints a +credential value. +""" + +from __future__ import annotations + +import http.cookiejar +import io +import json +import os +import re +import urllib.error +import urllib.parse +import urllib.request +import uuid as _uuid +from typing import Tuple + +_CSRF_RE = re.compile(r'name="csrf_token"[^>]*value="([^"]+)"') +_UPLOAD_BLOCK = 1024 * 1024 + + +def resolve_calibre_credentials(credentials_file: str) -> Tuple[str, str]: + """(username, password) for Calibre-Web: env K2GO_CALIBRE_USER / _PASS, else the calibre + entry in credentials_file, else the Ansible default Admin / changeme.""" + env_user = os.environ.get("K2GO_CALIBRE_USER") + env_pass = os.environ.get("K2GO_CALIBRE_PASS") + if env_user and env_pass: + return env_user, env_pass + try: + with open(credentials_file, encoding="utf-8") as handle: + entry = (json.load(handle) or {}).get("calibre") or {} + if entry.get("username") and entry.get("password"): + return entry["username"], entry["password"] + except (OSError, ValueError): + pass + return "Admin", "changeme" + + +def safe_upload_name(name: str) -> str: + """A filename safe to place in a multipart Content-Disposition header. The name comes + from an untrusted archive member, so CR / LF (which would inject headers) and double + quotes (which would break the quoted value) are stripped. Never empty.""" + cleaned = name.replace("\r", "").replace("\n", "").replace('"', "").strip() + cleaned = os.path.basename(cleaned) + return cleaned or "upload.bin" + + +class _ConcatStream(io.RawIOBase): + """A read-only stream of prefix bytes, then a file's bytes, then suffix bytes. Lets the + multipart body be sent without reading the (possibly multi-gigabyte) file into memory.""" + + def __init__(self, prefix: bytes, file_path: str, suffix: bytes): + self._pre = io.BytesIO(prefix) + self._file = open(file_path, "rb") + self._suf = io.BytesIO(suffix) + self._stage = 0 # 0 prefix, 1 file, 2 suffix, 3 done + + def readable(self) -> bool: + return True + + def readinto(self, buffer) -> int: + sources = (self._pre, self._file, self._suf) + while self._stage < 3: + got = sources[self._stage].readinto(buffer) + if got: + return got + self._stage += 1 + return 0 + + def close(self) -> None: + try: + self._file.close() + finally: + super().close() + + +def _multipart_frame(boundary: str, fields: dict, file_field: str, filename: str) -> Tuple[bytes, bytes]: + sep = f"--{boundary}\r\n" + head = "" + for name, value in fields.items(): + head += sep + f'Content-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n' + head += sep + f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n' + head += "Content-Type: application/octet-stream\r\n\r\n" + return head.encode("utf-8"), f"\r\n--{boundary}--\r\n".encode("utf-8") + + +class CalibreWebClient: + """A minimal Calibre-Web client: log in, then upload book files.""" + + def __init__(self, base_url: str, username: str, password: str, timeout: int = 60): + self._base = base_url.rstrip("/") + self._user = username + self._pass = password + self._timeout = timeout + self._csrf = "" + self._jar = http.cookiejar.CookieJar() + self._opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self._jar)) + + def login(self) -> bool: + """Establish a session and confirm it actually authenticated. Calibre-Web re-serves + the login form with 200 on bad credentials, so a 2xx alone is not success.""" + page = self._opener.open(f"{self._base}/login", timeout=self._timeout).read().decode("utf-8", "replace") + match = _CSRF_RE.search(page) + if not match: + return False + self._csrf = match.group(1) + form = urllib.parse.urlencode({ + "csrf_token": self._csrf, + "username": self._user, + "password": self._pass, + "remember_me": "on", + }).encode("utf-8") + req = urllib.request.Request( + f"{self._base}/login", data=form, + headers={"Content-Type": "application/x-www-form-urlencoded", "Referer": f"{self._base}/login"}, + ) + try: + with self._opener.open(req, timeout=self._timeout) as resp: + final_url = resp.geturl() + body = resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError: + return False + # A successful login (remember_me=on) sets a remember_token cookie and redirects off + # /login; a failure re-renders the login form (password field present). + if any(c.name == "remember_token" for c in self._jar): + return True + return not final_url.rstrip("/").endswith("/login") and 'name="password"' not in body + + def upload(self, file_path: str, filename: str) -> bool: + """POST one book file to /upload as multipart, streaming the file. Returns True on a + 2xx/redirect.""" + name = safe_upload_name(filename) + boundary = "----cxcore" + _uuid.uuid4().hex + prefix, suffix = _multipart_frame(boundary, {"csrf_token": self._csrf}, "btn-upload", name) + length = len(prefix) + os.path.getsize(file_path) + len(suffix) + body = _ConcatStream(prefix, file_path, suffix) + req = urllib.request.Request( + f"{self._base}/upload", data=body, + headers={ + "Content-Type": f"multipart/form-data; boundary={boundary}", + "Content-Length": str(length), + "Referer": f"{self._base}/", + }, + ) + try: + with self._opener.open(req, timeout=self._timeout) as resp: + return 200 <= resp.status < 400 + except urllib.error.HTTPError as exc: + return 200 <= exc.code < 400 + finally: + body.close() diff --git a/static/cx-core/cx_core/adapters/kiwix.py b/static/cx-core/cx_core/adapters/kiwix.py new file mode 100644 index 000000000..626f98c57 --- /dev/null +++ b/static/cx-core/cx_core/adapters/kiwix.py @@ -0,0 +1,220 @@ +"""Kiwix adapter (read side). + +Kiwix identity is the cleanest: the ZIM header carries a UUID set by the upstream +scraper at build time and byte-copied on download, so the same file always has the +same UUID and we never generate one. We read it (we do not compute it), which is the +ADR "delegate to the app's own mechanism" rule. + +Source of truth is the ZIM files on disk, not library.xml: the box may run no Kiwix +indexer, so library.xml is not guaranteed, but the .zim files always are. The line +(creator, lang, flavour) and the version (date) come from the Kiwix filename +convention ___.zim, the same keys kiwix_catalog.csv uses. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import uuid +from typing import List, Optional, Tuple + +from ..export import file_stream +from ..model import ( + ABSENT, + AUTHORITATIVE, + NEWER_HERE, + OLDER_HERE, + SAME_VERSION, + SOFT, + Dedup, + Identity, + ManifestItem, +) +from ..ports import ContentAdapter, ExportStream + +# openzim header: magic number is uint32 little-endian 0x044D495A at offset 0, and the +# 16-byte UUID is at offset 8. We only need the first 24 bytes. +ZIM_MAGIC = 0x044D495A +_ZIM_HEADER_MIN = 24 + +# A trailing YYYY-MM or YYYY-MM-DD is the version (date) axis in the filename. +_DATE_RE = re.compile(r"^\d{4}-\d{2}(-\d{2})?$") + + +def read_zim_uuid(header: bytes) -> Optional[str]: + """Return the canonical UUID string from a ZIM header, or None when the bytes are + not a valid ZIM header. Pure: takes the header bytes, reads nothing from disk.""" + if len(header) < _ZIM_HEADER_MIN: + return None + if int.from_bytes(header[0:4], "little") != ZIM_MAGIC: + return None + return str(uuid.UUID(bytes=header[8:24])) + + +def read_zim_uuid_from_file(path: str) -> Optional[str]: + """Read just the header of a ZIM file and return its UUID, or None on any error.""" + try: + with open(path, "rb") as f: + return read_zim_uuid(f.read(_ZIM_HEADER_MIN)) + except OSError: + return None + + +def is_safe_local_ref(local_ref: str) -> bool: + """True when local_ref is a plain filename contained in one directory: no path + separators, no parent/current reference, no null byte. So joining it onto the + content dir cannot escape that dir (path-traversal guard). Pure and filesystem + free, like the repo's ArchiveEntry.escapesRoot / ModuleName.isAllowed guards. + Reused by get() now and by export() in the next slice.""" + if not local_ref or local_ref in (".", ".."): + return False + return not ("/" in local_ref or "\\" in local_ref or "\x00" in local_ref) + + +def parse_zim_filename(name: str) -> Tuple[str, str, str, str]: + """Decompose a Kiwix filename into (creator, lang, flavour, date). + + The convention is ___.zim, where the flavour may hold + several underscore tokens (e.g. wikipedia_en_all_maxi_2023-10.zim). So the date is + taken from the trailing dated token and the flavour is everything between the lang + and the date. A filename that does not follow the convention still yields a stable + creator (the stem) with empty lang / flavour / date.""" + stem = name[:-4] if name.lower().endswith(".zim") else name + parts = stem.split("_") + date = "" + if parts and _DATE_RE.match(parts[-1]): + date = parts[-1] + parts = parts[:-1] + creator = parts[0] if parts else stem + lang = parts[1] if len(parts) > 1 else "" + flavour = "_".join(parts[2:]) if len(parts) > 2 else "" + return creator, lang, flavour, date + + +def build_item(name: str, size_bytes: int, zim_uuid: Optional[str]) -> ManifestItem: + """Build the manifest item for one ZIM from its name, size and header UUID. Pure.""" + creator, lang, flavour, date = parse_zim_filename(name) + dedup = Dedup( + line={"creator": creator, "lang": lang, "flavour": flavour}, + build=zim_uuid, + version=date, + # The UUID is the authoritative cross-box key. When it could not be read + # (short / non-ZIM / unreadable header) the item is degraded, so the dedup + # is advisory only: never a confident authoritative match on a missing id. + id_kind=AUTHORITATIVE if zim_uuid else SOFT, + ) + return ManifestItem( + app="kiwix", + kind="zim", + # The ZIM title lives in an internal metadata entry; the filename stem is a + # cheap, always-available stand-in until metadata reading is added. + title=name[:-4] if name.lower().endswith(".zim") else name, + bytes=size_bytes, + identity=Identity(local_ref=name, dedup=dedup), + # Upstream hash (.meta4) is deleted after download, so none is retained on-device. + integrity=None, + ) + + +class KiwixAdapter(ContentAdapter): + app = "kiwix" + id_kind = AUTHORITATIVE + + def __init__(self, zims_dir: str, indexer: str = "/usr/bin/iiab-make-kiwix-lib"): + self._dir = zims_dir + self._indexer = indexer + + def is_installed(self) -> bool: + return os.path.isdir(self._dir) + + def list(self) -> List[ManifestItem]: + items: List[ManifestItem] = [] + try: + names = os.listdir(self._dir) + except OSError: + return items + for name in names: + if not name.lower().endswith(".zim"): + continue + path = os.path.join(self._dir, name) + try: + size = os.path.getsize(path) + except OSError: + continue # vanished between listdir and stat + items.append(build_item(name, size, read_zim_uuid_from_file(path))) + items.sort(key=lambda it: it.identity.local_ref) + return items + + def get(self, local_ref: str) -> Optional[ManifestItem]: + # Resolve the one requested file instead of scanning list() and opening every + # ZIM header. The containment guard runs FIRST, so a traversal ref never reaches + # the filesystem. + if not is_safe_local_ref(local_ref) or not local_ref.lower().endswith(".zim"): + return None + path = os.path.join(self._dir, local_ref) + try: + size = os.path.getsize(path) + except OSError: + return None + return build_item(local_ref, size, read_zim_uuid_from_file(path)) + + def open_export(self, local_ref: str) -> Optional[ExportStream]: + # The item IS the .zim file: stream it as-is (no archive wrapper). Same containment + # guard as get(), so a traversal ref never reaches the filesystem. + if not is_safe_local_ref(local_ref) or not local_ref.lower().endswith(".zim"): + return None + path = os.path.join(self._dir, local_ref) + if not os.path.isfile(path): + return None + return ExportStream( + filename=local_ref, + content_type="application/octet-stream", + chunks=file_stream(path), + ) + + def check(self, dedup: dict) -> str: + # Same (creator, lang, flavour) line is the comparable set; the UUID is the exact + # build and the date is the version axis. Authoritative, so the verdict is a hard fact. + line = dedup.get("line") + build = dedup.get("build") + version = dedup.get("version") or "" + local = [it.identity.dedup for it in self.list() if it.identity.dedup.line == line] + if not local: + return ABSENT + if build and any(d.build == build for d in local): + return SAME_VERSION + local_version = max((d.version or "") for d in local) + if local_version == version: + return SAME_VERSION + return OLDER_HERE if local_version < version else NEWER_HERE + + def import_item(self, entry: dict, payload_path: str) -> dict: + # The payload is the .zim itself: place it in the zims dir under its own name, then + # re-run the indexer so the library entry appears. Overwriting the same name is + # idempotent (same content, same UUID). + local_ref = (entry.get("identity") or {}).get("localRef", "") + if not is_safe_local_ref(local_ref) or not local_ref.lower().endswith(".zim"): + return {"ok": False, "reason": "invalid localRef"} + if not os.path.isfile(payload_path): + return {"ok": False, "reason": "payload not found"} + os.makedirs(self._dir, exist_ok=True) + dest = os.path.join(self._dir, local_ref) + try: + shutil.copyfile(payload_path, dest) + except OSError as exc: + return {"ok": False, "reason": f"copy failed: {exc}"} + self._reindex() + return {"ok": True, "app": "kiwix", "localRef": local_ref, "bytes": os.path.getsize(dest)} + + def _reindex(self) -> None: + """Rebuild the Kiwix library index. A seam, so a test need not run the real indexer. + NOTE: this runs outside the dash-node jobs engine, so a concurrent kiwix download + + its end-of-run reindex can race (routes.ts ADFA-5004). The front serializes imports.""" + if not self._indexer or not os.path.exists(self._indexer): + return + try: + subprocess.run([self._indexer], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) + except OSError: + pass diff --git a/static/cx-core/cx_core/adapters/kolibri.py b/static/cx-core/cx_core/adapters/kolibri.py new file mode 100644 index 000000000..9725b23ab --- /dev/null +++ b/static/cx-core/cx_core/adapters/kolibri.py @@ -0,0 +1,246 @@ +"""Kolibri adapter (read side). + +Kolibri identity is authoritative and upstream: channel_id (32 hex) plus an integer +version come from Kolibri Studio, so we reuse them, never recompute. The box keeps them +in the Kolibri content database (db.sqlite3), read in readonly: the same source and the +same aggregation dash-node uses (sockets/kolibri.query.ts), so there is one source of truth. + +bytes is the on-disk available size of the channel (what the box actually holds), summed +over its DISTINCT local files. The DISTINCT matters: one local file can hang off several +content nodes, and a flat join would count its bytes once per node. +""" + +from __future__ import annotations + +import os +import re +import shutil +import sqlite3 +import subprocess +import tarfile +import tempfile +from typing import List, Optional + +from ..export import has_room, tar_stream +from ..importing import safe_extract_tar, single_child_dir +from ..model import ( + ABSENT, + AUTHORITATIVE, + NEWER_HERE, + OLDER_HERE, + SAME_VERSION, + Dedup, + Identity, + ManifestItem, +) +from ..ports import ContentAdapter, ExportStream + +_CHANNEL_ID_RE = re.compile(r"^[0-9a-fA-F]{32}$") + + +def export_commands(channel_id: str, dest: str, kolibri_bin: str) -> List[List[str]]: + """The two Kolibri management commands that stage a channel export into dest: the + channel DB, then its content files. Pure (builds argv only). Delegating to Kolibri is + the one owner of "how a channel is exported"; the content store is content-addressed, + so import dedups shared files across channels by itself.""" + base = [kolibri_bin, "manage"] + return [ + base + ["exportchannel", channel_id, dest], + base + ["exportcontent", channel_id, dest], + ] + + +def import_commands(channel_id: str, source: str, kolibri_bin: str) -> List[List[str]]: + """The two Kolibri disk-import commands: register the channel DB, then copy its content + from the exported folder. Pure (argv only). The content store is content-addressed, so + files shared with channels already present are deduped by Kolibri itself.""" + base = [kolibri_bin, "manage"] + return [ + base + ["importchannel", "disk", channel_id, source], + base + ["importcontent", "disk", channel_id, source], + ] + + +def _to_int(*values) -> Optional[int]: + """First value that parses as an int, else None. The version may arrive as an int or a + string over JSON, and the build mirrors it.""" + for value in values: + try: + return int(value) + except (TypeError, ValueError): + continue + return None + + + +# Available bytes per installed channel. {where} scopes it to one channel for get(). +_CHANNELS_SQL = """ +WITH channel_files AS ( + SELECT DISTINCT cn.channel_id AS channel_id, f.local_file_id AS local_file_id + FROM content_file f + JOIN content_contentnode cn ON cn.id = f.contentnode_id +) +SELECT cm.id, cm.name, cm.version, + COALESCE(SUM(CASE WHEN lf.available = 1 THEN lf.file_size ELSE 0 END), 0) AS bytes_available +FROM content_channelmetadata cm +LEFT JOIN channel_files p ON p.channel_id = cm.id +LEFT JOIN content_localfile lf ON lf.id = p.local_file_id +{where} +GROUP BY cm.id, cm.name, cm.version +ORDER BY cm.name +""" + + +def build_channel_item(channel_id: str, name: Optional[str], version, size_bytes: int) -> ManifestItem: + """Build the manifest item for one installed channel. Pure.""" + v = int(version) if version is not None else 0 + dedup = Dedup( + line=channel_id, + build=str(v), # the integer version is both the exact build and the version axis + version=v, + id_kind=AUTHORITATIVE, + ) + return ManifestItem( + app="kolibri", + kind="channel", + title=name or channel_id, + bytes=size_bytes, + identity=Identity(local_ref=channel_id, dedup=dedup), + ) + + +class KolibriAdapter(ContentAdapter): + app = "kolibri" + + def __init__( + self, db_path: str, kolibri_bin: str = "/usr/bin/kolibri", + staging_dir: str = "/library/.cx-staging", + ): + self._db = db_path + self._bin = kolibri_bin + self._staging_dir = staging_dir + # KOLIBRI_HOME is the directory that holds db.sqlite3; the export CLI reads it. + self._home = os.path.dirname(db_path) + + def is_installed(self) -> bool: + return os.path.exists(self._db) + + def _query(self, only_id: Optional[str]) -> List[ManifestItem]: + if not os.path.exists(self._db): + return [] + sql = _CHANNELS_SQL.format(where="WHERE cm.id = ?" if only_id else "") + params = (only_id,) if only_id else () + try: + con = sqlite3.connect(f"file:{self._db}?mode=ro", uri=True) + except sqlite3.Error: + return [] + try: + rows = con.execute(sql, params).fetchall() + except sqlite3.Error: + # A locked DB (Kolibri writing during an import) or a schema change: report + # nothing rather than crash. Kolibri remains the authority. + return [] + finally: + con.close() + return [build_channel_item(r[0], r[1], r[2], r[3]) for r in rows] + + def list(self) -> List[ManifestItem]: + return self._query(None) + + def get(self, local_ref: str) -> Optional[ManifestItem]: + # localRef is a channel_id used only as a bound SQL parameter (never a path), so a + # single scoped query is enough; no path-containment guard applies here. + if not local_ref: + return None + items = self._query(local_ref) + return items[0] if items else None + + def open_export(self, local_ref: str) -> Optional[ExportStream]: + # Delegate to Kolibri's own export: it stages the channel DB + the channel's + # content-addressed files into a staging tree, which we then tar-stream. Read-only on + # the source (export copies out). The tree is removed after streaming. + if not _CHANNEL_ID_RE.match(local_ref or ""): + return None + channel = self._query(local_ref) + if not channel: # not an installed channel + return None + # Preflight the staging disk against the channel size, so we fail cleanly here + # instead of hitting ENOSPC part way through the export (the box owns its own disk + # check, mirroring the front's phone-disk preflight). + try: + os.makedirs(self._staging_dir, exist_ok=True) + except OSError: + return None + if not has_room(self._staging_dir, channel[0].bytes): + return None + dest = tempfile.mkdtemp(prefix="cxkolibri-", dir=self._staging_dir) + try: + staged = self._stage_export(local_ref, dest) + except OSError: + staged = False + if not staged: + shutil.rmtree(dest, ignore_errors=True) + return None + return ExportStream( + filename=f"{local_ref}.tar", + content_type="application/x-tar", + chunks=tar_stream(dest, arcname=local_ref), + on_close=lambda: shutil.rmtree(dest, ignore_errors=True), + ) + + def _stage_export(self, channel_id: str, dest: str) -> bool: + """Run the Kolibri export CLI into dest. A seam, so a test can stage a fake tree + without a live Kolibri. Returns True on success.""" + env = dict(os.environ, KOLIBRI_HOME=self._home) + for argv in export_commands(channel_id, dest, self._bin): + result = subprocess.run( + argv, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False + ) + if result.returncode != 0: + return False + return True + + def check(self, dedup: dict) -> str: + # The line is the channel_id; the integer version is the axis. Authoritative. + line = dedup.get("line") + incoming = _to_int(dedup.get("version"), dedup.get("build")) + local = [it.identity.dedup for it in self.list() if it.identity.dedup.line == line] + if not local: + return ABSENT + local_version = max(d.version for d in local) + if incoming is None or local_version == incoming: + return SAME_VERSION + return OLDER_HERE if local_version < incoming else NEWER_HERE + + def import_item(self, entry: dict, payload_path: str) -> dict: + # The payload is the export tar. Extract it safely, then delegate the disk import to + # Kolibri. Idempotent: Kolibri's import re-registers and dedups, never double-counts. + channel_id = (entry.get("identity") or {}).get("localRef", "") + if not _CHANNEL_ID_RE.match(channel_id or ""): + return {"ok": False, "reason": "invalid channel id"} + if not os.path.isfile(payload_path): + return {"ok": False, "reason": "payload not found"} + os.makedirs(self._staging_dir, exist_ok=True) + work = tempfile.mkdtemp(prefix="cximport-", dir=self._staging_dir) + try: + try: + safe_extract_tar(payload_path, work) + except (ValueError, tarfile.TarError) as exc: + return {"ok": False, "reason": f"bad archive: {exc}"} + source = single_child_dir(work) or work + if not self._stage_import(channel_id, source): + return {"ok": False, "reason": "kolibri import failed"} + return {"ok": True, "app": "kolibri", "localRef": channel_id} + finally: + shutil.rmtree(work, ignore_errors=True) + + def _stage_import(self, channel_id: str, source: str) -> bool: + """Run the Kolibri disk-import CLI from source. A seam, like _stage_export.""" + env = dict(os.environ, KOLIBRI_HOME=self._home) + for argv in import_commands(channel_id, source, self._bin): + result = subprocess.run( + argv, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False + ) + if result.returncode != 0: + return False + return True diff --git a/static/cx-core/cx_core/config.py b/static/cx-core/cx_core/config.py new file mode 100644 index 000000000..c4bb5f05a --- /dev/null +++ b/static/cx-core/cx_core/config.py @@ -0,0 +1,52 @@ +"""Runtime configuration, read from the environment so the same code runs on a systemd +IIAB host and under the proot host on a phone. Defaults match the box layout.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass + +DEFAULT_PORT = 9500 + + +def _parse_port(raw: str) -> int: + """Parse a TCP port from the environment, falling back to the default on an empty, + non-numeric or out-of-range value instead of crashing the service at startup.""" + try: + port = int(raw) + except (TypeError, ValueError): + return DEFAULT_PORT + return port if 1 <= port <= 65535 else DEFAULT_PORT + + +@dataclass(frozen=True) +class Config: + host: str = "127.0.0.1" # localhost only, like dash-node; the front reaches it in-box + port: int = DEFAULT_PORT + zims_dir: str = "/library/zims/content/" + kiwix_indexer: str = "/usr/bin/iiab-make-kiwix-lib" + kolibri_db: str = "/library/kolibri/db.sqlite3" + kolibri_bin: str = "/usr/bin/kolibri" + calibre_db: str = "/library/calibre-web/metadata.db" + calibre_url: str = "http://127.0.0.1:8083" + credentials_file: str = "/library/dashboard/credentials.json" + # Where an export is staged. On the content volume, not /tmp (often tmpfs / small), so a + # multi-gigabyte channel export has room and the free-space preflight measures the right + # disk. + staging_dir: str = "/library/.cx-staging" + + @staticmethod + def from_env() -> "Config": + return Config( + host=os.environ.get("CX_HOST", "127.0.0.1"), + port=_parse_port(os.environ.get("CX_PORT", str(DEFAULT_PORT))), + zims_dir=os.environ.get("CX_ZIMS_DIR", "/library/zims/content/"), + kiwix_indexer=os.environ.get("CX_KIWIX_INDEXER", "/usr/bin/iiab-make-kiwix-lib"), + kolibri_db=os.environ.get("CX_KOLIBRI_DB", "/library/kolibri/db.sqlite3"), + kolibri_bin=os.environ.get("CX_KOLIBRI_BIN", "/usr/bin/kolibri"), + calibre_db=os.environ.get("CX_CALIBRE_DB", "/library/calibre-web/metadata.db"), + calibre_url=os.environ.get("CX_CALIBRE_URL", "http://127.0.0.1:8083"), + credentials_file=os.environ.get( + "K2GO_CREDENTIALS_FILE", "/library/dashboard/credentials.json"), + staging_dir=os.environ.get("CX_STAGING_DIR", "/library/.cx-staging"), + ) diff --git a/static/cx-core/cx_core/export.py b/static/cx-core/cx_core/export.py new file mode 100644 index 000000000..67afaf9be --- /dev/null +++ b/static/cx-core/cx_core/export.py @@ -0,0 +1,109 @@ +"""Shared export streaming helpers (Pillar 2, output side). + +The core STAGES and STREAMS one item; the front moves the bytes and owns the whole +operation (ADR D1c). These helpers are read-only on the source: they copy bytes out, +they never mutate an app's data. + +The tar is streamed file by file (mode "w|", non-seekable), so a large item is never +buffered whole in memory and no second full copy is written to disk. +""" + +from __future__ import annotations + +import os +import queue +import shutil +import tarfile +import threading +from typing import Iterator, List, Optional, Tuple + +CHUNK = 1024 * 1024 + + +def has_room(path: str, needed_bytes: int) -> bool: + """True when the volume holding path has room for about needed_bytes, with a small + headroom factor. On an unmeasurable path, allow it (the operation still fails cleanly on + ENOSPC). Shared by the export staging preflight and the import preflight.""" + try: + free = shutil.disk_usage(path).free + except OSError: + return True + return free >= int(needed_bytes * 1.05) + + +def file_stream(path: str, chunk: int = CHUNK) -> Iterator[bytes]: + """Yield a file's bytes in chunks. Opens lazily (on first iteration), read-only.""" + with open(path, "rb") as f: + while True: + block = f.read(chunk) + if not block: + return + yield block + + +def resolve_within(root: str, rel: str) -> Optional[str]: + """Join a relative path onto root and return its real path only when it stays inside + root. Guards a multi-segment relative path (e.g. a Calibre book path) against + traversal. Pure except for realpath resolution.""" + if not rel: + return None + root_real = os.path.realpath(root) + target = os.path.realpath(os.path.join(root_real, rel)) + if target == root_real or target.startswith(root_real + os.sep): + return target + return None + + +def _entries(root: str, arcname: str) -> List[Tuple[str, str]]: + """(absolute path, archive name) pairs for root and everything under it, sorted so the + archive is deterministic. Directories are included so empty ones survive.""" + pairs: List[Tuple[str, str]] = [(root, arcname)] + for dirpath, dirnames, filenames in os.walk(root): + dirnames.sort() + for name in sorted(dirnames) + sorted(filenames): + full = os.path.join(dirpath, name) + arc = os.path.join(arcname, os.path.relpath(full, root)) + pairs.append((full, arc)) + return pairs + + +_DONE = object() + + +def tar_stream(root: str, arcname: str = ".", chunk: int = CHUNK) -> Iterator[bytes]: + """Stream a tar of a directory tree. tarfile writes into a bounded queue that the + consumer drains, so a producer that gets ahead BLOCKS: the memory held is a few of + tarfile's write blocks (tens of KB), never a whole member. So a multi-gigabyte file + inside the tree streams without being buffered. Read-only on root.""" + q: "queue.Queue" = queue.Queue(maxsize=8) + error: dict = {} + + class _QueueSink: + def write(self, data: bytes) -> int: + if data: + q.put(bytes(data)) # blocks when full: backpressure bounds memory + return len(data) + + def produce() -> None: + try: + tar = tarfile.open(fileobj=_QueueSink(), mode="w|") + try: + for full, arc in _entries(root, arcname): + tar.add(full, arcname=arc, recursive=False) + finally: + tar.close() + except BaseException as exc: # surfaced to the consumer below + error["exc"] = exc + finally: + q.put(_DONE) + + worker = threading.Thread(target=produce, daemon=True) + worker.start() + while True: + item = q.get() + if item is _DONE: + break + yield item + worker.join() + if "exc" in error: + raise error["exc"] diff --git a/static/cx-core/cx_core/importing.py b/static/cx-core/cx_core/importing.py new file mode 100644 index 000000000..28d734d11 --- /dev/null +++ b/static/cx-core/cx_core/importing.py @@ -0,0 +1,105 @@ +"""Import-side safety helpers (Pillar 3). + +An imported archive came from another box or a disk, so it is UNTRUSTED. Before any +extraction, every member name is validated against path traversal (absolute paths and +".." climbing out), mirroring the repo's D11 guard (ArchiveEntry.escapesRoot). Links are +refused outright: a tar from a trusted exporter never needs them, and a symlink member is +the classic way to escape the destination. payload_path containment keeps the core from +reading an arbitrary path the caller names. +""" + +from __future__ import annotations + +import os +import shutil +import tarfile +from typing import Optional + +# A sane ceiling on members in one item archive. A legitimate Kolibri channel bundle is +# thousands of files; millions is a decompression-bomb shape, not a real item. +MAX_MEMBERS = 500000 + + +def escapes_root(name: str) -> bool: + """True if extracting ``name`` could escape the destination root: an absolute path, or + ".." segments that climb above the root. A leading "./" and an internal "a/../b" that + stays inside are fine. Pure; mirrors ArchiveEntry.escapesRoot (D11).""" + if not name: + return False + n = name.replace("\\", "/").strip() + if not n: + return False + if n.startswith("/"): + return True + depth = 0 + for seg in n.split("/"): + if seg in ("", "."): + continue + if seg == "..": + depth -= 1 + if depth < 0: + return True + else: + depth += 1 + return False + + +def is_within_dir(root: str, path: str) -> bool: + """True when path resolves inside root. Guards the caller-named payload path.""" + root_real = os.path.realpath(root) + path_real = os.path.realpath(path) + return path_real == root_real or path_real.startswith(root_real + os.sep) + + +def safe_extract_tar( + tar_path: str, dest: str, max_members: int = MAX_MEMBERS, max_bytes: Optional[int] = None +) -> None: + """Extract a tar into dest after validating every member. Raises ValueError on a member + that escapes the root or is a link / special file, when the member count exceeds + ``max_members``, or when the summed ACTUAL member sizes (from the tar metadata, not from + any caller-supplied figure) exceed ``max_bytes`` or, when that is None, the free space on + the destination volume. This bounds a decompression bomb that declares a tiny size but + extracts to gigabytes / millions of files. Never writes outside dest.""" + with tarfile.open(tar_path, "r") as tar: + members = tar.getmembers() + if len(members) > max_members: + raise ValueError(f"archive has too many members ({len(members)} > {max_members})") + total = 0 + for m in members: + if escapes_root(m.name): + raise ValueError(f"unsafe archive member (path traversal): {m.name!r}") + if m.issym() or m.islnk(): + raise ValueError(f"unsafe archive member (link): {m.name!r}") + if not (m.isfile() or m.isdir()): + raise ValueError(f"unsafe archive member (special file): {m.name!r}") + if m.isfile(): + total += max(0, m.size) + os.makedirs(dest, exist_ok=True) + limit = max_bytes + if limit is None: + try: + limit = shutil.disk_usage(dest).free + except OSError: + limit = None + if limit is not None and total > limit: + raise ValueError(f"archive too large to extract ({total} bytes > {limit} free)") + # Members are already validated; the stdlib "data" filter is a second, independent + # barrier (it also rejects traversal and dangerous members) where available. + try: + tar.extractall(dest, filter="data") + except TypeError: # Python without the extraction filter argument + tar.extractall(dest) + + +def single_child_dir(root: str) -> Optional[str]: + """If root holds exactly one subdirectory and no files, return it. The export tar wraps + an item under one top directory (its id), so this finds the real bundle root.""" + try: + entries = os.listdir(root) + except OSError: + return None + if len(entries) == 1: + child = os.path.join(root, entries[0]) + if os.path.isdir(child): + return child + return None diff --git a/static/cx-core/cx_core/model.py b/static/cx-core/cx_core/model.py new file mode 100644 index 000000000..5c96e8dd9 --- /dev/null +++ b/static/cx-core/cx_core/model.py @@ -0,0 +1,97 @@ +"""Shared, app-agnostic content model and the manifest shapes. + +These types are the data half of Pillar 0. The core never interprets the inside of +a dedup key: an adapter builds it, and the matching adapter on another box reads it. +So fields like ``line`` and ``version`` carry whatever shape the owning app needs. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any, Optional + +# idKind values. "authoritative" means the id is safe for a hard skip / delete +# (Kiwix UUID, Kolibri channel_id+version). "soft" means advisory only, never an +# automatic action (Calibre, which has no native key for arbitrary media). +AUTHORITATIVE = "authoritative" +SOFT = "soft" + +# Presence: the receiver's verdict for an incoming item (ADR check()). For an +# authoritative idKind the verdict is a hard fact; for a soft idKind (Calibre) it is +# advisory only, never an automatic skip. OLDER_HERE means the box's copy is older than +# the incoming one (import would upgrade); NEWER_HERE means the box's copy is newer. +ABSENT = "ABSENT" +SAME_VERSION = "SAME_VERSION" +OLDER_HERE = "OLDER_HERE" +NEWER_HERE = "NEWER_HERE" + +_WS = re.compile(r"\s+") + + +def normalize_text(value: str) -> str: + """Normalize a free-text field for a soft dedup key: trim, lowercase, collapse + runs of whitespace to one space. Shared so every adapter that needs a soft key + (Calibre first) normalizes the same way, instead of each inventing its own.""" + if not value: + return "" + return _WS.sub(" ", value.strip().lower()) + + +@dataclass(frozen=True) +class Dedup: + """Cross-box "do you already have this?" envelope. The core passes it through; + only the owning app's adapter interprets ``line`` / ``build`` / ``version``.""" + + line: Any # app-shaped line key: Kiwix {creator,lang,flavour}, Kolibri channel_id + build: Optional[str] # exact-build id: Kiwix ZIM UUID; may be None where an app has none + version: Any # version axis: Kiwix date, Kolibri integer version + id_kind: str # AUTHORITATIVE or SOFT + + def to_json(self) -> dict: + return { + "line": self.line, + "build": self.build, + "version": self.version, + "idKind": self.id_kind, + } + + +@dataclass(frozen=True) +class Identity: + """Two handles (ADR "Identity semantics"): ``local_ref`` is the app's own handle + to THIS item on THIS box (export / delete, always free and authoritative-local); + ``dedup`` is the cross-box key.""" + + local_ref: str + dedup: Dedup + + def to_json(self) -> dict: + return {"localRef": self.local_ref, "dedup": self.dedup.to_json()} + + +@dataclass(frozen=True) +class ManifestItem: + """One content item, as both the read-API row and a manifest entry. Export-only + fields (``payload``) stay None on the read side.""" + + app: str + kind: str + title: str + bytes: int + identity: Identity + integrity: Optional[dict] = None # upstream hash when present; never computed on-device + payload: Optional[str] = None # per-item archive path, set only at export (Pillar 2) + requires: list = field(default_factory=list) + + def to_json(self) -> dict: + return { + "app": self.app, + "kind": self.kind, + "title": self.title, + "bytes": self.bytes, + "identity": self.identity.to_json(), + "integrity": self.integrity, + "payload": self.payload, + "requires": list(self.requires), + } diff --git a/static/cx-core/cx_core/ports.py b/static/cx-core/cx_core/ports.py new file mode 100644 index 000000000..fd48bd1a1 --- /dev/null +++ b/static/cx-core/cx_core/ports.py @@ -0,0 +1,73 @@ +"""The inner contract: the app-adapter port (Pillar 0). + +One adapter owns "how THIS app identifies, stores, exports, imports and deletes its +content". The core and the manifest stay app-agnostic; a new app = a new adapter. + +This slice is the READ side only, so the port declares the read methods. The full +port in the ADR also has check / export / importItem / delete; those arrive with the +later pillars and are added here then. Where an app has an authoritative mechanism, +the adapter DELEGATES to it rather than re-deriving: one source of truth. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Callable, Iterable, List, Optional + +from .model import ABSENT, AUTHORITATIVE, ManifestItem + + +@dataclass +class ExportStream: + """One item staged for export: a byte stream the core serves and the front moves + (ADR D1c). ``on_close`` releases any staging (a temp export tree) after streaming.""" + + filename: str + content_type: str + chunks: Iterable[bytes] + on_close: Optional[Callable[[], None]] = None + + +class ContentAdapter(ABC): + """Read-side port for one content app.""" + + #: Stable adapter key used in the REST API (e.g. "kiwix"). Lowercase, URL-safe. + app: str = "" + #: Authority of this app's dedup id: AUTHORITATIVE (hard verdict) or SOFT (advisory). + id_kind: str = AUTHORITATIVE + + @abstractmethod + def is_installed(self) -> bool: + """True when this app is present on the box. The registry loads an adapter + only when this is true, so the service is aware only of installed apps.""" + + @abstractmethod + def list(self) -> List[ManifestItem]: + """Enumerate indexed content with identity + size (read side of Pillar 1).""" + + def get(self, local_ref: str) -> Optional[ManifestItem]: + """One item by its local_ref. Default: scan ``list``. An adapter overrides + this when it can look up a single item more cheaply.""" + for item in self.list(): + if item.identity.local_ref == local_ref: + return item + return None + + def open_export(self, local_ref: str) -> Optional[ExportStream]: + """Stage one item and return a byte stream, or None when the item is absent or the + adapter cannot export it. Read-only on the source. Default: export not supported.""" + return None + + def check(self, dedup: dict) -> str: + """The receiver's verdict for an incoming item, from its dedup key (ABSENT / + SAME_VERSION / OLDER_HERE / NEWER_HERE). Reads only; moves nothing. Default: ABSENT. + A soft idKind (Calibre) makes the verdict advisory, never an automatic skip.""" + return ABSENT + + def import_item(self, entry: dict, payload_path: str) -> dict: + """Ingest one already-local item archive into the app index, delegating to the app's + own import. Idempotent: a re-import must not double-count or corrupt. ``payload_path`` + is a box-visible local file the front placed. Default: not supported. + (The full ADR port also has delete; it arrives with its own slice.)""" + return {"ok": False, "reason": "import not supported"} diff --git a/static/cx-core/cx_core/registry.py b/static/cx-core/cx_core/registry.py new file mode 100644 index 000000000..90d8b18da --- /dev/null +++ b/static/cx-core/cx_core/registry.py @@ -0,0 +1,51 @@ +"""Adapter registry: enumerate the content apps present on the box and load each one's +adapter. The read API is just the core composing every loaded adapter (ADR mapping). + +Keeping the candidate list here is the one place a new app is wired in. An adapter is +loaded only when its app is installed, so the service is aware only of what is present. + +The registry is a STARTUP SNAPSHOT: it resolves installed-state once at load. Reacting to +a module being installed or removed at runtime is a deferred design item, and it must +consume the install system's single source of truth (ModuleRegistry / install events), not +re-derive installed-state per request or add a self-invalidating cache here: a second owner +of "what is installed" is the ADR-5343 failure mode. +""" + +from __future__ import annotations + +from typing import Dict, List + +from .adapters.calibre import CalibreAdapter +from .adapters.kiwix import KiwixAdapter +from .adapters.kolibri import KolibriAdapter +from .config import Config +from .ports import ContentAdapter + + +class Registry: + def __init__(self, adapters: List[ContentAdapter], import_root: str = "/library/.cx-staging"): + self._by_app: Dict[str, ContentAdapter] = {a.app: a for a in adapters} + # The only directory an import payload may live in: the core refuses a payloadPath + # outside it (containment). The front places the payload here. + self.import_root = import_root + + @staticmethod + def load(config: Config) -> "Registry": + candidates: List[ContentAdapter] = [ + KiwixAdapter(config.zims_dir, config.kiwix_indexer), + KolibriAdapter(config.kolibri_db, config.kolibri_bin, config.staging_dir), + CalibreAdapter(config.calibre_db, config.calibre_url, config.credentials_file, config.staging_dir), + ] + return Registry([a for a in candidates if a.is_installed()], config.staging_dir) + + def apps(self) -> List[str]: + return sorted(self._by_app.keys()) + + def get(self, app: str) -> ContentAdapter: + return self._by_app[app] + + def has(self, app: str) -> bool: + return app in self._by_app + + def adapters(self) -> List[ContentAdapter]: + return [self._by_app[a] for a in self.apps()] diff --git a/static/cx-core/cx_core/router.py b/static/cx-core/cx_core/router.py new file mode 100644 index 000000000..ec66a82bd --- /dev/null +++ b/static/cx-core/cx_core/router.py @@ -0,0 +1,170 @@ +"""Pure request routing for the /v1 API. Kept free of the HTTP server so the route logic +is unit-testable without a socket: given a registry, a method, a path and (for POST) a +parsed body, it returns (status, payload). The outer contract (ADR) maps each route 1:1 to +an adapter operation. A read route's payload is JSON; the export-item route's payload is an +ExportStream the server streams as octets. +""" + +from __future__ import annotations + +from typing import Any, List, Optional, Tuple +from urllib.parse import unquote + +from .export import has_room +from .importing import is_within_dir +from .registry import Registry + +Response = Tuple[int, Any] + + +def _content_rows(registry: Registry, only_app: Optional[str]) -> Response: + if only_app is not None and not registry.has(only_app): + return 404, {"error": f"unknown app: {only_app}"} + adapters = [registry.get(only_app)] if only_app else registry.adapters() + items: List[dict] = [] + for adapter in adapters: + items.extend(item.to_json() for item in adapter.list()) + return 200, {"items": items} + + +def _export_plan(registry: Registry, body: Any) -> Response: + """Return the manifest entries + exact bytes for the requested items, moving NO payload, + so the front can preflight the phone disk and let the user pick before any byte moves. + Partial is first-class: items that cannot be planned are reported, not fatal.""" + items = body.get("items") if isinstance(body, dict) else None + if not isinstance(items, list): + return 400, {"error": "body must be {items: [{app, localRef}]}"} + found: List[dict] = [] + missing: List[dict] = [] + total = 0 + for req in items: + app = req.get("app") if isinstance(req, dict) else None + local_ref = req.get("localRef") if isinstance(req, dict) else None + if not registry.has(app): + missing.append({"app": app, "localRef": local_ref, "reason": "unknown app"}) + continue + item = registry.get(app).get(local_ref) if local_ref else None + if item is None: + missing.append({"app": app, "localRef": local_ref, "reason": "not found"}) + continue + found.append(item.to_json()) + total += item.bytes + return 200, {"items": found, "missing": missing, "totalBytes": total} + + +def _dedup_check(registry: Registry, body: Any) -> Response: + """Per item {app, verdict, idKind}. Runs on the receiver; moves nothing.""" + items = body.get("items") if isinstance(body, dict) else None + if not isinstance(items, list): + return 400, {"error": "body must be {items: [{app, dedup}]}"} + results = [] + for req in items: + app = req.get("app") if isinstance(req, dict) else None + dedup = req.get("dedup") if isinstance(req, dict) else None + if not registry.has(app) or not isinstance(dedup, dict): + results.append({"app": app, "verdict": "NO_APP", "idKind": None}) + continue + adapter = registry.get(app) + results.append({"app": app, "verdict": adapter.check(dedup), "idKind": adapter.id_kind}) + return 200, {"results": results} + + +def _import_validate(registry: Registry, body: Any) -> Response: + """Per item: importable + dedup verdict, or NO_APP. Nothing moved. Partial is first-class.""" + items = body.get("items") if isinstance(body, dict) else None + if not isinstance(items, list): + return 400, {"error": "manifest must be {items: [...]}"} + results = [] + for entry in items: + app = entry.get("app") if isinstance(entry, dict) else None + local_ref = (entry.get("identity") or {}).get("localRef") if isinstance(entry, dict) else None + if not registry.has(app): + results.append({"app": app, "localRef": local_ref, "status": "NO_APP"}) + continue + adapter = registry.get(app) + dedup = (entry.get("identity") or {}).get("dedup") or {} + results.append({ + "app": app, "localRef": local_ref, "status": "importable", + "verdict": adapter.check(dedup), "idKind": adapter.id_kind, + }) + return 200, {"results": results} + + +def _import_item(registry: Registry, body: Any) -> Response: + """Ingest one already-local item archive. The front placed payloadPath on a box-visible + path inside the import area and drives the per-item sequence.""" + if not isinstance(body, dict): + return 400, {"error": "body must be {app, entry, payloadPath}"} + app = body.get("app") + entry = body.get("entry") + payload_path = body.get("payloadPath") + if not registry.has(app): + return 404, {"error": f"unknown app: {app}"} + if not isinstance(entry, dict) or not isinstance(payload_path, str) or not payload_path: + return 400, {"error": "entry and payloadPath are required"} + # Containment: the payload must live inside the import area, never an arbitrary path. + if not is_within_dir(registry.import_root, payload_path): + return 400, {"error": "payloadPath is outside the import area"} + # Preflight the staging disk against the declared item size, so a large import fails + # cleanly here rather than ENOSPC mid-extract (the box checks its own disk). + declared = entry.get("bytes") + if isinstance(declared, int) and declared > 0 and not has_room(registry.import_root, declared): + return 507, {"error": "insufficient space to import"} + result = registry.get(app).import_item(entry, payload_path) + return (200, result) if result.get("ok") else (422, result) + + +def dispatch(registry: Registry, method: str, path: str, query: dict, body: Any = None) -> Response: + """Route one request. ``query`` is a dict of first values; ``body`` is the parsed JSON + for a POST.""" + trimmed = path.rstrip("/") or "/" + segments = [unquote(s) for s in trimmed.split("/") if s != ""] + + if method == "POST": + # POST /v1/export/plan : plan an export (sizes only, no payload moved). + if segments == ["v1", "export", "plan"]: + return _export_plan(registry, body) + # POST /v1/dedup/check : receiver dedup verdicts, nothing moved. + if segments == ["v1", "dedup", "check"]: + return _dedup_check(registry, body) + # POST /v1/import/validate : what will import and what is skipped, nothing moved. + if segments == ["v1", "import", "validate"]: + return _import_validate(registry, body) + # POST /v1/import/item : ingest one already-local item archive. + if segments == ["v1", "import", "item"]: + return _import_item(registry, body) + return 404, {"error": "not found"} + + if method != "GET": + return 405, {"error": "method not allowed"} + + # GET /v1/apps : installed apps that have a loaded adapter. + if segments == ["v1", "apps"]: + return 200, {"apps": registry.apps()} + + # GET /v1/content[?app=] : everything this box has, optionally filtered by app. + if segments == ["v1", "content"]: + return _content_rows(registry, query.get("app")) + + # GET /v1/content/{app}/{localRef} : one item detail. + if len(segments) == 4 and segments[0] == "v1" and segments[1] == "content": + app, local_ref = segments[2], segments[3] + if not registry.has(app): + return 404, {"error": f"unknown app: {app}"} + item = registry.get(app).get(local_ref) + if item is None: + return 404, {"error": "item not found"} + return 200, item.to_json() + + # GET /v1/export/item/{app}/{localRef} : stream that one item's archive (payload is an + # ExportStream; the server streams it). The front moves the bytes and owns the sequence. + if len(segments) == 5 and segments[0] == "v1" and segments[1] == "export" and segments[2] == "item": + app, local_ref = segments[3], segments[4] + if not registry.has(app): + return 404, {"error": f"unknown app: {app}"} + stream = registry.get(app).open_export(local_ref) + if stream is None: + return 404, {"error": "item not found or not exportable"} + return 200, stream + + return 404, {"error": "not found"} diff --git a/static/cx-core/cx_core/server.py b/static/cx-core/cx_core/server.py new file mode 100644 index 000000000..d664c2a53 --- /dev/null +++ b/static/cx-core/cx_core/server.py @@ -0,0 +1,111 @@ +"""The HTTP layer: a thin stdlib http.server wrapper around the pure router. No +third-party dependency, so the core runs on any of AMD64 / ARM64 / ARM32 with just +the system Python 3. Bound to localhost, like dash-node; the front reaches it in-box. +""" + +from __future__ import annotations + +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +from .config import Config +from .ports import ExportStream +from .registry import Registry +from .router import dispatch + +_MAX_BODY = 1 * 1024 * 1024 # a plan request is small; cap the read defensively +_BAD_JSON = object() # sentinel: body present but not valid JSON +_TOO_LARGE = object() # sentinel: declared body exceeds _MAX_BODY + + +def make_handler(registry: Registry): + class Handler(BaseHTTPRequestHandler): + server_version = "cx-core/0.1" + # HTTP/1.1 so the chunked export stream is valid (HTTP/1.0 would hand the client the + # chunk-size lines as body). The JSON path sends Content-Length, so keep-alive holds. + protocol_version = "HTTP/1.1" + + def do_GET(self) -> None: # noqa: N802 (http.server naming) + parts = urlsplit(self.path) + query = {k: v[0] for k, v in parse_qs(parts.query).items()} + status, payload = dispatch(registry, "GET", parts.path, query) + if isinstance(payload, ExportStream): + self._stream(status, payload) + else: + self._send(status, payload) + + def do_POST(self) -> None: # noqa: N802 (http.server naming) + parts = urlsplit(self.path) + body = self._read_json_body() + if body is _TOO_LARGE: + # Unread body would desync the next keep-alive request, so close the socket. + self.close_connection = True + self._send(413, {"error": "request body too large"}) + return + if body is _BAD_JSON: + self._send(400, {"error": "invalid JSON body"}) + return + status, payload = dispatch(registry, "POST", parts.path, {}, body) + self._send(status, payload) + + def _read_json_body(self): + try: + length = int(self.headers.get("Content-Length", 0)) + except ValueError: + return _BAD_JSON + if length <= 0: + return None + if length > _MAX_BODY: + return _TOO_LARGE # do not read a truncated body + raw = self.rfile.read(length) + try: + return json.loads(raw.decode("utf-8")) + except (ValueError, UnicodeDecodeError): + return _BAD_JSON + + def _send(self, status: int, payload) -> None: + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _stream(self, status: int, stream: ExportStream) -> None: + # Chunked transfer: the item size is not known up front for a tar, and the front + # moves the bytes. on_close releases any staging after the last byte. + # Close after the stream: the body length is unknown up front, so a chunked + # response plus an explicit close keeps the connection state simple. + self.close_connection = True + self.send_response(status) + self.send_header("Content-Type", stream.content_type) + self.send_header("Content-Disposition", f'attachment; filename="{stream.filename}"') + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Connection", "close") + self.end_headers() + try: + for block in stream.chunks: + if not block: + continue + self.wfile.write(b"%X\r\n" % len(block)) + self.wfile.write(block) + self.wfile.write(b"\r\n") + self.wfile.write(b"0\r\n\r\n") + finally: + if stream.on_close: + stream.on_close() + + def log_message(self, *_args) -> None: + # Quiet by default; the front owns user-facing progress / logging. + pass + + return Handler + + +def serve(config: Config) -> None: + registry = Registry.load(config) + httpd = ThreadingHTTPServer((config.host, config.port), make_handler(registry)) + print(f"cx-core listening on http://{config.host}:{config.port} " + f"(apps: {', '.join(registry.apps()) or 'none'})") + httpd.serve_forever() diff --git a/static/cx-core/tests/__init__.py b/static/cx-core/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/static/cx-core/tests/test_calibre.py b/static/cx-core/tests/test_calibre.py new file mode 100644 index 000000000..1a5c4b8d2 --- /dev/null +++ b/static/cx-core/tests/test_calibre.py @@ -0,0 +1,227 @@ +import os +import sqlite3 +import tempfile +import unittest + +import io +import json +import tarfile + +from cx_core.adapters.calibre import CalibreAdapter, _content_files, build_book_item +from cx_core.adapters.calibreweb import resolve_calibre_credentials +from cx_core.model import SOFT + + +class BuildBookItemTest(unittest.TestCase): + def test_soft_identity_with_formats_and_external_id(self): + item = build_book_item("u-1", "The Hobbit", "Tolkien", "PDF,EPUB", 3000, "9780261103344") + self.assertEqual(item.app, "calibre") + self.assertEqual(item.kind, "book") + self.assertEqual(item.bytes, 3000) + self.assertEqual(item.identity.local_ref, "u-1") + self.assertEqual(item.identity.dedup.id_kind, SOFT) + self.assertEqual(item.identity.dedup.build, "9780261103344") + self.assertEqual( + item.identity.dedup.line, + {"title": "the hobbit", "authors": "tolkien", "formats": ["EPUB", "PDF"], "bytes": 3000}, + ) + + def test_no_formats_no_id_no_authors(self): + item = build_book_item("u-2", "Untitled", None, None, 0, None) + self.assertIsNone(item.identity.dedup.build) + self.assertEqual(item.identity.dedup.line["authors"], "") + self.assertEqual(item.identity.dedup.line["formats"], []) + self.assertEqual(item.bytes, 0) + + def test_missing_title_falls_back_to_uuid(self): + item = build_book_item("u-3", None, None, "EPUB", 10, None) + self.assertEqual(item.title, "u-3") + + +def _make_db(path, book_path="Tolkien/The Hobbit (1)"): + con = sqlite3.connect(path) + con.executescript(""" + CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, sort TEXT, path TEXT, uuid TEXT); + CREATE TABLE data (id INTEGER PRIMARY KEY, book INTEGER, format TEXT, uncompressed_size INTEGER, name TEXT); + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books_authors_link (id INTEGER PRIMARY KEY, book INTEGER, author INTEGER); + CREATE TABLE identifiers (id INTEGER PRIMARY KEY, book INTEGER, type TEXT, val TEXT); + INSERT INTO authors (id, name) VALUES (1, 'J.R.R. Tolkien'); + INSERT INTO books_authors_link (book, author) VALUES (1, 1); + INSERT INTO data (book, format, uncompressed_size, name) VALUES (1, 'EPUB', 1000, 'hobbit'), (1, 'PDF', 2000, 'hobbit'); + INSERT INTO identifiers (book, type, val) VALUES (1, 'isbn', '9780261103344'); + """) + con.execute( + "INSERT INTO books (id, title, sort, path, uuid) VALUES (1, 'The Hobbit', 'Hobbit, The', ?, 'u-1')", + (book_path,), + ) + con.commit() + con.close() + + +class CalibreAdapterEndToEndTest(unittest.TestCase): + def test_list_builds_soft_identity_from_db(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "metadata.db") + _make_db(db) + adapter = CalibreAdapter(db) + self.assertTrue(adapter.is_installed()) + items = adapter.list() + self.assertEqual(len(items), 1) + it = items[0] + self.assertEqual(it.identity.local_ref, "u-1") + self.assertEqual(it.bytes, 3000) # EPUB 1000 + PDF 2000 + self.assertEqual(it.identity.dedup.build, "9780261103344") + self.assertEqual(it.identity.dedup.line["formats"], ["EPUB", "PDF"]) + self.assertEqual(it.identity.dedup.line["authors"], "j.r.r. tolkien") + + def test_get_single_book(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "metadata.db") + _make_db(db) + adapter = CalibreAdapter(db) + self.assertIsNotNone(adapter.get("u-1")) + self.assertIsNone(adapter.get("nope")) + + def test_absent_db_not_installed(self): + adapter = CalibreAdapter("/no/such/metadata.db") + self.assertFalse(adapter.is_installed()) + self.assertEqual(adapter.list(), []) + + +class CalibreExportTest(unittest.TestCase): + def test_open_export_tars_the_book_dir(self): + import io + import tarfile + + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + book_dir = os.path.join(lib, "Tolkien", "The Hobbit (1)") + os.makedirs(book_dir) + with open(os.path.join(book_dir, "hobbit.epub"), "wb") as f: + f.write(b"EPUBDATA") + with open(os.path.join(book_dir, "cover.jpg"), "wb") as f: + f.write(b"JPG") + + stream = CalibreAdapter(db).open_export("u-1") + self.assertIsNotNone(stream) + self.assertEqual(stream.filename, "u-1.tar") + blob = b"".join(stream.chunks) + with tarfile.open(fileobj=io.BytesIO(blob), mode="r") as tar: + names = sorted(m.name for m in tar.getmembers() if m.isfile()) + self.assertEqual(names, ["u-1/cover.jpg", "u-1/hobbit.epub"]) + + def test_open_export_missing_book_or_dir_is_none(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) # row exists but the book dir was never created + adapter = CalibreAdapter(db) + self.assertIsNone(adapter.open_export("u-1")) + self.assertIsNone(adapter.open_export("no-such-uuid")) + + def test_open_export_rejects_traversal_path(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + # a malicious books.path must not escape the library root. + _make_db(db, book_path="../../etc") + self.assertIsNone(CalibreAdapter(db).open_export("u-1")) + + +class CalibreCheckTest(unittest.TestCase): + def test_soft_match_is_advisory_same_version_else_absent(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + adapter = CalibreAdapter(db) + self.assertEqual(adapter.id_kind, SOFT) + self.assertEqual( + adapter.check({"line": {"title": "the hobbit", "authors": "j.r.r. tolkien"}}), + "SAME_VERSION", + ) + self.assertEqual(adapter.check({"line": {"title": "other", "authors": "x"}}), "ABSENT") + + +class ContentFilesTest(unittest.TestCase): + def test_selects_by_format_else_excludes_sidecars(self): + with tempfile.TemporaryDirectory() as d: + for name in ["hobbit.epub", "hobbit.pdf", "cover.jpg", "metadata.opf"]: + with open(os.path.join(d, name), "wb") as f: + f.write(b"x") + by_format = sorted(os.path.basename(p) for p in _content_files(d, {"epub", "pdf"})) + self.assertEqual(by_format, ["hobbit.epub", "hobbit.pdf"]) + no_format = sorted(os.path.basename(p) for p in _content_files(d, set())) + self.assertEqual(no_format, ["hobbit.epub", "hobbit.pdf"]) # cover/opf excluded + + +class ResolveCredentialsTest(unittest.TestCase): + def setUp(self): + self._saved = {k: os.environ.pop(k, None) for k in ("K2GO_CALIBRE_USER", "K2GO_CALIBRE_PASS")} + + def tearDown(self): + for k, v in self._saved.items(): + if v is not None: + os.environ[k] = v + else: + os.environ.pop(k, None) + + def test_env_wins(self): + os.environ["K2GO_CALIBRE_USER"] = "envuser" + os.environ["K2GO_CALIBRE_PASS"] = "envpass" + self.assertEqual(resolve_calibre_credentials("/no/file"), ("envuser", "envpass")) + + def test_file_then_default(self): + with tempfile.TemporaryDirectory() as d: + store = os.path.join(d, "credentials.json") + with open(store, "w") as f: + json.dump({"calibre": {"username": "fileuser", "password": "filepass"}}, f) + self.assertEqual(resolve_calibre_credentials(store), ("fileuser", "filepass")) + self.assertEqual(resolve_calibre_credentials("/no/such/file"), ("Admin", "changeme")) + + +class _UploadStubCalibre(CalibreAdapter): + def _upload_files(self, files): + self.uploaded = sorted(os.path.basename(f) for f in files) + return len(files) + + +def _book_tar(tar_path, uuid, names): + with tarfile.open(tar_path, "w") as t: + for name in names: + data = b"book-bytes" + ti = tarfile.TarInfo(f"{uuid}/{name}") + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + + +class CalibreImportTest(unittest.TestCase): + def test_import_extracts_and_uploads_format_files(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "metadata.db") + _make_db(db) + tar_path = os.path.join(d, "book.tar") + _book_tar(tar_path, "u-1", ["hobbit.epub", "cover.jpg", "metadata.opf"]) + adapter = _UploadStubCalibre(db, staging_dir=os.path.join(d, "staging")) + entry = {"identity": {"localRef": "u-1", "dedup": {"line": {"formats": ["EPUB"]}}}} + result = adapter.import_item(entry, tar_path) + self.assertTrue(result["ok"]) + self.assertEqual(result["uploaded"], 1) + self.assertEqual(adapter.uploaded, ["hobbit.epub"]) + + def test_import_rejects_bad_archive(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "metadata.db") + _make_db(db) + tar_path = os.path.join(d, "evil.tar") + with tarfile.open(tar_path, "w") as t: + data = b"x" + ti = tarfile.TarInfo("../escape") + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + adapter = _UploadStubCalibre(db, staging_dir=os.path.join(d, "staging")) + result = adapter.import_item({"identity": {"localRef": "u-1"}}, tar_path) + self.assertFalse(result["ok"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_calibreweb.py b/static/cx-core/tests/test_calibreweb.py new file mode 100644 index 000000000..b2c9c3393 --- /dev/null +++ b/static/cx-core/tests/test_calibreweb.py @@ -0,0 +1,52 @@ +import os +import tempfile +import unittest + +from cx_core.adapters.calibreweb import _ConcatStream, _multipart_frame, safe_upload_name + + +class SafeUploadNameTest(unittest.TestCase): + def test_strips_crlf_and_quotes_and_path(self): + self.assertEqual(safe_upload_name('a"b.epub'), "ab.epub") + self.assertEqual(safe_upload_name("evil\r\nContent-Disposition: x.epub"), "evilContent-Disposition: x.epub") + self.assertEqual(safe_upload_name("../../etc/passwd"), "passwd") + self.assertEqual(safe_upload_name('\r\n"'), "upload.bin") + + def test_header_cannot_be_injected(self): + name = safe_upload_name('x"\r\nX-Injected: 1') + self.assertNotIn("\r", name) + self.assertNotIn("\n", name) + self.assertNotIn('"', name) + + +class ConcatStreamTest(unittest.TestCase): + def test_reads_prefix_file_suffix_in_order(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "f.bin") + file_bytes = os.urandom(3 * 1024 * 1024 + 11) # spans several reads + with open(path, "wb") as f: + f.write(file_bytes) + prefix, suffix = b"PREFIX---", b"---SUFFIX" + stream = _ConcatStream(prefix, path, suffix) + try: + got = stream.read() # RawIOBase.read() drains via readinto + finally: + stream.close() + self.assertEqual(got, prefix + file_bytes + suffix) + + def test_declared_length_matches_bytes(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "f.bin") + with open(path, "wb") as f: + f.write(b"12345") + prefix, suffix = _multipart_frame("B", {"csrf_token": "t"}, "btn-upload", "x.epub") + length = len(prefix) + os.path.getsize(path) + len(suffix) + stream = _ConcatStream(prefix, path, suffix) + try: + self.assertEqual(len(stream.read()), length) + finally: + stream.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_config.py b/static/cx-core/tests/test_config.py new file mode 100644 index 000000000..f8bb7db27 --- /dev/null +++ b/static/cx-core/tests/test_config.py @@ -0,0 +1,22 @@ +import unittest + +from cx_core.config import DEFAULT_PORT, _parse_port + + +class ParsePortTest(unittest.TestCase): + def test_valid_port(self): + self.assertEqual(_parse_port("8080"), 8080) + + def test_non_numeric_falls_back(self): + self.assertEqual(_parse_port("abc"), DEFAULT_PORT) + + def test_empty_falls_back(self): + self.assertEqual(_parse_port(""), DEFAULT_PORT) + + def test_out_of_range_falls_back(self): + self.assertEqual(_parse_port("0"), DEFAULT_PORT) + self.assertEqual(_parse_port("70000"), DEFAULT_PORT) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_export.py b/static/cx-core/tests/test_export.py new file mode 100644 index 000000000..fbf7f005a --- /dev/null +++ b/static/cx-core/tests/test_export.py @@ -0,0 +1,51 @@ +import io +import os +import tarfile +import tempfile +import unittest + +from cx_core.export import file_stream, resolve_within, tar_stream + + +class FileStreamTest(unittest.TestCase): + def test_streams_whole_file(self): + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "f.bin") + data = os.urandom(3 * 1024 * 1024 + 7) # spans several chunks + with open(p, "wb") as f: + f.write(data) + self.assertEqual(b"".join(file_stream(p, chunk=1024 * 1024)), data) + + +class ResolveWithinTest(unittest.TestCase): + def test_inside_is_resolved(self): + with tempfile.TemporaryDirectory() as d: + os.makedirs(os.path.join(d, "a", "b")) + self.assertEqual(resolve_within(d, "a/b"), os.path.realpath(os.path.join(d, "a", "b"))) + + def test_traversal_rejected(self): + with tempfile.TemporaryDirectory() as d: + self.assertIsNone(resolve_within(d, "../etc")) + self.assertIsNone(resolve_within(d, "a/../../x")) + self.assertIsNone(resolve_within(d, "")) + + +class TarStreamTest(unittest.TestCase): + def test_round_trips_a_tree(self): + with tempfile.TemporaryDirectory() as src: + os.makedirs(os.path.join(src, "sub")) + with open(os.path.join(src, "a.txt"), "wb") as f: + f.write(b"hello") + with open(os.path.join(src, "sub", "b.bin"), "wb") as f: + f.write(b"\x00\x01\x02world") + + blob = b"".join(tar_stream(src, arcname="item")) + with tarfile.open(fileobj=io.BytesIO(blob), mode="r") as tar: + names = sorted(m.name for m in tar.getmembers() if m.isfile()) + self.assertEqual(names, ["item/a.txt", "item/sub/b.bin"]) + self.assertEqual(tar.extractfile("item/a.txt").read(), b"hello") + self.assertEqual(tar.extractfile("item/sub/b.bin").read(), b"\x00\x01\x02world") + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_importing.py b/static/cx-core/tests/test_importing.py new file mode 100644 index 000000000..591bc1ada --- /dev/null +++ b/static/cx-core/tests/test_importing.py @@ -0,0 +1,96 @@ +import io +import os +import tarfile +import tempfile +import unittest + +from cx_core.importing import escapes_root, is_within_dir, safe_extract_tar, single_child_dir + + +def _tar(path, entries): + """entries: list of (name, type) where type in {'file','../','abs','sym'} or a plain name.""" + with tarfile.open(path, "w") as t: + for name, kind in entries: + if kind == "sym": + ti = tarfile.TarInfo(name) + ti.type = tarfile.SYMTYPE + ti.linkname = "/etc/passwd" + t.addfile(ti) + else: + data = b"data" + ti = tarfile.TarInfo(name) + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + + +class EscapesRootTest(unittest.TestCase): + def test_safe_names(self): + for n in ["a.txt", "./a.txt", "sub/b.bin", "a/../b.txt", "chan/content/databases/x.sqlite3"]: + self.assertFalse(escapes_root(n), n) + + def test_unsafe_names(self): + for n in ["../x", "a/../../x", "/etc/passwd", "..", "sub/../../out"]: + self.assertTrue(escapes_root(n), n) + + +class IsWithinDirTest(unittest.TestCase): + def test_inside_and_outside(self): + with tempfile.TemporaryDirectory() as d: + inside = os.path.join(d, "a", "b") + self.assertTrue(is_within_dir(d, inside)) + self.assertFalse(is_within_dir(d, os.path.dirname(d))) + + +class SafeExtractTarTest(unittest.TestCase): + def test_extracts_a_safe_tar(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "ok.tar") + _tar(tar_path, [("item/a.txt", "file"), ("item/sub/b.txt", "file")]) + dest = os.path.join(d, "out") + safe_extract_tar(tar_path, dest) + self.assertTrue(os.path.isfile(os.path.join(dest, "item", "a.txt"))) + self.assertEqual(single_child_dir(dest), os.path.join(dest, "item")) + + def test_rejects_traversal_member(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "evil.tar") + _tar(tar_path, [("good.txt", "file"), ("../escape.txt", "file")]) + with self.assertRaises(ValueError): + safe_extract_tar(tar_path, os.path.join(d, "out")) + # nothing extracted outside + self.assertFalse(os.path.exists(os.path.join(d, "escape.txt"))) + + def test_rejects_absolute_member(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "abs.tar") + _tar(tar_path, [("/etc/evil", "file")]) + with self.assertRaises(ValueError): + safe_extract_tar(tar_path, os.path.join(d, "out")) + + def test_rejects_symlink_member(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "sym.tar") + _tar(tar_path, [("link", "sym")]) + with self.assertRaises(ValueError): + safe_extract_tar(tar_path, os.path.join(d, "out")) + + def test_rejects_too_many_members(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "many.tar") + _tar(tar_path, [("a.txt", "file"), ("b.txt", "file")]) + with self.assertRaises(ValueError): + safe_extract_tar(tar_path, os.path.join(d, "out"), max_members=1) + + def test_rejects_summed_size_over_cap(self): + with tempfile.TemporaryDirectory() as d: + tar_path = os.path.join(d, "big.tar") + # each member is 4 bytes of "data"; two members = 8 > cap of 5. + _tar(tar_path, [("a.txt", "file"), ("b.txt", "file")]) + with self.assertRaises(ValueError): + safe_extract_tar(tar_path, os.path.join(d, "out"), max_bytes=5) + # nothing landed + self.assertFalse(os.path.exists(os.path.join(d, "out", "a.txt"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_kiwix.py b/static/cx-core/tests/test_kiwix.py new file mode 100644 index 000000000..bce62ca22 --- /dev/null +++ b/static/cx-core/tests/test_kiwix.py @@ -0,0 +1,221 @@ +import os +import tempfile +import unittest +import uuid + +from cx_core.adapters.kiwix import ( + KiwixAdapter, + build_item, + is_safe_local_ref, + parse_zim_filename, + read_zim_uuid, +) +from cx_core.model import AUTHORITATIVE, SOFT + + +def _zim_header(u: uuid.UUID) -> bytes: + # magic uint32 LE + 4 version bytes + 16-byte uuid at offset 8. + return (0x044D495A).to_bytes(4, "little") + b"\x06\x00\x00\x00" + u.bytes + + +class ReadZimUuidTest(unittest.TestCase): + def test_reads_uuid_from_valid_header(self): + u = uuid.UUID("abcdabcd-1234-5678-9abc-def012345678") + self.assertEqual(read_zim_uuid(_zim_header(u)), str(u)) + + def test_rejects_bad_magic(self): + bad = b"\x00\x00\x00\x00" + b"\x00" * 20 + self.assertIsNone(read_zim_uuid(bad)) + + def test_rejects_short_header(self): + self.assertIsNone(read_zim_uuid(b"\x5a\x49\x4d\x04")) + + +class ParseZimFilenameTest(unittest.TestCase): + def test_simple_name(self): + self.assertEqual( + parse_zim_filename("devdocs_en_angular_2026-05.zim"), + ("devdocs", "en", "angular", "2026-05"), + ) + + def test_multi_token_flavour(self): + self.assertEqual( + parse_zim_filename("wikipedia_en_all_maxi_2023-10.zim"), + ("wikipedia", "en", "all_maxi", "2023-10"), + ) + + def test_full_date(self): + self.assertEqual( + parse_zim_filename("gutenberg_en_all_2024-01-15.zim"), + ("gutenberg", "en", "all", "2024-01-15"), + ) + + def test_no_date_token(self): + self.assertEqual(parse_zim_filename("something_odd.zim"), ("something", "odd", "", "")) + + def test_off_convention_name_keeps_stable_creator(self): + self.assertEqual(parse_zim_filename("weird.zim"), ("weird", "", "", "")) + + +class BuildItemTest(unittest.TestCase): + def test_builds_authoritative_identity(self): + item = build_item("devdocs_en_angular_2026-05.zim", 2411725, "the-uuid") + self.assertEqual(item.app, "kiwix") + self.assertEqual(item.kind, "zim") + self.assertEqual(item.bytes, 2411725) + self.assertEqual(item.identity.local_ref, "devdocs_en_angular_2026-05.zim") + self.assertEqual(item.identity.dedup.build, "the-uuid") + self.assertEqual(item.identity.dedup.version, "2026-05") + self.assertEqual(item.identity.dedup.id_kind, AUTHORITATIVE) + self.assertEqual( + item.identity.dedup.line, + {"creator": "devdocs", "lang": "en", "flavour": "angular"}, + ) + self.assertIsNone(item.integrity) + + def test_missing_uuid_degrades_to_soft(self): + item = build_item("devdocs_en_angular_2026-05.zim", 2411725, None) + self.assertIsNone(item.identity.dedup.build) + self.assertEqual(item.identity.dedup.id_kind, SOFT) + + +class IsSafeLocalRefTest(unittest.TestCase): + def test_plain_filename_allowed(self): + self.assertTrue(is_safe_local_ref("wikipedia_en_all_2023-10.zim")) + + def test_traversal_and_separators_rejected(self): + for bad in ["../x.zim", "a/b.zim", "a\\b.zim", "/etc/passwd", "..", ".", ""]: + self.assertFalse(is_safe_local_ref(bad), bad) + + +class KiwixAdapterEndToEndTest(unittest.TestCase): + def test_list_reads_installed_zims_with_uuid_and_size(self): + u = uuid.UUID("11111111-2222-3333-4444-555555555555") + with tempfile.TemporaryDirectory() as d: + name = "wikipedia_en_all_maxi_2023-10.zim" + payload = _zim_header(u) + b"\x00" * 100 # header + filler body + with open(os.path.join(d, name), "wb") as f: + f.write(payload) + # a non-zim file must be ignored + with open(os.path.join(d, "readme.txt"), "w") as f: + f.write("x") + + adapter = KiwixAdapter(d) + self.assertTrue(adapter.is_installed()) + items = adapter.list() + self.assertEqual(len(items), 1) + it = items[0] + self.assertEqual(it.identity.local_ref, name) + self.assertEqual(it.identity.dedup.build, str(u)) + self.assertEqual(it.bytes, len(payload)) + + # get() finds it by local_ref, and misses cleanly. + got = adapter.get(name) + self.assertIsNotNone(got) + self.assertEqual(got.identity.dedup.build, str(u)) + self.assertIsNone(adapter.get("nope.zim")) + + def test_bad_header_zim_lists_soft_with_no_build(self): + with tempfile.TemporaryDirectory() as d: + # a .zim whose header is too short / not a ZIM: still listed, but degraded. + with open(os.path.join(d, "broken_en_x_2020-01.zim"), "wb") as f: + f.write(b"not a zim") + items = KiwixAdapter(d).list() + self.assertEqual(len(items), 1) + self.assertIsNone(items[0].identity.dedup.build) + self.assertEqual(items[0].identity.dedup.id_kind, SOFT) + + def test_get_rejects_traversal_without_touching_fs(self): + with tempfile.TemporaryDirectory() as d: + # a readable ZIM one level up must NOT be reachable through a traversal ref. + with open(os.path.join(d, "secret_en_x_2020-01.zim"), "wb") as f: + f.write(_zim_header(uuid.uuid4())) + sub = os.path.join(d, "content") + os.mkdir(sub) + adapter = KiwixAdapter(sub) + self.assertIsNone(adapter.get("../secret_en_x_2020-01.zim")) + self.assertIsNone(adapter.get("..\\secret_en_x_2020-01.zim")) + + def test_absent_dir_is_not_installed(self): + adapter = KiwixAdapter("/no/such/dir/for/cx-core") + self.assertFalse(adapter.is_installed()) + self.assertEqual(adapter.list(), []) + + +class KiwixExportTest(unittest.TestCase): + def test_open_export_streams_the_zim_as_is(self): + with tempfile.TemporaryDirectory() as d: + name = "devdocs_en_angular_2026-05.zim" + payload = _zim_header(uuid.uuid4()) + os.urandom(200) + with open(os.path.join(d, name), "wb") as f: + f.write(payload) + stream = KiwixAdapter(d).open_export(name) + self.assertIsNotNone(stream) + self.assertEqual(stream.filename, name) + self.assertEqual(stream.content_type, "application/octet-stream") + self.assertEqual(b"".join(stream.chunks), payload) + + def test_open_export_rejects_traversal_and_missing(self): + with tempfile.TemporaryDirectory() as d: + adapter = KiwixAdapter(d) + self.assertIsNone(adapter.open_export("../x.zim")) + self.assertIsNone(adapter.open_export("absent.zim")) + + +class KiwixCheckTest(unittest.TestCase): + def setUp(self): + self._d = tempfile.TemporaryDirectory() + self.u1 = uuid.uuid4() + with open(os.path.join(self._d.name, "wikipedia_en_all_2023-10.zim"), "wb") as f: + f.write(_zim_header(self.u1) + b"\x00" * 10) + self.adapter = KiwixAdapter(self._d.name) + + def tearDown(self): + self._d.cleanup() + + def _dedup(self, creator="wikipedia", flavour="all", build=None, version="2023-10"): + return {"line": {"creator": creator, "lang": "en", "flavour": flavour}, + "build": build, "version": version} + + def test_same_uuid_is_same_version(self): + self.assertEqual(self.adapter.check(self._dedup(build=str(self.u1))), "SAME_VERSION") + + def test_newer_incoming_means_older_here(self): + self.assertEqual(self.adapter.check(self._dedup(build="other", version="2024-01")), "OLDER_HERE") + + def test_older_incoming_means_newer_here(self): + self.assertEqual(self.adapter.check(self._dedup(build="other", version="2022-01")), "NEWER_HERE") + + def test_different_line_is_absent(self): + self.assertEqual(self.adapter.check(self._dedup(creator="gutenberg")), "ABSENT") + + +class KiwixImportTest(unittest.TestCase): + def test_import_places_zim_and_reports_ok(self): + with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as zdir: + payload = os.path.join(src, "payload.zim") + data = _zim_header(uuid.uuid4()) + os.urandom(64) + with open(payload, "wb") as f: + f.write(data) + adapter = KiwixAdapter(zdir, indexer="/nonexistent/indexer") # reindex is a no-op + entry = {"identity": {"localRef": "gutenberg_en_all_2024-01.zim"}} + result = adapter.import_item(entry, payload) + self.assertTrue(result["ok"]) + placed = os.path.join(zdir, "gutenberg_en_all_2024-01.zim") + self.assertTrue(os.path.isfile(placed)) + with open(placed, "rb") as f: + self.assertEqual(f.read(), data) + + def test_import_rejects_traversal_localref(self): + with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as zdir: + payload = os.path.join(src, "p.zim") + with open(payload, "wb") as f: + f.write(b"x") + adapter = KiwixAdapter(zdir, indexer="/nonexistent") + result = adapter.import_item({"identity": {"localRef": "../evil.zim"}}, payload) + self.assertFalse(result["ok"]) + self.assertFalse(os.path.exists(os.path.join(os.path.dirname(zdir), "evil.zim"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_kolibri.py b/static/cx-core/tests/test_kolibri.py new file mode 100644 index 000000000..c202d67cc --- /dev/null +++ b/static/cx-core/tests/test_kolibri.py @@ -0,0 +1,239 @@ +import os +import sqlite3 +import tempfile +import unittest + +import io +import tarfile + +from cx_core.adapters.kolibri import ( + KolibriAdapter, + build_channel_item, + export_commands, + import_commands, +) +from cx_core.model import AUTHORITATIVE + +VALID_ID = "c1f2b7e6ac9f56a2bb44fa7a48b66dce" + + +class BuildChannelItemTest(unittest.TestCase): + def test_authoritative_identity(self): + item = build_channel_item("c1f2b7e6ac9f56a2bb44fa7a48b66dce", "Khan Academy", 14, 5000) + self.assertEqual(item.app, "kolibri") + self.assertEqual(item.kind, "channel") + self.assertEqual(item.title, "Khan Academy") + self.assertEqual(item.bytes, 5000) + self.assertEqual(item.identity.local_ref, "c1f2b7e6ac9f56a2bb44fa7a48b66dce") + self.assertEqual(item.identity.dedup.line, "c1f2b7e6ac9f56a2bb44fa7a48b66dce") + self.assertEqual(item.identity.dedup.build, "14") + self.assertEqual(item.identity.dedup.version, 14) + self.assertEqual(item.identity.dedup.id_kind, AUTHORITATIVE) + + def test_missing_name_falls_back_to_id(self): + item = build_channel_item("abc", None, None, 0) + self.assertEqual(item.title, "abc") + self.assertEqual(item.identity.dedup.build, "0") + + +def _make_db(path, cid="C1"): + con = sqlite3.connect(path) + con.executescript(""" + CREATE TABLE content_channelmetadata (id TEXT, name TEXT, version INTEGER); + CREATE TABLE content_contentnode (id TEXT, channel_id TEXT); + CREATE TABLE content_file (contentnode_id TEXT, local_file_id TEXT); + CREATE TABLE content_localfile (id TEXT, file_size INTEGER, available INTEGER); + INSERT INTO content_localfile VALUES ('lf1', 100, 1), ('lf2', 200, 0); + """) + con.execute("INSERT INTO content_channelmetadata VALUES (?, 'Chan One', 14)", (cid,)) + con.execute("INSERT INTO content_contentnode VALUES ('n1', ?), ('n2', ?)", (cid, cid)) + # lf1 is referenced by two nodes: it must be counted ONCE (DISTINCT). + con.execute("INSERT INTO content_file VALUES ('n1', 'lf1'), ('n2', 'lf1'), ('n1', 'lf2')") + con.commit() + con.close() + + +class KolibriAdapterEndToEndTest(unittest.TestCase): + def test_list_counts_available_distinct_bytes(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db) + adapter = KolibriAdapter(db) + self.assertTrue(adapter.is_installed()) + items = adapter.list() + self.assertEqual(len(items), 1) + # only lf1 is available (100), counted once despite two node refs; lf2 not available. + self.assertEqual(items[0].bytes, 100) + self.assertEqual(items[0].identity.local_ref, "C1") + + def test_get_single_channel(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db) + adapter = KolibriAdapter(db) + self.assertIsNotNone(adapter.get("C1")) + self.assertIsNone(adapter.get("missing")) + + def test_absent_db_not_installed(self): + adapter = KolibriAdapter("/no/such/kolibri/db.sqlite3") + self.assertFalse(adapter.is_installed()) + self.assertEqual(adapter.list(), []) + + +class ExportCommandsTest(unittest.TestCase): + def test_builds_the_two_delegated_commands(self): + self.assertEqual( + export_commands(VALID_ID, "/tmp/dest", "/usr/bin/kolibri"), + [ + ["/usr/bin/kolibri", "manage", "exportchannel", VALID_ID, "/tmp/dest"], + ["/usr/bin/kolibri", "manage", "exportcontent", VALID_ID, "/tmp/dest"], + ], + ) + + +class ImportCommandsTest(unittest.TestCase): + def test_builds_the_two_disk_import_commands(self): + self.assertEqual( + import_commands(VALID_ID, "/src/dir", "/usr/bin/kolibri"), + [ + ["/usr/bin/kolibri", "manage", "importchannel", "disk", VALID_ID, "/src/dir"], + ["/usr/bin/kolibri", "manage", "importcontent", "disk", VALID_ID, "/src/dir"], + ], + ) + + +class KolibriCheckTest(unittest.TestCase): + def setUp(self): + self._d = tempfile.TemporaryDirectory() + self.db = os.path.join(self._d.name, "db.sqlite3") + _make_db(self.db, cid=VALID_ID) # version 14 + self.adapter = KolibriAdapter(self.db) + + def tearDown(self): + self._d.cleanup() + + def test_same_version(self): + self.assertEqual(self.adapter.check({"line": VALID_ID, "version": 14}), "SAME_VERSION") + + def test_older_here_when_incoming_newer(self): + self.assertEqual(self.adapter.check({"line": VALID_ID, "version": 20}), "OLDER_HERE") + + def test_newer_here_when_incoming_older(self): + self.assertEqual(self.adapter.check({"line": VALID_ID, "version": 5}), "NEWER_HERE") + + def test_absent_when_no_such_channel(self): + self.assertEqual(self.adapter.check({"line": "f" * 32, "version": 1}), "ABSENT") + + +class _ImportStubKolibri(KolibriAdapter): + def _stage_import(self, channel_id, source): + self.import_channel = channel_id + self.import_source = source + return True + + +def _bundle_tar(tar_path, channel_id): + with tarfile.open(tar_path, "w") as t: + for rel, data in [ + (f"{channel_id}/content/databases/{channel_id}.sqlite3", b"DB"), + (f"{channel_id}/content/storage/a/b/abc.mp4", b"MP4"), + ]: + ti = tarfile.TarInfo(rel) + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + + +class KolibriImportTest(unittest.TestCase): + def test_import_extracts_and_delegates_to_kolibri(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db, cid=VALID_ID) + tar_path = os.path.join(d, "chan.tar") + _bundle_tar(tar_path, VALID_ID) + adapter = _ImportStubKolibri(db, staging_dir=os.path.join(d, "staging")) + result = adapter.import_item({"identity": {"localRef": VALID_ID}}, tar_path) + self.assertTrue(result["ok"]) + self.assertEqual(adapter.import_channel, VALID_ID) + # single_child_dir found the inner bundle root. + self.assertEqual(os.path.basename(adapter.import_source), VALID_ID) + + def test_import_rejects_bad_archive(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db, cid=VALID_ID) + tar_path = os.path.join(d, "evil.tar") + with tarfile.open(tar_path, "w") as t: + data = b"x" + ti = tarfile.TarInfo("../escape") + ti.size = len(data) + t.addfile(ti, io.BytesIO(data)) + adapter = _ImportStubKolibri(db, staging_dir=os.path.join(d, "staging")) + result = adapter.import_item({"identity": {"localRef": VALID_ID}}, tar_path) + self.assertFalse(result["ok"]) + + +class _StubbedKolibri(KolibriAdapter): + """Overrides the CLI seam so the export assembly + streaming is testable without a live + Kolibri: it writes a tiny Kolibri-shaped export tree into dest.""" + + def _stage_export(self, channel_id, dest): + self.staged_dest = dest + dbs = os.path.join(dest, "content", "databases") + storage = os.path.join(dest, "content", "storage", "a", "b") + os.makedirs(dbs) + os.makedirs(storage) + with open(os.path.join(dbs, channel_id + ".sqlite3"), "wb") as f: + f.write(b"DB") + with open(os.path.join(storage, "abc.mp4"), "wb") as f: + f.write(b"MP4") + return True + + +class KolibriExportTest(unittest.TestCase): + def test_open_export_streams_tar_of_the_bundle_and_cleans_up(self): + import io + import tarfile + + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db, cid=VALID_ID) + adapter = _StubbedKolibri(db, staging_dir=os.path.join(d, "staging")) + stream = adapter.open_export(VALID_ID) + self.assertIsNotNone(stream) + self.assertEqual(stream.filename, f"{VALID_ID}.tar") + blob = b"".join(stream.chunks) + with tarfile.open(fileobj=io.BytesIO(blob), mode="r") as tar: + names = sorted(m.name for m in tar.getmembers() if m.isfile()) + self.assertIn(f"{VALID_ID}/content/databases/{VALID_ID}.sqlite3", names) + self.assertIn(f"{VALID_ID}/content/storage/a/b/abc.mp4", names) + # the staging tree is removed after streaming. + self.assertTrue(os.path.isdir(adapter.staged_dest)) + stream.on_close() + self.assertFalse(os.path.exists(adapter.staged_dest)) + + def test_open_export_rejects_non_channel_id_and_uninstalled(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db, cid=VALID_ID) + adapter = _StubbedKolibri(db, staging_dir=os.path.join(d, "staging")) + self.assertIsNone(adapter.open_export("not-a-channel-id")) + self.assertIsNone(adapter.open_export("a" * 32)) # valid shape, not installed + + def test_open_export_fails_when_staging_disk_is_short(self): + with tempfile.TemporaryDirectory() as d: + db = os.path.join(d, "db.sqlite3") + _make_db(db, cid=VALID_ID) # channel available bytes = 100 in the fixture + adapter = _StubbedKolibri(db, staging_dir=os.path.join(d, "staging")) + # Force the preflight to see almost no free space. + adapter._stage_export = lambda *a: (_ for _ in ()).throw(AssertionError("must not stage")) + import cx_core.adapters.kolibri as k + orig = k.shutil.disk_usage + k.shutil.disk_usage = lambda p: type("U", (), {"total": 0, "used": 0, "free": 1})() + try: + self.assertIsNone(adapter.open_export(VALID_ID)) + finally: + k.shutil.disk_usage = orig + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_model.py b/static/cx-core/tests/test_model.py new file mode 100644 index 000000000..d2b551212 --- /dev/null +++ b/static/cx-core/tests/test_model.py @@ -0,0 +1,62 @@ +import unittest + +from cx_core.model import ( + AUTHORITATIVE, + Dedup, + Identity, + ManifestItem, + normalize_text, +) + + +class NormalizeTextTest(unittest.TestCase): + def test_trims_lowercases_and_collapses_whitespace(self): + self.assertEqual(normalize_text(" The Hobbit\tPart 1 "), "the hobbit part 1") + + def test_empty_and_none_safe(self): + self.assertEqual(normalize_text(""), "") + self.assertEqual(normalize_text(None), "") + + +class ManifestItemJsonTest(unittest.TestCase): + def test_to_json_shape_matches_contract(self): + item = ManifestItem( + app="kiwix", + kind="zim", + title="wikipedia_en_all_maxi_2023-10", + bytes=42, + identity=Identity( + local_ref="wikipedia_en_all_maxi_2023-10.zim", + dedup=Dedup( + line={"creator": "wikipedia", "lang": "en", "flavour": "all_maxi"}, + build="11111111-2222-3333-4444-555555555555", + version="2023-10", + id_kind=AUTHORITATIVE, + ), + ), + ) + self.assertEqual( + item.to_json(), + { + "app": "kiwix", + "kind": "zim", + "title": "wikipedia_en_all_maxi_2023-10", + "bytes": 42, + "identity": { + "localRef": "wikipedia_en_all_maxi_2023-10.zim", + "dedup": { + "line": {"creator": "wikipedia", "lang": "en", "flavour": "all_maxi"}, + "build": "11111111-2222-3333-4444-555555555555", + "version": "2023-10", + "idKind": "authoritative", + }, + }, + "integrity": None, + "payload": None, + "requires": [], + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_router.py b/static/cx-core/tests/test_router.py new file mode 100644 index 000000000..16ddc7588 --- /dev/null +++ b/static/cx-core/tests/test_router.py @@ -0,0 +1,202 @@ +import os +import tempfile +import unittest + +from cx_core.model import AUTHORITATIVE, Dedup, Identity, ManifestItem +from cx_core.ports import ContentAdapter, ExportStream +from cx_core.registry import Registry +from cx_core.router import dispatch + + +def _item(app: str, local_ref: str) -> ManifestItem: + return ManifestItem( + app=app, + kind="zim", + title=local_ref, + bytes=10, + identity=Identity( + local_ref=local_ref, + dedup=Dedup(line={}, build=None, version="", id_kind=AUTHORITATIVE), + ), + ) + + +class FakeAdapter(ContentAdapter): + def __init__(self, app, items, export=None, verdict="ABSENT", id_kind="authoritative", import_result=None): + self.app = app + self.id_kind = id_kind + self._items = items + self._export = export + self._verdict = verdict + self._import_result = import_result or {"ok": True, "app": app} + + def is_installed(self): + return True + + def list(self): + return self._items + + def open_export(self, local_ref): + return self._export + + def check(self, dedup): + return self._verdict + + def import_item(self, entry, payload_path): + self.imported = (entry, payload_path) + return self._import_result + + +def _registry(): + return Registry([ + FakeAdapter("kiwix", [_item("kiwix", "a.zim"), _item("kiwix", "b.zim")]), + FakeAdapter("calibre", [_item("calibre", "book-uuid-1")]), + ]) + + +class RouterTest(unittest.TestCase): + def setUp(self): + self.reg = _registry() + + def test_apps(self): + status, body = dispatch(self.reg, "GET", "/v1/apps", {}) + self.assertEqual(status, 200) + self.assertEqual(body, {"apps": ["calibre", "kiwix"]}) + + def test_content_all(self): + status, body = dispatch(self.reg, "GET", "/v1/content", {}) + self.assertEqual(status, 200) + self.assertEqual(len(body["items"]), 3) + + def test_content_filtered_by_app(self): + status, body = dispatch(self.reg, "GET", "/v1/content", {"app": "kiwix"}) + self.assertEqual(status, 200) + self.assertEqual([i["identity"]["localRef"] for i in body["items"]], ["a.zim", "b.zim"]) + + def test_content_unknown_app_filter_404(self): + status, body = dispatch(self.reg, "GET", "/v1/content", {"app": "nope"}) + self.assertEqual(status, 404) + + def test_item_detail(self): + status, body = dispatch(self.reg, "GET", "/v1/content/calibre/book-uuid-1", {}) + self.assertEqual(status, 200) + self.assertEqual(body["identity"]["localRef"], "book-uuid-1") + + def test_item_detail_unknown_app(self): + status, _ = dispatch(self.reg, "GET", "/v1/content/nope/x", {}) + self.assertEqual(status, 404) + + def test_item_detail_missing_item(self): + status, _ = dispatch(self.reg, "GET", "/v1/content/kiwix/missing.zim", {}) + self.assertEqual(status, 404) + + def test_trailing_slash_tolerated(self): + status, _ = dispatch(self.reg, "GET", "/v1/apps/", {}) + self.assertEqual(status, 200) + + def test_unknown_get_404_and_unknown_post_404(self): + status, _ = dispatch(self.reg, "GET", "/v1/unknown", {}) + self.assertEqual(status, 404) + status, _ = dispatch(self.reg, "POST", "/v1/unknown", {}, {}) + self.assertEqual(status, 404) + + def test_other_method_405(self): + status, _ = dispatch(self.reg, "DELETE", "/v1/apps", {}) + self.assertEqual(status, 405) + + +class ExportRouteTest(unittest.TestCase): + def setUp(self): + self.reg = _registry() + + def test_export_plan_found_and_missing(self): + body = {"items": [ + {"app": "kiwix", "localRef": "a.zim"}, + {"app": "kiwix", "localRef": "gone.zim"}, + {"app": "nope", "localRef": "x"}, + ]} + status, out = dispatch(self.reg, "POST", "/v1/export/plan", {}, body) + self.assertEqual(status, 200) + self.assertEqual([i["identity"]["localRef"] for i in out["items"]], ["a.zim"]) + self.assertEqual(out["totalBytes"], 10) + self.assertEqual(len(out["missing"]), 2) + + def test_export_plan_bad_body(self): + status, _ = dispatch(self.reg, "POST", "/v1/export/plan", {}, {"nope": 1}) + self.assertEqual(status, 400) + + def test_export_item_streams(self): + stream = ExportStream("a.zim", "application/octet-stream", [b"abc"]) + reg = Registry([FakeAdapter("kiwix", [_item("kiwix", "a.zim")], export=stream)]) + status, payload = dispatch(reg, "GET", "/v1/export/item/kiwix/a.zim", {}) + self.assertEqual(status, 200) + self.assertIs(payload, stream) + + def test_export_item_not_exportable_404(self): + status, _ = dispatch(self.reg, "GET", "/v1/export/item/kiwix/a.zim", {}) + self.assertEqual(status, 404) # FakeAdapter has no export stream + + def test_export_item_unknown_app_404(self): + status, _ = dispatch(self.reg, "GET", "/v1/export/item/nope/x", {}) + self.assertEqual(status, 404) + + +class ImportRouteTest(unittest.TestCase): + def test_dedup_check_returns_verdict_and_idkind(self): + reg = Registry([ + FakeAdapter("kiwix", [], verdict="OLDER_HERE", id_kind="authoritative"), + FakeAdapter("calibre", [], verdict="SAME_VERSION", id_kind="soft"), + ]) + body = {"items": [ + {"app": "kiwix", "dedup": {"line": {}}}, + {"app": "calibre", "dedup": {"line": {}}}, + {"app": "nope", "dedup": {"line": {}}}, + ]} + status, out = dispatch(reg, "POST", "/v1/dedup/check", {}, body) + self.assertEqual(status, 200) + self.assertEqual(out["results"][0], {"app": "kiwix", "verdict": "OLDER_HERE", "idKind": "authoritative"}) + self.assertEqual(out["results"][1], {"app": "calibre", "verdict": "SAME_VERSION", "idKind": "soft"}) + self.assertEqual(out["results"][2]["verdict"], "NO_APP") + + def test_import_validate_partial(self): + reg = Registry([FakeAdapter("kiwix", [], verdict="ABSENT")]) + body = {"items": [ + {"app": "kiwix", "identity": {"localRef": "a.zim", "dedup": {"line": {}}}}, + {"app": "calibre", "identity": {"localRef": "b", "dedup": {}}}, + ]} + status, out = dispatch(reg, "POST", "/v1/import/validate", {}, body) + self.assertEqual(status, 200) + self.assertEqual(out["results"][0]["status"], "importable") + self.assertEqual(out["results"][0]["verdict"], "ABSENT") + self.assertEqual(out["results"][1]["status"], "NO_APP") + + def test_import_item_happy_path(self): + with tempfile.TemporaryDirectory() as root: + fake = FakeAdapter("kiwix", [], import_result={"ok": True, "app": "kiwix"}) + reg = Registry([fake], import_root=root) + payload = os.path.join(root, "a.zim") + body = {"app": "kiwix", "entry": {"identity": {"localRef": "a.zim"}, "bytes": 10}, "payloadPath": payload} + status, out = dispatch(reg, "POST", "/v1/import/item", {}, body) + self.assertEqual(status, 200) + self.assertTrue(out["ok"]) + self.assertEqual(fake.imported[1], payload) + + def test_import_item_rejects_payload_outside_area(self): + with tempfile.TemporaryDirectory() as root: + reg = Registry([FakeAdapter("kiwix", [])], import_root=root) + body = {"app": "kiwix", "entry": {"identity": {"localRef": "a.zim"}}, "payloadPath": "/etc/passwd"} + status, _ = dispatch(reg, "POST", "/v1/import/item", {}, body) + self.assertEqual(status, 400) + + def test_import_item_adapter_failure_422(self): + with tempfile.TemporaryDirectory() as root: + fake = FakeAdapter("kiwix", [], import_result={"ok": False, "reason": "bad archive"}) + reg = Registry([fake], import_root=root) + body = {"app": "kiwix", "entry": {"identity": {"localRef": "a.zim"}}, "payloadPath": os.path.join(root, "x")} + status, out = dispatch(reg, "POST", "/v1/import/item", {}, body) + self.assertEqual(status, 422) + self.assertFalse(out["ok"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/static/cx-core/tests/test_server.py b/static/cx-core/tests/test_server.py new file mode 100644 index 000000000..a55207741 --- /dev/null +++ b/static/cx-core/tests/test_server.py @@ -0,0 +1,75 @@ +import http.client +import json +import os +import tempfile +import threading +import unittest +import uuid +from http.server import ThreadingHTTPServer + +from cx_core.adapters.kiwix import KiwixAdapter +from cx_core.registry import Registry +from cx_core.server import make_handler + + +def _zim(path, body_len=500): + hdr = (0x044D495A).to_bytes(4, "little") + b"\x06\x00\x00\x00" + uuid.uuid4().bytes + data = hdr + os.urandom(body_len) + with open(path, "wb") as f: + f.write(data) + return data + + +class ServerHttpTest(unittest.TestCase): + """End-to-end over a real socket with http.client, so the chunked export stream is + decoded by a real HTTP client: a wrong HTTP version would leak the chunk-size lines into + the body and the reassembled bytes would not match the source.""" + + def setUp(self): + self._dir = tempfile.TemporaryDirectory() + self.zim_name = "wikipedia_en_all_2024-01.zim" + self.zim_bytes = _zim(os.path.join(self._dir.name, self.zim_name), body_len=200000) + reg = Registry([KiwixAdapter(self._dir.name)]) + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(reg)) + self.port = self.httpd.server_address[1] + self._t = threading.Thread(target=self.httpd.serve_forever, daemon=True) + self._t.start() + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self._dir.cleanup() + + def _conn(self): + return http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) + + def test_export_item_stream_matches_source(self): + c = self._conn() + c.request("GET", f"/v1/export/item/kiwix/{self.zim_name}") + resp = c.getresponse() + self.assertEqual(resp.status, 200) + got = resp.read() + c.close() + self.assertEqual(got, self.zim_bytes) + + def test_export_plan_over_http(self): + c = self._conn() + payload = json.dumps({"items": [{"app": "kiwix", "localRef": self.zim_name}]}) + c.request("POST", "/v1/export/plan", body=payload, headers={"Content-Type": "application/json"}) + resp = c.getresponse() + out = json.loads(resp.read()) + c.close() + self.assertEqual(resp.status, 200) + self.assertEqual(out["totalBytes"], len(self.zim_bytes)) + + def test_apps_json_over_http(self): + c = self._conn() + c.request("GET", "/v1/apps") + resp = c.getresponse() + out = json.loads(resp.read()) + c.close() + self.assertEqual(out, {"apps": ["kiwix"]}) + + +if __name__ == "__main__": + unittest.main()