From 121e662e6546d03867b74a096843220eaf0669ee Mon Sep 17 00:00:00 2001 From: Titus Date: Sat, 28 Nov 2026 13:28:49 +0100 Subject: [PATCH 1/4] folder: write_folder refuses an element id that would write outside its folder An element whose name gives no slug is written as .json, and the collision rule can fall back to the full id at any time, so an id holding a path, such as ../../x from an export or a server, wrote a file outside the folder write_folder was asked to write. write_folder now refuses, before anything is written, an element id that holds / or a backslash, or a control character (U+0000 to U+001F), or is . or .., whatever the name: a ValueError naming the type, the id as JSON text and why. The target is not made, and an empty one is left as it was, as on the writer's other refusals. Every writer that names files by id goes through write_folder (export_world and the five import doors); the world's id names no path. The cases are tests/fixtures/unsafe-ids.cases.json, the same bytes as the npm SDK's copy, both suites holding its sha256. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 2 + CHANGELOG.md | 2 + src/onlyworlds/folder.py | 29 ++++++++- tests/fixtures/unsafe-ids.cases.json | 93 +++++++++++++++++++++++++++ tests/test_unsafe_ids.py | 96 ++++++++++++++++++++++++++++ 5 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 tests/fixtures/unsafe-ids.cases.json create mode 100644 tests/test_unsafe_ids.py 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..6df8bcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +- **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 an element id that holds `/`, `\` or a control character (U+0000 to U+001F), or is `.` or `..`, whatever the name, before anything is written: `ValueError: character element id "../../x" cannot be a file name: it holds a path separator, / or \.` Every writer that names files by id goes through it: `write_folder`, `export_world` 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/folder.py b/src/onlyworlds/folder.py index 3c76bb2..7ce1292 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,24 @@ 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: a path separator, 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).""" + if _SEPARATOR.search(element_id): + return "it holds a path separator, / or \\" + if _CONTROL.search(element_id): + return "it holds a control character" + if element_id in (".", ".."): + return "it is . or .." + return None + + def element_filename(element_id: str, name: str | None) -> str: """``--.json``; an unsluggable name gives ``.json`` (§3.2).""" slug = slugify(name) @@ -294,7 +313,10 @@ 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 + holds ``/``, ``\\`` or a control character, or is ``.`` or ``..``: as ``.json`` + it would leave its type folder), whatever the name, 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 @@ -316,6 +338,11 @@ def write_folder( eid = body.get("id") if not isinstance(eid, str) or not eid: 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 diff --git a/tests/fixtures/unsafe-ids.cases.json b/tests/fixtures/unsafe-ids.cases.json new file mode 100644 index 0000000..b932e10 --- /dev/null +++ b/tests/fixtures/unsafe-ids.cases.json @@ -0,0 +1,93 @@ +{ + "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 holds / or a backslash, or 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 \\" + } + ], + "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..c61f75d --- /dev/null +++ b/tests/test_unsafe_ids.py @@ -0,0 +1,96 @@ +"""``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 +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, write_folder +from onlyworlds.http import Response + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "unsafe-ids.cases.json" +FIXTURE_SHA256 = "76de0404c2700b2d187490ad43a8593ab8af014ee8bb2e5e673dc5e10d905700" +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"]) == 12 + 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"] + + +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()) == [] From 4e0efdb718a4cd6d6c903a6bd4b05f9a283a08db Mon Sep 17 00:00:00 2001 From: Titus Date: Sat, 28 Nov 2026 13:41:27 +0100 Subject: [PATCH 2/4] folder: refuse an empty id and a colon, and hold every id-named path inside its folder Two more shapes refused by write_folder's id rule: an empty id, which would be written as the hidden file .json, and an id holding a colon. On Windows C:evil.json joined to a relative folder is a path on drive C, D:/x.json one at the root of drive D, and a:b.json in a folder names a stream of the file a. Behind the character rule, a second guard: before anything is written, every file a writer names from an id must have a path that lies inside its folder, resolved. write_folder checks each element file against its type folder (and that the name joins as one plain name); write_bundle, the OKF export, checks each path against the bundle; the LegendKeeper import checks its board record paths before it writes the folder. A ValueError names the path. The shared cases file gains the empty id, a:b, C:evil and D:/x; its sha256 moves in both suites. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/onlyworlds/folder.py | 45 ++++++++++++++++++++++---- src/onlyworlds/legendkeeper.py | 11 ++++++- src/onlyworlds/okf.py | 7 +++- tests/fixtures/unsafe-ids.cases.json | 37 ++++++++++++++++++++- tests/test_unsafe_ids.py | 48 ++++++++++++++++++++++++++-- 6 files changed, 136 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df8bcb..722d716 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased -- **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 an element id that holds `/`, `\` or a control character (U+0000 to U+001F), or is `.` or `..`, whatever the name, before anything is written: `ValueError: character element id "../../x" cannot be a file name: it holds a path separator, / or \.` Every writer that names files by id goes through it: `write_folder`, `export_world` 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. +- **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 `C:evil.json` is a path on drive C), 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`, 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) diff --git a/src/onlyworlds/folder.py b/src/onlyworlds/folder.py index 7ce1292..1cc7ba1 100644 --- a/src/onlyworlds/folder.py +++ b/src/onlyworlds/folder.py @@ -193,10 +193,16 @@ def id_tail(element_id: str) -> str: 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: a path separator, 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).""" + 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 (".", ".."): @@ -204,6 +210,15 @@ def _unsafe_id_why(element_id: str) -> str | None: 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 element_filename(element_id: str, name: str | None) -> str: """``--.json``; an unsluggable name gives ``.json`` (§3.2).""" slug = slugify(name) @@ -314,9 +329,10 @@ def write_folder( 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, and so is an id that cannot name a file (one that - holds ``/``, ``\\`` or a control character, or is ``.`` or ``..``: as ``.json`` - it would leave its type folder), whatever the name, before anything is written. - The world's id names no path. + 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 @@ -336,7 +352,7 @@ 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: @@ -348,6 +364,21 @@ def write_folder( slot.pop(eid, None) # last wins, and takes the last position slot[eid] = body + # Every file's name, each held inside its type folder of the finished folder before anything is written. + 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(): + # One plain name (a drive-relative `C:evil.json` joined to a path on drive C keeps the folder + # but names `evil.json`), whose path lies inside the type folder. + if Path(filename).name != filename or not _inside(root / ELEMENTS_DIR / etype, filename): + 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]}" @@ -359,7 +390,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 index b932e10..445a5cd 100644 --- a/tests/fixtures/unsafe-ids.cases.json +++ b/tests/fixtures/unsafe-ids.cases.json @@ -1,5 +1,5 @@ { - "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 holds / or a backslash, or 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.", + "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": [ { @@ -61,6 +61,41 @@ "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": [ diff --git a/tests/test_unsafe_ids.py b/tests/test_unsafe_ids.py index c61f75d..1a3a28d 100644 --- a/tests/test_unsafe_ids.py +++ b/tests/test_unsafe_ids.py @@ -11,6 +11,7 @@ import hashlib import json import re +import sys from collections.abc import Callable, Mapping from pathlib import Path from typing import Any @@ -19,11 +20,12 @@ import pytest from conftest import FakeTransport, jresp -from onlyworlds import Client, export_world, write_folder +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 = "76de0404c2700b2d187490ad43a8593ab8af014ee8bb2e5e673dc5e10d905700" +FIXTURE_SHA256 = "cc6c0c016b441c0ebdc2840304f28c69e05a7ddf6eb0a333b343188717eb5581" W = {"id": "w-1", "name": "W"} @@ -40,7 +42,7 @@ 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"]) == 12 + assert len(data["refused"]) == 19 assert len(data["written"]) == 5 @@ -78,6 +80,46 @@ def test_the_world_id_names_no_path(tmp_path: Path) -> None: 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/") From ee32e93ee5da186c49d0e1f2145cf7e0cee7fd5f Mon Sep 17 00:00:00 2001 From: Titus Date: Sat, 28 Nov 2026 13:50:37 +0100 Subject: [PATCH 3/4] folder: hold each element file inside the temp folder write_folder writes, too write_folder writes its files into a temp folder beside the target and renames it into place. The second guard checked each element file's path against the target's type folder only; it now checks the temp folder's as well, before anything is written, since that is where the bytes land first. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/onlyworlds/folder.py | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 722d716..aad7a3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased -- **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 `C:evil.json` is a path on drive C), 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`, 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. +- **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 `C:evil.json` is a path on drive C), 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) diff --git a/src/onlyworlds/folder.py b/src/onlyworlds/folder.py index 1cc7ba1..44f1f83 100644 --- a/src/onlyworlds/folder.py +++ b/src/onlyworlds/folder.py @@ -219,6 +219,12 @@ def _inside(folder: Path, rel: str) -> bool: 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) @@ -364,15 +370,15 @@ def write_folder( slot.pop(eid, None) # last wins, and takes the last position slot[eid] = body - # Every file's name, each held inside its type folder of the finished folder before anything is written. + # 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(): - # One plain name (a drive-relative `C:evil.json` joined to a path on drive C keeps the folder - # but names `evil.json`), whose path lies inside the type folder. - if Path(filename).name != filename or not _inside(root / ELEMENTS_DIR / etype, filename): + 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." @@ -381,7 +387,6 @@ def write_folder( 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: From 52f4802bc86d9d473282163fd7efe6b9fee94680 Mon Sep 17 00:00:00 2001 From: Titus Date: Sat, 28 Nov 2026 13:52:08 +0100 Subject: [PATCH 4/4] 0.158.5: write_folder refuses an element id that would write outside its folder The release entry; its colon example is a drive the folder is not on, where the join leaves the folder (on the folder's own drive it names another file inside it). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++- src/onlyworlds/_version.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aad7a3f..c7e092a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,9 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased -- **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 `C:evil.json` is a path on drive C), 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.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) 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"