diff --git a/.gitattributes b/.gitattributes index a0dc726..362ca03 100644 --- a/.gitattributes +++ b/.gitattributes @@ -32,3 +32,5 @@ src/onlyworlds/convert/kanka.json -text tests/fixtures/pins-known-to.cases.json -text # The most linked reader's shared cases, the same bytes as the npm SDK's copy (both tests hold its sha256). tests/fixtures/most-linked.fixture.json -text +# The folder writers' refused and written ids, the same bytes as the npm SDK's copy (both tests hold its sha256). +tests/fixtures/unsafe-ids.cases.json -text diff --git a/CHANGELOG.md b/CHANGELOG.md index 990855b..c7e092a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.158.5 (2026-11-28) + +- **Fixed: a folder writer no longer writes outside its folder for an element id that holds a path; such an id is refused.** An element whose name gives no slug is written as `.json`, so an id such as `../../x`, from an export or a server, wrote a file outside the folder it was asked to write. `write_folder` now refuses, whatever the name and before anything is written, an element id that is empty (it would be the hidden file `.json`), holds `/` or `\`, holds a colon (on Windows `D:x.json` is a path on drive D), holds a control character (U+0000 to U+001F), or is `.` or `..`: `ValueError: character element id "../../x" cannot be a file name: it holds a path separator, / or \.` Behind that rule, a second guard refuses any file whose path would not lie inside its folder: in `write_folder` (inside its type folder, both in the temp folder it writes and in the folder that temp folder becomes), in `write_bundle` (the OKF export, whose files are named from ids) and for the LegendKeeper import's board records. Every writer that names files by id goes through these: `write_folder`, `export_world`, `export_okf` and the Kanka, Campfire, LegendKeeper, Notion and World Anvil imports. The world's id names no path and is not checked. The cases are in `tests/fixtures/unsafe-ids.cases.json`, which the npm SDK's folder writer is held to as well. + ## 0.158.4 (2026-11-28) - **Fixed: a date written with its weekday parses back.** `parse_date` read era, month and intercalary names and never a weekday's, so a world whose `format` prints `{weekday}` could not read its own dates: `"Moonday, 3 Frost 454"` answered `unrecognized: "moonday"`. A weekday name is now read after every other name, longest first, as a whole word: a word that is both a month's and a weekday's still reads as the month, a name that reads as a number is never tried, and a calendar whose names do not match its week's length (it prints no weekday) reads none. A weekday that is not the date's own is refused, naming both (`that date falls on Sunday, not Moonday`; `that date has no weekday, not Moonday` for a day outside the week), and a weekday alone names no date. The separators stay whitespace, the comma, the period and the word `year`. Nothing that parsed before parses differently. The npm SDK 4.220.1 reads the same. diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 92f7daf..229da94 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.158.4" +__version__ = "0.158.5" diff --git a/src/onlyworlds/folder.py b/src/onlyworlds/folder.py index 3c76bb2..44f1f83 100644 --- a/src/onlyworlds/folder.py +++ b/src/onlyworlds/folder.py @@ -15,6 +15,7 @@ from __future__ import annotations +import json import os import re import shutil @@ -185,6 +186,45 @@ def id_tail(element_id: str) -> str: return raw +_SEPARATOR = re.compile(r"[/\\]") +_CONTROL = re.compile(r"[\x00-\x1f]") + + +def _unsafe_id_why(element_id: str) -> str | None: + """Why an element id cannot name a file, or None when it can: used as ``.json`` (a name with + no slug, or the collision rule's full-id form) it must be one plain file name inside its type + folder. Checked in this order: empty (``.json``, a hidden file), a path separator, a colon (on Windows + ``C:evil.json`` is a path on drive C, and ``a:b.json`` names a stream of file ``a``), a control + character (U+0000 to U+001F), ``.`` or ``..``. The npm SDK's writer refuses the same ids in the same + words (tests/fixtures/unsafe-ids.cases.json). ``_inside`` is the second guard, on the path itself.""" + if not element_id: + return "it is empty" + if _SEPARATOR.search(element_id): + return "it holds a path separator, / or \\" + if ":" in element_id: + return "it holds a colon" + if _CONTROL.search(element_id): + return "it holds a control character" + if element_id in (".", ".."): + return "it is . or .." + return None + + +def _inside(folder: Path, rel: str) -> bool: + """True when ``folder / rel``, resolved, is a path under ``folder``, resolved (neither need exist yet): + the second guard of every writer that names a file from an id, behind its character rule, so a path + the rule did not foresee is refused before anything is written.""" + base = folder.resolve() + target = (folder / rel).resolve() + return target != base and target.is_relative_to(base) + + +def _one_file_in(filename: str, folders: Iterable[Path]) -> bool: + """True when ``filename`` joins as one plain name (a drive-relative ``C:evil.json`` joined to a path on + drive C keeps the folder but names ``evil.json``) and its path lies inside each of ``folders``.""" + return Path(filename).name == filename and all(_inside(f, filename) for f in folders) + + def element_filename(element_id: str, name: str | None) -> str: """``--.json``; an unsluggable name gives ``.json`` (§3.2).""" slug = slugify(name) @@ -294,7 +334,11 @@ def write_folder( Within a type, a repeated id keeps its LAST body (id-keyed overwrite, the spec's answer to a keyset walk that met a mid-walk write), so a stub that later arrives whole is written whole, without ``known_of`` (§4.4 rule 4). The same id - under two types is an error. + under two types is an error, and so is an id that cannot name a file (one that + is empty, holds ``/``, ``\\``, ``:`` or a control character, or is ``.`` or ``..``: + as ``.json`` it would leave its type folder or name a hidden file), whatever + the name, and a file name whose path would not lie inside its type folder, all + before anything is written. The world's id names no path. ``root`` must not exist, or be an empty directory: this writes a folder's birth, never over another folder (stale files from renamed or deleted @@ -314,16 +358,35 @@ def write_folder( slot = by_type.setdefault(etype, {}) for body in bodies: eid = body.get("id") - if not isinstance(eid, str) or not eid: + if not isinstance(eid, str): raise ValueError(f"{etype} element without a non-empty string id: {dict(body)!r:.200}") + why = _unsafe_id_why(eid) + if why is not None: + raise ValueError( + f"{etype} element id {json.dumps(eid, ensure_ascii=False)} cannot be a file name: {why}." + ) if owner.setdefault(eid, etype) != etype: raise ValueError(f"id {eid} appears under both {owner[eid]} and {etype}") slot.pop(eid, None) # last wins, and takes the last position slot[eid] = body + # Every file's name, each held inside its type folder, in the temp folder it is written to and in the + # finished folder it is renamed to, before anything is written. + tmp = root.parent / f".{root.name}.tmp-{uuid.uuid4().hex[:8]}" + names_by_type: dict[str, dict[str, str]] = {} + for etype in ELEMENT_TYPES: + if by_type.get(etype): + names = resolve_filenames((eid, _name_of(b)) for eid, b in by_type[etype].items()) + for eid, filename in names.items(): + if not _one_file_in(filename, (tmp / ELEMENTS_DIR / etype, root / ELEMENTS_DIR / etype)): + raise ValueError( + f"{etype} element id {json.dumps(eid, ensure_ascii=False)} gives the file name " + f"{json.dumps(filename, ensure_ascii=False)}, which does not lie inside its type folder." + ) + names_by_type[etype] = names + counts: dict[str, int] = {} collisions: list[str] = [] - tmp = root.parent / f".{root.name}.tmp-{uuid.uuid4().hex[:8]}" tmp.mkdir(parents=True) try: for etype in ELEMENT_TYPES: @@ -332,7 +395,7 @@ def write_folder( continue # §4: empty type directories are omitted tdir = tmp / ELEMENTS_DIR / etype tdir.mkdir(parents=True) - names = resolve_filenames((eid, _name_of(b)) for eid, b in bodies_by_id.items()) + names = names_by_type[etype] for eid, body in bodies_by_id.items(): filename = names[eid] if filename != element_filename(eid, _name_of(body)): diff --git a/src/onlyworlds/legendkeeper.py b/src/onlyworlds/legendkeeper.py index 94817c6..37c6082 100644 --- a/src/onlyworlds/legendkeeper.py +++ b/src/onlyworlds/legendkeeper.py @@ -389,7 +389,7 @@ from ._version import __version__ from .calendar import CALENDAR_FIELD, CALENDAR_SUPERTYPE from .errors import parse_retry_after -from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, write_folder +from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, _inside, write_folder from .http import Response, Transport, UrllibTransport from .worldfile import RECORDS_MANIFEST @@ -4043,12 +4043,21 @@ def import_legendkeeper( if plan_only: return report assert out is not None + _check_records(out, conv.board_records) write_folder(out, report.world, elements) _write_records(out, conv.board_records, private=report.records_private) report.out = out return report +def _check_records(out: Path, boards: Mapping[str, dict[str, Any]]) -> None: + """Every board's record path lies inside ``out`` (it is named from a document id, or the Map's when that is + not a plain name): a ValueError before the folder is written, the second guard behind ``_SAFE_NAME``.""" + for rel in boards: + if not _inside(out, rel): + raise ValueError(f"the board record path {rel!r} does not lie inside {out}; nothing was written") + + def _write_records(out: Path, boards: Mapping[str, dict[str, Any]], *, private: bool) -> None: """The boards' records into the finished folder (folder spec §4.5): one file a board under ``records/legendkeeper/``, in the folder's own JSON (UTF-8, LF, two-space indent), and the diff --git a/src/onlyworlds/okf.py b/src/onlyworlds/okf.py index 71aeb64..d53074c 100644 --- a/src/onlyworlds/okf.py +++ b/src/onlyworlds/okf.py @@ -159,6 +159,7 @@ WORLD_FILE, WORLD_FOLDER_KEYS, Folder, + _inside, is_hidden, is_known_of, read_folder, @@ -659,8 +660,12 @@ def noted(msg: str) -> None: def write_bundle(files: Mapping[str, str], out: str | os.PathLike[str]) -> None: - """Write ``files`` under ``out``, which must not exist (``FileExistsError``).""" + """Write ``files`` under ``out``, which must not exist (``FileExistsError``). A path that would not lie + inside ``out`` (the element files are named from their ids) is a ValueError before anything is written.""" out = Path(out) + for rel in files: + if not _inside(out, rel): + raise ValueError(f"the bundle path {rel!r} does not lie inside {out}; nothing was written") out.mkdir(parents=True, exist_ok=False) for rel in sorted(files): path = out / rel diff --git a/tests/fixtures/unsafe-ids.cases.json b/tests/fixtures/unsafe-ids.cases.json new file mode 100644 index 0000000..445a5cd --- /dev/null +++ b/tests/fixtures/unsafe-ids.cases.json @@ -0,0 +1,128 @@ +{ + "about": "Element ids a world folder writer refuses and ids it writes: the npm SDK's folder writer (worldFolderFiles, convertKanka) and the Python package's write_folder. The same bytes in both repositories; both suites hold its sha256. An id is refused when used as .json it would not be one plain file name: it is empty, it holds / or a backslash, it holds a colon (on Windows C:evil.json is a path on drive C), it holds a control character U+0000 to U+001F, or it is . or .. (checked in that order), whatever the name, since the collision rule can fall back to the full id. A refusal names the type, the id as JSON text and the why given here; no file is written. A written case gives the file's path. Cases written by hand.", + "version": 1, + "refused": [ + { + "id": "a/b", + "name": "", + "why": "it holds a path separator, / or \\" + }, + { + "id": "a\\b", + "name": "", + "why": "it holds a path separator, / or \\" + }, + { + "id": "../../x", + "name": "", + "why": "it holds a path separator, / or \\" + }, + { + "id": "../../x", + "name": "Escape", + "why": "it holds a path separator, / or \\" + }, + { + "id": "/abs", + "name": "Abs", + "why": "it holds a path separator, / or \\" + }, + { + "id": "..", + "name": "", + "why": "it is . or .." + }, + { + "id": ".", + "name": "", + "why": "it is . or .." + }, + { + "id": "..", + "name": "Two Dots", + "why": "it is . or .." + }, + { + "id": "a\u0000b", + "name": "", + "why": "it holds a control character" + }, + { + "id": "tab\tid", + "name": "Tab", + "why": "it holds a control character" + }, + { + "id": "\u001f", + "name": "", + "why": "it holds a control character" + }, + { + "id": "../\u0000", + "name": "", + "why": "it holds a path separator, / or \\" + }, + { + "id": "", + "name": "", + "why": "it is empty" + }, + { + "id": "", + "name": "Named", + "why": "it is empty" + }, + { + "id": "a:b", + "name": "", + "why": "it holds a colon" + }, + { + "id": "C:evil", + "name": "", + "why": "it holds a colon" + }, + { + "id": "C:evil", + "name": "Evil", + "why": "it holds a colon" + }, + { + "id": "D:/x", + "name": "", + "why": "it holds a path separator, / or \\" + }, + { + "id": ":\u0000", + "name": "", + "why": "it holds a colon" + } + ], + "written": [ + { + "id": "v1.2", + "name": "", + "path": "elements/character/v1.2.json" + }, + { + "id": "élan", + "name": "", + "path": "elements/character/élan.json" + }, + { + "id": "...", + "name": "", + "path": "elements/character/....json" + }, + { + "id": "a..b", + "name": "Dots", + "path": "elements/character/dots--a..b.json" + }, + { + "id": "c-", + "name": "", + "path": "elements/character/c-.json" + } + ] +} diff --git a/tests/test_unsafe_ids.py b/tests/test_unsafe_ids.py new file mode 100644 index 0000000..1a3a28d --- /dev/null +++ b/tests/test_unsafe_ids.py @@ -0,0 +1,138 @@ +"""``write_folder`` refuses an element id that cannot name a file. The shared cases +(``tests/fixtures/unsafe-ids.cases.json``, the same bytes as the npm SDK's ``test/fixtures/unsafe-ids.cases.json``; +both suites hold its sha256): an id that holds ``/``, ``\\`` or a control character, or is ``.`` or ``..``, is +refused whatever the name, since ``.json`` would leave its type folder, with a ValueError naming the type, the +id as JSON text and the case's why, and nothing is written (the target is not made, an empty one is left as it +was). Each written case gives its path. Then the same refusal through ``export_world``, whose ids come from the +server.""" + +from __future__ import annotations + +import hashlib +import json +import re +import sys +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +import pytest +from conftest import FakeTransport, jresp + +from onlyworlds import Client, export_world, folder, legendkeeper, write_folder +from onlyworlds.http import Response +from onlyworlds.okf import write_bundle + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "unsafe-ids.cases.json" +FIXTURE_SHA256 = "cc6c0c016b441c0ebdc2840304f28c69e05a7ddf6eb0a333b343188717eb5581" +W = {"id": "w-1", "name": "W"} + + +def _data() -> dict[str, Any]: + data: dict[str, Any] = json.loads(FIXTURE.read_bytes()) + return data + + +def _want(etype: str, case: Mapping[str, str]) -> str: + return f"{etype} element id {json.dumps(case['id'], ensure_ascii=False)} cannot be a file name: {case['why']}." + + +def test_the_cases_file_is_the_pinned_bytes() -> None: + assert hashlib.sha256(FIXTURE.read_bytes()).hexdigest() == FIXTURE_SHA256 + data = _data() + assert data["version"] == 1 + assert len(data["refused"]) == 19 + assert len(data["written"]) == 5 + + +@pytest.mark.parametrize("case", _data()["refused"], ids=lambda c: json.dumps(c["id"])) +def test_a_refused_id_writes_nothing(tmp_path: Path, case: dict[str, str]) -> None: + out = tmp_path / "out" + elements = {"character": [{"id": "ok-1", "name": "Fine"}, {"id": case["id"], "name": case["name"]}]} + with pytest.raises(ValueError, match=f"^{re.escape(_want('character', case))}$"): + write_folder(out, W, elements) + assert list(tmp_path.iterdir()) == [], "the target is not made, and no temp folder is left" + + +def test_an_empty_target_is_left_as_it_was(tmp_path: Path) -> None: + out = tmp_path / "out" + out.mkdir() + with pytest.raises(ValueError, match="cannot be a file name"): + write_folder(out, W, {"zone": [{"id": "../../x", "name": ""}]}) + assert out.is_dir() and list(out.iterdir()) == [] + assert list(tmp_path.iterdir()) == [out] + + +@pytest.mark.parametrize("case", _data()["written"], ids=lambda c: json.dumps(c["id"])) +def test_a_written_id_lands_at_its_path(tmp_path: Path, case: dict[str, str]) -> None: + out = tmp_path / "out" + write_folder(out, W, {"character": [{"id": case["id"], "name": case["name"]}]}) + files = sorted(p.relative_to(out).as_posix() for p in out.rglob("*") if p.is_file()) + assert files == sorted([case["path"], "world.json"]) + assert json.loads((out / case["path"]).read_bytes())["id"] == case["id"] + + +def test_the_world_id_names_no_path(tmp_path: Path) -> None: + out = tmp_path / "out" + write_folder(out, {"id": "../w", "name": "W"}, {"character": [{"id": "c", "name": "C"}]}) + files = sorted(p.relative_to(out).as_posix() for p in out.rglob("*") if p.is_file()) + assert files == ["elements/character/c--c.json", "world.json"] + + +ESCAPES = ["../../x", "../x"] + (["C:evil", "D:/x"] if sys.platform == "win32" else []) + + +@pytest.mark.parametrize("eid", ESCAPES) +def test_the_second_guard_alone_refuses_a_path_outside_the_type_folder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, eid: str +) -> None: + """With the character rule taken out, the containment check still refuses, before anything is written.""" + monkeypatch.setattr(folder, "_unsafe_id_why", lambda _eid: None) + out = tmp_path / "w" / "out" + with pytest.raises(ValueError, match="which does not lie inside its type folder"): + write_folder(out, W, {"character": [{"id": eid, "name": ""}]}) + assert list(tmp_path.iterdir()) == [] + + +def test_the_second_guard_passes_a_plain_name(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + assert folder._inside(tmp_path / "out" / "elements" / "character", "v1.2.json") + assert not folder._inside(tmp_path / "out", "../x.json") + assert not folder._inside(tmp_path / "out", ".") + if sys.platform == "win32": + # A relative folder joined to a drive-relative name is that name alone: a path on drive C, outside. + monkeypatch.chdir(tmp_path) + assert not folder._inside(Path("w") / "out" / "elements" / "character", "C:evil.json") + assert not folder._inside(Path("w") / "out", "D:/x.json") + + +def test_an_okf_bundle_path_outside_its_folder_is_refused(tmp_path: Path) -> None: + out = tmp_path / "bundle" + with pytest.raises(ValueError, match="does not lie inside"): + write_bundle({"index.md": "# W\n", "../escaped.md": "x"}, out) + assert list(tmp_path.iterdir()) == [] + + +def test_a_board_record_path_outside_its_folder_is_refused(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="does not lie inside"): + legendkeeper._check_records(tmp_path / "out", {"records/legendkeeper/boards/../../../../x.json": {}}) + legendkeeper._check_records(tmp_path / "out", {"records/legendkeeper/boards/doc-1.json": {}}) + assert list(tmp_path.iterdir()) == [] + + +def test_export_world_refuses_an_id_from_the_server(tmp_path: Path, make_client: Callable[..., Client]) -> None: + def handler(method: str, url: str, headers: Mapping[str, str], body: bytes | None) -> Response: + path = urlparse(url).path.removeprefix("/api/v2/") + if path == "world/": + return jresp(200, {"id": "w1", "name": "World"}) + if path == "me/": + return jresp(404, {"error": {"type": "invalid_request_error", "code": "not_found", "message": "no"}}) + if path == "location/": + rows = [{"id": "../../../escaped", "type": "location", "name": ""}] + return jresp(200, {"data": rows, "has_more": False, "next_cursor": None}) + return jresp(200, {"data": [], "has_more": False, "next_cursor": None}) + + out = tmp_path / "out" + with pytest.raises(ValueError, match=re.escape('location element id "../../../escaped" cannot be a file name')): + export_world(out, client=make_client(FakeTransport(handler=handler), attempts=1)) + assert list(tmp_path.iterdir()) == []