From e3cf2a3adcb24cc4d12c38fae69f48ebb83f159e Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:22 -0800 Subject: [PATCH 1/5] fix(llm-helper): one rule for a number, a duration and a page list; a wrong audit grace or retention stops the start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A number in a request or a setting was read by each pack's own reader. Here digits of any script were taken ("٣" was 3; "²" raised out of prepare(), the host's 500 where the contract says 400) and the JSON float 16000.0 was refused, while the Node twin, which cannot tell it from 16000, accepted it. Both packs now read one rule: a JSON number with a whole value or a string of ASCII digits, with the 24 white-space characters both runtimes' trim take ignored around it, at most 9007199254740991. A duration and a page list follow it. The refusals keep their messages. A malformed llm.transcript.audit.grace or llm.transcript.audit.retention was read inside the save of a loop's closing turn: a 503 after the model had been called, the turn unsaved. Both are read when the helper starts and stop the start by name, as its other settings do. llm-helper-vectors.json gains the `numbers` section - 98 probes, each read as a whole number, a duration and a page list - byte-identical with the Node twin; the digest pin moves with it. The README's sentence on the upload bound follows the REST automation: files and text fields, in bytes. Co-Authored-By: Claude Fable 5.2 --- extensions/llm-helper/README.md | 23 +- extensions/llm-helper/llm_helper.py | 79 ++- tests/test_llm_helper.py | 139 ++++- tests/test_transcript_audit.py | 33 ++ tests/vectors/llm-helper-vectors.json | 819 +++++++++++++++++++++++++- 5 files changed, 1066 insertions(+), 27 deletions(-) diff --git a/extensions/llm-helper/README.md b/extensions/llm-helper/README.md index 7bf9caf..826ffea 100644 --- a/extensions/llm-helper/README.md +++ b/extensions/llm-helper/README.md @@ -107,6 +107,15 @@ token batches as they are produced. Any other `params` key is a 400 that names the supported ones. The current Claude models take no sampling parameters (`temperature`, `top_p`, `top_k`), so none is forwarded. +**A number is read the same way by both packs.** A whole number - `params.max_tokens`, +`params.timeout_ms`, a loop turn's `turn`, a page of `attachments` - is a JSON number with a whole +value (`16000`, or `16000.0`, which one runtime cannot tell from it) or a string of the ASCII digits +0 to 9 (`"16000"`), up to 9007199254740991, the largest whole number both runtimes hold exactly; a +whole-number key of the configuration is read as such a string. A duration is such a number of +seconds, or ASCII digits and one unit (`30m`, `12h`, `2d`). White space around it is ignored. +Anything else - a fraction, a sign, an underscore, the digits of another script - is a 400 that +names the field or the key. + **`llm.chat` reply** (a map): `text`, or `data` for a `schema` request; `model` (the model that answered); `stop_reason`; `usage {input_tokens, output_tokens}`; `request_id` when the API sent one; `stop_details {category, explanation}` when the model refused. @@ -281,7 +290,8 @@ or an image) or a conversion comes first (a word-processor file or a spreadsheet the agent tools turns into text; a PDF rendering of it is the other way). `sha256` is the hash the audit keeps, so an exchange can be checked against the file. The saved name is new on every upload (`-`), so nothing is overwritten and a reference stays valid for the audit's retention. -The files of one upload are bounded together by `rest.upload.max.bytes` (16 MiB; 413 beyond it), and the +The files and the text fields of one upload are bounded together, in bytes, by `rest.upload.max.bytes` +(16 MiB; 413 beyond it), and the upload is a 503 by name until `llm.attachments.root` is set. **The folder is readable through the model, and this entry writes into it:** in production put an authentication function in front of the entry (`authentication: 'my.auth'`) or the gateway, and give the folder a retention of its own. @@ -466,8 +476,8 @@ installation's, applied on read. | `llm.transcript.retention` | `0` | A loop turn's `retention` when the request carries none. | | `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). | | `llm.transcript.audit` | unset | `postgres`: record every model turn in the audit store (see The audit store). Unset, no audit. | -| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. | -| `llm.transcript.audit.grace` | `1d` | How long a closed working record waits for its integrity check before it expires unreleased. | +| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. A value that is not a duration stops the application at start, by name. | +| `llm.transcript.audit.grace` | `1d` | How long a closed working record waits for its integrity check before it expires unreleased. A value that is not a duration of a second or more stops the application at start, by name. | | `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. | | `llm.transcript.audit.single` | `false` | `true`: record a call without `tools` as a conversation of one turn (see The audit of a single call). Needs `llm.transcript.store`. | | `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` is `sslmode=require`, `false` `sslmode=disable`; `timeout.ms` bounds a connection attempt, a wait for the pool and, on the server, a statement (`statement_timeout`). | @@ -551,7 +561,9 @@ by reference; it still decides nothing about control flow. `tests/test_llm_helper.py` runs the shared `tests/vectors/llm-helper-vectors.json` against a fake of the SDK (68 cases: request validation, the exact SDK call, replies, the error contract, streaming, -the shape of a Bedrock call on either surface) and the shared `tests/vectors/llm-loop-vectors.json` (66 cases of +the shape of a Bedrock call on either surface; and 98 values under `numbers`, each read as a whole +number, as a duration and as the pages of a PDF, with the one answer both packs give) and the shared +`tests/vectors/llm-loop-vectors.json` (66 cases of one or more turns: the loop fields, the exact SDK call of each turn with the transcript sent back, the reply, and the stored record after each step), the loop cases once on the memory store and again on a Redis fake that runs the store's Lua. Then come the tests a vector cannot express (token batches are never held back, no prompt or tool text @@ -560,7 +572,8 @@ region and credential checks, the stored blocks as the SDK sends them back, the compare-and-set and connection settings). No token is spent and no credential is needed. `tests/test_transcript_audit.py` pins the audit store: record version 2 and the facts a turn saves, the two events behind a turn and the grace, the function driven through its mailbox (a write that fails, the check that repairs it -before the release, an open record only filled), the sweep, the audited mark on Redis, and the PostgreSQL store on a +before the release, an open record only filled), the sweep, the start that a malformed grace or retention stops, +the audited mark on Redis, and the PostgreSQL store on a recording fake of the pool that pins every statement and its parameters; the loop vector file gains no case, because the audit is a side effect of a turn, not part of the loop contract. The audit of a single call has a shared file of its own, `tests/vectors/llm-audit-vectors.json` (25 cases: the two rows a call without `tools` leaves on either route, diff --git a/extensions/llm-helper/llm_helper.py b/extensions/llm-helper/llm_helper.py index ee0db32..e807d51 100644 --- a/extensions/llm-helper/llm_helper.py +++ b/extensions/llm-helper/llm_helper.py @@ -118,6 +118,19 @@ # session" without "AWS"); matched without case on the words both carry AWS_CREDENTIAL_RUNTIME_ERROR = ("could not resolve", "credentials from session") +# --- how a number is read: the same in both packs ------------------------------------------- +# the largest whole number both packs hold exactly (2**53 - 1): above it the Node.js twin's +# numbers round, and the twins would read two different numbers from one request +MAX_WHOLE = 9007199254740991 +# the white space ignored around a number, and anywhere in pages: the characters Python's +# str.strip() and JavaScript's trim() both take for white space, so neither pack accepts a +# character the other refuses +_SPACE = r"[\t-\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" +_SPACES = re.compile(f"{_SPACE}+") +# the digits 0 to 9 and no other, by flag: Python's own \d takes the digits of every script, the +# Node.js twin's these ten - the patterns of a duration and of pages ask for them the same way +WHOLE = re.compile(rf"{_SPACE}*(\d+){_SPACE}*", re.ASCII) + # --- the loop contract's defaults and limits (RFC-0011) ----------------------------------- # a request that carries tools is one turn of an agent loop; the other loop fields need tools LOOP_FIELDS = ("conversation", "turn", "results", "ttl", "retention") @@ -127,7 +140,7 @@ # loop's catalog to an API-safe name, never advertised TOOL_NAME = re.compile(r"[a-zA-Z0-9_-]{1,128}") CONVERSATION_ID = re.compile(r"[0-9a-f]{32}") -DURATION = re.compile(r"(\d+)([smhd]?)") +DURATION = re.compile(rf"{_SPACE}*(\d+)([smhd]?){_SPACE}*", re.ASCII) DURATION_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400} DEFAULT_TRANSCRIPT_TTL = "7d" DEFAULT_TRANSCRIPT_RETENTION = "0" @@ -162,7 +175,7 @@ DEFAULT_ATTACHMENTS_MAX_COUNT = 20 DEFAULT_ATTACHMENTS_MAX_BYTES = 20 * 1024 * 1024 ATTACHMENT_KEYS = ("path", "pages") -PAGES = re.compile(r"\d+(-\d+)?(,\d+(-\d+)?)*") +PAGES = re.compile(r"\d+(-\d+)?(,\d+(-\d+)?)*", re.ASCII) PDF_MEDIA_TYPE = "application/pdf" # an image's limit as the provider counts it, base64-encoded: by the route to the models IMAGE_MAX_ENCODED = 10 * 1024 * 1024 @@ -239,14 +252,37 @@ class LlmRequest: attachments: tuple[Attachment, ...] = () # llm.chat only, never a loop turn +def _number_text(value: Any) -> str | None: + """What a number is read from: a string as written, or the digits of a JSON number with a + whole value - an integer, or a float, which the Node.js twin cannot tell from one. None for + anything else: a boolean, a fraction, a number beyond MAX_WHOLE.""" + if isinstance(value, str): + return value + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_WHOLE: + return None + return str(value) + + +def _whole(digits: str) -> int | None: + """The whole number a run of ASCII digits spells, or None above MAX_WHOLE - told by the + count of its digits first, so a run of any length is judged without being converted.""" + significant = digits.lstrip("0") + if len(significant) > len(str(MAX_WHOLE)): + return None + number = int(significant or "0") + return number if number <= MAX_WHOLE else None + + def _whole_number(name: str, value: Any, minimum: int) -> int: """A whole number from a JSON number or a config string, or a 400 naming the field.""" - valid = (isinstance(value, int) and not isinstance(value, bool)) or ( - isinstance(value, str) and value.strip().isdigit() - ) - if not valid or int(value) < minimum: + text = _number_text(value) + match = WHOLE.fullmatch(text) if text is not None else None + number = _whole(match.group(1)) if match else None + if number is None or number < minimum: raise AppException(400, f"{name} must be a whole number >= {minimum}") - return int(value) + return number def _setting(params: dict[str, Any], key: str, config_key: str, default: str) -> Any: @@ -336,9 +372,9 @@ def _pages(index: int, raw: Any) -> tuple[tuple[tuple[int, int], ...], str]: """The pages of a PDF to send, as ranges in the order named, with the text as written. A mapping may carry a page number as a number. Whether a page exists is the document's to say, when it is read.""" - text = "".join(raw.split()) if isinstance(raw, str) else None - if isinstance(raw, int) and not isinstance(raw, bool): - text = str(raw) + text = _number_text(raw) + if text is not None: + text = _SPACES.sub("", text) malformed = AppException( 400, f"attachments[{index}].pages must name pages from 1, such as 13 or 1-3,7" ) @@ -347,8 +383,8 @@ def _pages(index: int, raw: Any) -> tuple[tuple[tuple[int, int], ...], str]: ranges: list[tuple[int, int]] = [] for part in text.split(","): first, _, last = part.partition("-") - low, high = int(first), int(last or first) - if low < 1 or high < low: + low, high = _whole(first), _whole(last or first) + if low is None or high is None or low < 1 or high < low: raise malformed if any(low <= held_high and held_low <= high for held_low, held_high in ranges): raise AppException(400, f"attachments[{index}].pages names a page twice") @@ -562,12 +598,11 @@ def _results(raw: Any) -> list[dict[str, Any]] | None: def _duration(name: str, value: Any, minimum: int) -> int: """Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it.""" - text = value.strip() if isinstance(value, str) else None - if isinstance(value, int) and not isinstance(value, bool): - text = str(value) + text = _number_text(value) match = DURATION.fullmatch(text) if text is not None else None - seconds = int(match.group(1)) * DURATION_SECONDS[match.group(2)] if match else -1 - if seconds < minimum: + count = _whole(match.group(1)) if match else None + seconds = -1 if match is None or count is None else count * DURATION_SECONDS[match.group(2)] + if not minimum <= seconds <= MAX_WHOLE: raise AppException( 400, f"{name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= {minimum}", @@ -2316,13 +2351,17 @@ async def _sweep_forever(interval_ms: int) -> None: async def audit_boot() -> None: """Start the audit when llm.transcript.audit is configured: register transcript.audit with one - instance, open the store and start the sweep. A driver that is not installed stops the - application by name (a deployment error); a database that does not answer is logged, and the - sweep repairs what the outage defers.""" + instance, open the store and start the sweep. A driver that is not installed, and a grace or + a retention that is not a duration, stops the application by name (a deployment error); a + database that does not answer is logged, and the sweep repairs what the outage defers.""" global _sweep_task if not audit_configured(): return try: + # read here, not first on a turn's save or in the audit function, where a malformed one + # would surface after the model was called + _audit_grace_s() + _audit_retention_s() audit = get_audit_store() except AppException as exc: log.error("transcript audit store cannot start - %s", exc.message) diff --git a/tests/test_llm_helper.py b/tests/test_llm_helper.py index 16ef985..1678112 100644 --- a/tests/test_llm_helper.py +++ b/tests/test_llm_helper.py @@ -36,7 +36,7 @@ _HELPER = _TESTS.parent / "extensions" / "llm-helper" / "llm_helper.py" _VECTORS = _TESTS / "vectors" / "llm-helper-vectors.json" # the Node.js twin pins the same digest: change the file in both packs or in neither -_VECTORS_SHA256 = "7bfffbf36c52488c246f250f36afc4e8012f119fd56c93e9de1cbe93bf5988b6" +_VECTORS_SHA256 = "eff1bfef426d6ac815f9a14ffc8de962eeac1894cbef0015b517b61c42b20b78" _spec = importlib.util.spec_from_file_location("llm_helper_under_test", _HELPER) assert _spec is not None @@ -426,6 +426,143 @@ async def test_loop_contract_on_the_redis_store( await _run_loop_case(case, monkeypatch, "redis") +# --- the shared contract: how a number is read ---------------------------------------------- +# +# llm-helper-vectors.json carries one list of values under "numbers", and for each what it +# spells as a whole number, as a duration and as the pages of a PDF. Both packs must give the +# same answer for every value: the number, or the one refusal of the field. + +NUMBERS: dict[str, Any] = VECTORS["numbers"] +NUMBER_PROBES: list[dict[str, Any]] = NUMBERS["probes"] +_NUMBER_IDS = [probe["name"] for probe in NUMBER_PROBES] +_ABSENT = "absent" # what a null spells: a field left out +_MISSING: Any = object() # the field left out of the request +_REPLY = { + "kind": "message", "model": "claude-opus-5-5", "stop_reason": "end_turn", + "deltas": ["ok"], "usage": {"input_tokens": 1, "output_tokens": 1}, +} # fmt: skip + + +def _refusal(kind: str, name: str, minimum: int) -> list[Any]: + """The one refusal of a field: a 400 and the kind's shared text, naming the field.""" + return [400, NUMBERS["refusals"][kind].format(name=name, minimum=minimum)] + + +def _spelled(wanted: Any, minimum: int, refusal: list[Any]) -> Any: + """What a field answers a probe with: the number the value spells, or the field's refusal + for a value that spells none and for a number below the field's minimum.""" + return refusal if wanted is None or wanted < minimum else wanted + + +def _exactly(answer: Any) -> str: + """An answer as JSON, which tells a whole number from a float and from a boolean.""" + return json.dumps(answer) + + +async def _max_tokens(monkeypatch: pytest.MonkeyPatch, value: Any) -> Any: + """params.max_tokens as the SDK call carries it, or the refusal - then with no call.""" + client = _FakeClient(_REPLY) + _install_backend(monkeypatch, client) + params = {} if value is _MISSING else {"max_tokens": value} + try: + await helper.llm_chat({}, {"prompt": "x", "params": params}) + except AppException as exc: + assert client.ledger.calls == [], "a refused request must not reach the provider" + return [exc.status, exc.message] + return client.ledger.calls[0][1]["max_tokens"] + + +async def _max_retries(monkeypatch: pytest.MonkeyPatch, value: str) -> Any: + """The setting llm.max.retries as the SDK call's options carry it, or the refusal.""" + client = _FakeClient(_REPLY) + _install_backend(monkeypatch, client, {"llm.max.retries": value}) + try: + await helper.llm_chat({}, {"prompt": "x"}) + except AppException as exc: + assert client.ledger.calls == [], "a refused request must not reach the provider" + return [exc.status, exc.message] + return client.ledger.options[0]["max_retries"] + + +async def _duration_turn(monkeypatch: pytest.MonkeyPatch, field: str, value: Any) -> Any: + """A first loop turn that carries the duration: what the stored record then holds - the + seconds it lives for ttl, its retention for retention - or the refusal, then with no call + and no record.""" + store = helper.MemoryStore(lambda: 0) # a clock at zero: the expiry is the seconds to live + monkeypatch.setattr(helper, "_store", store) + client = _FakeClient(_TURN) + _install_backend(monkeypatch, client, _LOOP_CONFIG) + body = {"prompt": "x", "tools": [_TOOL]} | ({} if value is _MISSING else {field: value}) + try: + reply = await helper.llm_chat({}, body) + except AppException as exc: + assert client.ledger.calls == [], "a refused turn must not reach the provider" + assert store._records == {}, "a refused turn stores nothing" + return [exc.status, exc.message] + expiry, _turn, record, _audited = store._records[reply["conversation"]] + return expiry if field == "ttl" else helper.Transcript.from_json(record).retention + + +def _pages_read(monkeypatch: pytest.MonkeyPatch, value: Any) -> Any: + """attachments[0].pages as the request check reads it: the ranges, None for the whole + document, or the refusal.""" + monkeypatch.setattr(helper, "_prop", lambda _key, default=None: default) + entry = {"path": "form.pdf"} if value is _MISSING else {"path": "form.pdf", "pages": value} + try: + request = helper.prepare({"prompt": "x", "attachments": [entry]}, streaming=False) + except AppException as exc: + return [exc.status, exc.message] + pages = request.attachments[0].pages + return None if pages is None else [list(pair) for pair in pages] + + +@pytest.mark.parametrize("probe", NUMBER_PROBES, ids=_NUMBER_IDS) +async def test_a_whole_number_is_read_as_the_node_twin_reads_it( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """params.max_tokens (minimum 1) and, for a string, the setting llm.max.retries (minimum 0).""" + value, wanted = probe["value"], probe["whole"] + answer = await _max_tokens(monkeypatch, value) + if wanted == _ABSENT: + assert _exactly(answer) == _exactly(await _max_tokens(monkeypatch, _MISSING)) + return + refused = _refusal("whole", "params.max_tokens", 1) + assert _exactly(answer) == _exactly(_spelled(wanted, 1, refused)) + if isinstance(value, str): + refused = _refusal("whole", "llm.max.retries", 0) + setting = await _max_retries(monkeypatch, value) + assert _exactly(setting) == _exactly(_spelled(wanted, 0, refused)) + + +@pytest.mark.parametrize("probe", NUMBER_PROBES, ids=_NUMBER_IDS) +@pytest.mark.parametrize(("field", "minimum"), [("ttl", 1), ("retention", 0)]) +async def test_a_duration_is_read_as_the_node_twin_reads_it( + field: str, minimum: int, probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The ttl (minimum 1) and the retention (minimum 0) of a first loop turn.""" + wanted = probe["duration"] + answer = await _duration_turn(monkeypatch, field, probe["value"]) + if wanted == _ABSENT: + assert _exactly(answer) == _exactly(await _duration_turn(monkeypatch, field, _MISSING)) + return + refused = _refusal("duration", field, minimum) + assert _exactly(answer) == _exactly(_spelled(wanted, minimum, refused)) + + +@pytest.mark.parametrize("probe", NUMBER_PROBES, ids=_NUMBER_IDS) +def test_pages_are_read_as_the_node_twin_reads_them( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """attachments[0].pages, whose shape the request check decides before any file is read.""" + wanted = probe["pages"] + answer = _pages_read(monkeypatch, probe["value"]) + if wanted == _ABSENT: + assert _exactly(answer) == _exactly(_pages_read(monkeypatch, _MISSING)) + return + refused = _refusal("pages", "attachments[0].pages", 1) + assert _exactly(answer) == _exactly(refused if wanted is None else wanted) + + # --- the loop turn: what a vector cannot pin ----------------------------------------------- diff --git a/tests/test_transcript_audit.py b/tests/test_transcript_audit.py index 964e403..673284e 100644 --- a/tests/test_transcript_audit.py +++ b/tests/test_transcript_audit.py @@ -836,6 +836,39 @@ async def test_a_configured_driver_that_is_not_installed_stops_the_application_b assert "mercury-composable[postgres]" in caplog.text +_NOT_A_DURATION = "must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d)" + + +@pytest.mark.parametrize( + ("key", "value", "minimum"), + [ + ("llm.transcript.audit.grace", "x", 1), + ("llm.transcript.audit.grace", "0", 1), + ("llm.transcript.audit.grace", "\u0663h", 1), + ("llm.transcript.audit.retention", "forever", 0), + ("llm.transcript.audit.retention", "-1d", 0), + ], +) +async def test_an_audit_duration_that_is_malformed_stops_the_application_by_name( + key: str, value: str, minimum: int, monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: # fmt: skip + """The grace and the retention are read when the helper starts, like the audit's other + settings: a malformed one stops the start before the store is opened or the sweep started - + it never surfaces on a turn's save, after the model was called.""" + pool = _FakePool() + monkeypatch.setattr(helper, "_audit", helper.PostgresAuditStore(pool)) + monkeypatch.setattr(helper, "_sweep_task", None) + _configure(monkeypatch, **{key: value}) + caplog.set_level(logging.ERROR) + with pytest.raises(SystemExit): + await helper.audit_boot() + refused = f"{key} {_NOT_A_DURATION} >= {minimum}" + assert f"transcript audit store cannot start - {refused}" in caplog.text + assert pool.opened is None + assert helper._sweep_task is None + + async def test_the_boot_does_nothing_without_an_audit_store(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(helper, "_sweep_task", None) monkeypatch.setattr(helper, "_prop", lambda _key, default=None: default) diff --git a/tests/vectors/llm-helper-vectors.json b/tests/vectors/llm-helper-vectors.json index 47fc4ad..a29f1e9 100644 --- a/tests/vectors/llm-helper-vectors.json +++ b/tests/vectors/llm-helper-vectors.json @@ -1,7 +1,7 @@ { "contract": "llm-helper", "version": 1, - "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream.", + "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream. numbers states how a number is read, the same in both packs: its own description gives the rule and what the harness checks.", "provider_kinds": { "message": "succeeds: deltas are the token batches; text is the final message text (default: the deltas joined); usage, model, stop_reason, request_id (the request-id response header), stop_details", "status": "an HTTP error from the API: status, type, message, request_id; after = the number of deltas delivered before it is raised (0: at open), deltas = those batches", @@ -10,6 +10,823 @@ "credential": "the SDK found no credential (it raises a bare TypeError before sending anything)", "hang": "never answers - the helper's own deadline must fire" }, + "numbers": { + "description": "How a number is read, the same in both packs: one list of values, each read as a whole number, as a duration and as the pages of a PDF. whole is the whole number the value spells, duration the seconds it spells, pages the ranges [first, last] it names, in the order named; null where it spells none, and \"absent\" for a null, which is a field left out. The rule: a whole number is a JSON number with a whole value (16000, or 16000.0, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9, up to 9007199254740991, the largest whole number both runtimes hold exactly; a duration is such a number of seconds, or ASCII digits and one of s, m, h, d, up to that many seconds; pages are numbers from 1 and ranges of them, joined by commas. The white space both runtimes' own trim takes (tab to carriage return, space, no-break space and the other space separators, the line and paragraph separators) is ignored around a whole number and a duration and anywhere in pages; any other character spells nothing - a sign, an underscore, a point, a digit of another script, a byte order mark. The harness reads each value as params.max_tokens (minimum 1) of llm.chat and, when it is a string, as the setting llm.max.retries (minimum 0): the SDK call carries the number, or the request is refused before any provider call. It reads it as the ttl (minimum 1) and as the retention (minimum 0) of a first loop turn on the memory store: the stored record lives that many seconds, or carries that retention, or the turn is refused before any provider call and no record is stored. It reads it as attachments[0].pages through the request check, which decides the shape before any file is read. A field refuses a number below its minimum as it refuses a value that spells none: status 400 and the text of refusals for its kind, {name} being the field and {minimum} its minimum.", + "refusals": { + "whole": "{name} must be a whole number >= {minimum}", + "duration": "{name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= {minimum}", + "pages": "{name} must name pages from 1, such as 13 or 1-3,7" + }, + "probes": [ + { + "name": "ascii-digits", + "value": "512", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "a-single-digit", + "value": "1", + "whole": 1, + "duration": 1, + "pages": [ + [ + 1, + 1 + ] + ] + }, + { + "name": "zero-as-text", + "value": "0", + "whole": 0, + "duration": 0, + "pages": null + }, + { + "name": "leading-zeros", + "value": "007", + "whole": 7, + "duration": 7, + "pages": [ + [ + 7, + 7 + ] + ] + }, + { + "name": "forty-leading-zeros", + "value": "00000000000000000000000000000000000000001", + "whole": 1, + "duration": 1, + "pages": [ + [ + 1, + 1 + ] + ] + }, + { + "name": "spaces-around", + "value": " 512 ", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "a-tab-and-a-newline-around", + "value": "\t512\n", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "no-break-spaces-around", + "value": "\u00a0512\u00a0", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "an-ideographic-space-before", + "value": "\u3000512", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "a-line-separator-before", + "value": "\u2028512", + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "a-space-inside", + "value": "5 12", + "whole": null, + "duration": null, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "a-byte-order-mark-before", + "value": "\ufeff512", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-byte-order-mark-after", + "value": "512\ufeff", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-next-line-character-after", + "value": "512\u0085", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-file-separator-before", + "value": "\u001c512", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-unit-separator-after", + "value": "512\u001f", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-zero-width-space-before", + "value": "\u200b512", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "empty-text", + "value": "", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "blank-text", + "value": " ", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-plus-sign", + "value": "+5", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-minus-sign", + "value": "-5", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-underscore", + "value": "5_0", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-point-in-text", + "value": "5.0", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-exponent-in-text", + "value": "5e2", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "hexadecimal-text", + "value": "0x10", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-word", + "value": "five", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-arabic-indic-digit", + "value": "\u0663", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "arabic-indic-digits", + "value": "\u0665\u0661\u0662", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "ascii-then-arabic-indic", + "value": "5\u0663", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "fullwidth-digits", + "value": "\uff15\uff11\uff12", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-devanagari-digit", + "value": "\u096b", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-mathematical-bold-digit", + "value": "\ud835\udfd3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "superscript-two", + "value": "\u00b2", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "ascii-then-superscript", + "value": "5\u00b2", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "subscript-two", + "value": "\u2082", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-circled-digit", + "value": "\u2460", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-vulgar-fraction", + "value": "\u00bd", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-roman-numeral", + "value": "\u2167", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-ideographic-number", + "value": "\u4e94", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "the-largest-whole-number-as-text", + "value": "9007199254740991", + "whole": 9007199254740991, + "duration": 9007199254740991, + "pages": [ + [ + 9007199254740991, + 9007199254740991 + ] + ] + }, + { + "name": "one-above-the-largest-as-text", + "value": "9007199254740992", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "twenty-nines", + "value": "99999999999999999999", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "four-hundred-nines", + "value": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "five-thousand-nines", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-number", + "value": 512, + "whole": 512, + "duration": 512, + "pages": [ + [ + 512, + 512 + ] + ] + }, + { + "name": "zero", + "value": 0, + "whole": 0, + "duration": 0, + "pages": null + }, + { + "name": "a-negative-number", + "value": -5, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "the-largest-whole-number", + "value": 9007199254740991, + "whole": 9007199254740991, + "duration": 9007199254740991, + "pages": [ + [ + 9007199254740991, + 9007199254740991 + ] + ] + }, + { + "name": "one-above-the-largest", + "value": 9007199254740992, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-number-of-twenty-nines", + "value": 99999999999999999999, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-float-with-a-whole-value", + "value": 16000.0, + "whole": 16000, + "duration": 16000, + "pages": [ + [ + 16000, + 16000 + ] + ] + }, + { + "name": "float-zero", + "value": 0.0, + "whole": 0, + "duration": 0, + "pages": null + }, + { + "name": "negative-zero", + "value": -0.0, + "whole": 0, + "duration": 0, + "pages": null + }, + { + "name": "a-negative-float-with-a-whole-value", + "value": -1.0, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-float-with-a-fraction", + "value": 2.5, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-float-just-above-a-whole-value", + "value": 5.000000000000001, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "the-largest-whole-number-as-a-float", + "value": 9007199254740991.0, + "whole": 9007199254740991, + "duration": 9007199254740991, + "pages": [ + [ + 9007199254740991, + 9007199254740991 + ] + ] + }, + { + "name": "a-float-above-the-largest", + "value": 1e+16, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-huge-float", + "value": 1e+300, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "true", + "value": true, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "false", + "value": false, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "null", + "value": null, + "whole": "absent", + "duration": "absent", + "pages": "absent" + }, + { + "name": "a-list", + "value": [ + 5 + ], + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-map", + "value": { + "value": 5 + }, + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "minutes", + "value": "30m", + "whole": null, + "duration": 1800, + "pages": null + }, + { + "name": "hours", + "value": "12h", + "whole": null, + "duration": 43200, + "pages": null + }, + { + "name": "days", + "value": "2d", + "whole": null, + "duration": 172800, + "pages": null + }, + { + "name": "seconds", + "value": "45s", + "whole": null, + "duration": 45, + "pages": null + }, + { + "name": "zero-days", + "value": "0d", + "whole": null, + "duration": 0, + "pages": null + }, + { + "name": "spaces-around-a-duration", + "value": " 2d ", + "whole": null, + "duration": 172800, + "pages": null + }, + { + "name": "a-space-before-the-unit", + "value": "2 d", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-upper-case-unit", + "value": "2D", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-unknown-unit", + "value": "2w", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "two-units", + "value": "1d12h", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-fraction-of-an-hour", + "value": "1.5h", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-unit-alone", + "value": "d", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "arabic-indic-hours", + "value": "\u0663h", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "fullwidth-hours", + "value": "\uff11\uff12h", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-fullwidth-unit", + "value": "2\uff44", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-byte-order-mark-before-a-duration", + "value": "\ufeff2d", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-next-line-character-after-a-duration", + "value": "2d\u0085", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "the-most-days", + "value": "104249991374d", + "whole": null, + "duration": 9007199254713600, + "pages": null + }, + { + "name": "one-day-more", + "value": "104249991375d", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "twenty-nines-of-days", + "value": "99999999999999999999d", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-range-of-pages", + "value": "1-3", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 3 + ] + ] + }, + { + "name": "pages-and-ranges", + "value": "1-3,7", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 3 + ], + [ + 7, + 7 + ] + ] + }, + { + "name": "pages-in-the-order-named", + "value": "7,1-3", + "whole": null, + "duration": null, + "pages": [ + [ + 7, + 7 + ], + [ + 1, + 3 + ] + ] + }, + { + "name": "pages-with-spaces", + "value": " 2 - 3 , 1 ", + "whole": null, + "duration": null, + "pages": [ + [ + 2, + 3 + ], + [ + 1, + 1 + ] + ] + }, + { + "name": "pages-with-no-break-spaces", + "value": "1\u00a0-\u00a03", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 3 + ] + ] + }, + { + "name": "pages-with-a-byte-order-mark", + "value": "1\ufeff-3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "pages-with-a-next-line-character", + "value": "1\u0085-3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-arabic-indic-page", + "value": "1-\u0663", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "fullwidth-pages", + "value": "\uff11-\uff13", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-fullwidth-hyphen", + "value": "1\uff0d3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "an-en-dash", + "value": "1\u20133", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-range-from-page-zero", + "value": "0-3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-range-to-the-largest-page", + "value": "1-9007199254740991", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 9007199254740991 + ] + ] + }, + { + "name": "a-range-beyond-the-largest-page", + "value": "1-9007199254740992", + "whole": null, + "duration": null, + "pages": null + } + ] + }, "cases": [ { "name": "prep/missing-prompt-and-messages", From 49f5b90c3da0b5681c1a9283d36446b0777fee4d Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:24 -0800 Subject: [PATCH 2/5] fix(ask-person, agent-question): one rule for a well-formed ticket, and one for a row id and a stream cursor ask-person: the packs answered a mangled ticket differently, and this one verified a part that ended in a newline (its pattern matched with `$`). One rule now: three non-empty parts; the payload and the signature canonical unpadded base64url from start to end - the alphabet, and the text equal to its own decoding encoded again; the signature exactly the 32 bytes of the MAC. A ticket that is not well-formed is 400 `Ticket is malformed`; a well-formed one whose MAC does not verify is 403 `Ticket signature is invalid`, compared in constant time as before. A second spelling of a valid ticket, which differs only in the unused bits of a last character, was accepted by both packs and is a 400 now. agent-question: a row id and `Last-Event-ID` went through int() here (" 7 ", -3, +7 and 1_0 passed), while the Node twin took 1.0, 1e3 and 0x10 as a `Last-Event-ID`. One rule: 1 to 19 ASCII digits from start to end, at most 9223372036854775807 - the BIGINT of the store's id; anything else is the 400 that was there. The cursor of a stream is `Last-Event-ID`, else `since`, else the start. The shared vectors pin both, byte-identical with the Node twin: ask-person-vectors.json version 3 (146 cases, 68 of them tickets to verify) and agent-question-vectors.json version 4 (111 cases, 40 row ids and 51 cursors). One existing ticket vector changed: the tampered signature now ends canonically and stays a 403, and its old spelling is the next case, a 400. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-question/README.md | 12 +- extensions/agent-question/agent_question.py | 41 +- extensions/ask-person/README.md | 6 +- extensions/ask-person/ask_person.py | 32 +- tests/test_agent_question.py | 71 ++- tests/test_ask_person.py | 38 +- tests/vectors/agent-question-vectors.json | 585 +++++++++++++++++- tests/vectors/ask-person-vectors.json | 651 +++++++++++++++++++- 8 files changed, 1406 insertions(+), 30 deletions(-) diff --git a/extensions/agent-question/README.md b/extensions/agent-question/README.md index 798108e..eb31219 100644 --- a/extensions/agent-question/README.md +++ b/extensions/agent-question/README.md @@ -29,6 +29,8 @@ application is one of those routes. It is a standalone application on the packag carries the change to every device. Every entry but the sign-in configuration names `question.identity` as its authentication function: it resolves who is at the UI once, by the configured mode, and the functions read `who` and `via` from the request's session map. An error is the engines' standard body, `{"status", "message", "type": "error"}`. + A row id and a stream's cursor - `Last-Event-ID`, else `since`, else the beginning - are one to nineteen ASCII digits + from start to end, no larger than the record's `BIGINT` columns hold (9223372036854775807); anything else is a 400. - **The feed** reads the record's change sequence: a poll every `question.poll` (1 s) and a wake-up from the intake or a click, whichever comes first. A wait is `open` until the engine accepts the decision (`answered`) or finds nothing waiting (`expired`); an advice has no state - whether a person has read it is the device's, kept by the UI. The @@ -106,8 +108,8 @@ flow as `decided_by` under its own bearer (`question.reply.token`, the reply end ## Tests `tests/test_agent_question.py` runs the shared vectors (`tests/vectors/agent-question-vectors.json`: the event the intake -accepts or refuses, the request the click sends, the pages the replay and the history read) and drives the app -in-process as the reader of the record: the intake waking the feed, the replay and the history pages and the stream, the -transcripts browsed, a decision forwarded to a fake reply endpoint and the row re-read as the recorder left it, the two -auth modes with the UI's configuration, the PostgreSQL reader's statements on a recording fake of the pool, and - gated -on `AGENT_QUESTION_TEST_URL` - the schemas and the rows on a live PostgreSQL. +accepts or refuses, the request the click sends, the pages the replay and the history read, the row id and the cursor a +request names) and drives the app in-process as the reader of the record: the intake waking the feed, the replay and the +history pages and the stream, the transcripts browsed, a decision forwarded to a fake reply endpoint and the row re-read +as the recorder left it, the two auth modes with the UI's configuration, the PostgreSQL reader's statements on a +recording fake of the pool, and - gated on `AGENT_QUESTION_TEST_URL` - the schemas and the rows on a live PostgreSQL. diff --git a/extensions/agent-question/agent_question.py b/extensions/agent-question/agent_question.py index c7555b5..7faa3de 100644 --- a/extensions/agent-question/agent_question.py +++ b/extensions/agent-question/agent_question.py @@ -110,6 +110,11 @@ TRANSCRIPTS_LIMIT = 50 TRANSCRIPTS_LIMIT_MAX = 200 CONVERSATION_ID = re.compile(r"^[0-9a-f]{32}$") +# a row id and a cursor are ASCII digits from start to end - int() alone also takes a sign, spaces, underscores and +# the digits of other scripts, as \d does without re.ASCII - no more of them than the largest number the record's +# BIGINT columns hold has, and no larger than it +RECORD_NUMBER = re.compile(r"^\d{1,19}$", re.ASCII) +RECORD_MAX = 2**63 - 1 # the media type of the click's request and of the JSON replies _APPLICATION_JSON = "application/json" @@ -368,6 +373,32 @@ def reply_request(link: str, ticket: str, decisions: Sequence[Mapping[str, Any]] return f"{base}/ask/reply", {"ticket": ticket, "decisions": [dict(d) for d in decisions], "decided_by": who} +def _record_number(text: str) -> int | None: + """A row id or a cursor as a request names it: one to nineteen ASCII digits from start to end, and no more + than the record's BIGINT columns hold - or None when the text is anything else.""" + if not RECORD_NUMBER.fullmatch(text): + return None + value = int(text) + return value if value <= RECORD_MAX else None + + +def row_id_of(text: str | None) -> int: + """The row a decision names in ``/questions/{id}/decide`` - or an AppException(400).""" + value = _record_number(text or "") + if value is None: + raise AppException(400, "the row id must be a whole number") + return value + + +def stream_cursor(last_event_id: str | None, since: str | None) -> int: + """Where a device's stream starts: the cursor its ``Last-Event-ID`` carries, else its ``since``, else the + beginning - or an AppException(400) when the one it gave is not a cursor.""" + value = _record_number(last_event_id or since or "0") + if value is None: + raise AppException(400, "Last-Event-ID must be a whole number") + return value + + def page_since(rows: Sequence[Row], since: int, limit: int) -> dict[str, Any]: """The replay's page: the rows whose sequence passed the cursor, oldest change first, and the cursor to continue from.""" @@ -1016,10 +1047,7 @@ async def question_events(_headers: dict[str, str], event: EventEnvelope) -> Non once, with a day's idle allowance; the rows since ``Last-Event-ID`` (or ``since``) and every later change follow from a task of their own, so the function's workers are never held by the devices.""" request = AsyncHttpRequest(event.body) - try: - since = int(request.header("last-event-id") or request.query_parameter("since") or "0") - except ValueError: - raise AppException(400, "Last-Event-ID must be a whole number") from None + since = stream_cursor(request.header("last-event-id"), request.query_parameter("since")) out = EventStreamWriter.from_request(event) out.first(200, "text/event-stream", ttl_seconds=STREAM_IDLE_SECONDS) out.write(None) # the head alone: the stream is open before the first row @@ -1125,10 +1153,7 @@ async def question_decide(_headers: dict[str, str], body: Body) -> Any: decisions = decision.get("decisions") if not isinstance(decisions, list) or not decisions or not all(isinstance(d, Mapping) for d in decisions): raise AppException(400, "decisions must be a non-empty list, one per waiting call") - try: - row_id = int(request.path_parameter("id") or "") - except ValueError: - raise AppException(400, "the row id must be a whole number") from None + row_id = row_id_of(request.path_parameter("id")) try: row = await reader().get(row_id) except Exception as exc: # noqa: BLE001 - a store that cannot be read is a 503 by type diff --git a/extensions/ask-person/README.md b/extensions/ask-person/README.md index 04b6537..a8560cb 100644 --- a/extensions/ask-person/README.md +++ b/extensions/ask-person/README.md @@ -107,7 +107,11 @@ padding. Opaque and clean - no question text, no business data, no person - and it with the key alone, so every channel works without a store. `ask.ticket.previous-key` verifies the tickets issued before a rotation. A ticket is accepted as many times as it is presented: single use is the engine's at-most-once resume, and the second presentation gets `nothing waiting`. An expired ticket (410) is refused without a call to the -engine; a malformed one or another version is a 400, one no key signs a 403. +engine; a malformed one or another version is a 400, one no key signs a 403. A ticket has one spelling: it is +well-formed only with its three parts, the payload and the signature each canonical base64url without padding - the +alphabet from start to end, no newline, no stray character, no bits left over in the last one - and the signature as +long as the MAC, so any other spelling is malformed whatever it resembles and a 403 is a well-formed ticket that no +key signs. ## The reply page and endpoint diff --git a/extensions/ask-person/ask_person.py b/extensions/ask-person/ask_person.py index 1fbebb2..2de2f88 100644 --- a/extensions/ask-person/ask_person.py +++ b/extensions/ask-person/ask_person.py @@ -415,6 +415,20 @@ def _b64u_decode(text: str) -> bytes: return base64.urlsafe_b64decode(padded.encode("ascii")) +def _part_bytes(text: str) -> bytes | None: + """The bytes of a ticket's payload or signature part, or None when the part is not canonical + base64url without padding: the alphabet from start to end, and the one spelling the encoder + gives its bytes - a part that ends in a newline, carries a character too many or leaves bits + over in its last character is refused, never read as the ticket it resembles.""" + if not BASE64URL.fullmatch(text): + return None + try: + data = _b64u_decode(text) + except ValueError: # base64's own error: a length no encoding has + return None + return data if _b64u(data) == text else None + + def canonical_json(value: Any) -> str: """The canonical JSON a ticket's payload is signed as: keys sorted, no spaces, Unicode kept - the same rule as the MCP binding's schema digest.""" @@ -425,6 +439,10 @@ def _mac(payload: bytes, key: bytes) -> bytes: return hmac.new(key, payload, hashlib.sha256).digest() +# an HMAC-SHA256 is 32 bytes: a signature part of another length is malformed, never compared +_MAC_BYTES = 32 + + def issue_ticket(payload: Mapping[str, Any], key: bytes) -> str: """``v1..``: the canonical payload and its HMAC-SHA256, both base64url without padding.""" @@ -457,20 +475,20 @@ def _payload_is_valid(payload: Any) -> bool: def verify_ticket(ticket: str, keys: Sequence[bytes], now: float) -> dict[str, Any]: """The payload of a ticket this process issued, or a TicketError: 400 when the ticket is - malformed or of another version, 403 when no key signs it, 410 when it has expired.""" + malformed or of another version, 403 when no key signs it, 410 when it has expired. A ticket + is well-formed when it has the three parts, its payload and its signature are canonical + base64url without padding and the signature is as long as the MAC; one that is not is + malformed whatever it resembles, so a 403 is a well-formed ticket that no key signs.""" parts = ticket.split(".") if len(parts) != 3 or not all(parts): raise TicketError(400, _TICKET_MALFORMED) version, encoded, signature = parts if version != TICKET_VERSION: raise TicketError(400, f"Ticket version {version} is not supported") - if not BASE64URL.match(encoded) or not BASE64URL.match(signature): + payload_bytes = _part_bytes(encoded) + mac = _part_bytes(signature) + if payload_bytes is None or mac is None or len(mac) != _MAC_BYTES: raise TicketError(400, _TICKET_MALFORMED) - try: - payload_bytes = _b64u_decode(encoded) - mac = _b64u_decode(signature) - except ValueError as exc: # base64's own error and a UnicodeEncodeError are both ValueErrors - raise TicketError(400, _TICKET_MALFORMED) from exc if not any(hmac.compare_digest(_mac(payload_bytes, key), mac) for key in keys): raise TicketError(403, "Ticket signature is invalid") try: diff --git a/tests/test_agent_question.py b/tests/test_agent_question.py index fdc7d0c..4c78192 100644 --- a/tests/test_agent_question.py +++ b/tests/test_agent_question.py @@ -1,7 +1,8 @@ """The agent-question app (extensions/agent-question/agent_question.py). The shared vectors first (tests/vectors/agent-question-vectors.json): the event the intake accepts or refuses, the -request the automated click sends, the pages the replay and the history read. Then the app in-process as the reader of +request the automated click sends, the pages the replay and the history read, and the row id and the cursor a +request names - digits the record holds, or the 400. Then the app in-process as the reader of the question record the main flow keeps: the intake waking the feed, the replay and the history pages and the stream over the host, the transcripts browsed, a decision forwarded to a fake reply endpoint under the app's bearer and the row re-read as the recorder left it, the two auth modes with the UI's configuration, the PostgreSQL reader's statements @@ -149,8 +150,8 @@ def _case(section: str, name: str) -> dict[str, Any]: def test_the_vector_file_is_the_shared_contract() -> None: assert VECTORS["contract"] == "agent-question" - assert VECTORS["version"] == 3 - for section in ("intake_cases", "click_cases", "feed_cases"): + assert VECTORS["version"] == 4 + for section in ("intake_cases", "click_cases", "feed_cases", "row_id_cases", "cursor_cases"): assert VECTORS[section], section @@ -208,6 +209,28 @@ async def test_feed_cases_page_the_rows_in_both_directions() -> None: assert await reader.latest() == max(s["seq"] for s in case["rows"]) +@pytest.mark.parametrize("name", _names("row_id_cases")) +def test_row_id_cases(name: str) -> None: + case = _case("row_id_cases", name) + if "row" in case: + assert str(aq.row_id_of(case["id"])) == case["row"] + else: + with pytest.raises(aq.AppException) as refused: + aq.row_id_of(case["id"]) + assert (refused.value.status, refused.value.message) == (case["status"], case["error"]) + + +@pytest.mark.parametrize("name", _names("cursor_cases")) +def test_cursor_cases(name: str) -> None: + case = _case("cursor_cases", name) + if "cursor" in case: + assert str(aq.stream_cursor(case["last_event_id"], case["since"])) == case["cursor"] + else: + with pytest.raises(aq.AppException) as refused: + aq.stream_cursor(case["last_event_id"], case["since"]) + assert (refused.value.status, refused.value.message) == (case["status"], case["error"]) + + # --- configuration and the fresh reader ------------------------------------------------------------ @@ -486,6 +509,48 @@ async def frame() -> list[str]: assert "whole number" in (await response.json())["message"] +async def test_a_decision_names_its_row_in_ascii_digits_the_record_holds( + configure: Callable[[dict[str, Any]], Any], host: str +) -> None: + configure(BASE) + put(advice_event(), 7, 1) + put(advice_event(correlation_id="case-10"), 10, 2) + body = {"decisions": [{"id": "toolu_01A", "approved": True}]} + largest = 2**63 - 1 + async with aiohttp.ClientSession() as http: + async with http.post(f"{host}/questions/007/decide", json=body) as response: + assert response.status == 409, "leading zeros are digits: row 7, which is an advice" + assert (await response.json())["message"] == "row 7 is an advice - nothing to decide" + # a sign, an underscore, a space, a newline, a fraction, a radix prefix, another script's seven, one past + # the largest number the column holds + for row_id in ("%2B7", "-7", "1_0", "%207", "7%0A", "7.0", "0x7", "%D9%A7", str(largest + 1)): + async with http.post(f"{host}/questions/{row_id}/decide", json=body) as response: + assert response.status == 400, row_id + assert (await response.json())["message"] == "the row id must be a whole number", row_id + async with http.post(f"{host}/questions/{largest}/decide", json=body) as response: + assert response.status == 404 + assert (await response.json())["message"] == f"row {largest} is not in the record" + + +async def test_a_stream_starts_at_a_cursor_in_ascii_digits_the_record_holds( + configure: Callable[[dict[str, Any]], Any], host: str +) -> None: + configure(BASE) + largest = 2**63 - 1 + async with aiohttp.ClientSession() as http: + for cursor in ("%2B1", "-1", "1_0", "%201", "1.0", "1e3", "0x10", "%D9%A1", str(largest + 1)): + async with http.get(f"{host}/questions/events?since={cursor}") as response: + assert response.status == 400, cursor + assert (await response.json())["message"] == "Last-Event-ID must be a whole number", cursor + for cursor in ("+1", "-1", "1_0", "1.0", "1e3", "0x10", str(largest + 1)): + async with http.get(f"{host}/questions/events", headers={"last-event-id": cursor}) as response: + assert response.status == 400, cursor + assert (await response.json())["message"] == "Last-Event-ID must be a whole number", cursor + async with http.get(f"{host}/questions/events", headers={"last-event-id": str(largest)}) as response: + assert response.status == 200, "the largest cursor the record holds opens a stream with nothing to replay" + assert response.content_type == "text/event-stream" + + async def test_the_ui_configuration_names_the_sign_in(configure: Callable[[dict[str, Any]], Any], host: str) -> None: configure(BASE) assert await get_json(f"{host}/questions/config") == (200, {"auth": "none", "title": "Agent questions"}) diff --git a/tests/test_ask_person.py b/tests/test_ask_person.py index 9d9241b..e5f8d22 100644 --- a/tests/test_ask_person.py +++ b/tests/test_ask_person.py @@ -100,7 +100,7 @@ def _case(section: str, name: str) -> dict[str, Any]: def test_the_vector_file_is_the_shared_contract() -> None: assert VECTORS["contract"] == "ask-person" - assert VECTORS["version"] == 2 + assert VECTORS["version"] == 3 for section in ("ticket_cases", "verify_cases", "message_cases", "readvice_cases", "reply_cases", "outcome_cases", "record_cases", "answer_cases", "transition_cases"): assert VECTORS[section], section @@ -241,6 +241,42 @@ def test_requested_at_defaults_to_now_and_the_expiry_follows_the_ttl() -> None: assert event["link"] == f"{REPLY_URL}/ask/{event['ticket']}" +_BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" + + +def _verifies(ticket: str, now: int) -> bool: + try: + ask.verify_ticket(ticket, [KEY.encode()], now) + except ask.TicketError: + return False + return True + + +def _respelled(part: str) -> list[str]: + """The texts one character away from a ticket part at its end: a character more, a character fewer, and + the last character replaced - among them every spelling a lenient decoder reads as the part itself.""" + more = [part + extra for extra in [*_BASE64URL, "=", "\n"]] + other = [part[:-1] + last for last in _BASE64URL if last != part[-1]] + return [*more, part[:-1], *other] + + +def test_a_ticket_has_one_spelling() -> None: + """For a payload part of every length base64url without padding can have, the ticket as issued verifies + and no other spelling of its payload or its signature does.""" + now = 1795089600 + lengths: set[int] = set() + for size in range(1, 13): + payload = {"g": "order-assistant", "c": "c" * size, "t": 2, "k": "approval", "e": now + 3600} + ticket = ask.issue_ticket(payload, KEY.encode()) + version, encoded, signature = ticket.split(".") + lengths.add(len(encoded) % 4) + assert ask.verify_ticket(ticket, [KEY.encode()], now) == payload + others = [f"{version}.{part}.{signature}" for part in _respelled(encoded)] + others += [f"{version}.{encoded}.{part}" for part in _respelled(signature)] + assert [other for other in others if _verifies(other, now)] == [], f"a correlation id of {size} characters" + assert lengths == {0, 2, 3} + + # --- configuration ---------------------------------------------------------------------------------- diff --git a/tests/vectors/agent-question-vectors.json b/tests/vectors/agent-question-vectors.json index fb4a22a..6196d47 100644 --- a/tests/vectors/agent-question-vectors.json +++ b/tests/vectors/agent-question-vectors.json @@ -1,7 +1,7 @@ { "contract": "agent-question", - "version": 3, - "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full.", + "version": 4, + "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full. Version 4 (the numbers a request names): row_id_cases pin the row a decision names in /questions/{id}/decide, and cursor_cases where a device's stream starts - its Last-Event-ID, else its since parameter, else the beginning. Each is one to nineteen ASCII digits from start to end and no larger than 9223372036854775807, the largest number the record's BIGINT id and seq columns hold; anything else is the exact 400. The number read is given as text, since a JSON number past 2^53 is not exact in every reader.", "intake_cases": [ { "name": "an approval", @@ -637,5 +637,586 @@ } ] } + ], + "row_id_cases": [ + { + "name": "digits", + "id": "7", + "row": "7" + }, + { + "name": "zero", + "id": "0", + "row": "0" + }, + { + "name": "leading zeros are digits", + "id": "007", + "row": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "id": "0000000000000000007", + "row": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "id": "9007199254740993", + "row": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "id": "9223372036854775807", + "row": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "id": "9223372036854775808", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "nineteen nines", + "id": "9999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "twenty digits", + "id": "00000000000000000007", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "four hundred digits", + "id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before and after", + "id": " 7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space after", + "id": "7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before", + "id": " 7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space alone", + "id": " ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a newline after", + "id": "7\n", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a tab before", + "id": "\t7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space between digits", + "id": "1 0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a minus sign", + "id": "-3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a plus sign", + "id": "+7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "minus zero", + "id": "-0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an underscore between digits", + "id": "1_0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a thousands separator", + "id": "1,000", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fraction", + "id": "1.0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a decimal point alone", + "id": "1.", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an exponent", + "id": "1e3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "id": "0x10", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a binary prefix", + "id": "0b11", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an octal prefix", + "id": "0o17", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a letter", + "id": "x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "digits then a letter", + "id": "7x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word NaN", + "id": "NaN", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word Infinity", + "id": "Infinity", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "id": "٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "id": "७", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "id": "7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "id": "𝟟", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "id": "²", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "id": "1٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an empty id", + "id": "", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "no id", + "id": null, + "status": 400, + "error": "the row id must be a whole number" + } + ], + "cursor_cases": [ + { + "name": "digits", + "last_event_id": "7", + "since": null, + "cursor": "7" + }, + { + "name": "zero", + "last_event_id": "0", + "since": null, + "cursor": "0" + }, + { + "name": "leading zeros are digits", + "last_event_id": "007", + "since": null, + "cursor": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "last_event_id": "0000000000000000007", + "since": null, + "cursor": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "last_event_id": "9007199254740993", + "since": null, + "cursor": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "last_event_id": "9223372036854775807", + "since": null, + "cursor": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "last_event_id": "9223372036854775808", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "nineteen nines", + "last_event_id": "9999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "twenty digits", + "last_event_id": "00000000000000000007", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "four hundred digits", + "last_event_id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before and after", + "last_event_id": " 7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space after", + "last_event_id": "7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before", + "last_event_id": " 7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space alone", + "last_event_id": " ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a newline after", + "last_event_id": "7\n", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a tab before", + "last_event_id": "\t7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space between digits", + "last_event_id": "1 0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a minus sign", + "last_event_id": "-3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a plus sign", + "last_event_id": "+7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "minus zero", + "last_event_id": "-0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an underscore between digits", + "last_event_id": "1_0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a thousands separator", + "last_event_id": "1,000", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fraction", + "last_event_id": "1.0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a decimal point alone", + "last_event_id": "1.", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an exponent", + "last_event_id": "1e3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "last_event_id": "0x10", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a binary prefix", + "last_event_id": "0b11", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an octal prefix", + "last_event_id": "0o17", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a letter", + "last_event_id": "x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "digits then a letter", + "last_event_id": "7x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word NaN", + "last_event_id": "NaN", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word Infinity", + "last_event_id": "Infinity", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "last_event_id": "٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "last_event_id": "७", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "last_event_id": "7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "last_event_id": "𝟟", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "last_event_id": "²", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "last_event_id": "1٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "no Last-Event-ID and no since: the beginning", + "last_event_id": null, + "since": null, + "cursor": "0" + }, + { + "name": "an empty Last-Event-ID is none", + "last_event_id": "", + "since": null, + "cursor": "0" + }, + { + "name": "since when there is no Last-Event-ID", + "last_event_id": null, + "since": "5", + "cursor": "5" + }, + { + "name": "since when the Last-Event-ID is empty", + "last_event_id": "", + "since": "5", + "cursor": "5" + }, + { + "name": "an empty since is none", + "last_event_id": null, + "since": "", + "cursor": "0" + }, + { + "name": "the Last-Event-ID wins over since", + "last_event_id": "7", + "since": "5", + "cursor": "7" + }, + { + "name": "a Last-Event-ID of zero wins over since", + "last_event_id": "0", + "since": "5", + "cursor": "0" + }, + { + "name": "a Last-Event-ID that is not a cursor is refused though since is one", + "last_event_id": "x", + "since": "5", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since that is not a cursor", + "last_event_id": null, + "since": "x", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a minus sign", + "last_event_id": null, + "since": "-3", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a fraction", + "last_event_id": null, + "since": "1.0", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since past the largest number", + "last_event_id": null, + "since": "9223372036854775808", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since of the largest number", + "last_event_id": null, + "since": "9223372036854775807", + "cursor": "9223372036854775807" + } ] } diff --git a/tests/vectors/ask-person-vectors.json b/tests/vectors/ask-person-vectors.json index f589540..0346e62 100644 --- a/tests/vectors/ask-person-vectors.json +++ b/tests/vectors/ask-person-vectors.json @@ -1,7 +1,7 @@ { "contract": "ask-person", - "version": 2, - "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from.", + "version": 3, + "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from. Version 3 (a ticket has one spelling): a ticket is well-formed only when it has the three parts and its payload and signature parts are canonical base64url without padding - the alphabet from start to end, and the one spelling the encoder gives the bytes - the signature as long as the MAC (32 bytes, 43 characters); a ticket that is not well-formed is the 400 whatever it resembles, and the 403 is a well-formed ticket that no key signs. ticket_cases gain a payload part of each length base64url without padding can have (4n characters, 4n+2 and 4n+3) and one that holds - and _; verify_cases gain the mangled tickets made from them - a newline, a character more or fewer, padding, the standard alphabet, bits left over in a last character, a part missing, empty or added, another version - each with the status it gets. One earlier case changed with the rule: the signature of 'a tampered signature' left bits over in its last character, so it is now tampered in canonical form (403) and its earlier ticket is the case after it (400).", "ticket_cases": [ { "name": "an approval's ticket", @@ -50,6 +50,42 @@ "e": 1795252324 }, "ticket": "v1.eyJjIjoiRmFsbC1Oci4gMTAwMiDigJMgUsO8Y2tlcnN0YXR0dW5nIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.8MSkDCfvRpvCkX7a6ZnFdfVdf9PRRmVIfmyY1CfxOKM" + }, + { + "name": "a payload part of 4n+2 characters", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-10020-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg" + }, + { + "name": "a payload part of 4n+3 characters", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-100200-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes" + }, + { + "name": "a payload part that holds - and _", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "Q3>Q2?", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoiUTM-UTI_IiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.2LiQLRopPATfnlsnqRn6KdQUuCLCTv5UzQGjbVFdlRI" } ], "verify_cases": [ @@ -114,10 +150,21 @@ "test-key-previous" ], "now": 1795089600, - "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqAB", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqAA", "status": 403, "message": "Ticket signature is invalid" }, + { + "name": "a tampered signature with bits left over in its last character", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqAB", + "status": 400, + "message": "Ticket is malformed" + }, { "name": "an expired ticket", "keys": [ @@ -223,6 +270,604 @@ "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", "status": 403, "message": "Ticket signature is invalid" + }, + { + "name": "a newline after the payload part (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9\n.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the payload part (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9A.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the payload part one character short (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the payload part two characters short (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOj.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "an = after the payload part (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9=.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a newline after the signature part (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI\n", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the signature part (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyIA", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part one character short (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqy", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a signature part of one character (payload part of 4n characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.A", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a ticket whose payload part is 4n+2 characters long", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "payload": { + "c": "order-10020-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "a newline after the payload part (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ\n.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the payload part (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQA.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 403, + "message": "Ticket signature is invalid" + }, + { + "name": "the payload part one character short (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0Ijoyf.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the payload part two characters short (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0Ijoy.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 403, + "message": "Ticket signature is invalid" + }, + { + "name": "the payload part padded with = (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ==.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "bits left over in the last character of the payload part (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfR.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a newline after the signature part (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg\n", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the signature part (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOgA", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part one character short (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf_TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTO", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a signature part of one character (payload part of 4n+2 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.A", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a ticket whose payload part is 4n+3 characters long", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "payload": { + "c": "order-100200-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "a newline after the payload part (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0\n.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the payload part (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0A.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 403, + "message": "Ticket signature is invalid" + }, + { + "name": "the payload part one character short (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the payload part two characters short (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6M.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the payload part padded with = (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0=.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "bits left over in the last character of the payload part (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn1.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a newline after the signature part (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhes\n", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "one more character after the signature part (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhesA", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part one character short (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.rlxfe_PgHeu_c2R82ZOs0YNuOXhH9pjDHnysvGAOhe", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a signature part of one character (payload part of 4n+3 characters)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.A", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a newline before the payload part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.\neyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a line break inside the payload part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVy\nLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a payload part of one character", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.e.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part two characters short", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZq", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part three characters short", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZ", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part padded with =", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI=", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "bits left over in the last character of the signature part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyJ", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a line break inside the signature part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brr\nvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a ticket whose payload part holds - and _", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoiUTM-UTI_IiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.2LiQLRopPATfnlsnqRn6KdQUuCLCTv5UzQGjbVFdlRI", + "payload": { + "c": "Q3>Q2?", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "the payload part in the standard alphabet (+ and / for - and _)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoiUTM+UTI/IiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.2LiQLRopPATfnlsnqRn6KdQUuCLCTv5UzQGjbVFdlRI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part in the standard alphabet (+ for -)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h+dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the signature part in the standard alphabet (/ for _)", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMjAtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.Q1JjEDf/TtZOiVNQHg090XGDDZZWlb79bzOtUrqbTOg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "an empty signature part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "an empty version part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": ".eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "no version part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "an extra part", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "a dot after the ticket", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI.", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "an empty ticket", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "the version in upper case", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "V1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket version V1 is not supported" + }, + { + "name": "a newline after the version", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1\n.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket version v1\n is not supported" + }, + { + "name": "a space before the ticket", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": " v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "status": 400, + "message": "Ticket version v1 is not supported" + }, + { + "name": "another version, whatever its parts", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v2.%%%.###", + "status": 400, + "message": "Ticket version v2 is not supported" } ], "message_cases": [ From 91616e92a01d77a159ea2dbd58b5f72b5f679f63 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:25 -0800 Subject: [PATCH 3/5] fix(rest): rest.yaml flags as the Java engine reads them, the upload bound in bytes, the engines' error body where the host answered its own - A flag of an entry - tracing, stream, upload - was on only for the YAML boolean, so `tracing: "true"` and `tracing: ${TRACING:true}` stayed off without a word. It is read as the Java engine reads it: the boolean or the text `true` in any letter case turns it on; `false`, no value and an empty one leave it off. Any other value, which the engine reads as off silently, fails the load by name: `rest[N] 'tracing' must be true or false`. - The upload bound counted a text field by the length of its text. It counts the bytes of every part as they arrive, and a field is read in chunks, so the 413 comes the moment the total passes. - A keep-alive comment is written only when a keep-alive interval has passed. The Node twin wrote it on a stream that is not Server-Sent Events when the idle timer fired a moment early; the same fall-through is guarded here, on the REST edge and on the Event API. - A reply the serializer refuses was the web framework's own 500 page, with no trace record. It is the engines' error body, 500 `Reply cannot be rendered`, with the edge's http.request record; a streamed segment fails the stream in band. The serializer's reason goes to the log. - A body over the 16 MiB the host reads into memory was the web framework's text/plain 413. Behind REST automation it is the engines' error body, `Request body exceeds 16777216 bytes`; on the Event API's own handler it is a 413 envelope, as its other transport failures are. - A part of an upload that is multipart itself failed the upload or was dropped, by its place in the body. It is refused: 400 `Upload takes text fields and files, not a nested multipart part`. rest-automation-vectors.json is version 3 (14 load cases for the flags), byte-identical with the Node twin and pinned by digest here as it is there. The guides, the configuration reference and the README follow. Co-Authored-By: Claude Fable 5.2 --- README.md | 3 +- docs/guides/configuration-reference.md | 2 +- docs/guides/http-surface-reference.md | 8 +- docs/guides/rest-automation.md | 29 ++- src/mercury_composable/rest_automation.py | 126 ++++++--- src/mercury_composable/rest_routing.py | 23 +- src/mercury_composable/server.py | 26 +- tests/test_event_stream.py | 91 ++++++- tests/test_rest_automation.py | 287 +++++++++++++++++++++ tests/test_server.py | 15 ++ tests/vectors/rest-automation-vectors.json | 183 ++++++++++++- 11 files changed, 731 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 4767737..014ae2d 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,8 @@ binding (`flow:` or `service: http.flow.adapter` — flows run in the engines), form of the engines' streaming upload: the files of a `multipart/form-data` body arrive in the request map under the engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with their bytes in `contents`, read with `AsyncHttpRequest.files()`, all together within -`rest.upload.max.bytes` (16 MiB; 413 beyond it); the form's text fields become query parameters. +`rest.upload.max.bytes` (16 MiB; 413 beyond it); the form's text fields become query parameters and +count, in bytes, toward the same bound. Deferred as in the Rust engine: `custom.content.types`, `mime.types`, XML and request-body streaming. With the switch off, the default, the host is exactly what it was. diff --git a/docs/guides/configuration-reference.md b/docs/guides/configuration-reference.md index 35f66c5..144e3d2 100644 --- a/docs/guides/configuration-reference.md +++ b/docs/guides/configuration-reference.md @@ -35,7 +35,7 @@ keywords: [configuration, reference, keys, substitution, overrides] | `optional.health.dependencies` | health check routes reported but never affecting status | (empty) | | `rest.automation` | REST automation on: the entries of `rest.yaml` served in front of the functions ([guide](rest-automation.md)) | `false` | | `yaml.rest.automation` | the one location of `rest.yaml`: `classpath:` the resources folder, `file:` an absolute path, a relative path under the application file's folder | `classpath:/rest.yaml` | -| `rest.upload.max.bytes` | the bound on the files of one upload entry, together (413 beyond it) | `16777216` | +| `rest.upload.max.bytes` | the bound on one upload: its files and its text fields together, counted in bytes (413 beyond it) | `16777216` | | `http.trace.id.header` | the trace-id header a traced entry reads when no W3C `traceparent` arrives (`trace.id.header` overrides it per entry) | `X-Trace-Id` | | `http.correlation.id.header` | the business correlation-id header, always ensured and echoed (`correlation.id.header` per entry) | `X-Correlation-Id` | | `http.traceparent.header` | a custom name for the W3C `traceparent` header, read only when the standard one is absent (`traceparent.header` per entry) | `traceparent` | diff --git a/docs/guides/http-surface-reference.md b/docs/guides/http-surface-reference.md index b090c69..a274983 100644 --- a/docs/guides/http-surface-reference.md +++ b/docs/guides/http-surface-reference.md @@ -21,7 +21,7 @@ Mirrors the engines' `event.api.service`: | `x-async: true` | drop-n-forget → HTTP 202 with ack envelope `{type: async, delivered: true, time}` | | Reply | always envelope bytes, `content-type: application/octet-stream` | | Handler outcome | rides **HTTP 200** with the status inside the envelope (including AppException and unexpected errors) | -| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`) | +| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`), 413 a body over the 16 MiB the host reads into memory (`Request body exceeds 16777216 bytes`) | | Header hygiene | inbound `x-event-api` and `my_*` removed; the `my_cid` tag becomes the read-only `my_correlation_id` header (local bus deliveries inject the same view). Outbound, the client stamps the current context's business correlation-id back onto the event as the `my_cid` tag — the engines' PostOffice parity, so the business correlation-id continues across every hop | | `accept: text/event-stream` | streaming-capable call to an interceptor target: a streamed reply rides the same call as SSE in the envelope-mode dialect; a single-shot reply stays byte-identical; a streaming reply to a NON-accepting caller → 406 `Streaming function requires a caller that accepts text/event-stream`. See [Event Streaming](streaming.md) | @@ -57,10 +57,10 @@ first, in the engines' grammar; `POST /api/event` and the actuators are the defa | Matching | the engines' precedence — the most specific route wins, `{param}` and a trailing `*`; a known path under another method → 405 `Method not allowed`; an unknown path → 404 `Resource not found`; `OPTIONS` → 204 with the entry's CORS `options` lines, 405 without a CORS block | | Request to the function | the whole request as the `AsyncHttpRequest` map — method, url, headers (lowercased, after the request transform), path and query parameters (a form's fields among them), the body parsed by its content type (JSON → map or list, text types → text, else bytes), cookies, the `session` map an authentication function left; `x-ttl` carries the entry's timeout in ms | | Reply | a returned value is the body; a returned `EventEnvelope` sets the status and headers (`set-cookie` values split on `\|`); the content type is the function's or negotiated from `Accept` (`text/html` wraps a map in the HTML shell; no `Accept` → no content type); a map or list is pretty-printed JSON with `null` entries omitted | -| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes` | +| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes`; 413 `Request body exceeds 16777216 bytes` for a body over the 16 MiB the host reads into memory; 500 `Reply cannot be rendered` for a reply the serializer refuses | | Correlation and tracing | `X-Correlation-Id` (or `http.correlation.id.header`) always ensured and echoed, delivered as `my_correlation_id`; with `tracing: true` a W3C `traceparent`, else `X-Trace-Id` (`http.trace.id.header`), else a fresh id, and the `http.request` record plus the function's round-trip record | -| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` overrides it; a keep-alive that cannot be written ends the stream | -| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; all files together within `rest.upload.max.bytes` (16 MiB) | +| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` overrides it; a keep-alive that cannot be written ends the stream; a segment the serializer refuses fails it in band with 500 `Reply cannot be rendered` | +| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; the files and the text fields together, counted in bytes, within `rest.upload.max.bytes` (16 MiB); a part that is multipart itself → 400 `Upload takes text fields and files, not a nested multipart part` | | Precedence | a `rest.yaml` entry, then an extension's mounted routes (`Platform.add_routes`), then the static folder (under the `static-content` block's `no-cache-pages` and `filter`), then the error signature below | ## Static content diff --git a/docs/guides/rest-automation.md b/docs/guides/rest-automation.md index cd83bdc..579de86 100644 --- a/docs/guides/rest-automation.md +++ b/docs/guides/rest-automation.md @@ -73,7 +73,11 @@ headers: - "Cache-Control: no-cache, no-store" ``` -`${key:default}` in any value resolves against the configuration, as in the engines. At the end +`${key:default}` in any value resolves against the configuration, as in the engines. A flag — +`tracing`, `stream`, `upload` — is `true` or `false`, read as the Java engine reads it: the +boolean, or the text in any letter case, which is what a reference such as `${TRACING:true}` +resolves to. Left out or empty it is off; any other value fails the start by name +(`rest[0] 'tracing' must be true or false`) rather than leave the flag off without a word. At the end of the boot the host announces every live entry — `REST [GET] /api/hello/{name} -> hello.rest` — and skips, with a warning, an entry whose function is not registered: never a live URL without a function behind it. @@ -148,8 +152,10 @@ unchanged — a flow binding apart — and behaves the same: - **Headers** — the entry's `headers` block drops, keeps or adds request and response headers (`keep` takes precedence over `drop`, the Java rule); its `cors` block's `headers` lines ride every response. -- **Errors** — 404 `Resource not found`, 405 `Method not allowed`, 401 `Unauthorized`, 408 and - 503 `Service X not reachable`, all in the engines' body and `content-type: application/json`. +- **Errors** — 404 `Resource not found`, 405 `Method not allowed`, 401 `Unauthorized`, 408, + 503 `Service X not reachable`, 413 `Request body exceeds 16777216 bytes` for a body over the + 16 MiB the host reads into memory, and 500 `Reply cannot be rendered` for a reply the serializer + refuses (the log names the reason), all in the engines' body and `content-type: application/json`. ## Authentication @@ -216,9 +222,12 @@ async def lines_stream(_headers: dict[str, str], event: EventEnvelope): ``` The entry's `timeout` is the **idle allowance** between segments, not a total bound; the head may -override it with `first(status, content_type, ttl_seconds)`. While the producer is quiet the edge -writes a keep-alive comment every `event.stream.keep.alive` (30 s), and a keep-alive that cannot be -written ends the stream and closes its reply sink. A long-lived producer — a device's feed that is +override it with `first(status, content_type, ttl_seconds)`. While the producer of a Server-Sent +Events stream is quiet the edge writes a keep-alive comment every `event.stream.keep.alive` (30 s) +— a chunked stream has no comment line and gets none — and a keep-alive that cannot be written +ends the stream and closes its reply sink. A segment the serializer refuses fails the stream in +band, as the producer's own failure does: 500 `Reply cannot be rendered`, in the `error` frame under +Server-Sent Events. A long-lived producer — a device's feed that is quiet for as long as nothing changes — opens the stream at once with a bare first segment (`out.write(None)` commits the head and writes no frame), follows its source from a task of its own so the function's workers are never held, and stops when `out.connected` turns false. The @@ -239,9 +248,11 @@ rest: files of a `multipart/form-data` body arrive in the request map under the engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with their bytes in `contents`, read with `request.files()` as `UploadedFile(name, content_type, size, tag, content)`; the form's -text fields become query parameters and the body stays absent, as in the Java engine. All the files -of one upload together may not exceed `rest.upload.max.bytes` (16 MiB by default) — 413 -`Upload exceeds N bytes` the moment they do, before anything is delivered; a malformed body is 400. +text fields become query parameters and the body stays absent, as in the Java engine. The files and +the text fields of one upload together, counted in bytes, may not exceed `rest.upload.max.bytes` +(16 MiB by default) — 413 `Upload exceeds N bytes` the moment they do, before anything is +delivered. A malformed body is 400, and so is a part that is multipart itself: +`Upload takes text fields and files, not a nested multipart part`. A non-multipart body on such an entry, and a multipart body on an entry without the flag, dispatch as any other body. The LLM helper's `llm.upload` — documents saved into the attachments root for a model to read — is the shipped example. diff --git a/src/mercury_composable/rest_automation.py b/src/mercury_composable/rest_automation.py index d90ec6f..4fd63cb 100644 --- a/src/mercury_composable/rest_automation.py +++ b/src/mercury_composable/rest_automation.py @@ -21,8 +21,9 @@ - ``upload: true`` on a POST entry reads a ``multipart/form-data`` body: each file arrives in the request map under the engines' keys (``filename``, ``file_type``, ``file_length``, the ``upload`` tags, ``size``) with its bytes in ``contents`` - the pack's bounded form of the engines' streaming - upload, within ``rest.upload.max.bytes`` (16 MiB; 413 beyond it) - and the form's text fields - become query parameters; + upload, within ``rest.upload.max.bytes`` (16 MiB; 413 beyond it), counted in bytes as the parts + arrive - and the form's text fields become query parameters; a part that is multipart itself is + refused; - ``stream: true`` renders an interceptor's segments as Server-Sent Events or chunked text on the pack's reply sink; a traced call leaves the edge's ``http.request`` record and the function's round-trip record, as the engines do; @@ -46,7 +47,7 @@ from typing import TYPE_CHECKING, Any import yaml -from aiohttp import BodyPartReader, web +from aiohttp import BodyPartReader, MultipartReader, web from .actuator import app_origin from .async_http_request import AsyncHttpRequest, UploadedFile @@ -108,6 +109,15 @@ UPLOAD_MAX_BYTES = "rest.upload.max.bytes" DEFAULT_UPLOAD_MAX_BYTES = 16 * 1024 * 1024 MULTIPART_FORM_DATA = "multipart/form-data" +# the host's limit on a request body it reads into memory - the web application's client_max_size +MAX_BODY_BYTES = 16 * 1024 * 1024 +# an upload's parts are text fields and files: the refusal of a part that is multipart itself +NESTED_PART = "Upload takes text fields and files, not a nested multipart part" +# the answer when a reply cannot be rendered, and what the serializer raises for a body it refuses: +# a type JSON does not hold, a structure that contains itself or runs too deep, text that is not +# Unicode +UNRENDERABLE = "Reply cannot be rendered" +_SERIALIZER_ERRORS = (TypeError, ValueError, RecursionError) # the edge's own service name in the trace records (the engines' REST edge) HTTP_REQUEST = "http.request" EVENT_API_SERVICE = "event.api.service" @@ -187,6 +197,18 @@ def _error(status: int, message: str) -> web.Response: headers={"Content-Type": "application/json"}) +def body_too_large() -> AppException: + """The refusal of a request body over the host's limit on what it reads into memory.""" + return AppException(413, f"Request body exceeds {MAX_BODY_BYTES} bytes") + + +def _unrendered(service: str | None, cause: Exception) -> AppException: + """The failure of a reply that cannot be rendered - a body the serializer refuses. The reason + goes to the log; the response and the trace record carry the one message both packs answer.""" + log.error("Unable to render the reply of %s - %s", service or "unknown", cause) + return AppException(500, UNRENDERABLE) + + def _stream_error_message(event: EventEnvelope) -> str: body = event.body if isinstance(body, dict): @@ -231,6 +253,16 @@ async def _prepare_headers(self) -> None: self._headers.popall("Content-Type", None) +class _NestedPart(MultipartReader): + """A part of an upload that is multipart itself - a ``multipart/*`` content type - as aiohttp + hands it over when told not to open it. An upload refuses such a part, so it is only told + apart from a field or a file: nothing of it is read, not even its boundary.""" + + def __init__(self, *_args: Any, **_limits: Any) -> None: + # nothing to set up: the part is never read + pass + + class _RestEdge: """The trace records of one traced call through a REST entry - what the engines leave: the edge's ``http.request`` round trip (the SERVER span, parented onto the caller's span from the @@ -463,7 +495,12 @@ async def _read_body(self, request: web.Request, info: RouteInfo, method: str, for name, value in fields.items(): query[name] = value return ParsedBody("upload", None), files - parsed = parse_body(headers.get("content-type"), await request.read()) + try: + data = await request.read() + except web.HTTPRequestEntityTooLarge: + # the host's limit on a body read into memory: the engines' error body, not aiohttp's page + raise body_too_large() from None + parsed = parse_body(headers.get("content-type"), data) if parsed.kind == "form": for name, value in parsed.value.items(): query[name] = value @@ -483,13 +520,16 @@ def _set_body(http_request: AsyncHttpRequest, parsed: ParsedBody, async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile], dict[str, str]]: """The parts of a multipart body: a part with a filename is a file (its field name the - upload tag, its declared type or octet-stream), any other part a text field. The files - together may not exceed ``rest.upload.max.bytes`` - a 413 the moment they do.""" + upload tag, its declared type or octet-stream), any other part a text field; a part that + is multipart itself is refused. The parts together, counted in bytes as they arrive, may + not exceed ``rest.upload.max.bytes`` - a 413 the moment they do.""" files: list[UploadedFile] = [] fields: dict[str, str] = {} total = 0 try: reader = await request.multipart() + # a part that is multipart itself is handed over as a marker, never opened + reader.multipart_reader_cls = _NestedPart while True: # reader.next() rather than an async for: the iteration protocol is not typed on # every Python the pack supports @@ -497,7 +537,7 @@ async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile if part is None: break if not isinstance(part, BodyPartReader): - continue + raise AppException(400, NESTED_PART) if part.filename: content, total = await self._read_file(part, total) content_type = part.headers.get("Content-Type", "application/octet-stream") @@ -513,8 +553,9 @@ async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile return files, fields async def _read_file(self, part: BodyPartReader, total: int) -> tuple[bytes, int]: - """A file part's bytes, read in chunks so the bound holds while they arrive; ``total`` is - the size of the upload before this part and comes back with it counted.""" + """A part's bytes - a file's, or a text field's before it is decoded - read in chunks so + the bound holds while they arrive; ``total`` is the size of the upload before this part + and comes back with it counted.""" chunks: list[bytes] = [] while True: chunk = await part.read_chunk(65536) @@ -527,12 +568,11 @@ async def _read_file(self, part: BodyPartReader, total: int) -> tuple[bytes, int return b"".join(chunks), total async def _read_field(self, part: BodyPartReader, total: int) -> tuple[str, int]: - """A text field of the form, counted against the same bound as the files.""" - text = await part.text() - total += len(text) - if total > self.upload_max_bytes: - raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") - return text, total + """A text field of the form, counted against the same bound as the files: the bytes that + arrive, never the length of the text they spell. The text is what aiohttp's ``part.text()`` + reads - the part's transfer encoding undone, then its charset.""" + data, total = await self._read_file(part, total) + return bytes(part.decode(data)).decode(part.get_charset(default="utf-8")), total @staticmethod def _event(to: str, prepared: _Prepared) -> EventEnvelope: @@ -627,11 +667,11 @@ async def _process(self, request: web.Request, assigned: AssignedRoute) -> web.S reply = self._single_shot(first, marker) else: reply = await self._rpc(info.service, service, prepared, info.timeout_ms) + return self._respond(info, prepared, reply) except AppException as e: if edge is not None: edge.record(e.status, e.message) return _error(e.status, e.message) - return self._respond(info, prepared, reply) @staticmethod def _single_shot(first: EventEnvelope, marker: str | None) -> EventEnvelope: @@ -648,11 +688,15 @@ def _single_shot(first: EventEnvelope, marker: str | None) -> EventEnvelope: @staticmethod def _respond(info: RouteInfo, prepared: _Prepared, reply: EventEnvelope) -> web.Response: - """The reply as the HTTP response under the engines' mapping, recorded on the edge.""" - mapped = map_response(status=reply.get_status(), reply_headers=reply.headers, - body=reply.body, accept=prepared.accept, is_head=prepared.is_head, - transform=info.headers.response if info.headers else None, - cors=info.cors, cid=prepared.cid, cid_header=prepared.cid_header) + """The reply as the HTTP response under the engines' mapping, recorded on the edge; a + reply that cannot be rendered is the 500 the caller answers and records.""" + try: + mapped = map_response(status=reply.get_status(), reply_headers=reply.headers, + body=reply.body, accept=prepared.accept, is_head=prepared.is_head, + transform=info.headers.response if info.headers else None, + cors=info.cors, cid=prepared.cid, cid_header=prepared.cid_header) + except _SERIALIZER_ERRORS as e: + raise _unrendered(info.service, e) from None response = _RestResponse(status=mapped.status, body=mapped.body) response.headers.popall("Content-Type", None) for name, value in mapped.headers: @@ -753,13 +797,16 @@ async def _render(self, response: web.StreamResponse, queue: asyncio.Queue[Event if segment is None: return await self._write_timeout(response, sse, idle_ms) event, marker = segment - if marker == DATA: - await self._write_data(response, event, sse) - elif marker == EOF: - await self._write_done(response, event, sse) - return head_status, None - else: - return await self._write_failure(response, event, sse) + try: + if marker == DATA: + await self._write_data(response, event, sse) + elif marker == EOF: + await self._write_done(response, event, sse) + return head_status, None + else: + return await self._write_failure(response, event, sse) + except _SERIALIZER_ERRORS as e: + return await self._write_unrendered(response, sse, _unrendered(event.sender, e)) async def _next_marked(self, response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], idle_ms: int, ping_ms: int) -> tuple[EventEnvelope, str] | None: @@ -790,6 +837,16 @@ async def _write_timeout(response: web.StreamResponse, sse: bool, await response.write(sse_frame("error", compact_json(error_body(408, message)))) return 408, message + @staticmethod + async def _write_unrendered(response: web.StreamResponse, sse: bool, + failure: AppException) -> tuple[int, str]: + """A segment that cannot be rendered fails the stream in band, as an ``exception`` segment + does: the ``error`` frame under SSE, and the failure as the stream's outcome.""" + if sse: + frame = compact_json(error_body(failure.status, failure.message)) + await response.write(sse_frame("error", frame)) + return failure.status, failure.message + @staticmethod async def _write_data(response: web.StreamResponse, event: EventEnvelope, sse: bool) -> None: """A data segment: an SSE frame under its event name, else its bytes as a chunk; a @@ -824,7 +881,8 @@ async def _write_failure(response: web.StreamResponse, event: EventEnvelope, async def _next(response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], idle_ms: int, ping_ms: int) -> EventEnvelope | None: """The next segment within the idle allowance, with SSE keep-alive comments while the - producer is quiet; None at expiry.""" + producer is quiet - ``ping_ms`` is 0 on a stream that is not Server-Sent Events, which has + no comment line; None at expiry.""" loop = asyncio.get_running_loop() deadline = loop.time() + idle_ms / 1000 while True: @@ -837,9 +895,13 @@ async def _next(response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope except TimeoutError: if loop.time() >= deadline: return None - # a keep-alive that cannot be written means the client is gone: the stream ends - # here and the caller closes the sink, instead of waiting out the idle allowance - await response.write(b": ping\n\n") + if wait < remaining: + # a keep-alive interval has passed. A keep-alive that cannot be written means + # the client is gone: the stream ends here and the caller closes the sink, + # instead of waiting out the idle allowance + await response.write(b": ping\n\n") + # else the allowance's own timer fired a moment before the clock reached the + # deadline: nothing is written, and the loop waits out what is left # ---- the built-in endpoints and static content ---- diff --git a/src/mercury_composable/rest_routing.py b/src/mercury_composable/rest_routing.py index 142c4f7..6b5d8f0 100644 --- a/src/mercury_composable/rest_routing.py +++ b/src/mercury_composable/rest_routing.py @@ -429,6 +429,23 @@ def _parse_methods(index: int, raw_methods: Any) -> list[str]: return methods +def _parse_flag(index: int, entry: Mapping[str, Any], key: str) -> bool: + """A boolean of an entry - ``tracing``, ``stream``, ``upload`` - read as the Java engine reads + it: ``true`` turns it on, the boolean or the text in any letter case, which is what a + ``${NAME:default}`` reference resolves to; ``false``, no value and an empty one leave it off. + The engine reads any other value as off without a word, which is how a flag meant to be on + stays off - so here it fails the load, by the entry and the flag.""" + value = _lookup(entry, key) + if value is None or value == "": + return False + if isinstance(value, bool): + return value + lowered = value.lower() if isinstance(value, str) else "" + if lowered in ("true", "false"): + return lowered == "true" + raise AppException(400, f"rest[{index}] '{key}' must be true or false") + + def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, CorsInfo], header_blocks: Mapping[str, HeaderInfo]) -> RouteInfo: service = _parse_service(index, entry) @@ -453,9 +470,9 @@ def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, timeout_ms=parse_timeout(_lookup(entry, "timeout")), cors=cors, headers=headers, authentication=_text(_lookup(entry, "authentication")), - tracing=_lookup(entry, "tracing") is True, - stream=_lookup(entry, "stream") is True, - upload=_lookup(entry, "upload") is True, + tracing=_parse_flag(index, entry, "tracing"), + stream=_parse_flag(index, entry, "stream"), + upload=_parse_flag(index, entry, "upload"), trace_id_header=_text(_lookup(entry, "trace.id.header")), correlation_id_header=_text(_lookup(entry, "correlation.id.header")), traceparent_header=_text(_lookup(entry, "traceparent.header")), diff --git a/src/mercury_composable/server.py b/src/mercury_composable/server.py index 02b44ed..e339ac3 100644 --- a/src/mercury_composable/server.py +++ b/src/mercury_composable/server.py @@ -9,9 +9,10 @@ - Reply body is always envelope bytes with ``content-type: application/octet-stream``. Transport-level failures produced by this host (400 undecodable / missing route, 403 private, 404 unknown route, 408 - timeout) set the HTTP status as well; a handler's own result — including an - AppException or an unexpected exception — rides HTTP 200 with the status - inside the envelope, exactly like an engine function's reply. + timeout, 413 a body over the 16 MiB the host reads into memory) set the HTTP + status as well; a handler's own result — including an AppException or an + unexpected exception — rides HTTP 200 with the status inside the envelope, + exactly like an engine function's reply. - Reserved header hygiene: ``x-event-api`` (the engines' relay recursion guard) and transported ``my_*`` keys are removed from the handler's header view; the ``my_cid`` tag is injected as the read-only ``my_correlation_id`` @@ -62,7 +63,7 @@ ) from .log import get_logger from .registry import FunctionRegistry, ServiceDef, default_registry -from .rest_automation import RestAutomation +from .rest_automation import MAX_BODY_BYTES, RestAutomation, body_too_large from .static_content import StaticContent, resolve_folder from .trace import MY_CID_TAG, MY_CORRELATION_ID @@ -237,7 +238,12 @@ def __init__(self, registry: FunctionRegistry | None = None): self.rest: RestAutomation | None = RestAutomation.load(app_config(), self) async def handle_event(self, request: web.Request) -> web.StreamResponse: - raw = await request.read() + try: + raw = await request.read() + except web.HTTPRequestEntityTooLarge: + # a transport failure as the others are - an envelope - not aiohttp's own page + refusal = body_too_large() + return _transport_error(refusal.status, refusal.message) ttl = _ttl(request) is_async = request.headers.get(X_ASYNC, "") == "true" try: @@ -428,8 +434,12 @@ async def _next_segment(response: web.StreamResponse, except TimeoutError: if loop.time() >= deadline: return None - with contextlib.suppress(ConnectionError): - await response.write(b": ping\n\n") + if wait < remaining: + # a keep-alive interval has passed + with contextlib.suppress(ConnectionError): + await response.write(b": ping\n\n") + # else the allowance's own timer fired a moment before the clock reached the + # deadline: nothing is written, and the loop waits out what is left def create_app(self, routes: Iterable[RouteMounter] = (), *, rest_startup: bool = True) -> web.Application: @@ -441,7 +451,7 @@ def create_app(self, routes: Iterable[RouteMounter] = (), *, automation on, the entries of ``rest.yaml`` come first - the host's paths among them as the engines' default entries - and its startup hook validates the table; ``Platform`` passes ``rest_startup=False`` to append that hook after the extensions' own boot work.""" - app = web.Application(client_max_size=16 * 1024 * 1024) + app = web.Application(client_max_size=MAX_BODY_BYTES) app.router.add_post("/api/event", self.handle_event) # the engines' landing page (or the static folder's index.html) + actuator endpoints # (see actuator.py) diff --git a/tests/test_event_stream.py b/tests/test_event_stream.py index 13b5fa8..e1d7cef 100644 --- a/tests/test_event_stream.py +++ b/tests/test_event_stream.py @@ -5,8 +5,9 @@ import asyncio import base64 import re -from collections.abc import AsyncIterator -from typing import Any +from collections.abc import AsyncIterator, Coroutine +from types import ModuleType, SimpleNamespace +from typing import Any, cast import aiohttp import pytest @@ -21,8 +22,11 @@ FunctionRegistry, PostOffice, event_stream, + rest_automation, + server, trace_context, ) +from mercury_composable.rest_automation import RestAutomation from mercury_composable.server import EventApiServer OCTET = "application/octet-stream" @@ -557,3 +561,86 @@ async def test_client_idle_guard_fails_in_band(misbehaving_peer: str): assert marker(error) == "exception" assert error.get_status() == 408 assert error.body["message"] == "Timeout for 2 seconds" + + +# ---- the keep-alive of a quiet stream: the clock and the timer driven by the test ---- + + +class _Wire: + """A response that keeps what is written to it.""" + + def __init__(self) -> None: + self.written: list[bytes] = [] + + async def write(self, data: bytes) -> None: + self.written.append(data) + + +class _Clock: + """The loop's clock and timer in the test's hands: every wait ends on its timer, with nothing + arrived, and a timer of a millisecond or more fires half a millisecond before the clock + reaches its time - as a timer may.""" + + def __init__(self) -> None: + self.now = 100.0 + + def time(self) -> float: + return self.now + + async def wait_for(self, waiting: Coroutine[Any, Any, Any], timeout: float) -> None: + waiting.close() + self.now += timeout - (0.0005 if timeout >= 0.001 else 0.0) + raise TimeoutError + + +def drive_clock(monkeypatch: pytest.MonkeyPatch, module: ModuleType) -> _Clock: + """Put a module's waits and its reading of the clock under the test's control.""" + clock = _Clock() + monkeypatch.setattr(module, "asyncio", + SimpleNamespace(get_running_loop=lambda: clock, wait_for=clock.wait_for)) + return clock + + +PING = b": ping\n\n" + + +async def test_a_stream_that_is_not_server_sent_events_gets_no_keep_alive(monkeypatch: pytest.MonkeyPatch): + # an idle allowance of one second whose timer fires a moment early: a chunked stream has no + # comment line, so nothing may be written into its body - the rest of the allowance runs out + wire = _Wire() + clock = drive_clock(monkeypatch, rest_automation) + waited = await RestAutomation._next(cast("web.StreamResponse", wire), asyncio.Queue(), 1000, 0) + assert waited is None + assert wire.written == [] + assert clock.now == 101.0 + + +async def test_a_keep_alive_is_written_when_its_interval_has_passed(monkeypatch: pytest.MonkeyPatch): + # the same allowance with a keep-alive every 400 ms: two intervals pass - and no keep-alive + # comes from the allowance's own timer, which fires a moment early at the end + wire = _Wire() + clock = drive_clock(monkeypatch, rest_automation) + waited = await RestAutomation._next(cast("web.StreamResponse", wire), asyncio.Queue(), 1000, 400) + assert waited is None + assert wire.written == [PING, PING] + assert clock.now == 101.0 + + +async def test_the_event_api_stream_gets_no_keep_alive_when_they_are_off(monkeypatch: pytest.MonkeyPatch): + # event.stream.keep.alive: 0 - the allowance's timer firing early must not write one + wire = _Wire() + clock = drive_clock(monkeypatch, server) + waited = await EventApiServer._next_segment(cast("web.StreamResponse", wire), asyncio.Queue(), 1000, 0) + assert waited is None + assert wire.written == [] + assert clock.now == 101.0 + + +async def test_the_event_api_stream_writes_a_keep_alive_when_its_interval_has_passed( + monkeypatch: pytest.MonkeyPatch): + wire = _Wire() + clock = drive_clock(monkeypatch, server) + waited = await EventApiServer._next_segment(cast("web.StreamResponse", wire), asyncio.Queue(), 1000, 400) + assert waited is None + assert wire.written == [PING, PING] + assert clock.now == 101.0 diff --git a/tests/test_rest_automation.py b/tests/test_rest_automation.py index 3de0820..cd9b227 100644 --- a/tests/test_rest_automation.py +++ b/tests/test_rest_automation.py @@ -47,6 +47,8 @@ Serve = Callable[[FunctionRegistry], AbstractAsyncContextManager[str]] VECTORS = Path(__file__).parent / "vectors" / "rest-automation-vectors.json" +# the Node twin pins the same digest: change the file in both packs or in neither +VECTORS_SHA256 = "02fb140f780a9b781dc6cfc7a1c48b1b8094a089cae350dbf5e813754517a51d" MY_CID = "my_correlation_id" @@ -69,6 +71,12 @@ def _route_view(route: Any) -> dict[str, Any]: "traceparent_header": route.traceparent_header} +def test_the_vector_file_is_the_one_the_node_twin_runs(vectors: dict[str, Any]): + digest = hashlib.sha256(VECTORS.read_bytes()).hexdigest() + assert digest == VECTORS_SHA256, "update both packs' pins when the shared file changes" + assert vectors["version"] == 3 + + def test_vectors_load_cases(vectors: dict[str, Any]): for case in vectors["load_cases"]: if "error" in case: @@ -1098,6 +1106,64 @@ def test_cors_lines_resolve_configuration_references( assert entry.info.cors.headers == [("Access-Control-Allow-Origin", "https://app.example")] +FLAGS_YAML = """\ +rest: + - service: "plain.text" + methods: ['POST'] + url: "/api/flags/environment" + tracing: ${REST_TEST_TRACING:true} + stream: ${REST_TEST_STREAM:false} + upload: ${REST_TEST_UPLOAD} + - service: "plain.text" + methods: ['POST'] + url: "/api/flags/configuration" + tracing: ${rest.test.flag} + stream: ${REST_TEST_UNSET:false} + upload: ${REST_TEST_UNSET:} +""" + + +def _flags(table: RoutingTable, path: str) -> dict[str, bool]: + entry = table.find("POST", path) + assert entry is not None, path + return {"tracing": entry.info.tracing, "stream": entry.info.stream, "upload": entry.info.upload} + + +def test_flags_resolve_configuration_references( + tmp_path: Path, probe: Probe, monkeypatch: pytest.MonkeyPatch +): + """A reference resolves to text - its default, an environment variable - or to the value of a + configuration key; a flag reads each of them as the Java engine does.""" + monkeypatch.delenv("REST_TEST_TRACING", raising=False) + monkeypatch.delenv("REST_TEST_UNSET", raising=False) + monkeypatch.setenv("REST_TEST_STREAM", "TRUE") + monkeypatch.setenv("REST_TEST_UPLOAD", "true") + write(tmp_path / "app" / "resources" / "application.yml", "rest.test.flag: true\n") + with configured(tmp_path, FLAGS_YAML): + server = EventApiServer(build_registry(probe)) + assert server.rest is not None + # the default after the colon, an environment variable over its default, one without a default + assert _flags(server.rest.table, "/api/flags/environment") == \ + {"tracing": True, "stream": True, "upload": True} + # a configuration key that holds a boolean, a default of false, an empty default + assert _flags(server.rest.table, "/api/flags/configuration") == \ + {"tracing": True, "stream": False, "upload": False} + + +def test_a_flag_reference_that_is_neither_true_nor_false_fails_the_start( + tmp_path: Path, probe: Probe, monkeypatch: pytest.MonkeyPatch +): + monkeypatch.setenv("REST_TEST_TRACING", "on") + monkeypatch.setenv("REST_TEST_UPLOAD", "true") + write(tmp_path / "app" / "resources" / "application.yml", "rest.test.flag: true\n") + with configured(tmp_path, FLAGS_YAML): + registry = build_registry(probe) + with pytest.raises(AppException) as raised: + EventApiServer(registry) + assert raised.value.status == 400 + assert raised.value.message == "rest[0] 'tracing' must be true or false" + + # ---- upload: the bounded form of the engines' streaming upload ---- PDF_BYTES = b"%PDF-1.4 a small document" @@ -1157,3 +1223,224 @@ async def test_an_upload_over_the_bound_is_413(tmp_path: Path, probe: Probe, ser status, body = await post_form(f"{base}/api/upload", _form()) assert status == 413 assert json.loads(body) == {"status": 413, "message": "Upload exceeds 40 bytes", "type": "error"} + + +BOUNDARY = "mercury-test-boundary" +Part = tuple[list[str], bytes] + + +def multipart_body(*parts: Part) -> tuple[dict[str, str], bytes]: + """A multipart/form-data request written out part by part - each part its header lines and its + content - so both packs post the same bytes.""" + body = b"".join(f"--{BOUNDARY}\r\n".encode() + "\r\n".join(lines).encode() + b"\r\n\r\n" + content + b"\r\n" + for lines, content in parts) + headers = {"Content-Type": f"multipart/form-data; boundary={BOUNDARY}", "Accept": "application/json"} + return headers, body + f"--{BOUNDARY}--\r\n".encode() + + +def text_field(name: str, text: str) -> Part: + return [f'Content-Disposition: form-data; name="{name}"'], text.encode("utf-8") + + +def file_part(name: str, filename: str, content: bytes) -> Part: + return ([f'Content-Disposition: form-data; name="{name}"; filename="{filename}"', + "Content-Type: application/octet-stream"], content) + + +async def test_the_upload_bound_counts_a_text_field_in_bytes(tmp_path: Path, probe: Probe, serve: Serve): + """The bound is a number of bytes: a field counts as the bytes that arrived, not as the length + of its text - 600 two-byte characters are 1,200 bytes.""" + too_large = {"status": 413, "message": "Upload exceeds 1000 bytes", "type": "error"} + over = { + "600 two-byte characters": [text_field("note", "é" * 600)], + "334 three-byte characters": [text_field("note", "€" * 334)], + "260 four-byte characters": [text_field("note", "😀" * 260)], + "a 600-byte file and 300 two-byte characters": [file_part("doc", "a.bin", b"\x01" * 600), + text_field("note", "é" * 300)], + } + within = { + "500 two-byte characters": [text_field("note", "é" * 500)], + "a 400-byte file and 300 two-byte characters": [file_part("doc", "a.bin", b"\x01" * 400), + text_field("note", "é" * 300)], + } + with configured(tmp_path, REST_YAML, {"rest.upload.max.bytes": 1000}): + async with serve(build_registry(probe)) as base: + for name, parts in over.items(): + headers, data = multipart_body(*parts) + status, _, body = await http(f"{base}/api/upload", "POST", headers, data) + assert status == 413, name + assert json.loads(body) == too_large, name + for name, parts in within.items(): + headers, data = multipart_body(*parts) + status, _, body = await http(f"{base}/api/upload", "POST", headers, data) + assert status == 200, name + assert json.loads(body)["query"] == {"note": parts[-1][1].decode("utf-8")}, name + + +NESTED_PART = "Upload takes text fields and files, not a nested multipart part" +INNER = (b'--inner\r\nContent-Disposition: attachment; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\nAAA\r\n' + b'--inner\r\nContent-Disposition: attachment; filename="b.txt"\r\nContent-Type: text/plain\r\n\r\nBBB\r\n' + b"--inner--") + + +async def test_an_upload_refuses_a_nested_multipart_part(rest_url: str): + """An upload's parts are text fields and files: a part that is multipart itself is refused by + name - wherever it stands in the body, with or without a filename.""" + nested: Part = (['Content-Disposition: form-data; name="files"', + "Content-Type: multipart/mixed; boundary=inner"], INNER) + named: Part = (['Content-Disposition: form-data; name="files"; filename="bundle"', + "Content-Type: Multipart/Mixed; boundary=inner"], INNER) + bare: Part = (['Content-Disposition: form-data; name="files"', "Content-Type: multipart/related"], b"x") + note = text_field("note", "hello") + refused = { + "ahead of a field": [nested, note], + "ahead of a file": [nested, file_part("doc", "a.bin", b"\x01\x02")], + "after a field": [note, nested], + "alone": [nested], + "with a filename, ahead of a field": [named, note], + "with a filename, after a field": [note, named], + "without a boundary of its own": [bare, note], + } + for name, parts in refused.items(): + headers, data = multipart_body(*parts) + status, lines, body = await http(f"{rest_url}/api/upload", "POST", headers, data) + assert status == 400, name + assert header(lines, "content-type") == "application/json", name + assert json.loads(body) == {"status": 400, "message": NESTED_PART, "type": "error"}, name + # the same form without the nested part is delivered + headers, data = multipart_body(note, file_part("doc", "a.bin", b"\x01\x02")) + status, _, body = await http(f"{rest_url}/api/upload", "POST", headers, data) + assert status == 200 + assert json.loads(body)["query"] == {"note": "hello"} + assert [f["name"] for f in json.loads(body)["files"]] == ["a.bin"] + + +async def test_an_upload_whose_parts_do_not_follow_the_declared_boundary_is_400(rest_url: str): + # the content type declares the boundary a,b and the parts are delimited by a: no reading of + # the header may deliver them + body = b'--a\r\nContent-Disposition: form-data; name="note"\r\n\r\nhello\r\n--a--\r\n' + headers = {"Content-Type": "multipart/form-data; boundary=a,b", "Accept": "application/json"} + status, _, reply = await http(f"{rest_url}/api/upload", "POST", headers, body) + assert status == 400 + assert json.loads(reply)["message"].startswith("Invalid multipart body - ") + + +# ---- the host's limit on a body it reads into memory ---- + +BODY_LIMIT = 16 * 1024 * 1024 +BODY_TOO_LARGE = b'{\n "status": 413,\n "message": "Request body exceeds 16777216 bytes",\n "type": "error"\n}' + + +async def test_a_body_over_the_hosts_limit_is_the_engines_413(rest_url: str): + """A body over 16 MiB is refused in the engines' error body - behind an entry, and behind the + default entry of the Event API - never with the web framework's own page.""" + octets = {"Content-Type": "application/octet-stream", "Accept": "application/json"} + for path in ("/api/upload", "/api/event"): + status, lines, body = await http(f"{rest_url}{path}", "POST", octets, b"\x00" * (BODY_LIMIT + 1)) + assert status == 413, path + assert header(lines, "content-type") == "application/json", path + assert body == BODY_TOO_LARGE, path + # a body of exactly the limit is read and delivered + status, _, body = await http(f"{rest_url}/api/upload", "POST", octets, b"\x00" * BODY_LIMIT) + assert status == 200 + assert json.loads(body)["body_present"] is True + + +# ---- a reply that cannot be rendered ---- + +UNRENDERABLE_YAML = """\ +rest: + - service: "unrenderable.reply" + methods: ['GET'] + url: "/api/unrenderable" + tracing: true + - service: "unrenderable.events" + methods: ['GET'] + url: "/api/unrenderable/events" + stream: true + tracing: true + - service: "unrenderable.lines" + methods: ['GET'] + url: "/api/unrenderable/lines" + stream: true + tracing: true +""" +UNRENDERABLE = b'{\n "status": 500,\n "message": "Reply cannot be rendered",\n "type": "error"\n}' +UNRENDERABLE_FRAME = 'event: error\ndata: {"status":500,"message":"Reply cannot be rendered","type":"error"}\n\n' + + +def unrenderable_registry(probe: Probe) -> FunctionRegistry: + """Functions whose reply the serializer refuses: a set is not JSON.""" + registry = build_registry(probe) + + async def reply(_headers: dict[str, str], _body: Body): + return {"when": {1, 2, 3}} + + async def events(_headers: dict[str, str], event: EventEnvelope): + out = EventStreamWriter.from_request(event, registry=registry) + out.first(200, "text/event-stream") + out.write("one") + out.write({"when": {1, 2, 3}}) + out.write("three") + out.close() + + async def lines(_headers: dict[str, str], event: EventEnvelope): + out = EventStreamWriter.from_request(event, registry=registry) + out.first(200, "application/json") + out.write("one") + out.write({"when": {1, 2, 3}}) + out.write("three") + out.close() + + registry.register("unrenderable.reply", reply) + registry.register("unrenderable.events", events, interceptor=True) + registry.register("unrenderable.lines", lines, interceptor=True) + return registry + + +async def _edge_record(probe: Probe, path: str) -> dict[str, Any]: + """The edge's ``http.request`` record of the request for ``path``.""" + def found() -> list[dict[str, Any]]: + return [d["trace"] for d in probe.datasets + if d["trace"]["service"] == "http.request" and d["trace"]["path"] == f"GET {path}"] + await _wait_for(lambda: bool(found())) + return found()[0] + + +async def test_a_reply_that_cannot_be_rendered_is_the_engines_500_and_is_traced( + tmp_path: Path, probe: Probe, serve: Serve +): + with configured(tmp_path, UNRENDERABLE_YAML): + async with serve(unrenderable_registry(probe)) as base: + status, lines, body = await http(f"{base}/api/unrenderable", headers={"Accept": "application/json"}) + assert status == 500 + assert header(lines, "content-type") == "application/json" + assert body == UNRENDERABLE + edge = await _edge_record(probe, "/api/unrenderable") + assert edge["status"] == 500 + assert edge["success"] is False + assert edge["exception"] == "Reply cannot be rendered" + + +async def test_a_segment_that_cannot_be_rendered_fails_the_stream_in_band_and_is_traced( + tmp_path: Path, probe: Probe, serve: Serve +): + with configured(tmp_path, UNRENDERABLE_YAML): + async with serve(unrenderable_registry(probe)) as base: + # Server-Sent Events: the segments before it, then the error frame - nothing after it + status, lines, body = await http(f"{base}/api/unrenderable/events", + headers={"Accept": "text/event-stream"}) + assert status == 200 + assert header(lines, "content-type") == "text/event-stream" + assert body.decode("utf-8") == "data: one\n\n" + UNRENDERABLE_FRAME + edge = await _edge_record(probe, "/api/unrenderable/events") + assert edge["status"] == 500 + assert edge["exception"] == "Reply cannot be rendered" + # a chunked stream has no error frame: it ends, and the record tells + status, lines, body = await http(f"{base}/api/unrenderable/lines", headers={"Accept": "*/*"}) + assert status == 200 + assert header(lines, "content-type") == "application/json" + assert body == b"one" + edge = await _edge_record(probe, "/api/unrenderable/lines") + assert edge["status"] == 500 + assert edge["exception"] == "Reply cannot be rendered" diff --git a/tests/test_server.py b/tests/test_server.py index 0de4322..86d8504 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -189,3 +189,18 @@ async def test_actuator_endpoints_are_wired(server_url: str): async with session.get(f"{server_url}/info") as response: assert response.status == 200 assert (await response.json())["runtime"]["language"] == "python" + + +async def test_a_body_over_the_hosts_limit_is_a_transport_failure_413(server_url: str): + # 16 MiB is what the host reads into memory; one byte more is refused before it is decoded - + # in an envelope, as every transport failure of the Event API is + async with ( + aiohttp.ClientSession() as session, + session.post(f"{server_url}/api/event", data=b"\x00" * (16 * 1024 * 1024 + 1), + headers={"content-type": OCTET, "x-ttl": "5000"}) as response, + ): + assert response.status == 413 + assert response.headers["content-type"] == OCTET + reply = EventEnvelope.from_bytes(await response.read()) + assert reply.get_status() == 413 + assert reply.body == "Request body exceeds 16777216 bytes" diff --git a/tests/vectors/rest-automation-vectors.json b/tests/vectors/rest-automation-vectors.json index dd06e61..0ee6efb 100644 --- a/tests/vectors/rest-automation-vectors.json +++ b/tests/vectors/rest-automation-vectors.json @@ -1,7 +1,7 @@ { "contract": "rest-automation", - "version": 2, - "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). timeout_cases pin the duration grammar and its clamp. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", + "version": 3, + "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). A flag of an entry (tracing, stream, upload) is true or false as the Java engine reads it - the boolean, or the text in any letter case, which is what a ${NAME:default} reference resolves to; no value and an empty one are off; any other value is refused by name. timeout_cases pin the duration grammar and its clamp. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", "tables": { "basic": "rest:\n - service: \"greeting.api\"\n methods: ['GET']\n url: \"/api/greeting/{user}\"\n timeout: 10s\n cors: cors_1\n headers: header_1\n tracing: true\n - service: \"catch.all\"\n methods: ['GET', 'POST']\n url: \"/api/files/*\"\n - service: \"exact.match\"\n methods: ['GET']\n url: \"/api/greeting/system\"\n - service: \"version.ping\"\n methods: ['GET']\n url: \"/api/v*/ping\"\n - service: \"mid.any\"\n methods: ['GET']\n url: \"/api/mid/*/end\"\n - service: \"secure.api\"\n methods: ['POST']\n url: \"/api/secure\"\n authentication: \"api.key.check\"\n stream: true\n trace.id.header: 'X-Legacy-Trace'\n correlation.id.header: 'X-Legacy-Cid'\n traceparent.header: 'X-Trace-Context'\ncors:\n - id: cors_1\n options:\n - \"Access-Control-Allow-Origin: *\"\n - \"Access-Control-Allow-Methods: GET, POST, OPTIONS\"\n headers:\n - \"Access-Control-Allow-Origin: *\"\nheaders:\n - id: header_1\n request:\n drop: ['x-secret']\n response:\n add: [\"x-served-by: mercury\"]\nstatic-content:\n no-cache-pages: [\"/\", \"/index.html\", \"/app/*\"]\n filter:\n path: [\"/\", \"/assets/*\", \"*.html\"]\n exclusion: [\"*.css\"]\n service: \"http.request.filter\"\n", "defaults": "rest:\n - service: \"event.api.service\"\n methods: ['POST']\n url: \"/api/event\"\n timeout: 60s\n tracing: true\n - service: \"info.actuator.service\"\n methods: ['GET']\n url: \"/info\"\n timeout: 10s\n - service: \"routes.actuator.service\"\n methods: ['GET']\n url: \"/info/routes\"\n timeout: 10s\n - service: \"env.actuator.service\"\n methods: ['GET']\n url: \"/env\"\n timeout: 10s\n - service: \"health.actuator.service\"\n methods: ['GET']\n url: \"/health\"\n timeout: 30s\n - service: \"liveness.actuator.service\"\n methods: ['GET']\n url: \"/livenessprobe\"\n timeout: 10s\n", @@ -465,6 +465,185 @@ "name": "the index names the failing entry", "yaml": "rest:\n - service: x.y\n methods: ['GET']\n url: /a\n - service: x.z\n methods: ['GET']\n", "error": "rest[1] missing 'url'" + }, + { + "name": "a flag written as text - what a ${NAME:default} reference resolves to - is read as the Java engine reads it: true in any letter case turns it on, false leaves it off", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: \"true\"\n stream: 'TRUE'\n upload: \"True\"\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: \"false\"\n stream: 'FALSE'\n upload: \"False\"\n", + "routes": [ + { + "service": "x.y", + "methods": [ + "POST" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": true, + "stream": true, + "upload": true, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.z", + "methods": [ + "POST" + ], + "url": "/b", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "the YAML 1.1 booleans turn a flag on and off: yes and on, no and off", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: yes\n stream: on\n upload: Yes\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: no\n stream: off\n upload: OFF\n", + "routes": [ + { + "service": "x.y", + "methods": [ + "POST" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": true, + "stream": true, + "upload": true, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.z", + "methods": [ + "POST" + ], + "url": "/b", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "a flag with no value, or an empty one, is off", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing:\n stream: \"\"\n upload: ~\n", + "routes": [ + { + "service": "x.y", + "methods": [ + "POST" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "a flag that is neither true nor false is refused by name - the text yes", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: \"yes\"\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "a flag that is neither true nor false is refused by name - the text on", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n stream: \"on\"\n", + "error": "rest[0] 'stream' must be true or false" + }, + { + "name": "a flag that is neither true nor false is refused by name - a number", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: 1\n", + "error": "rest[0] 'upload' must be true or false" + }, + { + "name": "a flag that is neither true nor false is refused by name - true with blanks around it", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: \" true \"\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "a flag that is neither true nor false is refused by name - a list", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n stream: [true]\n", + "error": "rest[0] 'stream' must be true or false" + }, + { + "name": "a flag that is neither true nor false is refused by name - a reference that did not resolve", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: ${TRACING}\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "the letter y is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: y\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "the letter n is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: n\n", + "error": "rest[0] 'upload' must be true or false" + }, + { + "name": "the index and the name tell which flag of which entry is at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: true\n - service: x.z\n methods: ['POST']\n url: /b\n stream: maybe\n", + "error": "rest[1] 'stream' must be true or false" + }, + { + "name": "an entry's flags are read in the order tracing, stream, upload", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: maybe\n stream: maybe\n", + "error": "rest[0] 'stream' must be true or false" + }, + { + "name": "an unknown cors id is found before a flag at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: maybe\n cors: nope\n", + "error": "rest[0] unknown cors id 'nope'" } ], "timeout_cases": [ From 64dbdf4253909b6c41c728185167e669c5c52a49 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:53:42 -0800 Subject: [PATCH 4/5] fix(agent-tools): one address table and one glob grammar in both packs, a pattern matched in bounded time, and the smaller differences Addresses. The web tools asked the ipaddress module which addresses are private, and its lists differ from one Python version to the next; the Node twin kept its own list and read an IPv4-mapped IPv6 address written in hex as public. Both packs now carry one table, the same text, and the first row of an address's own family that holds it decides. An IPv4 address is refused inside the special-purpose blocks that are not globally reachable and the shared address space (100.64.0.0/10, new here). An IPv6 address is reached only inside the global unicast block 2000::/3, outside 2001::/23, 2001:db8::/32, 2002::/16 and 3fff::/20: every other IPv6 address is refused, an IPv4-mapped one in any spelling among them, so no block has to be listed to be refused. Globs. file.list and file.search used Path.glob, whose reading of `**` changed between Python 3.12 and 3.13, and the Node twin returned nothing for a pattern that ends in `**`. Both packs now compile a glob by one grammar and walk the workspace themselves: `**` is any run of folders and, at the end, everything beneath; a slash at the end names folders only; a symbolic link is an entry and is never descended into; `..` and an absolute pattern are refused by name. A name is matched item by item, going back to the last star only, so the time is bounded by the pattern's length times the name's, however many stars the pattern has. The walk enters only the folders a pattern can still match beneath. The host patterns of tools.web.allow are matched by the same function; fnmatch is no longer used, and differs on one construct (a `!` after a backwards range in a class is a member here, as it already was in the globs). Also, where this pack answered a 500 or differed from its twin: file.list skips a symbolic link whose target is gone; file.write under a file is 400 ` is not a directory`; an address on a page that cannot be read stays as written and its link is skipped, and a redirect to one is a 400; a link's scheme is read in any letter case; file.search counts lines by the line feed; `pages` takes the digits 0 to 9 only; an allowlist entry that starts with a class is a pattern. tests/test_agent_tools.py: 165 passed before, 184 now (1 skipped, the live graph). The probes of the address table, of the globs and of the host patterns are the same text in the Node twin's test file. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-tools/README.md | 23 +- extensions/agent-tools/agent_tools.py | 543 ++++++++++++++--- tests/test_agent_tools.py | 811 +++++++++++++++++++++++++- 3 files changed, 1277 insertions(+), 100 deletions(-) diff --git a/extensions/agent-tools/README.md b/extensions/agent-tools/README.md index ef0b280..2fb6839 100644 --- a/extensions/agent-tools/README.md +++ b/extensions/agent-tools/README.md @@ -66,10 +66,19 @@ the tree. | `file.read` | `file_read` | `path` (required); `max_bytes` (default and cap `tools.file.max.bytes`, 256 KiB) | `{path, bytes, text, truncated}` - `bytes` is the file's size, `truncated` says the text was cut at `max_bytes`; UTF-8 text only, a binary file is a 400 naming the detected type (a PDF, a PNG image, a ZIP archive or an Office document, …) | | `file.write` | `file_write`, **`write: true`** | `path`, `content` (required); `mode`: `create` (default), `overwrite`, `append` | `{path, bytes, mode}`; `create` refuses an existing file with a 409; parent folders are created inside the root; the content is bounded by `tools.file.max.bytes`; `tools.file.write.extensions` may restrict the suffixes | | `file.list` | `file_list` | `path` (a folder, default `.`); `glob` (optional, `*.md` or `**/*.md`); `max_entries` (default 200, cap 2000) | `{entries: [{path, type, bytes, modified}], truncated}`, sorted by path; `type` is `file`, `directory` or `other`; `modified` in UTC | -| `file.search` | `file_search` | `pattern` (required; a literal, or a regular expression with `regex: true`); `path` (default `.`); `glob` (default `**/*`); `case_sensitive` (default false); `context` (default 0, cap 3); `max_results` (default 100, cap 1000) | `{matches: [{path, line, text, before, after}], files_searched, truncated}`; text files only, binaries skipped, each line cut to `tools.file.line.max.chars` (500) | +| `file.search` | `file_search` | `pattern` (required; a literal, or a regular expression with `regex: true`); `path` (default `.`); `glob` (default `**/*`); `case_sensitive` (default false); `context` (default 0, cap 3); `max_results` (default 100, cap 1000) | `{matches: [{path, line, text, before, after}], files_searched, truncated}`; text files only, binaries skipped, a line ends at a line feed (with the carriage return before it) and nowhere else, each line cut to `tools.file.line.max.chars` (500) | | `file.extract` | `file_extract` | `path` (required); `pages` (a range such as `1-3,7`, default all); `max_chars` (default and cap `tools.file.extract.max.chars`, 60 000) | `{path, type, pages, text, truncated}`; `type` is `pdf`, `docx`, `html` or `text`, `pages` the document's page count, the text carries a `--- page N ---` marker before each page; a PDF or Word document needs the `documents` extra (`pypdf`, `python-docx`), without which the tool does not register; an encrypted PDF or another format is a 400 | +A `glob` is a pattern relative to `path`, read by the tool's own walk, the same in both packs: `*` is any run of +characters inside a name, `?` one character, `[seq]` one character of a class and `[!seq]` one outside it; `**` is any +number of folders (`**/*.md`) and, at the end of a pattern, everything beneath (`src/**`); a pattern that ends in `/` +names folders only. Names are matched with their case. A symbolic link is an entry - listed when it stays inside the +workspace and something is there - and a pattern never goes through it. A pattern that is absolute, holds `..` or +names no entry is refused. A name is matched item by item, so the time a pattern takes is bounded by its length times +the length of the path, however many stars it has, and the walk reads only the folders the pattern can still match +in. + `file.write` carries the write mark, so under the node's default mode a person approves it; the other file tools are reads and run unasked. @@ -80,7 +89,12 @@ matches, over `https` (an `http` host must be listed with its scheme), and **eve list**. The host is resolved before the request, every address it resolves to is checked, and the request is made to the address that was checked, so a second resolution cannot point elsewhere. Addresses in loopback, private, link-local, multicast, reserved and unspecified ranges are refused unless `tools.web.allow.private=true`, which closes -the request-forgery route to a cloud metadata service or an internal admin port. The download stops at +the request-forgery route to a cloud metadata service or an internal admin port. One table that both packs carry +decides. An IPv4 address is refused inside the special-purpose blocks that are not globally reachable and the +shared address space (`100.64.0.0/10`). An IPv6 address is reached only inside the global unicast block +(`2000::/3`), outside the four blocks set aside within it (`2001::/23`, `2001:db8::/32`, `2002::/16`, +`3fff::/20`): every other IPv6 address is refused, an IPv4-mapped one in any spelling and the translated +(`64:ff9b::/96`) and IPv4-compatible ones among them. The download stops at `tools.web.max.bytes` (1 MiB), the request at `tools.web.timeout.ms` (10 s), cookies are never kept, and the tool identifies itself as `Mercury-Composable-AgentTools/`. @@ -168,7 +182,7 @@ time zone database (some containers) needs the `tzdata` package for any zone but | `tools.file.hidden` | `false` | expose hidden entries (a name starting with `.`) to the file tools | | `tools.file.write.extensions` | any | the suffixes `file.write` accepts, comma-separated (`.md, .txt`) | | `tools.file.line.max.chars` | `500` | the longest line `file.search` returns | -| `tools.web.allow` | empty | the host patterns the web tools may reach, comma-separated: `docs.example.com`, `*.example.org`, `http://intranet.example`, `host:8443`; empty, the web tools do not register | +| `tools.web.allow` | empty | the host patterns the web tools may reach, comma-separated: `docs.example.com`, `*.example.org`, `http://intranet.example`, `host:8443`; `*` is any run of characters and `[seq]` one character of a class (`[ab].example.com`), and brackets that hold an address are that address (`[::1]:8443`); empty, the web tools do not register | | `tools.web.allow.private` | `false` | allow addresses in loopback, private, link-local and multicast ranges | | `tools.web.max.bytes` | `1048576` | the most bytes read from one response | | `tools.web.timeout.ms` | `10000` | how long one request may take | @@ -289,3 +303,6 @@ scan, the row cap, the delete gate, the ingest's statement order and its endpoin the clause scan, the ingest plan, the error mapping on the driver's own exception classes); `file.extract` on a PDF and a Word document generated in the test; the boot, the health route, the `describe` output and the catalog files complete the suite. The live graph test runs when `TOOLS_GRAPH_TEST_URI` names a database. + +Four texts in the test file are the same, line for line, in the other pack's test file: the probes of the address +classification, the URL probes, and the tree and the probes of the glob grammar. A change to one goes into both. diff --git a/extensions/agent-tools/agent_tools.py b/extensions/agent-tools/agent_tools.py index e1dc2a6..f103f44 100644 --- a/extensions/agent-tools/agent_tools.py +++ b/extensions/agent-tools/agent_tools.py @@ -46,17 +46,18 @@ import asyncio import base64 -import fnmatch import io import ipaddress import json +import os import re import socket +import stat import sys import urllib.robotparser import zipfile from collections import deque -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterable, Sequence from dataclasses import dataclass from datetime import UTC, datetime from html.parser import HTMLParser @@ -780,29 +781,225 @@ def decode_utf8(data: bytes, *, truncated: bool) -> str | None: return None -def _modified(stat: Any) -> str: - moment = datetime.fromtimestamp(stat.st_mtime, tz=UTC) +def _modified(info: os.stat_result) -> str: + moment = datetime.fromtimestamp(info.st_mtime, tz=UTC) return moment.isoformat(timespec="seconds").replace("+00:00", "Z") -def _entry(shown: str, resolved: Path) -> dict[str, Any]: +def _entry(shown: str, info: os.stat_result) -> dict[str, Any]: """One entry of a listing: its path, what it is, its size when it is a file and when it was last modified.""" - stat = resolved.stat() - if resolved.is_dir(): + if stat.S_ISDIR(info.st_mode): kind = "directory" - elif resolved.is_file(): + elif stat.S_ISREG(info.st_mode): kind = "file" else: kind = "other" return { "path": shown, "type": kind, - "bytes": stat.st_size if kind == "file" else 0, - "modified": _modified(stat), + "bytes": info.st_size if kind == "file" else 0, + "modified": _modified(info), } +# One item of the pattern a name is matched against: ``*`` any run of characters, ``?`` any one +# character, any other character itself, or a class - whether it is negated, and its members as +# ranges. +_Item = str | tuple[bool, list[tuple[str, str]]] + + +def _match_run( + pattern: Sequence[Any], subject: Sequence[Any], star: str, holds: Callable[[Any, Any], bool] +) -> bool: + """Whether a pattern holds a subject from end to end: an item of the pattern holds one item + of the subject, and the star any run of them. A mismatch goes back to the last star only, + which then takes one item more, so the time is bounded by the two lengths multiplied - + however many stars the pattern has.""" + at = taken = 0 + star_at = star_taken = -1 + while taken < len(subject): + if at < len(pattern) and pattern[at] == star: + star_at, star_taken = at + 1, taken + at += 1 + elif at < len(pattern) and holds(pattern[at], subject[taken]): + at += 1 + taken += 1 + elif star_at >= 0: + star_taken += 1 + at, taken = star_at, star_taken + else: + return False + while at < len(pattern) and pattern[at] == star: + at += 1 + return at == len(pattern) + + +def _holds_char(item: _Item, char: str) -> bool: + """Whether one item of a name's pattern holds a character: ``?`` any, a class by its + ranges, a character itself.""" + if isinstance(item, str): + return item in ("?", char) + negated, members = item + return any(low <= char <= high for low, high in members) != negated + + +def _match_name(items: Sequence[_Item], name: str) -> bool: + """Whether the items of one segment hold one name - a file's, a folder's or a host's.""" + return _match_run(items, name, "*", _holds_char) + + +@dataclass(frozen=True) +class Glob: + """A compiled glob: its segments - ``**`` for any run of folders, else the items a name is + matched against; how many of them stand before the first ``**``; how deep the walk goes + (``None`` for a recursive pattern); and whether the pattern names folders only.""" + + segments: tuple[str | list[_Item], ...] + lead: int + depth: int | None + folders_only: bool + + def test(self, relative: str) -> bool: + return _match_run(self.segments, relative.split("/"), "**", _match_name) + + def enters(self, name: str, level: int) -> bool: + """Whether the walk goes into a folder it found at a level, counted from 1: only where + the pattern can still match something beneath it. Above the first ``**`` the folder's + name must match the segment at its level, and a segment must be left for what it + holds; beneath the first ``**`` every folder is entered.""" + if level > self.lead: + return self.depth is None + return level != self.depth and _match_name(self.segments[level - 1], name) + + +def _class_members(body: str) -> list[tuple[str, str]]: + """The members of a glob's class as ranges, a single character as a range of one; a range + written backwards holds nothing.""" + members: list[tuple[str, str]] = [] + index = 0 + while index < len(body): + ranged = body.startswith("-", index + 1) and index + 2 < len(body) + low, high = body[index], body[index + 2 if ranged else index] + index += 3 if ranged else 1 + if low <= high: + members.append((low, high)) + return members + + +def _glob_class(segment: str, at: int) -> tuple[_Item, int]: + """The ``[...]`` of a glob that starts at an index of a segment, as an item, with the index + of its ``]``; a ``[`` that never closes is itself, and ends where it stands. A ``!`` first + negates the class and a ``]`` first is a member of it.""" + negated = segment.startswith("!", at + 1) + start = at + 2 if negated else at + 1 + close = segment.find("]", start + 1) + if close < 0: + return "[", at + return (negated, _class_members(segment[start:close])), close + + +def _glob_segment(segment: str) -> list[_Item]: + """One segment of a glob - or a host pattern - as the items a name is matched against: + ``*`` any run of characters, ``?`` one character, ``[...]`` a class, anything else itself.""" + items: list[_Item] = [] + index = 0 + while index < len(segment): + char = segment[index] + if char == "[": + item, index = _glob_class(segment, index) + items.append(item) + elif char != "*" or items[-1:] != ["*"]: + # a run of stars is one + items.append(char) + index += 1 + return items + + +def _glob_segments(parts: list[str]) -> list[str | list[_Item]]: + """The segments of a glob, compiled: ``**`` stays as it is, a run of them as one, and any + other segment becomes its items.""" + segments: list[str | list[_Item]] = [] + for part in parts: + if part != "**": + segments.append(_glob_segment(part)) + elif segments[-1:] != ["**"]: + segments.append(part) + return segments + + +def compile_glob(pattern: str) -> Glob: + """A glob pattern - ``*`` within a name, ``?`` one character, ``[...]`` a class, ``**`` any + number of folders and, at the end of the pattern, everything beneath; a slash at the end for + folders only - compiled to a matcher over slash-separated relative paths, with the depth the + walk needs. The grammar is this function's, the same in the Node.js twin, so the entries + never depend on a runtime's own glob, and the match is made item by item, never by an + expression that could try a pattern of many stars in every way.""" + if pattern.startswith(("/", "\\")) or _DRIVE.match(pattern) or not pattern.strip(): + raise AppException(400, "glob is not a valid pattern (a pattern is relative to path)") + parts = [part for part in pattern.split("/") if part and part != "."] + if ".." in parts: + raise AppException(400, "glob is not a valid pattern (no .. in a pattern)") + if not parts: + raise AppException(400, "glob is not a valid pattern (it names no entry)") + segments = _glob_segments(parts) + recursive = "**" in segments + return Glob( + tuple(segments), + segments.index("**") if recursive else len(segments), + None if recursive else len(segments), + pattern.endswith("/"), + ) + + +def _is_folder(entry: os.DirEntry[str]) -> bool: + """Whether a directory entry is a folder itself - a link to one is not, and neither is an + entry that cannot be asked.""" + try: + return entry.is_dir(follow_symlinks=False) + except OSError: + return False + + +def _scan_entry( + entry: os.DirEntry[str], + here: tuple[str, str, int], + glob: Glob, + found: list[Path], + queue: deque[tuple[str, str, int]], +) -> bool: + """One entry of a walk, in the directory the walk is at: it joins ``found`` when the glob + matches it, and the queue when it is a directory the glob reaches into. True when the scan + limit is passed.""" + _directory, relative_dir, level = here + relative = f"{relative_dir}/{entry.name}" if relative_dir else entry.name + if glob.test(relative): + found.append(Path(entry.path)) + if len(found) > SCAN_LIMIT: + return True + if _is_folder(entry) and glob.enters(entry.name, level): + queue.append((entry.path, relative, level + 1)) + return False + + +def _glob_walk(base: Path, glob: Glob) -> list[Path]: + """Every entry under a directory that matches a compiled glob, bounded by the scan limit; a + symbolic link is an entry, never descended into.""" + found: list[Path] = [] + queue: deque[tuple[str, str, int]] = deque([(str(base), "", 1)]) + while queue and len(found) <= SCAN_LIMIT: + here = queue.popleft() + try: + with os.scandir(here[0]) as listing: + entries = list(listing) + except OSError: + continue + for entry in entries: + if _scan_entry(entry, here, glob, found, queue): + break + return found + + def _search_matcher(pattern: str, *, regex: bool, case_sensitive: bool) -> re.Pattern[str]: """The pattern of a search, compiled: a literal unless it is a regular expression, any case unless the search is case-sensitive.""" @@ -826,6 +1023,18 @@ def _text_bytes(resolved: Path) -> bytes | None: return data +# the end of a line of text: a line feed, with the carriage return before it +_LINE_END = re.compile(r"\r?\n") + + +def _lines_of(data: bytes) -> list[str]: + """The lines of a text file; the newline that ends the file starts no line.""" + lines = _LINE_END.split(data.decode("utf-8", errors="replace")) + if lines[-1] == "": + lines.pop() + return lines + + def _match_lines( lines: list[str], matcher: re.Pattern[str], @@ -888,44 +1097,64 @@ def resolve(self, text: str, *, what: str = "path") -> tuple[Path, str]: return resolved, relative def _inside(self, entry: Path) -> Path | None: - """The resolved target of a directory entry when it stays inside the workspace, else None.""" + """The resolved target of a directory entry when it is there and stays inside the + workspace, else None.""" try: - resolved = entry.resolve() + resolved = entry.resolve(strict=True) except (OSError, RuntimeError): return None if resolved != self.root and self.root not in resolved.parents: return None return resolved + def _exposed_entry( + self, entry: Path, *, files_only: bool, folders_only: bool + ) -> tuple[str, Path, os.stat_result] | None: + """A walked entry as the workspace shows it - its relative path, its real path and what + it is - or None for one that is hidden, escapes the workspace, is gone, or is not of the + kind that counts.""" + try: + relative = entry.relative_to(self.root).as_posix() + except ValueError: + return None + if not self.sandbox.hidden and _is_hidden(relative): + return None + resolved = self._inside(entry) + if resolved is None: + return None + try: + info = resolved.stat() + except OSError: + return None + if files_only and not stat.S_ISREG(info.st_mode): + return None + if folders_only and not stat.S_ISDIR(info.st_mode): + return None + return relative, resolved, info + def _walk( self, base: Path, pattern: str | None, *, files_only: bool - ) -> tuple[list[tuple[str, Path]], bool]: - """The entries under a directory, sorted by their workspace-relative path, as (relative, - resolved) pairs; hidden entries and entries that escape the workspace are left out. The - second value says the walk hit the scan bound.""" - try: - candidates = base.glob(pattern) if pattern else base.iterdir() - except (ValueError, NotImplementedError) as exc: - raise AppException(400, f"glob is not a valid pattern ({exc})") from exc - found: list[tuple[str, Path]] = [] + ) -> tuple[list[tuple[str, Path, os.stat_result]], bool]: + """The entries under a directory, sorted by their workspace-relative path, each with its + real path and what it is; hidden entries, entries that escape the workspace and entries + that are gone are left out. The second value says the walk hit the scan bound.""" + folders_only = False + candidates: Iterable[Path] + if pattern: + glob = compile_glob(pattern) + folders_only = glob.folders_only + candidates = _glob_walk(base, glob) + else: + candidates = base.iterdir() + found: list[tuple[str, Path, os.stat_result]] = [] bounded = False - try: - for entry in candidates: - if len(found) >= SCAN_LIMIT: - bounded = True - break - try: - relative = entry.relative_to(self.root).as_posix() - except ValueError: - continue - if not self.sandbox.hidden and _is_hidden(relative): - continue - resolved = self._inside(entry) - if resolved is None or (files_only and not resolved.is_file()): - continue - found.append((relative, resolved)) - except (ValueError, NotImplementedError) as exc: - raise AppException(400, f"glob is not a valid pattern ({exc})") from exc + for entry in candidates: + if len(found) >= SCAN_LIMIT: + bounded = True + break + exposed = self._exposed_entry(entry, files_only=files_only, folders_only=folders_only) + if exposed is not None: + found.append(exposed) found.sort(key=lambda item: item[0]) return found, bounded @@ -942,6 +1171,16 @@ def _directory(self, path: str) -> Path: ) return base + def _file_above(self, target: Path) -> str | None: + """The workspace-relative path of the file a path runs through where a folder must be, + or None when every folder above the path is one or is yet to be made.""" + for parent in target.parents: + if parent.is_dir(): + return None + if parent.exists(): + return parent.relative_to(self.root).as_posix() + return None + def read(self, _headers: dict[str, str], body: Body) -> Any: args = _arguments(body, FILE_READ_ROW) path = _string(args, "path") @@ -991,6 +1230,9 @@ def write(self, _headers: dict[str, str], body: Body) -> Any: raise AppException( 409, f"{relative} exists - mode overwrite replaces it, append extends it" ) + above = self._file_above(target) + if above is not None: + raise AppException(400, f"{above} is not a directory") target.parent.mkdir(parents=True, exist_ok=True) flags = {"create": "xb", "overwrite": "wb", "append": "ab"}[mode] try: @@ -1013,8 +1255,8 @@ def list(self, _headers: dict[str, str], body: Body) -> Any: base = self._directory(path) found, bounded = self._walk(base, pattern or None, files_only=False) entries: list[dict[str, Any]] = [] - for shown, resolved in found[:max_entries]: - entries.append(_entry(shown, resolved)) + for shown, _resolved, info in found[:max_entries]: + entries.append(_entry(shown, info)) truncated = bounded or len(found) > max_entries log.info("file.list 200 %d entries%s", len(entries), _CUT_MARK if truncated else "") return {"entries": entries, "truncated": truncated} @@ -1037,16 +1279,21 @@ def search(self, _headers: dict[str, str], body: Body) -> Any: matches: list[dict[str, Any]] = [] searched = 0 truncated = bounded - for shown, resolved in found: + for shown, resolved, _info in found: if truncated and len(matches) >= max_results: break data = _text_bytes(resolved) if data is None: continue searched += 1 - lines = data.decode("utf-8", errors="replace").splitlines() if _match_lines( - lines, matcher, shown, matches, context=context, width=width, limit=max_results + _lines_of(data), + matcher, + shown, + matches, + context=context, + width=width, + limit=max_results, ): truncated = True if truncated and len(matches) >= max_results: @@ -1148,14 +1395,27 @@ def document_kind(data: bytes, suffix: str) -> str | None: return "text" +# one part of a page selection: a page number, or two with a dash between; \d is the digits 0 to 9 +# only under re.ASCII - without the flag it would let in the digits of every script +_PAGE_SPAN = re.compile(r"(\d+)(?:-(\d+))?", re.ASCII) + + +def _page_number(digits: str) -> int: + """A run of digits as a page number; a run too long for the integer reader is a page beyond + any document.""" + try: + return int(digits) + except ValueError: + return sys.maxsize + + def _page_span(part: str) -> tuple[int, int]: """``7`` or ``1-3`` to the first and the last page number it names, counted from 1.""" - first, dash, last = part.partition("-") - try: - start = int(first) - end = int(last) if dash else start - except ValueError as exc: - raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") from exc + match = _PAGE_SPAN.fullmatch(part) + if match is None: + raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") + start = _page_number(match.group(1)) + end = start if match.group(2) is None else _page_number(match.group(2)) if start < 1 or end < start: raise AppException( 400, "pages must be page numbers and ranges such as 1-3,7, counted from 1" @@ -1282,6 +1542,15 @@ def _docx_text(data: bytes, relative: str) -> str: _SPACES = re.compile(r"[ \t\r\n\f\v]+") +def _safe_join(base: str, href: str) -> str: + """A reference joined to the address it was read at; one that cannot be read as an address + stays as written.""" + try: + return urljoin(base, href) + except ValueError: + return href + + def _is_chrome(attrs: list[tuple[str, str | None]]) -> bool: for name, value in attrs: if name == "role" and (value or "").strip().lower() in _DROP_ROLES: @@ -1354,9 +1623,9 @@ def _start_link(self, attrs: list[tuple[str, str | None]]) -> None: """Open a link when the element has a target a reader can follow - not a fragment, a script, a mail or a phone link; the link that was open is closed first.""" href = dict(attrs).get("href") - if href and not href.startswith(("#", "javascript:", "mailto:", "tel:")): + if href and not href.lower().startswith(("#", "javascript:", "mailto:", "tel:")): self._end_link() - self._href = urljoin(self.base_url, href) if self.base_url else href + self._href = _safe_join(self.base_url, href) if self.base_url else href self._link_text = [] # -- the parser's callbacks @@ -1526,23 +1795,46 @@ def parse_host_rules(entries: tuple[str, ...]) -> tuple[HostRule, ...]: if scheme not in ("http", "https"): raise ToolsError(f"{WEB_ALLOW}: {entry} - the scheme must be http or https") if "/" in text or "?" in text or "@" in text or not text: - raise ToolsError( - f"{WEB_ALLOW}: {entry} is not a host pattern (a host, a *.pattern, " - f"optionally with http:// or a :port)" - ) - port: int | None = None - host = text - if text.startswith("["): - host, _, rest = text[1:].partition("]") - if rest.startswith(":"): - port = _port(entry, rest[1:]) - elif text.count(":") == 1: - host, _, port_text = text.partition(":") - port = _port(entry, port_text) + raise _not_a_host_pattern(entry) + host, port = _host_and_port(entry, text) rules.append(HostRule(pattern=host.lower().rstrip("."), scheme=scheme, port=port)) return tuple(rules) +def _not_a_host_pattern(entry: str) -> ToolsError: + return ToolsError( + f"{WEB_ALLOW}: {entry} is not a host pattern (a host, a *.pattern, " + f"optionally with http:// or a :port)" + ) + + +def _is_address(text: str) -> bool: + try: + ipaddress.ip_address(text) + except ValueError: + return False + return True + + +def _host_and_port(entry: str, text: str) -> tuple[str, int | None]: + """The host of a pattern, and its port when it names one: ``[::1]:8080`` for an address in + brackets, ``host:8443`` when there is one colon. Brackets that hold no address are a class + of the pattern (``[ab].example.com``); brackets that never close, and an address in + brackets with anything but a port after it, are no host pattern.""" + if text.startswith("["): + inside, closed, rest = text[1:].partition("]") + if not closed: + raise _not_a_host_pattern(entry) + if _is_address(inside): + if rest and not rest.startswith(":"): + raise _not_a_host_pattern(entry) + return inside, (_port(entry, rest[1:]) if rest else None) + if text.count(":") == 1: + host, _, port_text = text.partition(":") + return host, _port(entry, port_text) + return text, None + + def _port(entry: str, text: str) -> int: try: port = int(text) @@ -1553,6 +1845,19 @@ def _port(entry: str, text: str) -> int: return port +# what a URL is told when it is no http(s) address, or none the reader can take apart +_NOT_A_WEB_ADDRESS = "url must start with https:// (or http:// for a host listed with it)" + + +def _url_parts(url: str) -> SplitResult: + """A URL taken apart; one the reader refuses - brackets that hold no address - is no web + address.""" + try: + return urlsplit(url.strip()) + except ValueError as exc: + raise AppException(400, _NOT_A_WEB_ADDRESS) from exc + + @dataclass(frozen=True) class WebSandbox: """The allowlist and the limits of the web tools.""" @@ -1569,7 +1874,8 @@ def matches(self, host: str, scheme: str, port: int) -> tuple[bool, bool]: """Whether a host is listed at all, and whether it is allowed over this scheme and port.""" listed = False for rule in self.rules: - if not fnmatch.fnmatchcase(host, rule.pattern): + # a host pattern is one segment of a glob, read and matched by the same functions + if not _match_name(_glob_segment(rule.pattern), host): continue listed = True if (scheme == "https" or rule.scheme == "http") and ( @@ -1582,12 +1888,10 @@ def check_url(self, url: str) -> SplitResult: """The URL a tool may fetch, by the allowlist alone (no network): an http(s) URL without credentials, whose host is listed for its scheme and port. Anything else is a 400 that names the rule; the fragment is dropped.""" - parts = urlsplit(url.strip()) + parts = _url_parts(url) scheme = parts.scheme.lower() if scheme not in ("http", "https"): - raise AppException( - 400, "url must start with https:// (or http:// for a host listed with it)" - ) + raise AppException(400, _NOT_A_WEB_ADDRESS) if parts.username is not None or parts.password is not None: raise AppException(400, "url must not carry credentials") host = (parts.hostname or "").lower().rstrip(".") @@ -1659,26 +1963,66 @@ async def _resolve(host: str, port: int) -> list[ipaddress.IPv4Address | ipaddre return addresses +# The address blocks the web tools refuse by default, each with the kind a refusal names and, for +# the reader, what the block is. The first row that holds an address decides, and a row holds only +# addresses of its own family. An IPv4 address is public unless a row holds it: the rows are the +# special-purpose blocks that are not globally reachable, and the shared address space. An IPv6 +# address is public only inside the global unicast block and outside the four blocks set aside +# within it; every other IPv6 address is refused by the last row, an IPv4-mapped one among them, +# so no block has to be listed to be refused. The rows are written out, never asked of the +# ipaddress module, whose own lists differ from one Python version to the next, and the Node.js +# twin carries the same text. +_ADDRESS_TABLE = """ +127.0.0.0/8 loopback +169.254.0.0/16 link-local +224.0.0.0/4 multicast +0.0.0.0/32 unspecified +0.0.0.0/8 private this network +10.0.0.0/8 private +100.64.0.0/10 private the shared address space of carrier-grade NAT +172.16.0.0/12 private +192.0.0.0/24 private IETF protocol assignments +192.0.2.0/24 private documentation +192.168.0.0/16 private +198.18.0.0/15 private benchmarking +198.51.100.0/24 private documentation +203.0.113.0/24 private documentation +240.0.0.0/4 private reserved, the limited broadcast address among it +::1/128 loopback +fe80::/10 link-local +ff00::/8 multicast +::/128 unspecified +fc00::/7 private unique local +2001::/23 private IETF protocol assignments, Teredo among them +2001:db8::/32 private documentation +2002::/16 private 6to4 +3fff::/20 private documentation +2000::/3 public global unicast +::/0 reserved every other IPv6 address, the IPv4-mapped ones among them +""" + + +def _address_ranges( + table: str, +) -> tuple[tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, str | None], ...]: + """The rows of the table as a block and its kind - ``None`` for a public block.""" + rows = [line.split() for line in table.splitlines() if line] + return tuple( + (ipaddress.ip_network(row[0]), None if row[1] == "public" else row[1]) for row in rows + ) + + +_ADDRESS_RANGES = _address_ranges(_ADDRESS_TABLE) + + def address_kind(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> str | None: """Why an address is refused by default - loopback, private, link-local, multicast, - reserved or unspecified - or ``None`` for a public address.""" - candidate: ipaddress.IPv4Address | ipaddress.IPv6Address = address - if isinstance(address, ipaddress.IPv6Address): - mapped = address.ipv4_mapped - if mapped is not None: - candidate = mapped - if candidate.is_loopback: - return "loopback" - if candidate.is_link_local: - return "link-local" - if candidate.is_multicast: - return "multicast" - if candidate.is_unspecified: - return "unspecified" - if candidate.is_private: - return "private" - if candidate.is_reserved: - return "reserved" + reserved or unspecified - or ``None`` for a public address: the kind of the first row of + the table that holds it. A block holds only addresses of its own family, so an IPv4-mapped + IPv6 address is an IPv6 address outside the global unicast block, and is refused.""" + for network, kind in _ADDRESS_RANGES: + if address in network: + return kind return None @@ -1785,16 +2129,23 @@ class _Crawl: truncated: bool = False +def _site(parts: SplitResult) -> tuple[str, str, int | None]: + """The site a URL is on, as a crawl compares it: its scheme, its host as the URL names it + and its port.""" + return parts.scheme.lower(), (parts.hostname or "").lower(), parts.port + + def _follow_links(links: list[str], depth: int, crawl: _Crawl) -> None: """The links of a page that a crawl goes on to, one link deeper: the ones on its own site and - inside its include, each once and without its fragment.""" + inside its include, each once and without its fragment. A link that cannot be read as an + address - brackets that hold none, a port that is no number - is passed over.""" for link in links: - candidate = urlsplit(link) - if ( - candidate.scheme.lower(), - (candidate.hostname or "").lower(), - candidate.port, - ) != crawl.site: + try: + candidate = urlsplit(link) + site = _site(candidate) + except ValueError: + continue + if site != crawl.site: continue if crawl.include and not _under(candidate.path, crawl.include): continue @@ -1865,7 +2216,7 @@ async def _request(self, session: aiohttp.ClientSession, current: str) -> Fetche ) as response: location = response.headers.get("Location") if response.status in REDIRECT_STATUSES and location: - return urljoin(urlunsplit(parts), location) + return _safe_join(urlunsplit(parts), location) data, truncated = await self._body(response) content_type = (response.content_type or "").lower() return Fetched( @@ -2000,7 +2351,7 @@ async def web_crawl(self, _headers: dict[str, str], body: Body) -> Any: if include is not None and not isinstance(include, str): raise AppException(400, "include must be a string") start = self.sandbox.check_url(url) - site = (start.scheme, (start.hostname or "").lower(), start.port) + site = _site(start) robots = await self._robots(start) start_url = urlunsplit(start) crawl = _Crawl( diff --git a/tests/test_agent_tools.py b/tests/test_agent_tools.py index 55d2a64..04bf0fd 100644 --- a/tests/test_agent_tools.py +++ b/tests/test_agent_tools.py @@ -13,6 +13,7 @@ from __future__ import annotations import asyncio +import contextlib import importlib.util import io import json @@ -20,11 +21,13 @@ import os import re import sys +import time from collections.abc import AsyncIterator, Callable, Iterator from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path from typing import Any +from urllib.parse import urlsplit import pytest import pytest_asyncio @@ -122,6 +125,11 @@ async def _astatus(coroutine: Any) -> tuple[int, str]: raise AssertionError("expected a refusal") +def _probes(block: str) -> list[list[str]]: + """The rows of a block of probes: the words of every line that is not a comment.""" + return [line.split() for line in block.splitlines() if line and not line.startswith("#")] + + # --- the workspace ------------------------------------------------------------------------------- @@ -307,6 +315,26 @@ def test_write_respects_the_extension_list_and_the_size_limit( assert "over the workspace's limit of 1024" in message +def test_write_refuses_a_path_that_runs_through_a_file(files: Any, workspace: Path) -> None: + for path in ("notes/plan.md/x.txt", "notes/plan.md/deep/x.txt"): + for mode in ("create", "overwrite", "append"): + body = {"path": path, "content": "a", "mode": mode} + assert _status(lambda body=body: files.write({}, body)) == ( + 400, + "notes/plan.md is not a directory", + ) + assert (workspace / "notes" / "plan.md").read_text(encoding="utf-8") == ( + "# Plan\n\nWrite the tools.\n" + ) + + +def test_list_skips_a_link_whose_target_is_gone(files: Any, workspace: Path) -> None: + os.symlink(workspace / "nowhere", workspace / "notes" / "gone") + assert [e["path"] for e in files.list({}, {"path": "notes"})["entries"]] == ["notes/plan.md"] + assert [e["path"] for e in files.list({}, {"glob": "notes/*"})["entries"]] == ["notes/plan.md"] + assert files.search({}, {"pattern": "Plan", "path": "notes"})["files_searched"] == 1 + + def test_list_the_root_and_a_folder(files: Any) -> None: reply = files.list({}, {}) assert reply["truncated"] is False @@ -351,6 +379,232 @@ def test_list_with_a_glob_and_a_cap(files: Any) -> None: ) +# The tree and the probes of the glob grammar. The Node.js twin's test file carries the same two +# texts, line for line: the walk is each pack's own, so a pattern returns the same entries in both. +GLOB_TREE = r""" +# the tree: a file, a folder, or a link and where it points (outside is a folder beside the workspace) +file README.md +file a.py +file Upper.PY +file src/app.py +file src/util.py +file src/README.md +file src/pkg/mod.py +file src/pkg/deep/leaf.py +file src/pkg/deep/leaf.txt +file docs/guide.md +file docs/api/index.md +file docs/api/v1/ref.md +folder empty +file .env +file .hidden/secret.md +file src/.cache/x.py +file odd/[x].txt +file odd/x.txt +file odd/y.txt +file odd/-.txt +file odd/!.txt +file odd/^.txt +file odd/].txt +file odd/a]b.txt +file odd/star*.txt +file odd/q?.txt +file odd/x.tx +file odd/x.txtt +file odd/noext +file odd/café.txt +file odd/😀.txt +link link-file.py src/app.py +link link-dir docs +link docs/link-pkg src/pkg +link link-out ../outside +link link-dangling nowhere +""" + +GLOB_PROBES = r""" +# a path, a glob and the entries file.list returns for them, a folder with a slash at its end +. ** => README.md Upper.PY a.py docs/ docs/api/ docs/api/index.md docs/api/v1/ docs/api/v1/ref.md docs/guide.md docs/link-pkg/ empty/ link-dir/ link-file.py odd/ odd/!.txt odd/-.txt odd/[x].txt odd/].txt odd/^.txt odd/a]b.txt odd/café.txt odd/noext odd/q?.txt odd/star*.txt odd/x.tx odd/x.txt odd/x.txtt odd/y.txt odd/😀.txt src/ src/README.md src/app.py src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py src/util.py +. **/* => README.md Upper.PY a.py docs/ docs/api/ docs/api/index.md docs/api/v1/ docs/api/v1/ref.md docs/guide.md docs/link-pkg/ empty/ link-dir/ link-file.py odd/ odd/!.txt odd/-.txt odd/[x].txt odd/].txt odd/^.txt odd/a]b.txt odd/café.txt odd/noext odd/q?.txt odd/star*.txt odd/x.tx odd/x.txt odd/x.txtt odd/y.txt odd/😀.txt src/ src/README.md src/app.py src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py src/util.py +. src/**/** => src/ src/README.md src/app.py src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py src/util.py +. src/** => src/ src/README.md src/app.py src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py src/util.py +src ** => src/README.md src/app.py src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py src/util.py +src/pkg ** => src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py +empty ** => +. docs/api/** => docs/api/ docs/api/index.md docs/api/v1/ docs/api/v1/ref.md +. **/pkg/** => src/pkg/ src/pkg/deep/ src/pkg/deep/leaf.py src/pkg/deep/leaf.txt src/pkg/mod.py +# a slash at the end: folders only +. **/ => docs/ docs/api/ docs/api/v1/ docs/link-pkg/ empty/ link-dir/ odd/ src/ src/pkg/ src/pkg/deep/ +. */ => docs/ empty/ link-dir/ odd/ src/ +. src/**/ => src/ src/pkg/ src/pkg/deep/ +. src/*.py/ => +# within a folder, and across folders with ** +. * => README.md Upper.PY a.py docs/ empty/ link-dir/ link-file.py odd/ src/ +. *.py => a.py link-file.py +. **/*.py => a.py link-file.py src/app.py src/pkg/deep/leaf.py src/pkg/mod.py src/util.py +. src/**/*.py => src/app.py src/pkg/deep/leaf.py src/pkg/mod.py src/util.py +. **/**/*.md => README.md docs/api/index.md docs/api/v1/ref.md docs/guide.md src/README.md +. src/* => src/README.md src/app.py src/pkg/ src/util.py +. src/*/* => src/pkg/deep/ src/pkg/mod.py +. */*.md => docs/guide.md src/README.md +. **/deep => src/pkg/deep/ +. **/leaf.* => src/pkg/deep/leaf.py src/pkg/deep/leaf.txt +. src => src/ +. src/pkg/deep/leaf.py => src/pkg/deep/leaf.py +. nothing => +# ** that is not a whole segment is a star; . and empty segments count for nothing +. **.py => a.py link-file.py +. src/**.py => src/app.py src/util.py +. src/*** => src/README.md src/app.py src/pkg/ src/util.py +. ./src/*.py => src/app.py src/util.py +. src/./*.py => src/app.py src/util.py +. src//*.py => src/app.py src/util.py +# names are matched with their case +. *.PY => Upper.PY +. upper.py => +. [Uu]pper.* => Upper.PY +# classes: ! first negates, ^ is a member, a ] first is a member, a range written backwards holds nothing, +# a [ that never closes is itself, and no class matches the slash +. odd/[x].txt => odd/x.txt +. odd/[[]x].txt => odd/[x].txt +. odd/[xy].txt => odd/x.txt odd/y.txt +. odd/[!x].txt => odd/!.txt odd/-.txt odd/].txt odd/^.txt odd/y.txt odd/😀.txt +. odd/[^x].txt => odd/^.txt odd/x.txt +. odd/[x-y].txt => odd/x.txt odd/y.txt +. odd/[y-x].txt => +. odd/[]].txt => odd/].txt +. odd/[!]].txt => odd/!.txt odd/-.txt odd/^.txt odd/x.txt odd/y.txt odd/😀.txt +. odd/[]x].txt => odd/].txt odd/x.txt +. odd/[-x].txt => odd/-.txt odd/x.txt +. odd/[x-].txt => odd/-.txt odd/x.txt +. odd/[.txt => +. odd/[x.txt => +. odd/[!].txt => +. odd/a[]]b.txt => odd/a]b.txt +. odd/star[*].txt => odd/star*.txt +. odd/star*.txt => odd/star*.txt +. odd/q[?].txt => odd/q?.txt +. odd[!x]x.txt => +. odd[+-a]x.txt => +# ? is one character, whatever its size +. odd/?.txt => odd/!.txt odd/-.txt odd/].txt odd/^.txt odd/x.txt odd/y.txt odd/😀.txt +. odd/??.txt => odd/q?.txt +. odd/caf?.txt => odd/café.txt +. odd/x.tx? => odd/x.txt +. odd/*.t* => odd/!.txt odd/-.txt odd/[x].txt odd/].txt odd/^.txt odd/a]b.txt odd/café.txt odd/q?.txt odd/star*.txt odd/x.tx odd/x.txt odd/x.txtt odd/y.txt odd/😀.txt +# hidden entries are not exposed +. .* => +. **/.cache/* => +# a link is an entry: it is shown when it stays inside the workspace and something is there, and a +# pattern never goes through it; the path argument is resolved first, links followed +. link-* => link-dir/ link-file.py +. link-file.py => link-file.py +. link-dir => link-dir/ +. link-dir/* => +. link-dir/** => link-dir/ +. docs/link-pkg/** => docs/link-pkg/ +. **/mod.py => src/pkg/mod.py +. link-out => +. link-out/* => +. link-dangling => +link-dir * => docs/api/ docs/guide.md docs/link-pkg/ +# refused by rule +. .. => 400 glob is not a valid pattern (no .. in a pattern) +. ../* => 400 glob is not a valid pattern (no .. in a pattern) +. src/../*.md => 400 glob is not a valid pattern (no .. in a pattern) +. /abs/* => 400 glob is not a valid pattern (a pattern is relative to path) +. \abs => 400 glob is not a valid pattern (a pattern is relative to path) +. C:\x => 400 glob is not a valid pattern (a pattern is relative to path) +. C:x => 400 glob is not a valid pattern (a pattern is relative to path) +. . => 400 glob is not a valid pattern (it names no entry) +. ./ => 400 glob is not a valid pattern (it names no entry) +""" + + +@pytest.fixture +def glob_files(tmp_path: Path, configure: Callable[[dict[str, Any]], None]) -> Any: + """The file tools over the tree GLOB_TREE describes.""" + root = tmp_path / "root" + (tmp_path / "outside").mkdir() + root.mkdir() + for kind, name, *target in _probes(GLOB_TREE): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + if kind == "file": + path.write_text(f"{name}\n", encoding="utf-8") + elif kind == "folder": + path.mkdir() + else: + os.symlink(root / target[0], path) + configure({tools.FILE_ROOT: str(root)}) + return tools.FileTools(tools.load_file_sandbox()) + + +def _listed(files: Any, path: str, glob: str) -> str: + """What file.list answers for a path and a glob, as the probes write it: the entries, a + folder with a slash at its end, or the status and the message of a refusal.""" + try: + entries = files.list({}, {"path": path, "glob": glob, "max_entries": 2000})["entries"] + except AppException as exc: + return f"{exc.status} {exc.message}" + return " ".join(e["path"] + ("/" if e["type"] == "directory" else "") for e in entries) + + +def test_a_glob_returns_the_same_entries_in_both_packs(glob_files: Any) -> None: + wrong: list[tuple[str, str, str]] = [] + for line in GLOB_PROBES.split("\n"): + if not line or line.startswith("#"): + continue + probe, _, expected = line.partition(" =>") + path, glob = probe.split() + got = _listed(glob_files, path, glob) + if got != expected.strip(): + wrong.append((probe, expected.strip(), got)) + assert wrong == [], "a pattern that ends in ** names everything beneath" + assert _listed(glob_files, ".", " ") == ( + "400 glob is not a valid pattern (a pattern is relative to path)" + ) + + +def test_a_search_walks_the_files_its_glob_names(glob_files: Any) -> None: + everything = glob_files.search({}, {"pattern": "leaf", "glob": "**"}) + assert everything["files_searched"] == 28, "every file beneath, a link to a file among them" + assert [m["path"] for m in everything["matches"]] == [ + "src/pkg/deep/leaf.py", + "src/pkg/deep/leaf.txt", + ] + assert glob_files.search({}, {"pattern": "leaf"})["files_searched"] == 28 + beneath = glob_files.search({}, {"pattern": "leaf", "glob": "src/**"}) + assert beneath["files_searched"] == 6 + assert len(beneath["matches"]) == 2 + assert glob_files.search({}, {"pattern": "leaf", "glob": "*/"})["files_searched"] == 0, ( + "a pattern that ends in a slash names folders, and a search reads files" + ) + + +def test_the_walk_reads_only_the_folders_a_pattern_can_reach( + glob_files: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + read: list[str] = [] + scandir = os.scandir + + def counting(path: str) -> Any: + read.append(os.path.relpath(path, glob_files.root)) + return scandir(path) + + monkeypatch.setattr(tools.os, "scandir", counting) + assert _listed(glob_files, ".", "src/pkg/*.py") == "src/pkg/mod.py" + assert sorted(read) == [".", "src", "src/pkg"], ( + "a folder is entered only when its name matches the segment at its level" + ) + read.clear() + assert _listed(glob_files, ".", "src/**/*.py") == ( + "src/app.py src/pkg/deep/leaf.py src/pkg/mod.py src/util.py" + ) + assert sorted(read) == [".", "src", "src/.cache", "src/pkg", "src/pkg/deep"], ( + "beneath the first ** every folder is entered" + ) + + def test_search_literal_regex_case_and_context(files: Any) -> None: reply = files.search({}, {"pattern": "todo"}) assert reply["files_searched"] == 5, "text files only - the binaries are skipped" @@ -400,6 +654,19 @@ def test_search_caps_and_refusals( assert _status(lambda: files.search({}, {"pattern": "a", "path": "../"}))[0] == 400 +def test_search_counts_lines_by_the_line_feed(files: Any, workspace: Path) -> None: + first = "one\rtwo\x0bthree\x0cfour\x1cfive\x1dsix\x1eseven\x85eight\u2028nine\u2029ten" + (workspace / "lines.txt").write_bytes(f"{first}\r\neleven\nneedle\n".encode()) + + def found(pattern: str) -> list[tuple[int, str]]: + reply = files.search({}, {"pattern": pattern, "glob": "lines.txt"}) + return [(m["line"], m["text"]) for m in reply["matches"]] + + assert found("needle") == [(3, "needle")], "a line ends at a line feed, and nowhere else" + assert found("eleven") == [(2, "eleven")] + assert found("four") == [(1, first)], "the carriage return before a line feed ends the line" + + # --- HTML to text -------------------------------------------------------------------------------- PAGE = """ Page Title @@ -466,6 +733,37 @@ def test_html_to_text_survives_broken_markup() -> None: assert tools.html_to_text("", "")[1] == "" +def test_html_names_match_the_tables_own_keys_only() -> None: + assert tools.html_to_text("

a &constructor; b &valueOf; c < d

")[1] == ( + "a &constructor; b &valueOf; c < d" + ) + page = "

before

inside

after

" + assert tools.html_to_text(page)[1] == "before\n\ninside\n\nafter" + assert tools.html_to_text(page, markdown=True)[1] == "before\n\ninside\n\nafter", ( + "an element that is no heading is not read as one" + ) + + +def test_a_link_scheme_is_read_in_any_case() -> None: + page = ( + '

one two ' + 'three four

' + ) + _title, text, links = tools.html_to_text(page, "https://h/", markdown=True) + assert links == ["https://h/ok"], "a script, a mail and a phone link are no links to follow" + assert text == "one two three [four](https://h/ok)" + + +def test_an_address_that_cannot_be_read_stays_as_written() -> None: + page = ( + '

one two ' + 'three four

' + ) + _title, text, links = tools.html_to_text(page, "https://h/") + assert text == "one two three four" + assert links == ["http://[bad", "//[bad/x", "http://h:port/x", "https://h/ok"] + + # --- the web sandbox without a network ----------------------------------------------------------- @@ -506,6 +804,76 @@ def test_host_rules_are_parsed_with_scheme_and_port() -> None: assert message in str(failure.value) +def test_an_allowlist_entry_that_starts_with_a_class_is_a_pattern() -> None: + rules = tools.parse_host_rules( + ( + "[ab].example.com", + "[ab].example.com:8443", + "http://[!ab].example.org", + "[::1]:8080", + "[127.0.0.1]", + "x[y.example.net", + ) + ) + assert [(r.pattern, r.scheme, r.port) for r in rules] == [ + ("[ab].example.com", "https", None), + ("[ab].example.com", "https", 8443), + ("[!ab].example.org", "http", None), + ("::1", "https", 8080), + ("127.0.0.1", "https", None), + ("x[y.example.net", "https", None), + ] + for bad in ("[::1]x", "[::1", "[ab.example.com"): + with pytest.raises(tools.ToolsError) as failure: + tools.parse_host_rules((bad,)) + assert f"{bad} is not a host pattern" in str(failure.value) + sandbox = tools.WebSandbox(rules=rules) + assert sandbox.check_url("https://a.example.com/").geturl() == "https://a.example.com/" + assert sandbox.check_url("https://b.example.com:8443/").geturl() == ( + "https://b.example.com:8443/" + ) + assert sandbox.check_url("http://c.example.org/x").geturl() == "http://c.example.org/x" + for url, host in ( + ("https://c.example.com/", "c.example.com"), + ("https://ab/", "ab"), + ("http://a.example.org/", "a.example.org"), + ("https://xy.example.net/", "xy.example.net"), + ): + assert _status(lambda url=url: sandbox.check_url(url)) == ( + 400, + f"{host} is not one of the sites this agent may reach ({tools.WEB_ALLOW})", + ) + + +def test_an_exclamation_mark_negates_a_class_only_when_it_is_first() -> None: + glob = tools.compile_glob("[b-a!x]") + assert [glob.test(name) for name in ("x", "!", "y")] == [True, True, False], ( + "a range written backwards holds nothing, and the ! after it is a member" + ) + sandbox = tools.WebSandbox( + rules=tools.parse_host_rules(("[b-a!x].example.com", "[!b-a!x].example.org")) + ) + assert sandbox.matches("x.example.com", "https", 443) == (True, True) + assert sandbox.matches("y.example.com", "https", 443) == (False, False) + assert sandbox.matches("y.example.org", "https", 443) == (True, True) + assert sandbox.matches("x.example.org", "https", 443) == (False, False) + + +def test_a_pattern_of_many_stars_is_matched_in_bounded_time() -> None: + pattern = "*a" * 11 + "*b" # twelve stars, a literal between each + name = "a" * 5000 # every literal but the last is there + began = time.perf_counter() + assert tools.compile_glob(pattern).test(name) is False + assert tools.compile_glob(pattern).test(f"{name}b") is True + folders = "/".join("a" * 400) # and the same one level up: twelve ** over 400 folders + assert tools.compile_glob("**/a/" * 12 + "b").test(folders) is False + sandbox = tools.WebSandbox(rules=tools.parse_host_rules((pattern,))) + assert sandbox.matches(name, "https", 443) == (False, False) + assert time.perf_counter() - began < 2, ( + "the time is bounded by the pattern times the name, however many stars" + ) + + @pytest.fixture def sandbox() -> Any: rules = tools.parse_host_rules( @@ -564,7 +932,7 @@ def test_check_url_refuses_by_rule(sandbox: Any, url: str, message: str) -> None ("224.0.0.1", "multicast"), ("0.0.0.0", "unspecified"), ("::1", "loopback"), - ("::ffff:10.0.0.1", "private"), + ("::ffff:10.0.0.1", "reserved"), ("fe80::1", "link-local"), ("fc00::1", "private"), ("93.184.216.34", None), @@ -577,6 +945,319 @@ def test_address_kinds(address: str, kind: str | None) -> None: assert tools.address_kind(ipaddress.ip_address(address)) == kind +# The probes of the address classification - an address and the kind its refusal names, `public` +# where it is not refused. The Node.js twin's test file carries the same text, line for line. +ADDRESS_PROBES = """ +# IPv4: each block of the table at its first and its last address, and the address on either side +126.255.255.255 public +127.0.0.0 loopback +127.255.255.255 loopback +128.0.0.0 public +169.253.255.255 public +169.254.0.0 link-local +169.254.255.255 link-local +169.255.0.0 public +223.255.255.255 public +224.0.0.0 multicast +239.255.255.255 multicast +240.0.0.0 private +0.0.0.0 unspecified +0.0.0.1 private +192.0.0.8 private +192.0.0.9 private +192.0.0.10 private +192.0.0.11 private +0.255.255.255 private +1.0.0.0 public +9.255.255.255 public +10.0.0.0 private +10.255.255.255 private +11.0.0.0 public +100.63.255.255 public +100.64.0.0 private +100.127.255.255 private +100.128.0.0 public +172.15.255.255 public +172.16.0.0 private +172.31.255.255 private +172.32.0.0 public +191.255.255.255 public +192.0.0.0 private +192.0.0.255 private +192.0.1.0 public +192.0.1.255 public +192.0.2.0 private +192.0.2.255 private +192.0.3.0 public +192.167.255.255 public +192.168.0.0 private +192.168.255.255 private +192.169.0.0 public +198.17.255.255 public +198.18.0.0 private +198.19.255.255 private +198.20.0.0 public +198.51.99.255 public +198.51.100.0 private +198.51.100.255 private +198.51.101.0 public +203.0.112.255 public +203.0.113.0 private +203.0.113.255 private +203.0.114.0 public +255.255.255.255 private +# IPv6: the same, and addresses of special-purpose blocks the table does not name one by one - they are +# refused with everything outside the global unicast block, or with the block they lie in +:: unspecified +::1 loopback +::2 reserved +fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +fe80:: link-local +febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff link-local +fec0:: reserved +feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +ff00:: multicast +ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff multicast +2001:1:: private +2001:1::1 private +2001:1::2 private +2001:1::3 private +2001:2:ffff:ffff:ffff:ffff:ffff:ffff private +2001:3:: private +2001:3:ffff:ffff:ffff:ffff:ffff:ffff private +2001:4:: private +2001:4:111:ffff:ffff:ffff:ffff:ffff private +2001:4:112:: private +2001:4:112:ffff:ffff:ffff:ffff:ffff private +2001:4:113:: private +2001:1f:ffff:ffff:ffff:ffff:ffff:ffff private +2001:20:: private +2001:2f:ffff:ffff:ffff:ffff:ffff:ffff private +2001:30:: private +2001:3f:ffff:ffff:ffff:ffff:ffff:ffff private +2001:40:: private +64:ff9b:0:ffff:ffff:ffff:ffff:ffff reserved +64:ff9b:1:: reserved +64:ff9b:1:ffff:ffff:ffff:ffff:ffff reserved +64:ff9b:2:: reserved +ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +100:: reserved +100::ffff:ffff:ffff:ffff reserved +100:0:0:1:: reserved +2000:ffff:ffff:ffff:ffff:ffff:ffff:ffff public +2001:: private +2001:1ff:ffff:ffff:ffff:ffff:ffff:ffff private +2001:200:: public +2001:db7:ffff:ffff:ffff:ffff:ffff:ffff public +2001:db8:: private +2001:db8:ffff:ffff:ffff:ffff:ffff:ffff private +2001:db9:: public +2001:ffff:ffff:ffff:ffff:ffff:ffff:ffff public +2002:: private +2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff private +2003:: public +3ffe:ffff:ffff:ffff:ffff:ffff:ffff:ffff public +3fff:: private +3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff private +3fff:1000:: public +fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +fc00:: private +fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff private +fe00:: reserved +1ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +200:: reserved +3ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +400:: reserved +7ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +800:: reserved +fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +1000:: reserved +1fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +2000:: public +3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff public +4000:: reserved +5fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +6000:: reserved +7fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +8000:: reserved +9fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +a000:: reserved +bfff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +c000:: reserved +dfff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +e000:: reserved +efff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +f000:: reserved +f7ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff reserved +f800:: reserved +# an IPv4-mapped address is no global unicast address: it is refused whatever it carries, in any spelling +::ffff:127.0.0.1 reserved +::ffff:7f00:1 reserved +::FFFF:7F00:1 reserved +0:0:0:0:0:ffff:7f00:1 reserved +0000:0000:0000:0000:0000:ffff:7f00:0001 reserved +0:0:0:0:0:ffff:127.0.0.1 reserved +::ffff:10.0.0.1 reserved +::ffff:a00:1 reserved +::ffff:0a00:0001 reserved +::ffff:172.16.5.5 reserved +::ffff:ac10:505 reserved +::ffff:192.168.1.1 reserved +::ffff:c0a8:101 reserved +::ffff:100.64.0.1 reserved +::ffff:6440:1 reserved +::ffff:192.0.2.1 reserved +::ffff:c000:201 reserved +::ffff:169.254.169.254 reserved +::ffff:a9fe:a9fe reserved +::ffff:224.0.0.1 reserved +::ffff:e000:1 reserved +::ffff:0.0.0.0 reserved +::ffff:0:0 reserved +::ffff:192.0.0.9 reserved +::ffff:8.8.8.8 reserved +::ffff:808:808 reserved +0:0:0:0:0:ffff:808:808 reserved +::ffff:93.184.216.34 reserved +# and so are the blocks beside the mapped one +::fffe:7f00:1 reserved +::fffe:808:808 reserved +::1:0:7f00:1 reserved +::1:0:808:808 reserved +::ffff:0:7f00:1 reserved +::ffff:0:8.8.8.8 reserved +# the other blocks whose addresses carry an IPv4 address are refused whole, whatever they carry: +# IPv4-compatible, translated (64:ff9b::/96 and the local-use block beside it), 6to4, Teredo +::127.0.0.1 reserved +::7f00:1 reserved +::8.8.8.8 reserved +::808:808 reserved +64:ff9b::127.0.0.1 reserved +64:ff9b::7f00:1 reserved +64:ff9b::8.8.8.8 reserved +64:ff9b::808:808 reserved +0064:ff9b:0000:0000:0000:0000:0808:0808 reserved +64:ff9b:1::10.0.0.1 reserved +64:ff9b:1::808:808 reserved +2002:7f00:1:: private +2002:7f00:0001:0000:0000:0000:0000:0000 private +2002:808:808::1 private +2001:0:7f00:1::1 private +2001:0:808:808::1 private +# the same address in other spellings: written out, with leading zeros, in upper case, with a zone +0:0:0:0:0:0:0:0 unspecified +0000:0000:0000:0000:0000:0000:0000:0000 unspecified +::0.0.0.0 unspecified +0:0:0:0:0:0:0:1 loopback +0000:0000:0000:0000:0000:0000:0000:0001 loopback +::0001 loopback +0::1 loopback +::0.0.0.1 loopback +FE80::1 link-local +fe80:0000:0000:0000:0000:0000:0000:0001 link-local +fe80::1%eth0 link-local +fe80::5efe:10.0.0.1 link-local +FF02::1 multicast +ff02:0:0:0:0:0:0:1 multicast +FC00::1 private +fd00:0:0:0:0:0:0:1 private +fd12:3456:789a::1 private +FEC0::1 reserved +fec0:0000:0000:0000:0000:0000:0000:0001 reserved +2001:DB8::1 private +2001:0db8:0000:0000:0000:0000:0000:0001 private +2001:db8::192.0.2.1 private +2606:4700:4700::1111 public +2606:4700:4700:0:0:0:0:1111 public +2606:4700:4700:0000:0000:0000:0000:1111 public +2606:4700:4700::17.17.17.17 public +2A00:1450:4001:81B::200E public +2606:2800:220:1:248:1893:25c8:1946 public +""" + +# The same for a URL: the kind the address check names for its host. +URL_PROBES = """ +# a URL whose host is an address literal is classified by the address, however the literal is spelled +http://[::ffff:127.0.0.1]:8080/ reserved +http://[::ffff:7f00:1]:8080/ reserved +http://[::FFFF:7F00:1]/ reserved +http://[0:0:0:0:0:ffff:7f00:1]/ reserved +http://[0000:0000:0000:0000:0000:ffff:7f00:0001]/ reserved +http://[0:0:0:0:0:FFFF:127.0.0.1]/ reserved +http://[::ffff:10.0.0.1]/ reserved +http://[::ffff:a00:1]/ reserved +http://[::ffff:169.254.169.254]/ reserved +http://[::ffff:a9fe:a9fe]/ reserved +http://[::ffff:100.64.0.1]/ reserved +http://[::ffff:6440:1]/ reserved +http://[::ffff:8.8.8.8]/ reserved +http://[::ffff:808:808]/ reserved +http://[::1]/ loopback +http://[0:0:0:0:0:0:0:1]/ loopback +http://[::]/ unspecified +http://[::127.0.0.1]/ reserved +http://[::7f00:1]/ reserved +http://[64:ff9b::127.0.0.1]/ reserved +http://[64:ff9b::808:808]/ reserved +http://[2002:7f00:1::]/ private +http://[2001:db8::1]/ private +http://[fe80::1]/ link-local +http://[fc00::1]/ private +http://[fec0::1]/ reserved +http://[ff02::1]/ multicast +http://[2606:4700:4700::1111]/ public +http://127.0.0.1/ loopback +http://127.0.0.1./ loopback +http://10.0.0.1:8080/ private +http://100.64.0.1/ private +http://192.0.2.1/ private +http://198.18.0.1/ private +http://240.0.0.1/ private +http://0.0.0.0/ unspecified +http://0.1.2.3/ private +http://8.8.8.8/ public +""" + + +def _kind(address: str) -> str: + """The kind the module names for an address, `public` when it names none.""" + import ipaddress + + return tools.address_kind(ipaddress.ip_address(address)) or "public" + + +async def _host_kind(sandbox: Any, url: str) -> str: + """The kind the address check names for the host of a URL the allowlist lets through, + `public` when the address is pinned.""" + parts = sandbox.check_url(url) + try: + await sandbox.pin((parts.hostname or "").lower().rstrip("."), parts.port or 80) + except AppException as exc: + named = re.search(r" resolves to a (\S+) address, which is refused ", exc.message) + return named.group(1) if named else exc.message + return "public" + + +def test_address_kinds_are_one_table_in_both_packs() -> None: + wrong: list[tuple[str, str, str]] = [] + for address, kind in _probes(ADDRESS_PROBES): + got = _kind(address) + if got != kind: + wrong.append((address, kind, got)) + assert wrong == [], "the first row of the table that holds an address decides its kind" + + +@pytest.mark.asyncio +async def test_a_literal_host_is_classified_by_the_address_it_names() -> None: + sandbox = tools.WebSandbox(rules=tools.parse_host_rules(("http://*",))) + wrong: list[tuple[str, str, str]] = [] + for url, kind in _probes(URL_PROBES): + got = await _host_kind(sandbox, url) + if got != kind: + wrong.append((url, kind, got)) + assert wrong == [], "the spelling of a literal never changes the kind of its address" + + @pytest.mark.asyncio async def test_pin_refuses_private_addresses_unless_allowed() -> None: closed = tools.WebSandbox( @@ -617,6 +1298,17 @@ async def test_pin_refuses_private_addresses_unless_allowed() -> None: "/docs/c": ("Section C", "

C

Text of C.

"), "/other": ("Other", "

Outside the docs.

"), "/private/secret": ("Secret", "

Robots keep out.

"), + "/detour": ( + "Detour", + '

See the copy and C.

', + ), + "/tangle": ( + "Tangle", + ( + '

one, two, ' + 'three, C.

' + ), + ), } @@ -660,6 +1352,12 @@ async def handler(_request: web.Request) -> web.Response: return handler + async def to_mapped(request: web.Request) -> web.Response: + raise web.HTTPFound(f"http://[::ffff:127.0.0.1]:{request.url.port}/docs/a") + + async def to_unreadable(_request: web.Request) -> web.Response: + return web.Response(status=302, headers={"Location": "http://[bad/"}) + async def latin1(_request: web.Request) -> web.Response: return web.Response( body=_page("Caf\xe9", "

Caf\xe9

").encode("latin-1"), @@ -687,6 +1385,8 @@ async def missing(_request: web.Request) -> web.Response: app.router.add_get("/redirect", redirect("/docs/a")) app.router.add_get("/redirect-private", redirect("http://10.0.0.1/")) app.router.add_get("/redirect-other", redirect("https://not-allowed.example/")) + app.router.add_get("/redirect-mapped", to_mapped) + app.router.add_get("/redirect-unreadable", to_unreadable) app.router.add_get("/loop", redirect("/loop")) app.router.add_get("/latin1", latin1) app.router.add_get("/meta-charset", meta_charset) @@ -848,6 +1548,57 @@ async def test_the_private_range_gate_closes_the_fixture_without_the_flag( await https_only.close() +@contextlib.asynccontextmanager +async def _site_tools(passes: int) -> AsyncIterator[Any]: + """The web tools over every http host, private addresses refused - except that the fixture + site's own address passes the address check that many times, as a public site's would.""" + left = [passes] + + class SiteSandbox(tools.WebSandbox): + async def pin(self, host: str, port: int) -> str: + if host == "127.0.0.1" and left[0] > 0: + left[0] -= 1 + return host + return await super().pin(host, port) + + client = tools.WebTools( + SiteSandbox(rules=tools.parse_host_rules(("http://*",)), timeout_ms=500, crawl_delay_ms=0) + ) + try: + yield client + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_a_mapped_literal_and_a_redirect_to_one_are_refused(site: str) -> None: + mapped = f"http://[::ffff:127.0.0.1]:{site.rsplit(':', 1)[1]}/" + async with _site_tools(0) as closed: + status, message = await _astatus(closed.web_fetch({}, {"url": mapped})) + assert status == 400 + assert "resolves to a reserved address, which is refused" in message + async with _site_tools(1) as client: + status, message = await _astatus(client.web_fetch({}, {"url": f"{site}/redirect-mapped"})) + assert status == 400, "the start passes once; the address the redirect names is checked" + assert "resolves to a reserved address, which is refused" in message + + +@pytest.mark.asyncio +async def test_every_page_of_a_crawl_goes_through_the_address_check(site: str) -> None: + async with _site_tools(2) as client: + reply = await client.web_crawl({}, {"url": f"{site}/"}) + assert [p["url"] for p in reply["pages"]] == [f"{site}/"], ( + "robots.txt and the start pass; every link is checked again when it is fetched" + ) + assert reply["visited"] == 1 + async with _site_tools(9) as client: + reply = await client.web_crawl({}, {"url": f"{site}/detour"}) + assert [p["url"] for p in reply["pages"]] == [f"{site}/detour", f"{site}/docs/c"], ( + "a link that redirects to an IPv4-mapped literal of a loopback address is passed over" + ) + assert reply["visited"] == 2 + + @pytest.mark.asyncio async def test_logs_carry_the_host_and_the_size_never_the_url( site: str, web_tools: Any, caplog: pytest.LogCaptureFixture @@ -921,6 +1672,52 @@ async def test_crawl_caps_max_pages_by_the_configured_cap( await client.close() +@pytest.mark.asyncio +async def test_a_crawl_follows_links_on_a_site_named_by_a_literal_or_with_a_dot( + site: str, configure: Callable[[dict[str, Any]], None], monkeypatch: pytest.MonkeyPatch +) -> None: + import ipaddress + + async def fixture_address(_host: str, _port: int) -> list[Any]: + return [ipaddress.ip_address("127.0.0.1")] + + monkeypatch.setattr(tools, "_resolve", fixture_address) + configure({**SITE_SETTINGS, tools.WEB_ALLOW: "http://*"}) + client = tools.WebTools(tools.load_web_sandbox()) + port = site.rsplit(":", 1)[1] + try: + for start in (f"http://[::ffff:127.0.0.1]:{port}/", f"http://fixture.test.:{port}/"): + reply = await client.web_crawl({}, {"url": start, "include": "/docs/"}) + assert [urlsplit(p["url"]).path for p in reply["pages"]] == [ + "/", + "/docs/a", + "/docs/b", + "/docs/c", + ], start + assert reply["visited"] == 4 + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_an_address_that_cannot_be_read_fails_no_fetch_and_no_crawl( + site: str, web_tools: Any +) -> None: + unreadable = (400, "url must start with https:// (or http:// for a host listed with it)") + page = await web_tools.web_fetch({}, {"url": f"{site}/tangle"}) + assert (page["status"], page["text"]) == (200, "one, two, three, C.") + assert await _astatus(web_tools.web_fetch({}, {"url": "http://[bad/"})) == unreadable + assert ( + await _astatus(web_tools.web_fetch({}, {"url": f"{site}/redirect-unreadable"})) + == unreadable + ), "a redirect is checked as the first address is" + reply = await web_tools.web_crawl({}, {"url": f"{site}/tangle"}) + assert [p["url"] for p in reply["pages"]] == [f"{site}/tangle", f"{site}/docs/c"], ( + "a link that is no address is passed over, and so is a page that redirects to one" + ) + assert reply["visited"] == 2 + + # --- the clock ----------------------------------------------------------------------------------- @@ -1991,6 +2788,18 @@ def test_page_range_and_document_kind() -> None: assert tools.document_kind(_docx(["x"]), ".docx") == "docx" +def test_pages_are_numbers_in_the_digits_0_to_9() -> None: + for spec in ("+2", "1_0", "1 - 3", "1- 2", "\u0663", "\uff11", "\u00b2", "1--2", "2.0", "0x2"): + assert _status(lambda spec=spec: tools.page_range(spec, 12)) == ( + 400, + "pages must be page numbers and ranges such as 1-3,7", + ), spec + assert tools.page_range(" 2 ", 12) == [2] + assert tools.page_range("00002, 1-3", 12) == [2, 1, 3] + assert tools.page_range("9" * 5000, 12) == [], "a page beyond the document selects nothing" + assert tools.page_range("2-" + "9" * 5000, 3) == [2, 3] + + # --- the boot with the graph and the documents -------------------------------------------------- From 868a9d9ca104bd0be8fb885d66659d7f03a19dee Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:57:31 -0800 Subject: [PATCH 5/5] docs(changelog): the four fixes of the defect round, each with its upgrade note The agent tools' address check, globs and bounded matching; the LLM helper's one rule for a number and the audit settings refused at start; the ticket rule and the row id of ask-person and agent-question; REST automation's flags, upload bound and error bodies. Entries 4 to 7 of Unreleased Fixed in the Python pack, 3 to 6 in the Node.js pack. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 346843c..eb8d9c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -286,6 +286,80 @@ ingested relationship only when it carries the label `_Ingested` and a key. A query that listed a node's labels now sees `_Ingested` among them. +4. **The agent tools' address check and globs follow one rule in both packs, and a pattern is matched in bounded time + (the code-quality round of 2026-11-29, in lockstep with the Node.js pack).** + - *Addresses.* The web tools asked the `ipaddress` module which addresses are private, and its lists differ from + one Python version to the next; the Node.js twin kept a shorter list of its own and read an IPv4-mapped IPv6 + address written in hex as public. Both packs carry one table now, the same text. An IPv4 address is refused + inside the special-purpose blocks that are not globally reachable and the shared address space + (`100.64.0.0/10`, new here). An IPv6 address is reached only inside the global unicast block `2000::/3`, + outside `2001::/23`, `2001:db8::/32`, `2002::/16` and `3fff::/20`: every other IPv6 address is refused, an + IPv4-mapped one in any spelling among them. + - *Globs.* `file.list` and `file.search` used `Path.glob`, whose reading of `**` changed between Python 3.12 and + 3.13, and the twin returned nothing for a pattern that ends in `**`. Both packs compile a glob by one grammar + and walk the workspace themselves: `**` is any run of folders and, at the end of a pattern, everything beneath; + a slash at the end names folders only; a symbolic link is an entry and is never descended into; `..` and an + absolute pattern are a 400 by name. A name is matched item by item, so the time is bounded by the pattern's + length times the name's however many stars the pattern has, and the walk enters only the folders a pattern can + still match beneath. The host patterns of `tools.web.allow` are matched by the same function. + - *Smaller differences.* `file.list` skips a symbolic link whose target is gone; `file.write` under a file is 400 + ` is not a directory`; an address on a page that cannot be read stays as written and its link is skipped, + and a redirect to one is a 400, where each was a 500; a link's scheme is read in any letter case; `file.search` + counts lines by the line feed; `pages` takes the digits 0 to 9 only; an allowlist entry that starts with a + class (`[ab].example.com`) is a pattern. + + **Upgrade note:** the agent tools are in no release yet. For an application that runs them from `main`: an address + in `100.64.0.0/10` and an IPv4-mapped address are refused unless `tools.web.allow.private=true`, and a glob no + longer reaches beneath a symbolic link to a folder. + +5. **The LLM helper reads a number, a duration and a page list by one rule in both packs, and a wrong + `llm.transcript.audit.grace` or `llm.transcript.audit.retention` stops the start.** A number in a request or a + setting was read by each pack's own reader: digits of any script were taken here (`"٣"` was 3, and `"²"` raised + while the request was prepared, a 500 where the contract says 400) and the JSON float `16000.0` was refused, + while the Node.js twin, which cannot tell it from `16000`, accepted it. One rule now: a JSON number with a whole + value, or a string of the digits 0 to 9, with white space ignored around it, at most 9007199254740991; a duration + and a page list follow it, and the refusals keep their messages. The audit's grace and retention were read inside + the save of a loop's closing turn - a 503 after the model had been called, the turn unsaved; they are read when + the helper starts, and a wrong value stops the start by name as the other settings do. The shared vectors gain a + `numbers` section of 98 probes. **Upgrade note:** a request that sends a whole number as a float is accepted; one + that sends digits of another script, or a number above 9007199254740991, is a 400. + +6. **ask-person and agent-question: one rule for a well-formed ticket, and one for a row id and a stream's cursor.** + The packs answered a mangled ticket differently, and this one verified a part that ended in a newline. A ticket + is well-formed when it has its three parts, the payload and the signature are canonical unpadded base64url from + start to end, and the signature is the 32 bytes of the MAC: anything else is 400 `Ticket is malformed`, and a + well-formed ticket whose MAC does not verify is 403 `Ticket signature is invalid`. A second spelling of a valid + ticket - one that differs only in the unused bits of a last character - was accepted by both packs and is a 400. + In agent-question a row id and `Last-Event-ID` went through `int()` (`" 7 "`, `-3`, `+7` and `1_0` passed); both + packs read 1 to 19 digits from start to end, at most 9223372036854775807, and answer the 400 that was there for + anything else. The shared vectors are `ask-person-vectors.json` version 3 (146 cases) and + `agent-question-vectors.json` version 4 (111 cases). **Upgrade note:** none for a ticket the pack issued or an id + it returned. + +7. **REST automation and the host: an entry's flags as the Java engine reads them, the upload bound in bytes, and + the engines' error body where the web framework answered its own.** + - A flag of an entry (`tracing`, `stream`, `upload`) was on only for the YAML boolean, so `tracing: "true"` and + `tracing: ${TRACING:true}` stayed off without a word. The boolean or the text `true` in any letter case turns + it on, as in the Java engine; `false`, no value and an empty one leave it off; any other value, which the + engine reads as off silently, fails the start: `rest[N] 'tracing' must be true or false`. + - The upload bound counted a text field by the length of its text; it counts the bytes of every part as they + arrive. + - A keep-alive comment is written only when a keep-alive interval has passed, so a stream that is not + Server-Sent Events never carries one and `event.stream.keep.alive: 0` writes none. + - A reply the serializer refuses is 500 `Reply cannot be rendered` in the engines' error body, with the edge's + `http.request` record, and a streamed segment fails the stream in band; it was the web framework's own page, + with no record. + - A body over the 16 MiB the host reads into memory is 413 `Request body exceeds 16777216 bytes` in the engines' + error body, and an envelope on `POST /api/event` without REST automation; it was the web framework's + `text/plain` page. + - A part of an upload that is multipart itself is 400 + `Upload takes text fields and files, not a nested multipart part`; it failed the upload or was dropped, by its + place in the body. + + **Upgrade note:** an entry whose flag is written as anything but `true` or `false` stops the start - write `true` + or `false`. A text field of an upload counts toward `rest.upload.max.bytes` by its bytes, so a long field in + another script counts for more than before. + 13. **REST automation: `rest.yaml` as the router of a Python application (RFC-0018 in mercury-composable, build plan step 1).** With `rest.automation: true` the host reads one `yaml.rest.automation` location (default `classpath:/rest.yaml`, the `resources/rest.yaml` next to the application file; `file:` an absolute path) in the