From 0a6409d663d0ee0330dfae648c536b052808edae Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:35 -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 A number in a request or a setting was read by each pack's own reader: the Python twin took digits of any script and refused the JSON float 16000.0, which this pack cannot tell from 16000 and accepted. 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 (U+FEFF is no longer one of them here), 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 Python 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.mjs | 73 ++- test/llm-helper.test.mjs | 125 +++- test/transcript-audit.test.mjs | 30 + test/vectors/llm-helper-vectors.json | 819 ++++++++++++++++++++++++++- 5 files changed, 1037 insertions(+), 33 deletions(-) diff --git a/extensions/llm-helper/README.md b/extensions/llm-helper/README.md index c6051047..c29a0018 100644 --- a/extensions/llm-helper/README.md +++ b/extensions/llm-helper/README.md @@ -110,6 +110,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. @@ -286,7 +295,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. @@ -473,8 +483,8 @@ of the box). The audit does not redact; a redaction policy is the installation's | `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}`). A command waits at most `timeout.ms`, and none is queued while the client is offline. | | `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` encrypts without verifying the server's certificate (libpq's `sslmode=require`), `false` is `sslmode=disable`. `timeout.ms` bounds a connection attempt, a query on the client and, on the server, a statement (`statement_timeout`). | @@ -558,7 +568,9 @@ by reference; it still decides nothing about control flow. `test/llm-helper.test.mjs` runs the shared `test/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 `test/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 +`test/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 applies the store script's rule. Then come the tests a vector cannot express (token batches are never held back, @@ -567,7 +579,8 @@ Bedrock clients with their region and credential checks, the stored blocks as th store's keys, compare-and-set, connection settings and fast failure). No token is spent and no credential is needed. `test/transcript-audit.test.mjs` 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 +repairs it 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, `test/vectors/llm-audit-vectors.json` (25 cases: the two rows a call without `tools` leaves on diff --git a/extensions/llm-helper/llm-helper.mjs b/extensions/llm-helper/llm-helper.mjs index 01465d56..2f4a264a 100644 --- a/extensions/llm-helper/llm-helper.mjs +++ b/extensions/llm-helper/llm-helper.mjs @@ -86,6 +86,17 @@ const CREDENTIAL_ERROR = 'Could not resolve authentication method'; // the AWS credential chain's own error when it resolves nothing (while the Bedrock SDK signs) const AWS_CREDENTIAL_ERROR = 'CredentialsProviderError'; +// --- how a number is read: the same in both packs ------------------------------------------- +// the white space ignored around a number, and anywhere in pages: the characters JavaScript's +// trim() and Python's str.strip() both take for white space, so neither pack accepts a character +// the other refuses +const SPACE = String.raw`[\t-\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]`; +const SPACES = new RegExp(`${SPACE}+`, 'g'); +// the digits 0 to 9 and no other: \d here, where the Python twin asks for them by flag. A number is at +// most Number.MAX_SAFE_INTEGER (2**53 - 1), the largest whole number both packs hold exactly: above +// it this pack's numbers round, and the twins would read two different numbers from one request +const WHOLE = new RegExp(String.raw`^${SPACE}*(\d+)${SPACE}*$`); + // --- 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 export const LOOP_FIELDS = ['conversation', 'turn', 'results', 'ttl', 'retention']; @@ -95,7 +106,7 @@ export const TOOL_KEYS = ['name', 'description', 'input_schema', 'strict']; // loop's catalog to an API-safe name, never advertised const TOOL_NAME = /^[a-zA-Z0-9_-]{1,128}$/; const CONVERSATION_ID = /^[0-9a-f]{32}$/; -const DURATION = /^(\d+)([smhd]?)$/; +const DURATION = new RegExp(String.raw`^${SPACE}*(\d+)([smhd]?)${SPACE}*$`); const DURATION_SECONDS = { '': 1, s: 1, m: 60, h: 3600, d: 86400 }; export const DEFAULT_TRANSCRIPT_TTL = '7d'; export const DEFAULT_TRANSCRIPT_RETENTION = '0'; @@ -171,14 +182,30 @@ function byCodeUnit(a, b) { return a > b ? 1 : 0; } +/** What a number is read from: a string as written, or the digits of a JSON number with a whole + * value - an integer, which is all this pack sees of a float such as 16000.0. Undefined for + * anything else: a boolean, a fraction, a number beyond Number.MAX_SAFE_INTEGER. */ +function numberText(value) { + if (typeof value === 'string') { + return value; + } + return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : undefined; +} + +/** The whole number a run of ASCII digits spells, or undefined above Number.MAX_SAFE_INTEGER. */ +function whole(digits) { + const number = Number(digits); + return Number.isSafeInteger(number) ? number : undefined; +} + /** A whole number from a JSON number or a config string, or a 400 naming the field. */ function wholeNumber(name, value, minimum) { - const valid = (typeof value === 'number' && Number.isInteger(value)) - || (typeof value === 'string' && /^\d+$/.test(value.trim())); - if (!valid || Number(value) < minimum) { + const match = WHOLE.exec(numberText(value) ?? ''); + const number = match ? whole(match[1]) : undefined; + if (number === undefined || number < minimum) { throw new AppException(400, `${name} must be a whole number >= ${minimum}`); } - return Number(value); + return number; } // --- provider failures as the portable error contract ---------------------------------- @@ -1038,12 +1065,7 @@ function schemaOf(body, streaming) { * mapping may carry a page number as a number. Whether a page exists is the document's to say, * when it is read. */ function pagesOf(index, raw) { - let text; - if (typeof raw === 'string') { - text = raw.replace(/\s+/g, ''); - } else if (typeof raw === 'number' && Number.isInteger(raw)) { - text = String(raw); - } + const text = numberText(raw)?.replace(SPACES, ''); const malformed = () => new AppException(400, `attachments[${index}].pages must name pages from 1, such as 13 or 1-3,7`); if (text === undefined || !PAGES.test(text)) { @@ -1052,9 +1074,9 @@ function pagesOf(index, raw) { const ranges = []; for (const part of text.split(',')) { const [first, last] = part.split('-'); - const low = Number(first); - const high = Number(last ?? first); - if (low < 1 || high < low) { + const low = whole(first); + const high = whole(last ?? first); + if (low === undefined || high === undefined || low < 1 || high < low) { throw malformed(); } if (ranges.some(([heldLow, heldHigh]) => low <= heldHigh && heldLow <= high)) { @@ -1125,15 +1147,10 @@ function resultsOf(raw) { /** Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it. */ function durationOf(name, value, minimum) { - let text; - if (typeof value === 'string') { - text = value.trim(); - } else if (typeof value === 'number' && Number.isInteger(value)) { - text = String(value); - } - const match = text === undefined ? null : DURATION.exec(text); - const seconds = match ? Number(match[1]) * DURATION_SECONDS[match[2]] : -1; - if (seconds < minimum) { + const match = DURATION.exec(numberText(value) ?? ''); + const count = match ? whole(match[1]) : undefined; + const seconds = count === undefined ? -1 : count * DURATION_SECONDS[match[2]]; + if (!Number.isSafeInteger(seconds) || seconds < minimum) { throw new AppException(400, `${name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) ` + `>= ${minimum}`); } @@ -2240,14 +2257,18 @@ export function createLlmHelper({ let auditStoreOpened; // the store the boot built, closed at shutdown /** 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. */ async function auditBoot() { if (!auditConfigured()) { 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 + auditGraceS(); + auditRetentionS(); auditStoreOpened = await audit(); } catch (error) { log.error(`transcript audit store cannot start - ${error.message}`); diff --git a/test/llm-helper.test.mjs b/test/llm-helper.test.mjs index e2cc68e5..e48a7932 100644 --- a/test/llm-helper.test.mjs +++ b/test/llm-helper.test.mjs @@ -25,7 +25,7 @@ import { delta, fakeBackend, FakeStream, FakeWriter, settings, silent, statusErr const VECTORS_FILE = new URL('./vectors/llm-helper-vectors.json', import.meta.url); // the Python twin pins the same digest: change the file in both packs or in neither -const VECTORS_SHA256 = '7bfffbf36c52488c246f250f36afc4e8012f119fd56c93e9de1cbe93bf5988b6'; +const VECTORS_SHA256 = 'eff1bfef426d6ac815f9a14ffc8de962eeac1894cbef0015b517b61c42b20b78'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const CHAT_CASES = VECTORS.cases.filter((c) => c.route === 'llm.chat'); const STREAM_CASES = VECTORS.cases.filter((c) => c.route === 'llm.stream'); @@ -290,6 +290,129 @@ for (const c of LOOP_CASES_ON_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. + +const NUMBERS = VECTORS.numbers; +const ABSENT = 'absent'; // what a null spells: a field left out +const MISSING = Symbol('the field left out of the request'); +const REPLY = { + kind: 'message', model: 'claude-opus-5-5', stop_reason: 'end_turn', deltas: ['ok'], + usage: { input_tokens: 1, output_tokens: 1 } +}; + +/** The one refusal of a field: a 400 and the kind's shared text, naming the field. */ +const refusalOf = (kind, name, minimum) => [400, + NUMBERS.refusals[kind].replace('{name}', name).replace('{minimum}', String(minimum))]; + +/** 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. */ +const spelled = (wanted, minimum, refusal) => (wanted === null || wanted < minimum ? refusal : wanted); + +function refusalFrom(error) { + assert.ok(error instanceof AppException, String(error)); + return [error.status, error.message]; +} + +/** params.max_tokens as the SDK call carries it, or the refusal - then with no call. */ +async function maxTokens(value) { + const { helper, ledger } = helperFor({ provider: REPLY }); + try { + await helper.chat({}, { prompt: 'x', params: value === MISSING ? {} : { max_tokens: value } }); + } catch (error) { + assert.equal(ledger.calls.length, 0, 'a refused request must not reach the provider'); + return refusalFrom(error); + } + return ledger.calls[0].params.max_tokens; +} + +/** The setting llm.max.retries as the SDK call's options carry it, or the refusal. */ +async function maxRetries(value) { + const { helper, ledger } = helperFor({ provider: REPLY, config: { 'llm.max.retries': value } }); + try { + await helper.chat({}, { prompt: 'x' }); + } catch (error) { + assert.equal(ledger.calls.length, 0, 'a refused request must not reach the provider'); + return refusalFrom(error); + } + return ledger.calls[0].options.maxRetries; +} + +/** 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. */ +async function durationTurn(field, value) { + const store = new MemoryStore({ clock: () => 0 }); // a clock at zero: the expiry is the seconds to live + const { helper, ledger } = loopHelper(TURN, { store: async () => store }); + let reply; + try { + reply = await helper.chat({}, { prompt: 'x', tools: [TOOL], ...(value === MISSING ? {} : { [field]: value }) }); + } catch (error) { + assert.equal(ledger.calls.length, 0, 'a refused turn must not reach the provider'); + assert.equal(store.records.size, 0, 'a refused turn stores nothing'); + return refusalFrom(error); + } + const [expiry, , record] = store.records.get(reply.conversation); + return field === 'ttl' ? expiry : recordFrom(record).retention; +} + +/** attachments[0].pages as the request check reads it: the ranges, null for the whole document, + * or the refusal. */ +function pagesRead(value) { + const { helper } = helperFor({}); + const entry = value === MISSING ? { path: 'form.pdf' } : { path: 'form.pdf', pages: value }; + try { + return helper.prepare({ prompt: 'x', attachments: [entry] }, { streaming: false }).attachments[0].pages ?? null; + } catch (error) { + return refusalFrom(error); + } +} + +for (const probe of NUMBERS.probes) { + // params.max_tokens (minimum 1) and, for a string, the setting llm.max.retries (minimum 0) + test(`a whole number is read as the python twin reads it: ${probe.name}`, async () => { + const answer = await maxTokens(probe.value); + if (probe.whole === ABSENT) { + assert.deepEqual(answer, await maxTokens(MISSING)); + return; + } + assert.deepEqual(answer, spelled(probe.whole, 1, refusalOf('whole', 'params.max_tokens', 1))); + if (typeof probe.value === 'string') { + const setting = await maxRetries(probe.value); + assert.deepEqual(setting, spelled(probe.whole, 0, refusalOf('whole', 'llm.max.retries', 0))); + } + }); +} + +for (const [field, minimum] of [['ttl', 1], ['retention', 0]]) { + for (const probe of NUMBERS.probes) { + // the ttl (minimum 1) and the retention (minimum 0) of a first loop turn + test(`a duration is read as the python twin reads it: ${field} ${probe.name}`, async () => { + const answer = await durationTurn(field, probe.value); + if (probe.duration === ABSENT) { + assert.deepEqual(answer, await durationTurn(field, MISSING)); + return; + } + assert.deepEqual(answer, spelled(probe.duration, minimum, refusalOf('duration', field, minimum))); + }); + } +} + +for (const probe of NUMBERS.probes) { + // attachments[0].pages, whose shape the request check decides before any file is read + test(`pages are read as the python twin reads them: ${probe.name}`, () => { + const answer = pagesRead(probe.value); + if (probe.pages === ABSENT) { + assert.deepEqual(answer, pagesRead(MISSING)); + return; + } + assert.deepEqual(answer, probe.pages ?? refusalOf('pages', 'attachments[0].pages', 1)); + }); +} + // --- the loop turn: what a vector cannot pin ----------------------------------------------- test('a stored block is the JSON the SDK would send back', () => { diff --git a/test/transcript-audit.test.mjs b/test/transcript-audit.test.mjs index 5d8511d1..e4117a65 100644 --- a/test/transcript-audit.test.mjs +++ b/test/transcript-audit.test.mjs @@ -714,6 +714,36 @@ test('a configured driver that is not installed stops the application by name', log.seen.join('\n')); }); +const NOT_A_DURATION = 'must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d)'; + +for (const [key, value, minimum, what] of [ + ['llm.transcript.audit.grace', 'x', 1, 'a word'], + ['llm.transcript.audit.grace', '0', 1, 'zero'], + ['llm.transcript.audit.grace', '\u0663h', 1, 'the digit of another script'], + ['llm.transcript.audit.retention', 'forever', 0, 'a word'], + ['llm.transcript.audit.retention', '-1d', 0, 'a negative duration'] +]) { + test(`an audit duration that is malformed stops the application by name: ${key}, ${what}`, async () => { + // 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 function is registered, the store opened or the + // sweep started - it never surfaces on a turn's save, after the model was called + const log = lines(); + const pool = new FakePool(); + const registry = new FunctionRegistry(); + const h = auditHelper({ audit: new PostgresAuditStore(pool), registry, log, config: { ...CONFIG, [key]: value } }); + const message = `${key} ${NOT_A_DURATION} >= ${minimum}`; + await assert.rejects(h.helper.auditBoot(), (error) => { + assert.ok(error instanceof AppException, String(error)); + assert.equal(error.message, message); + return true; + }); + assert.ok(log.seen.includes(`transcript audit store cannot start - ${message}`), log.seen.join('\n')); + assert.equal(registry.exists(AUDIT_ROUTE), false); + assert.deepEqual(pool.log, [], 'the store is not opened'); + assert.equal(h.helper.sweeping(), false); + }); +} + test('the boot does nothing without an audit store', async () => { const registry = new FunctionRegistry(); const h = auditHelper({ config: { 'llm.transcript.store': 'memory' }, registry }); diff --git a/test/vectors/llm-helper-vectors.json b/test/vectors/llm-helper-vectors.json index 47fc4ade..a29f1e91 100644 --- a/test/vectors/llm-helper-vectors.json +++ b/test/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 b6389a8eb80de6093b1cf6412c6e704841d81b75 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:37 -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. This one accepted a stray character after a payload and answered 403 where the Python twin answered 400 for a part that is too short; the twin verified a part that ended in a newline. 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: `Last-Event-ID` went through Number() here (1.0, 1e3 and 0x10 passed), while the Python twin read a row id and the header with int() (" 7 ", -3, +7 and 1_0 passed). 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. Above 2^53-1 the id is carried as a BigInt, into the reader's lookup only. The cursor of a stream is `Last-Event-ID`, else `since`, else the start. The shared vectors pin both, byte-identical with the Python 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 | 14 +- extensions/agent-question/agent-question.mjs | 41 +- extensions/ask-person/README.md | 6 +- extensions/ask-person/ask-person.mjs | 25 +- test/agent-question.test.mjs | 80 ++- test/ask-person.test.mjs | 44 +- test/vectors/agent-question-vectors.json | 585 ++++++++++++++++- test/vectors/ask-person-vectors.json | 651 ++++++++++++++++++- 8 files changed, 1419 insertions(+), 27 deletions(-) diff --git a/extensions/agent-question/README.md b/extensions/agent-question/README.md index aacc0fc1..b8653c2d 100644 --- a/extensions/agent-question/README.md +++ b/extensions/agent-question/README.md @@ -26,7 +26,9 @@ application is one of those routes. It is a standalone application on the packag them. The person selects which card to answer, in any order; the card's button **automates the click**: `POST /questions/{id}/decide` posts `{ticket, decisions, decided_by}` to the main flow's reply endpoint - the link's own base, under this app's bearer - and answers with the row as the recorder then left it and the engine's outcome; - the feed carries the change to every device. + the feed carries the change to every device. 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 @@ -113,8 +115,8 @@ flow as `decided_by` under its own bearer (`question.reply.token`, the reply end ## Tests `test/agent-question.test.mjs` runs the shared vectors (`test/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.mjs b/extensions/agent-question/agent-question.mjs index 84ab5d8f..e5cb8e4c 100644 --- a/extensions/agent-question/agent-question.mjs +++ b/extensions/agent-question/agent-question.mjs @@ -79,6 +79,11 @@ export const LIST_LIMIT_MAX = 1000; export const TRANSCRIPTS_LIMIT = 50; export const TRANSCRIPTS_LIMIT_MAX = 200; const CONVERSATION_ID = /^[0-9a-f]{32}$/; +// a row id and a cursor are ASCII digits from start to end - Number() alone also takes a sign, spaces, a fraction, an +// exponent and a radix prefix - no more of them than the largest number the record's BIGINT columns hold has, and no +// larger than it +const RECORD_NUMBER = /^\d{1,19}$/; +const RECORD_MAX = 9223372036854775807n; // configuration keys export const STORE = 'question.store'; @@ -262,6 +267,35 @@ export function replyRequest(link, ticket, decisions, who) { return [`${link.slice(0, at)}/ask/reply`, { ticket, decisions: decisions.map((d) => ({ ...d })), decided_by: who }]; } +/** + * 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 null when the text is anything else. A number, or a BigInt past the whole numbers + * a number holds exactly, so the value read is the value named. + */ +function recordNumber(text) { + if (!isText(text) || !RECORD_NUMBER.test(text)) return null; + const value = BigInt(text); + if (value > RECORD_MAX) return null; + return value > Number.MAX_SAFE_INTEGER ? value : Number(value); +} + +/** The row a decision names in /questions/{id}/decide - or an AppException(400). */ +export function rowIdOf(text) { + const value = recordNumber(text ?? ''); + if (value === null) throw new AppException(400, 'the row id must be a whole number'); + return value; +} + +/** + * 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. + */ +export function streamCursor(lastEventId, since) { + const value = recordNumber(lastEventId || since || '0'); + if (value === null) throw new AppException(400, 'Last-Event-ID must be a whole number'); + return value; +} + /** The replay's page: the rows whose sequence passed the cursor, oldest change first, and the cursor to continue from. */ export function pageSince(rows, since, limit) { const changed = rows.filter((row) => row.seq > since).sort((a, b) => a.seq - b.seq).slice(0, limit); @@ -904,8 +938,7 @@ async function follow(out, since) { */ export async function questionEvents(_headers, event) { const request = new AsyncHttpRequest(event.body); - const since = Number(request.header('last-event-id') || request.queryParameter('since') || '0'); - if (!Number.isInteger(since)) throw new AppException(400, 'Last-Event-ID must be a whole number'); + const since = streamCursor(request.header('last-event-id'), request.queryParameter('since')); const out = EventStreamWriter.fromRequest(event); out.first(200, 'text/event-stream', STREAM_IDLE_SECONDS); out.write(null); // the head alone: the stream is open before the first row @@ -985,9 +1018,7 @@ export async function questionDecide(_headers, requestBody) { if (!Array.isArray(decisions) || decisions.length === 0 || !decisions.every(isMap)) { throw new AppException(400, 'decisions must be a non-empty list, one per waiting call'); } - const idText = request.pathParameter('id') ?? ''; - if (!/^\d+$/.test(idText)) throw new AppException(400, 'the row id must be a whole number'); - const id = Number(idText); + const id = rowIdOf(request.pathParameter('id')); let row; try { row = await reader().get(id); diff --git a/extensions/ask-person/README.md b/extensions/ask-person/README.md index 77ca0072..c18486ec 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.mjs b/extensions/ask-person/ask-person.mjs index 96edf7c6..eaa486b6 100644 --- a/extensions/ask-person/ask-person.mjs +++ b/extensions/ask-person/ask-person.mjs @@ -316,6 +316,18 @@ export function currentSettings() { const b64u = (buffer) => Buffer.from(buffer).toString('base64url'); +/** + * The bytes of a ticket's payload or signature part, or null 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. + */ +function partBytes(text) { + if (!BASE64URL.test(text)) return null; + const bytes = Buffer.from(text, 'base64url'); + return b64u(bytes) === text ? bytes : null; +} + /** The canonical JSON a ticket's payload is signed as: keys sorted, no spaces, Unicode kept - the binding's digest rule. */ export function canonicalJson(value) { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; @@ -328,6 +340,9 @@ export function canonicalJson(value) { const mac = (payload, key) => createHmac('sha256', key).update(payload).digest(); +// an HMAC-SHA256 is 32 bytes: a signature part of another length is malformed, never compared +const MAC_BYTES = 32; + /** v1..: the canonical payload and its HMAC-SHA256, both base64url without padding. */ export function issueTicket(payload, key) { const encoded = Buffer.from(canonicalJson(payload), 'utf8'); @@ -344,16 +359,18 @@ function payloadIsValid(payload) { /** * 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. + * 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. */ export function verifyTicket(ticket, keys, nowSeconds) { const parts = String(ticket).split('.'); if (parts.length !== 3 || parts.some((p) => !p)) throw new TicketError(400, 'Ticket is malformed'); const [version, encoded, signature] = parts; if (version !== TICKET_VERSION) throw new TicketError(400, `Ticket version ${version} is not supported`); - if (!BASE64URL.test(encoded) || !BASE64URL.test(signature)) throw new TicketError(400, 'Ticket is malformed'); - const payloadBytes = Buffer.from(encoded, 'base64url'); - const given = Buffer.from(signature, 'base64url'); + const payloadBytes = partBytes(encoded); + const given = partBytes(signature); + if (payloadBytes === null || given === null || given.length !== MAC_BYTES) throw new TicketError(400, 'Ticket is malformed'); const signed = keys.some((key) => { const expected = mac(payloadBytes, key); return expected.length === given.length && timingSafeEqual(expected, given); diff --git a/test/agent-question.test.mjs b/test/agent-question.test.mjs index 5813564c..3fc76432 100644 --- a/test/agent-question.test.mjs +++ b/test/agent-question.test.mjs @@ -3,7 +3,8 @@ * * The shared contract file test/vectors/agent-question-vectors.json (byte-identical in mercury-python) pins the pure * half: the event the intake accepts or refuses, the request the automated click sends, the pages the replay and the - * history read. The tests after the vector runs drive the app in-process as the reader of the question record the main + * history read, and the row id and the cursor a request names - digits the record holds, or the 400. The tests after + * the vector runs drive 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 on a recording @@ -21,7 +22,7 @@ import * as aq from '../extensions/agent-question/agent-question.mjs'; const VECTORS_FILE = new URL('./vectors/agent-question-vectors.json', import.meta.url); // the Python twin runs the same file: change it in both packs or in neither -const VECTORS_SHA256 = 'ec5f3490cb2993feaf40e9ac91c8fc1748d5e2c6fa1c8cd55122ad9f84d22dba'; +const VECTORS_SHA256 = 'ad693f2b6924735e0590a67e0799caf739a51e233cd9c3dd261d100a4147c030'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const RECORD_SCHEMA = new URL('../extensions/ask-person/schema/postgres.sql', import.meta.url); const PUBLIC = fileURLToPath(new URL('../extensions/agent-question/resources/public', import.meta.url)); @@ -99,8 +100,10 @@ const getJson = async (url, headers = {}) => { const response = await fetch(url, test('the vector file is the one the Python twin runs', () => { assert.equal(createHash('sha256').update(readFileSync(VECTORS_FILE)).digest('hex'), VECTORS_SHA256); assert.equal(VECTORS.contract, 'agent-question'); - assert.equal(VECTORS.version, 3); - for (const section of ['intake_cases', 'click_cases', 'feed_cases']) assert.ok(VECTORS[section].length > 0, section); + assert.equal(VECTORS.version, 4); + for (const section of ['intake_cases', 'click_cases', 'feed_cases', 'row_id_cases', 'cursor_cases']) { + assert.ok(VECTORS[section].length > 0, section); + } }); for (const c of VECTORS.intake_cases) { @@ -147,6 +150,26 @@ for (const c of VECTORS.feed_cases) { }); } +for (const c of VECTORS.row_id_cases) { + test(`row id: ${c.name}`, () => { + if ('row' in c) { + assert.equal(String(aq.rowIdOf(c.id)), c.row); + } else { + assert.throws(() => aq.rowIdOf(c.id), (e) => e instanceof AppException && e.status === c.status && e.message === c.error); + } + }); +} + +for (const c of VECTORS.cursor_cases) { + test(`cursor: ${c.name}`, () => { + if ('cursor' in c) { + assert.equal(String(aq.streamCursor(c.last_event_id, c.since)), c.cursor); + } else { + assert.throws(() => aq.streamCursor(c.last_event_id, c.since), (e) => e instanceof AppException && e.status === c.status && e.message === c.error); + } + }); +} + // --- configuration ------------------------------------------------------------------------------ for (const [values, names] of [ @@ -371,6 +394,55 @@ test('the stream replays, then follows the feed with keep-alives', async () => { } }); +test('a decision names its row in ASCII digits the record holds', async () => { + const clear = configure(BASE); + try { + put(adviceEvent(), 7, 1); + put(adviceEvent({ correlation_id: 'case-10' }), 10, 2); + const body = { decisions: [{ id: 'toolu_01A', approved: true }] }; + const largest = 2n ** 63n - 1n; + let response = await postJson(`${host}/questions/007/decide`, body); + assert.equal(response.status, 409, 'leading zeros are digits: row 7, which is an advice'); + assert.equal((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 (const rowId of ['%2B7', '-7', '1_0', '%207', '7%0A', '7.0', '0x7', '%D9%A7', String(largest + 1n)]) { + response = await postJson(`${host}/questions/${rowId}/decide`, body); + assert.equal(response.status, 400, rowId); + assert.equal((await response.json()).message, 'the row id must be a whole number', rowId); + } + response = await postJson(`${host}/questions/${largest}/decide`, body); + assert.equal(response.status, 404); + assert.equal((await response.json()).message, `row ${largest} is not in the record`); + } finally { + clear(); + } +}); + +test('a stream starts at a cursor in ASCII digits the record holds', async () => { + const clear = configure(BASE); + const controller = new AbortController(); + try { + const largest = 2n ** 63n - 1n; + for (const cursor of ['%2B1', '-1', '1_0', '%201', '1.0', '1e3', '0x10', '%D9%A1', String(largest + 1n)]) { + const response = await fetch(`${host}/questions/events?since=${cursor}`, { signal: controller.signal }); + assert.equal(response.status, 400, cursor); + assert.equal((await response.json()).message, 'Last-Event-ID must be a whole number', cursor); + } + for (const cursor of ['+1', '-1', '1_0', '1.0', '1e3', '0x10', String(largest + 1n)]) { + const response = await fetch(`${host}/questions/events`, { headers: { 'last-event-id': cursor }, signal: controller.signal }); + assert.equal(response.status, 400, cursor); + assert.equal((await response.json()).message, 'Last-Event-ID must be a whole number', cursor); + } + const response = await fetch(`${host}/questions/events`, { headers: { 'last-event-id': String(largest) }, signal: controller.signal }); + assert.equal(response.status, 200, 'the largest cursor the record holds opens a stream with nothing to replay'); + assert.match(response.headers.get('content-type'), /text\/event-stream/); + } finally { + controller.abort(); + clear(); + } +}); + test('the UI configuration names the sign-in', async () => { const clear = configure(BASE); try { diff --git a/test/ask-person.test.mjs b/test/ask-person.test.mjs index 1406f4cb..ba744683 100644 --- a/test/ask-person.test.mjs +++ b/test/ask-person.test.mjs @@ -26,7 +26,7 @@ const VECTORS_FILE = new URL('./vectors/ask-person-vectors.json', import.meta.ur // the reply page and endpoint are rest.yaml entries: the host reads the extension's file (RFC-0018) const REST_YAML = fileURLToPath(new URL('../extensions/ask-person/resources/rest.yaml', import.meta.url)); // the Python twin runs the same file: change it in both packs or in neither -const VECTORS_SHA256 = 'd825e6296ff3b5b808c921d94e19b902c05f14fafcdc4cb383bbd6dcfd39fa7f'; +const VECTORS_SHA256 = '969f01fac46a3af11632fc6343fe4379386393dd183b0ed3b5c4e1ec5ac3b9b5'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const KEY = 'test-key-current'; @@ -85,7 +85,7 @@ const readJson = (req) => new Promise((resolveBody) => { test('the vector file is the one the Python twin runs', () => { assert.equal(createHash('sha256').update(readFileSync(VECTORS_FILE)).digest('hex'), VECTORS_SHA256); assert.equal(VECTORS.contract, 'ask-person'); - assert.equal(VECTORS.version, 2); + assert.equal(VECTORS.version, 3); for (const section of ['ticket_cases', 'verify_cases', 'message_cases', 'readvice_cases', 'reply_cases', 'outcome_cases', 'record_cases', 'answer_cases', 'transition_cases']) { assert.ok(VECTORS[section].length > 0, section); @@ -198,6 +198,46 @@ test('the duration grammar and the default requested_at', () => { assert.equal(event.link, `${REPLY_URL}/ask/${event.ticket}`); }); +const BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; + +function verifies(ticket, now) { + try { + ask.verifyTicket(ticket, [Buffer.from(KEY)], now); + return true; + } catch (error) { + if (!(error instanceof ask.TicketError)) throw error; + return false; + } +} + +/** + * 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. + */ +const respelled = (part) => [ + ...[...BASE64URL, '=', '\n'].map((extra) => part + extra), + part.slice(0, -1), + ...[...BASE64URL].filter((last) => last !== part.at(-1)).map((last) => part.slice(0, -1) + last) +]; + +test('a ticket has one spelling', () => { + // 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 + const now = 1795089600; + const lengths = new Set(); + for (let size = 1; size <= 12; size += 1) { + const payload = { g: 'order-assistant', c: 'c'.repeat(size), t: 2, k: 'approval', e: now + 3600 }; + const ticket = ask.issueTicket(payload, Buffer.from(KEY)); + const [version, encoded, signature] = ticket.split('.'); + lengths.add(encoded.length % 4); + assert.deepEqual(ask.verifyTicket(ticket, [Buffer.from(KEY)], now), payload); + const others = [...respelled(encoded).map((part) => `${version}.${part}.${signature}`), + ...respelled(signature).map((part) => `${version}.${encoded}.${part}`)]; + assert.deepEqual(others.filter((other) => verifies(other, now)), [], `a correlation id of ${size} characters`); + } + assert.deepEqual([...lengths].sort((a, b) => a - b), [0, 2, 3]); +}); + // --- configuration -------------------------------------------------------------------------------- test('the settings read lists and pairs in both forms', () => { diff --git a/test/vectors/agent-question-vectors.json b/test/vectors/agent-question-vectors.json index fb4a22a3..6196d473 100644 --- a/test/vectors/agent-question-vectors.json +++ b/test/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/test/vectors/ask-person-vectors.json b/test/vectors/ask-person-vectors.json index f5895404..0346e62a 100644 --- a/test/vectors/ask-person-vectors.json +++ b/test/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 79b70ee745521dfe1d98d2c0f2d6efb6a6d67eae Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:38 -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`. rest.yaml is read with the boolean words of the Python pack's reader and the engine's, so the single letters y and n are text here as they are there. - The upload bound counted a text field by the length of its text. Each field counts as the bytes of its part in the body. The body is read within the bound and 1 MiB; past that the rest is let go by unread, so the client takes the 413 instead of a broken connection. - nextSegment wrote the keep-alive comment on a stream that is not Server-Sent Events when the idle timer fired a moment before the clock reached the deadline: `: ping` in the body of a text/plain stream. A keep-alive is written only when a keep-alive interval has passed. - A reply the serializer refuses was the host's catch-all 500 with no trace record, and a stream was destroyed. 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 request body had no limit: 40 MiB was read into memory and delivered. The host takes the Python pack's 16 MiB. Behind REST automation a body over it is the engines' error body, 413 `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 was delivered as a text field, or as a file of that type. It is refused: 400 `Upload takes text fields and files, not a nested multipart part`. An upload whose parts do not follow the boundary its content type declares is a 400 as well, as it is in the Python pack. rest-automation-vectors.json is version 3 (14 load cases for the flags), byte-identical with the Python twin. The three sequential awaits of the host's start and stop carry their reason on the line. The guides, the configuration reference and the README follow. Co-Authored-By: Claude Fable 5.2 --- README.md | 5 +- docs/guides/configuration-reference.md | 2 +- docs/guides/http-surface-reference.md | 8 +- docs/guides/rest-automation.md | 29 ++- src/event-stream.ts | 12 +- src/rest-automation.ts | 188 +++++++++++--- src/rest-routing.ts | 55 +++- src/server.ts | 43 +++- test/event-stream.test.ts | 63 +++++ test/rest-automation.test.ts | 297 +++++++++++++++++++++- test/server.test.ts | 15 ++ test/vectors/rest-automation-vectors.json | 183 ++++++++++++- 12 files changed, 820 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 181b2bf5..808c7ad0 100644 --- a/README.md +++ b/README.md @@ -298,8 +298,9 @@ 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. The -edge is `node:http`, as the host is: no web framework and no new dependency. +`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. The edge is `node:http`, as the host is: no web framework and +no new dependency. The pack's own applications are written this way: the ask-a-person main flow's reply page and endpoint and the agent-question app's person's side are `rest.yaml` entries of their applications diff --git a/docs/guides/configuration-reference.md b/docs/guides/configuration-reference.md index 14dcfce5..9ae4ee99 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 4ebda6e6..b63e8919 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.addRoutes`), 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 9da6bfa9..9fd090b7 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. @@ -150,8 +154,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 @@ -220,9 +226,12 @@ preload('lines.stream', { instances: 10, interceptor: true }, async (_headers, e ``` The entry's `timeout` is the **idle allowance** between segments, not a total bound; the head may -override it with `first(status, contentType, ttlSeconds)`. 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, contentType, ttlSeconds)`. 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(null)` 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 @@ -243,9 +252,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, contentType, 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/event-stream.ts b/src/event-stream.ts index a6d58af1..eea366e9 100644 --- a/src/event-stream.ts +++ b/src/event-stream.ts @@ -196,9 +196,10 @@ export const CLIENT_GONE: unique symbol = Symbol('client-gone'); /** * Wait for the next segment of a streaming reply within the idle allowance, emitting SSE * keep-alive comments while the producer is quiet (best-effort; pings never extend the idle - * allowance); null at expiry, `CLIENT_GONE` when a keep-alive cannot be written because the - * client is gone - the stream ends there and the caller closes the sink, instead of waiting out - * the idle allowance. Shared by the Event API edge and the REST automation edge. + * allowance) - `pingMs` is 0 on a stream that is not Server-Sent Events, which has no comment + * line; null at expiry, `CLIENT_GONE` when a keep-alive cannot be written because the client is + * gone - the stream ends there and the caller closes the sink, instead of waiting out the idle + * allowance. Shared by the Event API edge and the REST automation edge. */ export async function nextSegment(res: http.ServerResponse, queue: Mailbox, idleMs: number, pingMs: number): Promise { @@ -218,6 +219,11 @@ export async function nextSegment(res: http.ServerResponse, queue: Mailbox= deadline) { return null; } + if (wait === remaining) { + // the allowance's own timer, fired a moment before the clock reached the deadline - no + // keep-alive interval has passed: nothing is written, and the loop waits out what is left + continue; + } if (res.writableEnded || res.destroyed) { return CLIENT_GONE; } diff --git a/src/rest-automation.ts b/src/rest-automation.ts index 50c0d9c9..77df6374 100644 --- a/src/rest-automation.ts +++ b/src/rest-automation.ts @@ -22,8 +22,8 @@ * - `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; + * within `rest.upload.max.bytes` (16 MiB; 413 beyond it), counted in bytes as the parts arrived - + * 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; @@ -37,7 +37,7 @@ import { randomBytes, randomUUID } from 'node:crypto'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { isAbsolute, join } from 'node:path'; -import { Readable } from 'node:stream'; +import { MIMEType } from 'node:util'; import { appOrigin } from './actuator.js'; import { AsyncHttpRequest, UploadedFile } from './async-http-request.js'; import { DeliveryTimeout, EventBus, Mailbox, raceMs, roundTripRecord } from './bus.js'; @@ -66,6 +66,7 @@ import { compactJson, errorBody, errorPayload, + MappedResponse, mapResponse, matchedElement, negotiateStreamType, @@ -105,6 +106,12 @@ export const DEFAULT_UPLOAD_MAX_BYTES = 16 * 1024 * 1024; // stays bounded as it is in the Python pack's part-by-part reading const MULTIPART_HEADROOM = 1024 * 1024; const MULTIPART_FORM_DATA = 'multipart/form-data'; +// the host's limit on a request body it reads into memory - the Python pack's client_max_size +export const MAX_BODY_BYTES = 16 * 1024 * 1024; +// an upload's parts are text fields and files: the refusal of a part that is multipart itself +const NESTED_PART = 'Upload takes text fields and files, not a nested multipart part'; +// the answer when a reply cannot be rendered - a body the serializer refuses +const UNRENDERABLE = 'Reply cannot be rendered'; // the edge's own service name in the trace records (the engines' REST edge) export const HTTP_REQUEST = 'http.request'; export const EVENT_API_SERVICE = 'event.api.service'; @@ -234,6 +241,17 @@ export function restError(res: http.ServerResponse, status: number, message: str res.end(bytes); } +/** + * The failure of a reply that cannot be rendered - a body the serializer refuses, a BigInt or a + * structure that contains itself. The reason goes to the log; the response and the trace record + * carry the one message both packs answer. + */ +function unrendered(service: string | undefined, cause: unknown): AppException { + const reason = cause instanceof Error ? cause.message : String(cause); + log.error(`Unable to render the reply of ${service || 'unknown'} - ${reason}`); + return new AppException(500, UNRENDERABLE); +} + function streamErrorMessage(event: EventEnvelope): string { const body = event.body; if (body !== null && typeof body === 'object' && !Array.isArray(body) && !(body instanceof Uint8Array)) { @@ -339,6 +357,24 @@ function writeSegment(res: http.ServerResponse, event: EventEnvelope, marker: st return [status, message]; } +/** + * One segment on the wire, or the stream's failure when the segment cannot be rendered - in band, + * as an `exception` segment fails it: the `error` frame for Server-Sent Events, and the failure as + * the stream's outcome. + */ +function renderSegment(res: http.ServerResponse, event: EventEnvelope, marker: string, sse: boolean, + headStatus: number): StreamOutcome | undefined { + try { + return writeSegment(res, event, marker, sse, headStatus); + } catch (e) { + const failure = unrendered(event.sender, e); + if (sse) { + res.write(sseFrame('error', compactJson(errorBody(failure.status, failure.message)))); + } + return [failure.status, failure.message]; + } +} + /** * Wait for the next segment of a stream that has begun and put it on the wire. Returns the * stream's outcome when it ends here - the client gone, the idle allowance spent (its 408 in band) @@ -370,7 +406,7 @@ async function renderNext(res: http.ServerResponse, queue: Mailbox { return headers; } -function readBody(req: http.IncomingMessage): Promise { +/** + * A request body read into memory within a limit. Past it the reading stops: what is left of the + * body is let go by unread, so the client can finish sending and take the answer, and the refusal + * is thrown. + */ +function readWithin(req: http.IncomingMessage, limit: number, refusal: () => AppException): Promise { return new Promise((resolve, reject) => { const chunks: Buffer[] = []; - req.on('data', (chunk: Buffer) => chunks.push(chunk)); + let size = 0; + const take = (chunk: Buffer): void => { + size += chunk.length; + if (size > limit) { + chunks.length = 0; + req.off('data', take); + req.resume(); + reject(refusal()); + } else { + chunks.push(chunk); + } + }; + req.on('data', take); req.on('end', () => resolve(Buffer.concat(chunks))); req.on('error', reject); }); } +/** A request body within the host's limit on what it reads into memory; one over it is the 413 thrown. */ +export function readBody(req: http.IncomingMessage): Promise { + return readWithin(req, MAX_BODY_BYTES, () => new AppException(413, `Request body exceeds ${MAX_BODY_BYTES} bytes`)); +} + +/** One part of a multipart body as it arrived: whether it is multipart itself, and the bytes of its content. */ +interface ArrivedPart { + nested: boolean; + size: number; +} + +/** True for a header line that declares a `multipart/*` content type - a part that is multipart itself. */ +function declaresMultipart(line: string): boolean { + const colon = line.indexOf(':'); + if (colon === -1 || line.slice(0, colon).trim().toLowerCase() !== 'content-type') { + return false; + } + const type = (baseContentType(line.slice(colon + 1)) ?? '').toLowerCase(); + return type === 'multipart' || type.startsWith('multipart/'); +} + +/** + * The parts of a multipart body the runtime has parsed, read off the same delimiters and so in + * the order of its entries. The runtime hands a part over as a text or a `File`; whether the part + * declared a `multipart/*` type, and how many bytes a text field arrived as, only the body tells. + */ +function arrivedParts(body: Buffer, contentType: string): ArrivedPart[] { + const boundary = Buffer.from(new MIMEType(contentType).params.get('boundary') ?? '', 'utf-8'); + const delimiter = Buffer.concat([Buffer.from('--'), boundary]); + const parts: ArrivedPart[] = []; + let at = body.indexOf(delimiter); + while (at !== -1) { + // after a delimiter, two more dashes close the body and a line end opens a part + at += delimiter.length; + if (body.toString('latin1', at, at + 2) === '--') { + break; + } + // the header lines, up to the empty one + at += 2; + let nested = false; + for (let end = body.indexOf('\r\n', at); end > at; end = body.indexOf('\r\n', at)) { + nested ||= declaresMultipart(body.toString('latin1', at, end)); + at = end + 2; + } + // the content, from the empty line to the line end and the dashes before the next boundary + at += 2; + const next = body.indexOf(boundary, at); + if (next === -1) { + break; + } + parts.push({ nested, size: next - 4 - at }); + at = next - 2; + } + return parts; +} + const uuidHex = (): string => randomUUID().replaceAll('-', ''); /** @@ -527,14 +636,20 @@ function callerTtlMs(req: http.IncomingMessage, timeoutMs: number): number { /** * A single-shot reply written as the response under the engines' mapping, the cookies as one - * `set-cookie` header each. Returns the status, for the edge's record. + * `set-cookie` header each. Returns the status, for the edge's record; a reply that cannot be + * rendered is the 500 thrown, before anything is written. */ function writeResponse(res: http.ServerResponse, info: RouteInfo, prepared: Prepared, reply: EventEnvelope): number { - const mapped = mapResponse({ - status: reply.getStatus(), replyHeaders: reply.headers, body: reply.body, accept: prepared.accept, - isHead: prepared.isHead, transform: info.headers?.response, cors: info.cors, cid: prepared.cid, - cidHeader: prepared.cidHeader - }); + let mapped: MappedResponse; + try { + mapped = mapResponse({ + status: reply.getStatus(), replyHeaders: reply.headers, body: reply.body, accept: prepared.accept, + isHead: prepared.isHead, transform: info.headers?.response, cors: info.cors, cid: prepared.cid, + cidHeader: prepared.cidHeader + }); + } catch (e) { + throw unrendered(info.service, e); + } const cookies: string[] = []; for (const [name, value] of mapped.headers) { if (name === 'set-cookie') { @@ -760,42 +875,38 @@ export class RestAutomation { /** * 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. + * 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 arrived, may not exceed + * `rest.upload.max.bytes` - a 413 the moment they do. */ private async readMultipart(req: http.IncomingMessage): Promise<{ files: UploadedFile[]; fields: Record }> { const files: UploadedFile[] = []; const fields: Record = {}; const bound = this.uploadMaxBytes; const exceeded = (): AppException => new AppException(413, `Upload exceeds ${bound} bytes`); - let refused: AppException | undefined; - const cap = bound + MULTIPART_HEADROOM; - async function* capped(): AsyncGenerator { - let seen = 0; - for await (const chunk of req) { - seen += (chunk as Buffer).length; - if (seen > cap) { - refused = exceeded(); - throw refused; - } - yield chunk as Buffer; - } - } + const contentType = String(req.headers['content-type']); + const raw = await readWithin(req, bound + MULTIPART_HEADROOM, exceeded); let form: FormData; try { - const body = Readable.toWeb(Readable.from(capped())) as ReadableStream; - const headers = { 'content-type': String(req.headers['content-type']) }; - form = await new Response(body, { headers }).formData(); + form = await new Response(raw as BodyInit, { headers: { 'content-type': contentType } }).formData(); } catch (e) { - if (refused) { - throw refused; - } throw new AppException(400, `Invalid multipart body - ${(e as Error).message ?? String(e)}`); } + const entries = [...form.entries()]; + const arrived = arrivedParts(raw, contentType); + if (arrived.length !== entries.length) { + // the runtime read the parts off another boundary than the one the content type declares + throw new AppException(400, 'Invalid multipart body - its boundary is not the one the content type declares'); + } let total = 0; - for (const [name, value] of form.entries()) { + for (const [index, [name, value]] of entries.entries()) { + const part = arrived[index]; + if (part.nested) { + throw new AppException(400, NESTED_PART); + } if (typeof value === 'string') { - total += value.length; + // the bytes the field arrived as, never the length of the text they spell + total += part.size; if (total > bound) { throw exceeded(); } @@ -970,6 +1081,9 @@ export class RestAutomation { } else { reply = await this.rpc(info.service, service, prepared, info.timeoutMs); } + // a reply that cannot be rendered fails here, answered and recorded as any other failure is + const status = writeResponse(res, info, prepared, reply); + edge?.record(status); } catch (e) { if (e instanceof AppException) { edge?.record(e.status, e.message); @@ -978,8 +1092,6 @@ export class RestAutomation { } throw e; } - const status = writeResponse(res, info, prepared, reply); - edge?.record(status); } /** @@ -1045,7 +1157,7 @@ export class RestAutomation { if (pending !== undefined) { const { event, marker } = pending; pending = undefined; - outcome = writeSegment(res, event, marker, sse, headStatus); + outcome = renderSegment(res, event, marker, sse, headStatus); } else { outcome = await renderNext(res, queue, sse, idleMs, pingMs, headStatus); } diff --git a/src/rest-routing.ts b/src/rest-routing.ts index d329988a..820b3d2e 100644 --- a/src/rest-routing.ts +++ b/src/rest-routing.ts @@ -20,6 +20,7 @@ * `mime.types`, XML and request-body streaming. */ import YAML from 'yaml'; +import type { ScalarTag } from 'yaml'; import { asText } from './envelope.js'; import { AppException } from './exceptions.js'; @@ -539,9 +540,32 @@ function parseMethods(index: number, entry: Mapping): string[] { return methods; } +/** + * 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. + */ +function parseFlag(index: number, entry: Mapping, key: string): boolean { + const value = lookup(entry, key); + if (value === undefined || value === null || value === '') { + return false; + } + if (typeof value === 'boolean') { + return value; + } + const lowered = typeof value === 'string' ? value.toLowerCase() : ''; + if (lowered === 'true' || lowered === 'false') { + return lowered === 'true'; + } + throw new AppException(400, `rest[${index}] '${key}' must be true or false`); +} + /** * One `rest` entry. Its faults are reported in this order, the first one found failing the load: - * the service, the url, the methods, then the cors and the headers reference. + * the service, the url, the methods, then the cors and the headers reference, then the flags - + * tracing, stream, upload. */ function parseRoute(index: number, entry: Mapping, corsBlocks: Map, headerBlocks: Map): RouteInfo { @@ -572,9 +596,9 @@ function parseRoute(index: number, entry: Mapping, corsBlocks: Map unkn return data; } +const BOOLEAN_TAG = 'tag:yaml.org,2002:bool'; + +/** A boolean as PyYAML resolves one: the words that spell `value`. */ +const booleanTag = (value: boolean, words: RegExp): ScalarTag => ({ + identify: (found) => found === value, default: true, tag: BOOLEAN_TAG, test: words, resolve: () => value +}); + +// PyYAML's booleans - and SnakeYAML's, the Java engine's reader: yes and no, true and false, on and +// off. The YAML 1.1 specification also reads the single letters y and n as booleans; to those two +// readers they are text, so they are text here +const PYYAML_BOOLEANS = [ + booleanTag(true, /^(?:yes|Yes|YES|true|True|TRUE|on|On|ON)$/), + booleanTag(false, /^(?:no|No|NO|false|False|FALSE|off|Off|OFF)$/) +]; + /** A YAML text as the Python pack's `yaml.safe_load` reads it: an empty document is null. */ export function parseYaml(yamlText: string): unknown { // YAML 1.1 (yes/no/on/off are booleans, as PyYAML reads them) with duplicate keys tolerated, the // last winning - so an engine's rest.yaml reads here as it reads in the Python pack - return YAML.parse(yamlText, { version: '1.1', uniqueKeys: false }); + return YAML.parse(yamlText, { + version: '1.1', + uniqueKeys: false, + customTags: (tags) => [ + ...tags.filter((tag) => typeof tag === 'string' || tag.tag !== BOOLEAN_TAG), ...PYYAML_BOOLEANS + ] + }); } const pathSegments = (path: string): string[] => path.split('/').filter((s) => s.length > 0); diff --git a/src/server.ts b/src/server.ts index 920a3440..3aef5ecd 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4,9 +4,10 @@ * Mirrors the Java engine's EventApiService: request body = envelope bytes; * x-ttl (ms, floor 1000) bounds handler execution; x-async: true means * drop-n-forget (HTTP 202 with an ack envelope). Transport-level failures - * (400 / 403 / 404 / 408) set the HTTP status; a handler's own outcome — - * including AppException and unexpected errors — rides HTTP 200 with the - * status inside the envelope, exactly like an engine function's reply. + * (400 / 403 / 404 / 408, and 413 for a body over the 16 MiB the host reads + * into memory) set the HTTP status; a handler's own outcome — including + * AppException and unexpected errors — rides HTTP 200 with the status inside + * the envelope, exactly like an engine function's reply. * Reserved header hygiene: x-event-api 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 header. @@ -48,10 +49,11 @@ import { TEXT_EVENT_STREAM, X_TTL } from './event-stream.js'; +import { AppException } from './exceptions.js'; import { getLogger } from './log.js'; import { activate as activateOtelForwarder } from './otel/index.js'; import { defaultRegistry, FunctionRegistry, ServiceDef } from './registry.js'; -import { RestAutomation, restError } from './rest-automation.js'; +import { readBody, RestAutomation, restError } from './rest-automation.js'; import { MY_CID_TAG, MY_CORRELATION_ID } from './trace.js'; const OCTET_STREAM = 'application/octet-stream'; @@ -88,6 +90,22 @@ function decodeEvent(res: http.ServerResponse, raw: Buffer): EventEnvelope | und } } +/** + * The body of a `POST /api/event` within the host's limit; a body over it is answered with the + * 413 - a transport failure as the others are, an envelope - and yields undefined. + */ +async function eventBody(req: http.IncomingMessage, res: http.ServerResponse): Promise { + try { + return await readBody(req); + } catch (e) { + if (e instanceof AppException) { + transportError(res, e.status, e.message); + return undefined; + } + throw e; + } +} + function handlerHeaders(event: EventEnvelope): Record { const headers: Record = {}; for (const [k, v] of Object.entries(event.headers)) { @@ -388,12 +406,6 @@ export class EventApiServer { } return false; }; - const readBody = (req: http.IncomingMessage): Promise => new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - req.on('data', (chunk: Buffer) => chunks.push(chunk)); - req.on('end', () => resolve(Buffer.concat(chunks))); - req.on('error', reject); - }); // a static file for a GET or HEAD that names one - under the static-content rules of rest.yaml // when REST automation is on const staticFile = (req: http.IncomingMessage, res: http.ServerResponse, url: URL): Promise => @@ -409,7 +421,10 @@ export class EventApiServer { return true; } if (method === 'POST' && url.pathname === '/api/event') { - await this.handleEvent(req, res, await readBody(req)); + const raw = await eventBody(req, res); + if (raw !== undefined) { + await this.handleEvent(req, res, raw); + } return true; } // the actuator's paths stay the host's (a static folder's index.html replaces the landing page @@ -590,10 +605,10 @@ export class Platform { /** Run the shutdown callbacks in order (the streams end), then the cleanup callbacks, last registered first. */ async shutdown(): Promise { for (const callback of this.stopping) { - await callback(); + await callback(); // NOSONAR - sequential: the shutdown callbacks run in the order they were registered } for (const callback of [...this.cleanup].reverse()) { - await callback(); + await callback(); // NOSONAR - sequential: the cleanup callbacks run one at a time, last registered first } } @@ -609,7 +624,7 @@ export class Platform { // an extension's boot work runs before the host listens, so the routes it registers are // announced with the others and a failure stops the start for (const callback of this.startup) { - await callback(); + await callback(); // NOSONAR - sequential: an extension's boot work runs in the order it was registered } for (const service of this.registry.routes()) { const visibility = service.isPrivate ? 'PRIVATE' : 'PUBLIC'; diff --git a/test/event-stream.test.ts b/test/event-stream.test.ts index d18690a6..d9bf95dd 100644 --- a/test/event-stream.test.ts +++ b/test/event-stream.test.ts @@ -6,10 +6,12 @@ import assert from 'node:assert/strict'; import type * as http from 'node:http'; import { after, before, test } from 'node:test'; +import { Mailbox } from '../src/bus.js'; import { PostOffice } from '../src/client.js'; import { EventEnvelope } from '../src/envelope.js'; import { EventStreamWriter, + nextSegment, streamEventName, streamSignal } from '../src/event-stream.js'; @@ -579,3 +581,64 @@ test('a writer whose reply sink is gone closes itself', () => { out.write('gamma'); // dropped quietly, as any write after close assert.equal(out.closed, true); }); + +// ---- the keep-alive of a quiet stream: the clock and the timer driven by the test ---- + +/** A response that keeps what is written to it. */ +function wire(): { res: http.ServerResponse; written: string[] } { + const written: string[] = []; + const res = { + writableEnded: false, + destroyed: false, + write: (chunk: string): boolean => { + written.push(chunk); + return true; + } + }; + return { res: res as unknown as http.ServerResponse, written }; +} + +/** Let the promise callbacks that are due run: the timers are the test's, an immediate is not. */ +const settle = (): Promise => new Promise((resolve) => setImmediate(resolve)); + +const PING = ': ping\n\n'; + +test('a stream that is not Server-Sent Events gets no keep-alive', async (t) => { + // an idle allowance of one second from 100,000: its timer fires when the clock reads 100,999, a moment + // before the deadline, and the rest of the allowance runs out at 101,000. A chunked stream has no comment + // line, so nothing may be written into its body + let now = 100_000; + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.mock.method(Date, 'now', () => now); + const { res, written } = wire(); + const waiting = nextSegment(res, new Mailbox(), 1000, 0); + now = 100_999; + t.mock.timers.tick(1000); + await settle(); + now = 101_000; + t.mock.timers.tick(1); + assert.equal(await waiting, null); + assert.deepEqual(written, []); +}); + +test('a keep-alive is written when its interval has passed', async (t) => { + // the same allowance with a keep-alive every 400 ms: two intervals pass, at 100,400 and 100,800 - and + // none comes from the idle timer that fires early at the end + let now = 100_000; + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.mock.method(Date, 'now', () => now); + const { res, written } = wire(); + const waiting = nextSegment(res, new Mailbox(), 1000, 400); + for (const reading of [100_400, 100_800]) { + now = reading; + t.mock.timers.tick(400); + await settle(); + } + now = 100_999; + t.mock.timers.tick(200); + await settle(); + now = 101_000; + t.mock.timers.tick(1); + assert.equal(await waiting, null); + assert.deepEqual(written, [PING, PING]); +}); diff --git a/test/rest-automation.test.ts b/test/rest-automation.test.ts index 358a656a..091231df 100644 --- a/test/rest-automation.test.ts +++ b/test/rest-automation.test.ts @@ -39,7 +39,7 @@ import { getTrace } from '../src/trace.js'; const here = path.dirname(fileURLToPath(import.meta.url)); const VECTORS_FILE = path.resolve(here, '../../test/vectors/rest-automation-vectors.json'); // the Python twin pins the same digest: change the file in both packs or in neither -const VECTORS_SHA256 = 'a9b7ef8b1b065dc3b9a0b3cd92e0d518ac1027406624445fa82c4d965f39082e'; +const VECTORS_SHA256 = '02fb140f780a9b781dc6cfc7a1c48b1b8094a089cae350dbf5e813754517a51d'; const MY_CID = 'my_correlation_id'; type Json = Record; // eslint-disable-line @typescript-eslint/no-explicit-any @@ -61,7 +61,7 @@ function routeView(route: RouteInfo): Json { test('the vector file is the one the python twin runs', () => { const digest = createHash('sha256').update(fs.readFileSync(VECTORS_FILE)).digest('hex'); assert.equal(digest, VECTORS_SHA256, "update both packs' pins when the shared file changes"); - assert.equal(vectors.version, 2); + assert.equal(vectors.version, 3); }); test('vectors: load cases', () => { @@ -995,8 +995,99 @@ describe('the edge over HTTP', () => { assert.equal(data.kind, 'bytes'); assert.ok(String(data.content).includes('report.pdf')); }); + + test('an upload refuses a nested multipart part', async () => { + // 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 + const nested: Part = [['Content-Disposition: form-data; name="files"', 'Content-Type: multipart/mixed; boundary=inner'], INNER]; + const named: Part = [['Content-Disposition: form-data; name="files"; filename="bundle"', + 'Content-Type: Multipart/Mixed; boundary=inner'], INNER]; + const bare: Part = [['Content-Disposition: form-data; name="files"', 'Content-Type: multipart/related'], Buffer.from('x')]; + const note = textField('note', 'hello'); + const refused: Record = { + 'ahead of a field': [nested, note], + 'ahead of a file': [nested, filePart('doc', 'a.bin', Buffer.from([1, 2]))], + '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 (const [name, parts] of Object.entries(refused)) { + const form = multipartBody(...parts); + const { status, lines, body } = await exchange(`${base}/api/upload`, 'POST', form.headers, form.body); + assert.equal(status, 400, name); + assert.equal(header(lines, 'content-type'), 'application/json', name); + assert.deepEqual(json(body), { status: 400, message: NESTED_PART, type: 'error' }, name); + } + // the same form without the nested part is delivered + const form = multipartBody(note, filePart('doc', 'a.bin', Buffer.from([1, 2]))); + const { status, body } = await exchange(`${base}/api/upload`, 'POST', form.headers, form.body); + assert.equal(status, 200); + assert.deepEqual(json(body).query, { note: 'hello' }); + assert.deepEqual(json(body).files.map((f: Json) => f.name), ['a.bin']); + }); + + test('an upload whose parts do not follow the declared boundary is 400', async () => { + // the content type declares the boundary a,b and the parts are delimited by a: no reading of the + // header may deliver them + const body = '--a\r\nContent-Disposition: form-data; name="note"\r\n\r\nhello\r\n--a--\r\n'; + const headers = { 'Content-Type': 'multipart/form-data; boundary=a,b', Accept: 'application/json' }; + const reply = await exchange(`${base}/api/upload`, 'POST', headers, body); + assert.equal(reply.status, 400); + assert.ok(String(json(reply.body).message).startsWith('Invalid multipart body - '), reply.body.toString()); + }); + + // ---- the host's limit on a body it reads into memory ---- + + test("a body over the host's limit is the engines' 413", async () => { + // a body over 16 MiB is refused in the engines' error body - behind an entry, and behind the default + // entry of the Event API - where the host used to read whatever arrived + const octets = { 'Content-Type': 'application/octet-stream', Accept: 'application/json' }; + for (const path of ['/api/upload', '/api/event']) { + const { status, lines, body } = await exchange(`${base}${path}`, 'POST', octets, Buffer.alloc(BODY_LIMIT + 1)); + assert.equal(status, 413, path); + assert.equal(header(lines, 'content-type'), 'application/json', path); + assert.equal(body.toString('utf-8'), BODY_TOO_LARGE, path); + } + // a body of exactly the limit is read and delivered + const { status, body } = await exchange(`${base}/api/upload`, 'POST', octets, Buffer.alloc(BODY_LIMIT)); + assert.equal(status, 200); + assert.equal(json(body).body_present, true); + }); }); +const BOUNDARY = 'mercury-test-boundary'; +type Part = [string[], Buffer]; + +/** + * 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. + */ +function multipartBody(...parts: Part[]): { headers: Record; body: Buffer } { + const chunks: Buffer[] = []; + for (const [lines, content] of parts) { + chunks.push(Buffer.from(`--${BOUNDARY}\r\n${lines.join('\r\n')}\r\n\r\n`, 'utf-8'), content, Buffer.from('\r\n')); + } + chunks.push(Buffer.from(`--${BOUNDARY}--\r\n`)); + return { + headers: { 'Content-Type': `multipart/form-data; boundary=${BOUNDARY}`, Accept: 'application/json' }, + body: Buffer.concat(chunks) + }; +} + +const textField = (name: string, text: string): Part => + [[`Content-Disposition: form-data; name="${name}"`], Buffer.from(text, 'utf-8')]; +const filePart = (name: string, filename: string, content: Buffer): Part => + [[`Content-Disposition: form-data; name="${name}"; filename="${filename}"`, 'Content-Type: application/octet-stream'], content]; + +const NESTED_PART = 'Upload takes text fields and files, not a nested multipart part'; +const INNER = Buffer.from('--inner\r\nContent-Disposition: attachment; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\nAAA\r\n' + + '--inner\r\nContent-Disposition: attachment; filename="b.txt"\r\nContent-Type: text/plain\r\n\r\nBBB\r\n' + + '--inner--'); +const BODY_LIMIT = 16 * 1024 * 1024; +const BODY_TOO_LARGE = '{\n "status": 413,\n "message": "Request body exceeds 16777216 bytes",\n "type": "error"\n}'; + const PDF_BYTES = Buffer.from('%PDF-1.4 a small document'); const PNG_BYTES = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from(' a small image')]); const sha256 = (data: Buffer): string => createHash('sha256').update(data).digest('hex'); @@ -1218,6 +1309,75 @@ test('cors lines resolve configuration references', () => { } }); +const 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:} +`; + +/** The flags' application folder: the rest.yaml beside an application.yml that holds a boolean. */ +function flagsConfigured(): void { + const folder = configured(FLAGS_YAML); + write(path.join(folder, 'resources', 'application.yml'), 'rest.test.flag: true\n'); + loadConfig(undefined, folder); + appConfig().set('rest.automation', true); +} + +function flagsOf(table: RoutingTable, url: string): Json { + const entry = table.find('POST', url); + assert.ok(entry, url); + return { tracing: entry.info.tracing, stream: entry.info.stream, upload: entry.info.upload }; +} + +test("an entry's flags resolve configuration references", () => { + // 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 + delete process.env.REST_TEST_TRACING; + delete process.env.REST_TEST_UNSET; + process.env.REST_TEST_STREAM = 'TRUE'; + process.env.REST_TEST_UPLOAD = 'true'; + try { + flagsConfigured(); + const api = new EventApiServer(buildRegistry(new Probe())); + assert.ok(api.rest); + // the default after the colon, an environment variable over its default, one without a default + assert.deepEqual(flagsOf(api.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.deepEqual(flagsOf(api.rest.table, '/api/flags/configuration'), { tracing: true, stream: false, upload: false }); + } finally { + delete process.env.REST_TEST_STREAM; + delete process.env.REST_TEST_UPLOAD; + loadConfig(); + } +}); + +test('a flag reference that is neither true nor false fails the start', () => { + process.env.REST_TEST_TRACING = 'on'; + process.env.REST_TEST_UPLOAD = 'true'; + try { + flagsConfigured(); + assert.throws(() => new EventApiServer(buildRegistry(new Probe())), (e: unknown) => { + assert.ok(e instanceof AppException); + assert.equal(e.status, 400); + assert.equal(e.message, "rest[0] 'tracing' must be true or false"); + return true; + }); + } finally { + delete process.env.REST_TEST_TRACING; + delete process.env.REST_TEST_UPLOAD; + loadConfig(); + } +}); + test('an upload over the bound is 413', async () => { configured(REST_YAML, { 'rest.upload.max.bytes': 40 }); const served = await start(buildRegistry(new Probe())); @@ -1230,3 +1390,136 @@ test('an upload over the bound is 413', async () => { loadConfig(); } }); + +test('the upload bound counts a text field in bytes', async () => { + // 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 + const tooLarge = { status: 413, message: 'Upload exceeds 1000 bytes', type: 'error' }; + const over: Record = { + '600 two-byte characters': [textField('note', 'é'.repeat(600))], + '334 three-byte characters': [textField('note', '€'.repeat(334))], + '260 four-byte characters': [textField('note', '😀'.repeat(260))], + 'a 600-byte file and 300 two-byte characters': [filePart('doc', 'a.bin', Buffer.alloc(600, 1)), textField('note', 'é'.repeat(300))] + }; + const within: Record = { + '500 two-byte characters': [textField('note', 'é'.repeat(500))], + 'a 400-byte file and 300 two-byte characters': [filePart('doc', 'a.bin', Buffer.alloc(400, 1)), textField('note', 'é'.repeat(300))] + }; + configured(REST_YAML, { 'rest.upload.max.bytes': 1000 }); + const served = await start(buildRegistry(new Probe())); + try { + for (const [name, parts] of Object.entries(over)) { + const form = multipartBody(...parts); + const { status, body } = await exchange(`${served.base}/api/upload`, 'POST', form.headers, form.body); + assert.equal(status, 413, name); + assert.deepEqual(json(body), tooLarge, name); + } + for (const [name, parts] of Object.entries(within)) { + const form = multipartBody(...parts); + const { status, body } = await exchange(`${served.base}/api/upload`, 'POST', form.headers, form.body); + assert.equal(status, 200, name); + assert.deepEqual(json(body).query, { note: parts.at(-1)![1].toString('utf-8') }, name); + } + } finally { + await served.stop(); + loadConfig(); + } +}); + +// ---- a reply that cannot be rendered ---- + +const 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 +`; +const UNRENDERABLE = '{\n "status": 500,\n "message": "Reply cannot be rendered",\n "type": "error"\n}'; +const UNRENDERABLE_FRAME = 'event: error\ndata: {"status":500,"message":"Reply cannot be rendered","type":"error"}\n\n'; + +/** Functions whose reply the serializer refuses: a BigInt is not JSON. */ +function unrenderableRegistry(probe: Probe): FunctionRegistry { + const registry = buildRegistry(probe); + registry.register('unrenderable.reply', async () => ({ when: 10n })); + registry.register('unrenderable.events', async (_headers, event) => { + const out = EventStreamWriter.fromRequest(event as EventEnvelope, registry); + out.first(200, 'text/event-stream'); + out.write('one'); + out.write({ when: 10n }); + out.write('three'); + out.close(); + }, { interceptor: true }); + registry.register('unrenderable.lines', async (_headers, event) => { + const out = EventStreamWriter.fromRequest(event as EventEnvelope, registry); + out.first(200, 'application/json'); + out.write('one'); + out.write({ when: 10n }); + out.write('three'); + out.close(); + }, { interceptor: true }); + return registry; +} + +/** The edge's `http.request` record of the request for `path`. */ +async function edgeRecord(probe: Probe, path: string): Promise { + const found = (): Json[] => probe.datasets.map((d) => d.trace) + .filter((trace) => trace.service === 'http.request' && trace.path === `GET ${path}`); + await waitFor(() => found().length > 0); + return found()[0]; +} + +test("a reply that cannot be rendered is the engines' 500 and is traced", async () => { + const probe = new Probe(); + configured(UNRENDERABLE_YAML); + const served = await start(unrenderableRegistry(probe)); + try { + const { status, lines, body } = await exchange(`${served.base}/api/unrenderable`, 'GET', { Accept: 'application/json' }); + assert.equal(status, 500); + assert.equal(header(lines, 'content-type'), 'application/json'); + assert.equal(body.toString('utf-8'), UNRENDERABLE); + const edge = await edgeRecord(probe, '/api/unrenderable'); + assert.equal(edge.status, 500); + assert.equal(edge.success, false); + assert.equal(edge.exception, 'Reply cannot be rendered'); + } finally { + await served.stop(); + loadConfig(); + } +}); + +test('a segment that cannot be rendered fails the stream in band and is traced', async () => { + const probe = new Probe(); + configured(UNRENDERABLE_YAML); + const served = await start(unrenderableRegistry(probe)); + try { + // Server-Sent Events: the segments before it, then the error frame - nothing after it + const events = await exchange(`${served.base}/api/unrenderable/events`, 'GET', { Accept: 'text/event-stream' }); + assert.equal(events.status, 200); + assert.equal(header(events.lines, 'content-type'), 'text/event-stream'); + assert.equal(events.body.toString('utf-8'), `data: one\n\n${UNRENDERABLE_FRAME}`); + const eventsEdge = await edgeRecord(probe, '/api/unrenderable/events'); + assert.equal(eventsEdge.status, 500); + assert.equal(eventsEdge.exception, 'Reply cannot be rendered'); + // a chunked stream has no error frame: it ends, and the record tells + const chunked = await exchange(`${served.base}/api/unrenderable/lines`, 'GET', { Accept: '*/*' }); + assert.equal(chunked.status, 200); + assert.equal(header(chunked.lines, 'content-type'), 'application/json'); + assert.equal(chunked.body.toString('utf-8'), 'one'); + const chunkedEdge = await edgeRecord(probe, '/api/unrenderable/lines'); + assert.equal(chunkedEdge.status, 500); + assert.equal(chunkedEdge.exception, 'Reply cannot be rendered'); + } finally { + await served.stop(); + loadConfig(); + } +}); diff --git a/test/server.test.ts b/test/server.test.ts index 09e0ac89..32d99485 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -172,3 +172,18 @@ test('actuator endpoints are wired', async () => { const body = await info.json() as { runtime: { language: string } }; assert.equal(body.runtime.language, 'node.js'); }); + +test("a body over the host's limit is a transport failure 413", async () => { + // 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 + const response = await fetch(`${base}/api/event`, { + method: 'POST', + headers: { 'content-type': OCTET, 'x-ttl': '5000' }, + body: new Uint8Array(16 * 1024 * 1024 + 1) + }); + assert.equal(response.status, 413); + assert.equal(response.headers.get('content-type'), OCTET); + const reply = EventEnvelope.fromBytes(new Uint8Array(await response.arrayBuffer())); + assert.equal(reply.getStatus(), 413); + assert.equal(reply.body, 'Request body exceeds 16777216 bytes'); +}); diff --git a/test/vectors/rest-automation-vectors.json b/test/vectors/rest-automation-vectors.json index dd06e618..0ee6efb8 100644 --- a/test/vectors/rest-automation-vectors.json +++ b/test/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 c8e43a65d49bbb9e691fca37a2ae391062ed5898 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:53:43 -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' address check read an IPv4-mapped IPv6 address written in hex (`::ffff:7f00:1`) as public, where the dotted spelling of the same address was loopback and the Python twin refused both; and its list of blocks was shorter than the twin's. 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 (the documentation, benchmarking and protocol-assignment blocks are new here) and the shared address space. 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. The table is read by the runtime's own subnet list (net.BlockList): the module parses no address itself. Globs. A pattern that ends in `**` returned nothing from file.list and file.search, and the Python twin's Path.glob read `**` differently from one Python version to the next. Both packs now compile a glob by one grammar: `**` 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 - as an expression, three stars against a name of 1,500 characters did not finish in two minutes, with the event loop blocked. 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. Also: the HTML reader looks a name from a page up in the tables' own keys only (`&constructor;` gave the text of a function, a `` element was a heading); a crawl that starts on an address literal or on a host written with a dot at its end follows its links; an allowlist entry that starts with a class is a pattern (`[ab].example.com` was read as the address `ab`), and one with a bracket that never closes is the pattern it spells, where it was a 500 at the first request; file.write under a file is 400 ` is not a directory`; a redirect to an address that cannot be read is a 400. test/agent-tools.test.mjs: 59 pass before, 78 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 Python twin's test file. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-tools/README.md | 23 +- extensions/agent-tools/agent-tools.mjs | 379 ++++++++----- test/agent-tools.test.mjs | 719 ++++++++++++++++++++++++- 3 files changed, 993 insertions(+), 128 deletions(-) diff --git a/extensions/agent-tools/README.md b/extensions/agent-tools/README.md index c3ad7571..a5042367 100644 --- a/extensions/agent-tools/README.md +++ b/extensions/agent-tools/README.md @@ -71,10 +71,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 `pdfjs-dist` and `mammoth`, 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. @@ -85,7 +94,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, the body is requested without compression, and the tool identifies itself as `Mercury-Composable-AgentTools/`. @@ -175,7 +189,7 @@ the time zone database. | `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 | @@ -297,3 +311,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 generated in the test and a Word fixture; 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.mjs b/extensions/agent-tools/agent-tools.mjs index 5014e5b0..c46c0def 100644 --- a/extensions/agent-tools/agent-tools.mjs +++ b/extensions/agent-tools/agent-tools.mjs @@ -44,7 +44,7 @@ import { lookup as dnsLookup } from 'node:dns/promises'; import { mkdir, open, readdir, readFile, realpath, stat, writeFile } from 'node:fs/promises'; import http from 'node:http'; import https from 'node:https'; -import { isIP } from 'node:net'; +import { BlockList, isIP } from 'node:net'; import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { AppException, appConfig, defaultRegistry, getLogger, isoUtc, loadConfig, platform, preload, VERSION } from 'mercury-composable'; @@ -784,60 +784,143 @@ function entryType(info) { } /** - * The `[...]` of a glob that starts at an index of a segment, as a class of the regular expression, with the - * index of its `]`; a `[` that never closes is a literal, and ends where it stands. + * 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. */ -function globClass(segment, at) { - const close = segment.indexOf(']', at + 1); - if (close < 0) return [String.raw`\[`, at]; - let body = segment.slice(at + 1, close); - if (body.startsWith('!')) body = '^' + body.slice(1); - return ['[' + body.replaceAll('\\', '\\\\') + ']', close]; +function matchRun(pattern, subject, star, holds) { + let at = 0; + let taken = 0; + let starAt = -1; + let starTaken = -1; + while (taken < subject.length) { + if (at < pattern.length && pattern[at] === star) { + starAt = at + 1; + starTaken = taken; + at += 1; + } else if (at < pattern.length && holds(pattern[at], subject[taken])) { + at += 1; + taken += 1; + } else if (starAt >= 0) { + starTaken += 1; + at = starAt; + taken = starTaken; + } else { + return false; + } + } + while (at < pattern.length && pattern[at] === star) at += 1; + return at === pattern.length; +} + +// whether one item of a name's pattern holds a character: `?` any, a class by its ranges, a character itself +function holdsChar(item, char) { + if (typeof item === 'string') return item === '?' || item === char; + const code = char.codePointAt(0); + return item.members.some(([low, high]) => low <= code && code <= high) !== item.negated; +} + +/** Whether the items of one segment hold one name - a file's, a folder's or a host's - character by character. */ +function matchName(items, name) { + return matchRun(items, Array.from(name), '*', holdsChar); } /** - * A glob pattern as Python's Path.glob reads it - `*` within a segment, `?` one character, `[...]` a class, - * `**` any number of segments - compiled to a matcher over slash-separated relative paths, with the depth the - * walk needs (undefined for a recursive pattern). Node 20 has no fs.glob, so the walk is in-house. + * The members of a glob's class as ranges of code points, a single character as a range of one; a range + * written backwards holds nothing. + */ +function classMembers(chars) { + const members = []; + let index = 0; + while (index < chars.length) { + const ranged = chars[index + 1] === '-' && index + 2 < chars.length; + const low = chars[index].codePointAt(0); + const high = chars[ranged ? index + 2 : index].codePointAt(0); + index += ranged ? 3 : 1; + if (low <= high) members.push([low, high]); + } + return members; +} + +/** + * The `[...]` of a glob that starts at an index of a segment's characters, 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. + */ +function globClass(chars, at) { + const negated = chars[at + 1] === '!'; + const start = negated ? at + 2 : at + 1; + const close = chars.indexOf(']', start + 1); + if (close < 0) return ['[', at]; + return [{ negated, members: classMembers(chars.slice(start, close)) }, close]; +} + +/** + * 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. + */ +function globSegment(segment) { + const chars = Array.from(segment); + const items = []; + let index = 0; + while (index < chars.length) { + const char = chars[index]; + if (char === '[') { + const [item, last] = globClass(chars, index); + items.push(item); + index = last; + } else if (char !== '*' || items.at(-1) !== '*') { + // a run of stars is one + items.push(char); + } + index++; + } + return items; +} + +/** The segments of a glob, compiled: `**` stays as it is, a run of them as one, and any other segment becomes its items. */ +function globSegments(parts) { + const segments = []; + for (const part of parts) { + if (part !== '**') segments.push(globSegment(part)); + else if (segments.at(-1) !== '**') segments.push(part); + } + return segments; +} + +/** + * 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 (undefined for a recursive pattern). The + * grammar is this function's, the same in the Python 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. */ export function compileGlob(pattern) { if (pattern.startsWith('/') || pattern.startsWith('\\') || DRIVE.test(pattern) || !pattern.trim()) { throw new AppException(400, 'glob is not a valid pattern (a pattern is relative to path)'); } - const segments = pattern.split('/').filter((part) => part && part !== '.'); - if (segments.includes('..')) { + const parts = pattern.split('/').filter((part) => part && part !== '.'); + if (parts.includes('..')) { throw new AppException(400, 'glob is not a valid pattern (no .. in a pattern)'); } - const recursive = segments.includes('**'); - const parts = segments.map((segment) => { - if (segment === '**') return '(?:[^/]+/)*'; - let out = ''; - let i = 0; - while (i < segment.length) { - const ch = segment[i]; - if (ch === '*') { - out += '[^/]*'; - } else if (ch === '?') { - out += '[^/]'; - } else if (ch === '[') { - const [piece, last] = globClass(segment, i); - out += piece; - i = last; - } else { - out += ch.replace(/[.+^$(){}|\\]/g, (c) => '\\' + c); - } - i++; - } - return out + '/'; - }); - const source = '^' + parts.join('').replace(/\/$/, '') + '$'; - let regex; - try { - regex = new RegExp(source); - } catch (e) { - throw new AppException(400, `glob is not a valid pattern (${e.message})`); + if (!parts.length) { + throw new AppException(400, 'glob is not a valid pattern (it names no entry)'); } - return { test: (relativePath) => regex.test(relativePath), depth: recursive ? undefined : segments.length }; + const segments = globSegments(parts); + const recursive = segments.includes('**'); + // how many segments stand before the first **, and how deep the walk goes + const lead = recursive ? segments.indexOf('**') : segments.length; + const depth = recursive ? undefined : segments.length; + return { + test: (relativePath) => matchRun(segments, relativePath.split('/'), '**', matchName), + // 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. + enters: (name, level) => (level > lead ? recursive : level !== depth && matchName(segments[level - 1], name)), + depth, + foldersOnly: pattern.endsWith('/') + }; } /** @@ -848,7 +931,7 @@ function scanEntry(entry, { dir, relativeDir, level }, matcher, found, queue) { const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name; if (matcher.test(relativePath)) found.push(join(dir, entry.name)); if (found.length > SCAN_LIMIT) return true; - if (entry.isDirectory() && !entry.isSymbolicLink() && (matcher.depth === undefined || level < matcher.depth)) { + if (entry.isDirectory() && !entry.isSymbolicLink() && matcher.enters(entry.name, level)) { queue.push({ dir: join(dir, entry.name), relativeDir: relativePath, level: level + 1 }); } return false; @@ -955,10 +1038,10 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin /** * A walked entry as the workspace shows it - its relative path, its real path and what it is - or - * undefined for one that is hidden, escapes the workspace, is gone, or is not a file when only - * files count. + * undefined for one that is hidden, escapes the workspace, is gone, or is not of the kind that + * counts. */ - async function exposedEntry(entry, filesOnly) { + async function exposedEntry(entry, { filesOnly, foldersOnly }) { const shown = relative(root, entry).split(sep).join('/'); if (!shown || shown.startsWith('..')) return undefined; if (!sandbox.hidden && isHidden(shown)) return undefined; @@ -971,6 +1054,7 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin if (!insideRoot(resolved)) return undefined; const info = await statOrUndefined(resolved); if (!info || (filesOnly && !info.isFile())) return undefined; + if (foldersOnly && !info.isDirectory()) return undefined; return { shown, resolved, info }; } @@ -981,9 +1065,12 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin async function walk(base, pattern, { filesOnly }) { const found = []; let bounded = false; + let foldersOnly = false; let candidates; if (pattern) { - candidates = await globWalk(base, compileGlob(pattern)); + const matcher = compileGlob(pattern); + foldersOnly = matcher.foldersOnly; + candidates = await globWalk(base, matcher); } else { candidates = (await readdir(base)).map((entry) => join(base, entry)); } @@ -992,13 +1079,26 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin bounded = true; break; } - const exposed = await exposedEntry(entry, filesOnly); // NOSONAR - sequential: the scan bound counts the entries found so far + const exposed = await exposedEntry(entry, { filesOnly, foldersOnly }); // NOSONAR - sequential: the scan bound counts the entries found so far if (exposed) found.push(exposed); } found.sort((a, b) => byCodeUnit(a.shown, b.shown)); return { found, bounded }; } + /** + * The workspace-relative path of the file a path runs through where a folder must be, or undefined + * when every folder above the path is one or is yet to be made. + */ + async function fileAbove(resolved) { + // from the path upward: the nearest entry that is there decides + for (let parent = dirname(resolved); insideRoot(parent); parent = dirname(parent)) { + const info = await statOrUndefined(parent); + if (info) return info.isDirectory() ? undefined : relative(root, parent).split(sep).join('/'); + } + return undefined; + } + async function read(_headers, body) { const args = argumentsOf(body, FILE_READ_ROW); const path = stringArg(args, 'path'); @@ -1058,6 +1158,10 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin if (mode === 'create' && info) { throw new AppException(409, `${relativePath} exists - mode overwrite replaces it, append extends it`); } + const above = await fileAbove(resolved); + if (above !== undefined) { + throw new AppException(400, `${above} is not a directory`); + } await mkdir(dirname(resolved), { recursive: true }); try { await writeFile(resolved, data, { flag: { create: 'wx', overwrite: 'w', append: 'a' }[mode] }); @@ -1296,12 +1400,13 @@ const DROP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'svg', 'na const DROP_ROLES = new Set(['navigation', 'banner', 'contentinfo']); const BLOCK_TAGS = new Set(['p', 'div', 'section', 'article', 'main', 'aside', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'tr', 'dl', 'dt', 'dd', 'figure', 'figcaption', 'form', 'fieldset', 'hr', 'address', 'details', 'summary']); -const HEADINGS = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; +// the two tables a name from a page is looked up in are maps: a name matches their own keys, never what an object inherits +const HEADINGS = new Map([['h1', 1], ['h2', 2], ['h3', 3], ['h4', 4], ['h5', 5], ['h6', 6]]); const VOID_TAGS = new Set(['br', 'hr', 'img', 'input', 'meta', 'link', 'area', 'base', 'col', 'embed', 'source', 'track', 'wbr', 'param']); // elements whose content is raw text until their closing tag const RAW_TEXT_TAGS = new Set(['script', 'style', 'textarea', 'title']); const SPACES = /[ \t\r\n\f\v]+/g; -const ENTITIES = { +const ENTITIES = new Map(Object.entries({ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', copy: '\u00a9', reg: '\u00ae', trade: '\u2122', mdash: '\u2014', ndash: '\u2013', hellip: '\u2026', laquo: '\u00ab', raquo: '\u00bb', lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d', bull: '\u2022', middot: '\u00b7', deg: '\u00b0', times: '\u00d7', euro: '\u20ac', @@ -1309,7 +1414,7 @@ const ENTITIES = { eacute: '\u00e9', egrave: '\u00e8', ecirc: '\u00ea', agrave: '\u00e0', aacute: '\u00e1', acirc: '\u00e2', auml: '\u00e4', ouml: '\u00f6', uuml: '\u00fc', oacute: '\u00f3', iacute: '\u00ed', uacute: '\u00fa', ccedil: '\u00e7', ntilde: '\u00f1', szlig: '\u00df', Eacute: '\u00c9', Auml: '\u00c4', Ouml: '\u00d6', Uuml: '\u00dc', larr: '\u2190', rarr: '\u2192' -}; +})); /** HTML character references decoded: the named ones a page commonly carries, and every numeric one. */ export function decodeEntities(text) { @@ -1323,7 +1428,7 @@ export function decodeEntities(text) { return whole; } } - return ENTITIES[body] ?? whole; + return ENTITIES.get(body) ?? whole; }); } @@ -1440,9 +1545,9 @@ class HtmlText { /** A heading, a list, a list item or preformatted text opens a block and sets its mark; true when the tag was one of them. */ startStructure(tag) { - if (tag in HEADINGS) { + if (HEADINGS.has(tag)) { this.openBlock(); - this.heading = HEADINGS[tag]; + this.heading = HEADINGS.get(tag); return true; } if (tag === 'ul' || tag === 'ol') { @@ -1503,7 +1608,7 @@ class HtmlText { this.inTitle = false; return; } - if (tag in HEADINGS) { + if (HEADINGS.has(tag)) { this.flush(); this.heading = undefined; return; @@ -1561,6 +1666,7 @@ class HtmlText { } } +// a reference joined to the address it was read at; one that cannot be read as an address stays as written function safeJoin(base, href) { try { return new URL(href, base).href; @@ -1709,25 +1815,36 @@ function hostRule(entry) { } } if (text.includes('/') || text.includes('?') || text.includes('@') || !text) { - throw new ToolsError(`${WEB_ALLOW}: ${entry} is not a host pattern (a host, a *.pattern, optionally with http:// or a :port)`); + throw notAHostPattern(entry); } const { host, port } = hostAndPort(entry, text); return { pattern: withoutTrailingDots(host.toLowerCase()), scheme, port }; } -// 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 +function notAHostPattern(entry) { + return new ToolsError(`${WEB_ALLOW}: ${entry} is not a host pattern (a host, a *.pattern, optionally with http:// or a :port)`); +} + +/** + * 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. + */ function hostAndPort(entry, text) { - let port; - let host = text; if (text.startsWith('[')) { const close = text.indexOf(']'); - host = text.slice(1, close < 0 ? undefined : close); - const rest = close < 0 ? '' : text.slice(close + 1); - if (rest.startsWith(':')) port = portOf(entry, rest.slice(1)); - } else if ((text.match(/:/g) ?? []).length === 1) { - [host, port] = [text.slice(0, text.indexOf(':')), portOf(entry, text.slice(text.indexOf(':') + 1))]; + if (close < 0) throw notAHostPattern(entry); + const inside = text.slice(1, close); + const rest = text.slice(close + 1); + if (isIP(inside)) { + if (rest && !rest.startsWith(':')) throw notAHostPattern(entry); + return { host: inside, port: rest ? portOf(entry, rest.slice(1)) : undefined }; + } + } + if ((text.match(/:/g) ?? []).length === 1) { + return { host: text.slice(0, text.indexOf(':')), port: portOf(entry, text.slice(text.indexOf(':') + 1)) }; } - return { host, port }; + return { host: text, port: undefined }; } function portOf(entry, text) { @@ -1747,60 +1864,73 @@ export function ruleText(rule) { return rule.scheme === 'http' || port ? `${rule.scheme}://${rule.pattern}${port}` : rule.pattern; } -/** fnmatch's `*`, `?` and `[seq]` over a host name, case-sensitively on the lower-cased host. */ +/** + * fnmatch's `*`, `?` and `[seq]` over a host name, case-sensitively on the lower-cased host - the grammar + * of one segment of a glob, read and matched by the same functions. + */ function hostMatches(host, pattern) { - const source = pattern.replace(/[.+^${}()|\\]/g, String.raw`\$&`).replaceAll('*', '.*').replaceAll('?', '.'); - return new RegExp(`^${source}$`).test(host); -} + return matchName(globSegment(pattern), host); +} + +// a row of the table below - a block and its kind, `public` for none - as the family the block belongs to, +// the block as the runtime's own subnet list, and the kind +function rangeOf([block, kind]) { + const [address, prefix] = block.split('/'); + const family = isIP(address); + const subnet = new BlockList(); + subnet.addSubnet(address, Number(prefix), `ipv${family}`); + return { family, subnet, kind: kind === 'public' ? undefined : kind }; +} + +// 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 Python twin carries +// the same text. +const 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 +`; +const ADDRESS_RANGES = ADDRESS_TABLE.split('\n').filter(Boolean).map((line) => rangeOf(line.split(/\s+/))); -/** Why an address is refused by default - loopback, private, link-local, multicast, reserved or unspecified - or undefined for a public address. */ +/** + * Why an address is refused by default - loopback, private, link-local, multicast, reserved or unspecified - or + * undefined 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. The runtime's own subnet list reads the address, in any spelling. + */ export function addressKind(address) { - let text = address.split('%', 1)[0].toLowerCase(); - if (isIP(text) === 6) { - const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(text); - if (mapped) text = mapped[1]; - } - if (isIP(text) === 4) return ipv4Kind(text); - if (isIP(text) === 6) return ipv6Kind(text); - return 'reserved'; -} - -// the same for an IPv4 address, by its first two numbers -function ipv4Kind(text) { - const [a, b] = text.split('.').map(Number); - if (a === 127) return 'loopback'; - if (a === 169 && b === 254) return 'link-local'; - if (a >= 224 && a <= 239) return 'multicast'; - if (a === 0) return 'unspecified'; - if (a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168)) return 'private'; - if (a === 100 && b >= 64 && b <= 127) return 'private'; - if (a >= 240) return 'reserved'; - return undefined; -} - -// the same for an IPv6 address, by its groups; an address that does not expand is reserved -function ipv6Kind(text) { - const groups = expandIpv6(text); - if (groups === undefined) return 'reserved'; - const first = groups[0]; - if (groups.every((g) => g === 0)) return 'unspecified'; - if (groups.slice(0, 7).every((g) => g === 0) && groups[7] === 1) return 'loopback'; - if ((first & 0xffc0) === 0xfe80) return 'link-local'; - if ((first & 0xff00) === 0xff00) return 'multicast'; - if ((first & 0xfe00) === 0xfc00) return 'private'; - if (first === 0x2001 && groups[1] === 0x0db8) return 'reserved'; - return undefined; -} - -function expandIpv6(text) { - const halves = text.split('::'); - if (halves.length > 2) return undefined; - const head = halves[0] ? halves[0].split(':') : []; - const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []; - const missing = 8 - head.length - tail.length; - if (missing < 0 || (halves.length === 1 && missing !== 0)) return undefined; - const groups = [...head, ...new Array(missing).fill('0'), ...tail].map((g) => Number.parseInt(g || '0', 16)); - return groups.some((g) => Number.isNaN(g)) ? undefined : groups; + const text = address.split('%', 1)[0]; + const family = isIP(text); + // a text that is no address is refused + if (!family) return 'reserved'; + return ADDRESS_RANGES.find((range) => range.family === family && range.subnet.check(text, `ipv${family}`))?.kind; } // the port a URL means when it names none @@ -2081,6 +2211,13 @@ function under(path, include) { return include.startsWith('/') ? path.startsWith(include) : path.includes(include); } +// the site a URL is on, as a crawl compares it: its scheme, its host as the URL names it and its port, the scheme's own when it names none +function siteOf(parsed) { + const scheme = parsed.protocol.replace(/:$/, '').toLowerCase(); + const port = parsed.port ? Number(parsed.port) : defaultPortOf(scheme); + return `${scheme}://${parsed.hostname.toLowerCase()}:${port}`; +} + /** The links of a page that a crawl goes on to: on its own site and inside its include, each once and without its fragment, one link deeper. */ function followLinks(links, depth, crawl) { for (const link of links) { @@ -2090,9 +2227,7 @@ function followLinks(links, depth, crawl) { } catch { continue; } - const scheme = candidate.protocol.replace(/:$/, '').toLowerCase(); - const port = candidate.port ? Number(candidate.port) : defaultPortOf(scheme); - if (`${scheme}://${candidate.hostname.toLowerCase()}:${port}` !== crawl.site) continue; + if (siteOf(candidate) !== crawl.site) continue; if (crawl.include && !under(candidate.pathname, crawl.include)) continue; candidate.hash = ''; const normalized = candidate.href; @@ -2125,7 +2260,7 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { } const location = response.headers.location; if (REDIRECT_STATUSES.includes(response.status) && location) { - current = new URL(location, target.url).href; + current = safeJoin(target.url, location); continue; } const [type, ...params] = String(response.headers['content-type'] ?? '').split(';'); @@ -2228,7 +2363,7 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { throw new AppException(400, 'include must be a string'); } const start = sandbox.checkUrl(url); - const site = `${start.scheme}://${start.host}:${start.port}`; + const site = siteOf(new URL(start.url)); const rules = await robots(start); const crawl = { host: start.host, site, include, maxDepth, queue: [[start.url, 0]], seen: new Set([start.url]), pages: [], diff --git a/test/agent-tools.test.mjs b/test/agent-tools.test.mjs index aab2f190..a8388838 100644 --- a/test/agent-tools.test.mjs +++ b/test/agent-tools.test.mjs @@ -14,9 +14,11 @@ */ import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'; +import fsPromises from 'node:fs/promises'; import http from 'node:http'; +import { syncBuiltinESMExports } from 'node:module'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join, relative } from 'node:path'; import { after, before, test } from 'node:test'; import { fileURLToPath } from 'node:url'; import neo4j from 'neo4j-driver'; @@ -75,6 +77,10 @@ function refusalSync(fn) { function includes(text, part) { assert.ok(text.includes(part), `expected ${JSON.stringify(text)} to include ${JSON.stringify(part)}`); } +/** The rows of a block of probes: the words of every line that is not a comment. */ +function probes(block) { + return block.split('\n').filter((line) => line && !line.startsWith('#')).map((line) => line.trim().split(/\s+/)); +} // --- the workspace ------------------------------------------------------------------------------- @@ -220,6 +226,26 @@ test('file.write respects the extension list and the size limit', async () => { includes(size.message, "over the workspace's limit of 1024"); }); +test('file.write refuses a path that runs through a file', async () => { + const root = workspace(); + const { files } = await fileTools(root); + for (const path of ['notes/plan.md/x.txt', 'notes/plan.md/deep/x.txt']) { + for (const mode of ['create', 'overwrite', 'append']) { + assert.deepEqual(await refusal(files.write({}, { path, content: 'a', mode })), { status: 400, message: 'notes/plan.md is not a directory' }); + } + } + assert.equal(readFileSync(join(root, 'notes', 'plan.md'), 'utf8'), '# Plan\n\nWrite the tools.\n'); +}); + +test('file.list skips a link whose target is gone', async () => { + const root = workspace(); + symlinkSync(join(root, 'nowhere'), join(root, 'notes', 'gone')); + const { files } = await fileTools(root); + assert.deepEqual((await files.list({}, { path: 'notes' })).entries.map((e) => e.path), ['notes/plan.md']); + assert.deepEqual((await files.list({}, { glob: 'notes/*' })).entries.map((e) => e.path), ['notes/plan.md']); + assert.equal((await files.search({}, { pattern: 'Plan', path: 'notes' })).files_searched, 1); +}); + test('file.list lists the root and a folder', async () => { const { files } = await fileTools(workspace()); const reply = await files.list({}, {}); @@ -246,6 +272,230 @@ test('file.list with a glob and a cap', async () => { assert.equal((await files.list({}, { max_entries: 5000 })).truncated, false, 'over the cap is capped, not refused'); }); +// The tree and the probes of the glob grammar. The Python 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. +const GLOB_TREE = String.raw` +# 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 +`; + +const GLOB_PROBES = String.raw` +# 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) +`; + +/** The file tools over the tree GLOB_TREE describes. */ +async function globFiles() { + const base = mkdtempSync(join(tmpdir(), 'agent-tools-glob-')); + const root = join(base, 'root'); + mkdirSync(join(base, 'outside')); + mkdirSync(root); + for (const [kind, name, target] of probes(GLOB_TREE)) { + const path = join(root, name); + mkdirSync(dirname(path), { recursive: true }); + if (kind === 'file') writeFileSync(path, `${name}\n`); + else if (kind === 'folder') mkdirSync(path); + else symlinkSync(join(root, target), path); + } + return (await fileTools(root)).files; +} + +/** + * 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. + */ +async function listed(files, path, glob) { + try { + const { entries } = await files.list({}, { path, glob, max_entries: 2000 }); + return entries.map((e) => e.path + (e.type === 'directory' ? '/' : '')).join(' '); + } catch (e) { + if (!(e instanceof AppException)) throw e; + return `${e.status} ${e.message}`; + } +} + +test('a glob returns the same entries in both packs', async () => { + const files = await globFiles(); + const wrong = []; + for (const line of GLOB_PROBES.split('\n')) { + if (!line || line.startsWith('#')) continue; + const [probe, expected] = line.split(' =>'); + const [path, glob] = probe.split(' '); + const got = await listed(files, path, glob); + if (got !== expected.trim()) wrong.push([probe, expected.trim(), got]); + } + assert.deepEqual(wrong, [], 'a pattern that ends in ** names everything beneath'); + assert.equal(await listed(files, '.', ' '), '400 glob is not a valid pattern (a pattern is relative to path)'); +}); + +test('a search walks the files its glob names', async () => { + const files = await globFiles(); + const everything = await files.search({}, { pattern: 'leaf', glob: '**' }); + assert.equal(everything.files_searched, 28, 'every file beneath, a link to a file among them'); + assert.deepEqual(everything.matches.map((m) => m.path), ['src/pkg/deep/leaf.py', 'src/pkg/deep/leaf.txt']); + assert.equal((await files.search({}, { pattern: 'leaf' })).files_searched, 28); + const beneath = await files.search({}, { pattern: 'leaf', glob: 'src/**' }); + assert.equal(beneath.files_searched, 6); + assert.equal(beneath.matches.length, 2); + assert.equal((await files.search({}, { pattern: 'leaf', glob: '*/' })).files_searched, 0, + 'a pattern that ends in a slash names folders, and a search reads files'); +}); + +/** The folders a call reads, relative to a root: the directory reader is wrapped for the time of the call. */ +async function foldersRead(root, call) { + const read = []; + const readdir = fsPromises.readdir; + fsPromises.readdir = (path, ...rest) => { + read.push(relative(root, String(path)) || '.'); + return readdir(path, ...rest); + }; + syncBuiltinESMExports(); + try { + await call(); + } finally { + fsPromises.readdir = readdir; + syncBuiltinESMExports(); + } + return read.sort(); +} + +test('the walk reads only the folders a pattern can reach', async () => { + const files = await globFiles(); + let read = await foldersRead(files.root, async () => assert.equal(await listed(files, '.', 'src/pkg/*.py'), 'src/pkg/mod.py')); + assert.deepEqual(read, ['.', 'src', 'src/pkg'], 'a folder is entered only when its name matches the segment at its level'); + read = await foldersRead(files.root, async () => assert.equal(await listed(files, '.', 'src/**/*.py'), + 'src/app.py src/pkg/deep/leaf.py src/pkg/mod.py src/util.py')); + assert.deepEqual(read, ['.', 'src', 'src/.cache', 'src/pkg', 'src/pkg/deep'], 'beneath the first ** every folder is entered'); +}); + test('file.search finds literals and regular expressions with context', async () => { const { files } = await fileTools(workspace()); const reply = await files.search({}, { pattern: 'todo' }); @@ -277,6 +527,17 @@ test('file.search caps and refusals', async () => { assert.equal((await refusal(files.search({}, { pattern: 'a', path: '../' }))).status, 400); }); +test('file.search counts lines by the line feed', async () => { + const root = workspace(); + const first = 'one\rtwo\x0bthree\x0cfour\x1cfive\x1dsix\x1eseven\x85eight\u2028nine\u2029ten'; + writeFileSync(join(root, 'lines.txt'), `${first}\r\neleven\nneedle\n`); + const { files } = await fileTools(root); + const found = async (pattern) => (await files.search({}, { pattern, glob: 'lines.txt' })).matches.map((m) => [m.line, m.text]); + assert.deepEqual(await found('needle'), [[3, 'needle']], 'a line ends at a line feed, and nowhere else'); + assert.deepEqual(await found('eleven'), [[2, 'eleven']]); + assert.deepEqual(await found('four'), [[1, first]], 'the carriage return before a line feed ends the line'); +}); + // --- HTML to text -------------------------------------------------------------------------------- const PAGE = ` Page Title @@ -330,6 +591,31 @@ test('html to text drops chrome marked by role or aria-hidden and survives broke assert.equal(tools.decodeEntities('a < b & © — &unknown;  x'), 'a < b & © — &unknown; \u00a0x'); }); +test("html names match the tables' own keys only", () => { + assert.equal(tools.decodeEntities('a &constructor; b &toString; c &valueOf; d &hasOwnProperty; e & f'), + 'a &constructor; b &toString; c &valueOf; d &hasOwnProperty; e & f'); + assert.equal(tools.htmlToText('

a &constructor; b &valueOf; c < d

').text, 'a &constructor; b &valueOf; c < d'); + const page = '

before

inside

after

'; + assert.equal(tools.htmlToText(page).text, 'before\n\ninside\n\nafter'); + assert.equal(tools.htmlToText(page, '', { markdown: true }).text, 'before\n\ninside\n\nafter', 'an element that is no heading is not read as one'); +}); + +test('a link scheme is read in any case', () => { + const page = '

one two ' + + 'three four

'; + const { text, links } = tools.htmlToText(page, 'https://h/', { markdown: true }); + assert.deepEqual(links, ['https://h/ok'], 'a script, a mail and a phone link are no links to follow'); + assert.equal(text, 'one two three [four](https://h/ok)'); +}); + +test('an address that cannot be read stays as written', () => { + const page = '

one two ' + + 'three four

'; + const { text, links } = tools.htmlToText(page, 'https://h/'); + assert.equal(text, 'one two three four'); + assert.deepEqual(links, ['http://[bad', '//[bad/x', 'http://h:port/x', 'https://h/ok']); +}); + // --- the web sandbox without a network ----------------------------------------------------------- test('host rules are parsed with scheme and port', () => { @@ -345,6 +631,51 @@ test('host rules are parsed with scheme and port', () => { } }); +test('an allowlist entry that starts with a class is a pattern', () => { + const rules = tools.parseHostRules(['[ab].example.com', '[ab].example.com:8443', 'http://[!ab].example.org', '[::1]:8080', '[127.0.0.1]', + 'x[y.example.net']); + assert.deepEqual(rules.map((r) => [r.pattern, r.scheme, r.port]), [ + ['[ab].example.com', 'https', undefined], ['[ab].example.com', 'https', 8443], ['[!ab].example.org', 'http', undefined], + ['::1', 'https', 8080], ['127.0.0.1', 'https', undefined], ['x[y.example.net', 'https', undefined] + ]); + for (const bad of ['[::1]x', '[::1', '[ab.example.com']) { + assert.throws(() => tools.parseHostRules([bad]), (e) => e instanceof tools.ToolsError && e.message.includes(`${bad} is not a host pattern`)); + } + const sandbox = new tools.WebSandbox({ rules }); + assert.equal(sandbox.checkUrl('https://a.example.com/').url, 'https://a.example.com/'); + assert.equal(sandbox.checkUrl('https://b.example.com:8443/').url, 'https://b.example.com:8443/'); + assert.equal(sandbox.checkUrl('http://c.example.org/x').url, 'http://c.example.org/x'); + for (const [url, host] of [['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.deepEqual(refusalSync(() => sandbox.checkUrl(url)), + { status: 400, message: `${host} is not one of the sites this agent may reach (${tools.WEB_ALLOW})` }); + } +}); + +test('an exclamation mark negates a class only when it is first', () => { + const glob = tools.compileGlob('[b-a!x]'); + assert.deepEqual(['x', '!', 'y'].map((name) => glob.test(name)), [true, true, false], + 'a range written backwards holds nothing, and the ! after it is a member'); + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules(['[b-a!x].example.com', '[!b-a!x].example.org']) }); + assert.deepEqual(sandbox.matches('x.example.com', 'https', 443), { listed: true, allowed: true }); + assert.deepEqual(sandbox.matches('y.example.com', 'https', 443), { listed: false, allowed: false }); + assert.deepEqual(sandbox.matches('y.example.org', 'https', 443), { listed: true, allowed: true }); + assert.deepEqual(sandbox.matches('x.example.org', 'https', 443), { listed: false, allowed: false }); +}); + +test('a pattern of many stars is matched in bounded time', () => { + const pattern = `${'*a'.repeat(11)}*b`; // twelve stars, a literal between each + const name = 'a'.repeat(5000); // every literal but the last is there + const began = performance.now(); + assert.equal(tools.compileGlob(pattern).test(name), false); + assert.equal(tools.compileGlob(pattern).test(`${name}b`), true); + const folders = Array.from('a'.repeat(400)).join('/'); // and the same one level up: twelve ** over 400 folders + assert.equal(tools.compileGlob(`${'**/a/'.repeat(12)}b`).test(folders), false); + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules([pattern]) }); + assert.deepEqual(sandbox.matches(name, 'https', 443), { listed: false, allowed: false }); + assert.ok(performance.now() - began < 2000, 'the time is bounded by the pattern times the name, however many stars'); +}); + const SANDBOX = new tools.WebSandbox({ rules: tools.parseHostRules(['docs.example.com', '*.example.org', 'http://127.0.0.1', 'host:8443']) }); test('checkUrl allows listed hosts and drops the fragment', () => { @@ -382,13 +713,316 @@ test('address kinds', () => { for (const [address, kind] of [ ['127.0.0.1', 'loopback'], ['10.0.0.1', 'private'], ['172.16.5.5', 'private'], ['192.168.1.1', 'private'], ['169.254.169.254', 'link-local'], ['224.0.0.1', 'multicast'], ['0.0.0.0', 'unspecified'], - ['::1', 'loopback'], ['::ffff:10.0.0.1', 'private'], ['fe80::1', 'link-local'], ['fc00::1', 'private'], + ['::1', 'loopback'], ['::ffff:10.0.0.1', 'reserved'], ['fe80::1', 'link-local'], ['fc00::1', 'private'], ['93.184.216.34', undefined], ['2606:2800:220:1:248:1893:25c8:1946', undefined] ]) { assert.equal(tools.addressKind(address), kind, address); } }); +// The probes of the address classification - an address and the kind its refusal names, `public` +// where it is not refused. The Python twin's test file carries the same text, line for line. +const 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. +const 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 +`; + +/** The kind the address check names for the host of a URL the allowlist lets through, `public` when the address is pinned. */ +async function hostKind(sandbox, url) { + try { + await sandbox.pin(sandbox.checkUrl(url).host); + } catch (e) { + if (!(e instanceof AppException)) throw e; + return / resolves to a (\S+) address, which is refused /.exec(e.message)?.[1] ?? e.message; + } + return 'public'; +} + +test('address kinds are one table in both packs', () => { + const wrong = []; + for (const [address, kind] of probes(ADDRESS_PROBES)) { + const got = tools.addressKind(address) ?? 'public'; + if (got !== kind) wrong.push([address, kind, got]); + } + assert.deepEqual(wrong, [], 'the first row of the table that holds an address decides its kind'); +}); + +test('a literal host is classified by the address it names', async () => { + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules(['http://*']) }); + const wrong = []; + for (const [url, kind] of probes(URL_PROBES)) { + const got = await hostKind(sandbox, url); + if (got !== kind) wrong.push([url, kind, got]); + } + assert.deepEqual(wrong, [], 'the spelling of a literal never changes the kind of its address'); +}); + test('pin refuses private addresses unless allowed', async () => { const lookup = async (host) => (host === 'no-such-host.invalid' ? Promise.reject(new Error('ENOTFOUND')) : [{ address: '127.0.0.1', family: 4 }]); const closed = new tools.WebSandbox({ rules: tools.parseHostRules(['http://127.0.0.1', 'http://169.254.169.254', 'localhost']), lookup }); @@ -429,7 +1063,10 @@ const SITE_PAGES = { '/docs/b': ['Section B', '

B

Text of B, back to A.

'], '/docs/c': ['Section C', '

C

Text of C.

'], '/other': ['Other', '

Outside the docs.

'], - '/private/secret': ['Secret', '

Robots keep out.

'] + '/private/secret': ['Secret', '

Robots keep out.

'], + '/detour': ['Detour', '

See the copy and C.

'], + '/tangle': ['Tangle', '

one, two, ' + + 'three, C.

'] }; const page = (title, body) => `${title}${body}`; @@ -453,6 +1090,8 @@ before(async () => { case '/redirect': return send(302, 'text/plain', '', { Location: '/docs/a' }); case '/redirect-private': return send(302, 'text/plain', '', { Location: 'http://10.0.0.1/' }); case '/redirect-other': return send(302, 'text/plain', '', { Location: 'https://not-allowed.example/' }); + case '/redirect-mapped': return send(302, 'text/plain', '', { Location: `http://[::ffff:127.0.0.1]:${server.address().port}/docs/a` }); + case '/redirect-unreadable': return send(302, 'text/plain', '', { Location: 'http://[bad/' }); case '/loop': return send(302, 'text/plain', '', { Location: '/loop' }); case '/latin1': return send(200, 'text/html; charset=iso-8859-1', Buffer.from(page('Caf\xe9', '

Caf\xe9

'), 'latin1')); case '/meta-charset': return send(200, 'text/html', Buffer.from('Caf\xe9

Caf\xe9

', 'latin1')); @@ -545,6 +1184,45 @@ test('the private-range gate closes the fixture without the flag, and http needs includes((await refusal(httpsOnly.webFetch({}, { url: `${site}/` }))).message, 'allowed over https only'); }); +/** + * 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. + */ +function siteTools(passes) { + let left = passes; + class SiteSandbox extends tools.WebSandbox { + async pin(host) { + if (host === '127.0.0.1' && left > 0) { + left -= 1; + return { address: host, family: 4 }; + } + return super.pin(host); + } + } + const sandbox = new SiteSandbox({ rules: tools.parseHostRules(['http://*']), timeoutMs: 500, crawlDelayMs: 0 }); + return tools.createWebTools(sandbox, { log: ledger() }); +} + +test('a mapped literal and a redirect to one are refused', async () => { + const mapped = `http://[::ffff:127.0.0.1]:${server.address().port}/`; + const direct = await refusal(siteTools(0).webFetch({}, { url: mapped })); + assert.equal(direct.status, 400); + includes(direct.message, 'resolves to a reserved address, which is refused'); + const hop = await refusal(siteTools(1).webFetch({}, { url: `${site}/redirect-mapped` })); + assert.equal(hop.status, 400, 'the start passes once; the address the redirect names is checked'); + includes(hop.message, 'resolves to a reserved address, which is refused'); +}); + +test('every page of a crawl goes through the address check', async () => { + const closed = await siteTools(2).webCrawl({}, { url: `${site}/` }); + assert.deepEqual(closed.pages.map((p) => p.url), [`${site}/`], 'robots.txt and the start pass; every link is checked again when it is fetched'); + assert.equal(closed.visited, 1); + const detour = await siteTools(9).webCrawl({}, { url: `${site}/detour` }); + assert.deepEqual(detour.pages.map((p) => p.url), [`${site}/detour`, `${site}/docs/c`], + 'a link that redirects to an IPv4-mapped literal of a loopback address is passed over'); + assert.equal(detour.visited, 2); +}); + test('logs carry the host and the size, never the URL', async () => { const { web, log } = webTools(); await web.webFetch({}, { url: `${site}/docs/a?token=do-not-log-me` }); @@ -592,6 +1270,31 @@ test('web.crawl honours robots.txt, the host and the caps', async () => { assert.equal(configured.truncated, true); }); +test('a crawl follows links on a site named by a literal or with a dot', async () => { + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules(['http://*']), allowPrivate: true, timeoutMs: 500, crawlDelayMs: 0, + lookup: async () => [{ address: '127.0.0.1', family: 4 }] }); + const web = tools.createWebTools(sandbox, { log: ledger() }); + const port = server.address().port; + for (const start of [`http://[::ffff:127.0.0.1]:${port}/`, `http://fixture.test.:${port}/`]) { + const reply = await web.webCrawl({}, { url: start, include: '/docs/' }); + assert.deepEqual(reply.pages.map((p) => new URL(p.url).pathname), ['/', '/docs/a', '/docs/b', '/docs/c'], start); + assert.equal(reply.visited, 4); + } +}); + +test('an address that cannot be read fails no fetch and no crawl', async () => { + const { web } = webTools(); + const unreadable = { status: 400, message: 'url must start with https:// (or http:// for a host listed with it)' }; + const page = await web.webFetch({}, { url: `${site}/tangle` }); + assert.deepEqual([page.status, page.text], [200, 'one, two, three, C.']); + assert.deepEqual(await refusal(web.webFetch({}, { url: 'http://[bad/' })), unreadable); + assert.deepEqual(await refusal(web.webFetch({}, { url: `${site}/redirect-unreadable` })), unreadable, 'a redirect is checked as the first address is'); + const reply = await web.webCrawl({}, { url: `${site}/tangle` }); + assert.deepEqual(reply.pages.map((p) => p.url), [`${site}/tangle`, `${site}/docs/c`], + 'a link that is no address is passed over, and so is a page that redirects to one'); + assert.equal(reply.visited, 2); +}); + // --- the clock ----------------------------------------------------------------------------------- test('time.now in UTC and in a zone', async () => { @@ -1056,6 +1759,16 @@ test('file.extract refuses by rule', async () => { assert.equal(tools.documentKind(readFileSync(fileURLToPath(new URL('./fixtures/policy.docx', import.meta.url))), '.docx'), 'docx'); }); +test('pages are numbers in the digits 0 to 9', () => { + for (const spec of ['+2', '1_0', '1 - 3', '1- 2', '\u0663', '\uff11', '\u00b2', '1--2', '2.0', '0x2']) { + assert.deepEqual(refusalSync(() => tools.pageRange(spec, 12)), { status: 400, message: 'pages must be page numbers and ranges such as 1-3,7' }, spec); + } + assert.deepEqual(tools.pageRange(' 2 ', 12), [2]); + assert.deepEqual(tools.pageRange('00002, 1-3', 12), [2, 1, 3]); + assert.deepEqual(tools.pageRange('9'.repeat(5000), 12), [], 'a page beyond the document selects nothing'); + assert.deepEqual(tools.pageRange(`2-${'9'.repeat(5000)}`, 3), [2, 3]); +}); + // --- the boot: what registers, the health route, describe --------------------------------------- function app(settings, options = {}) { From c8c5c806a91fcf0cd60f67a5fe2eb54796d668a5 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:57:32 -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 | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 181bd515..72498c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -310,6 +310,89 @@ only when it carries the label `_Ingested` and a key. A query that listed a node's labels now sees `_Ingested` among them. +3. **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 Python pack).** + - *Addresses.* The web tools' address check read an IPv4-mapped IPv6 address written in hex (`::ffff:7f00:1`) as + public, where the dotted spelling of the same address was loopback and the Python twin refused both; and its + list of blocks was shorter than the twin's. Both packs carry one table now, the same text. An IPv4 address is + refused inside the special-purpose blocks that are not globally reachable (the documentation, benchmarking + and protocol-assignment blocks are new here) and the shared address space. 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. The table is read by the + runtime's own subnet list (`net.BlockList`), so the module parses no address itself. + - *Globs.* A pattern that ends in `**` returned nothing from `file.list` and `file.search`, and the twin's + `Path.glob` read `**` differently from one Python version to the next. Both packs compile a glob by one + grammar: `**` 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 - as a regular expression, three stars against a name of 1,500 characters + did not finish in two minutes, with the event loop blocked - 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.* The HTML reader looks a name from a page up in its tables' own keys only + (`&constructor;` gave the text of a function, and a `` element was a heading); a crawl that + starts on an address literal, or on a host written with a dot at its end, follows its links; an allowlist + entry that starts with a class (`[ab].example.com`, which was read as the address `ab`) is a pattern, and one + with a bracket that never closes is the pattern it spells, where it was a 500 at the first request; + `file.write` under a file is 400 ` is not a directory`; a redirect to an address that cannot be read is + a 400. + + **Upgrade note:** the agent tools are in no release yet. For an application that runs them from `main`: an + IPv4-mapped address, the documentation and benchmarking blocks, and every IPv6 address outside the global unicast + block are refused unless `tools.web.allow.private=true` - on a network that reaches IPv4 sites through + `64:ff9b::/96`, that includes every such site. + +4. **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**, in lockstep with the Python + pack. A number in a request or a setting was read by each pack's own reader: the Python twin took digits of any + script and refused the JSON float `16000.0`, which this pack cannot tell from `16000` and accepted. 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 (the 24 + characters both runtimes' trim take, so U+FEFF is no longer one of them here), 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 number above 9007199254740991 is a 400. + +5. **ask-person and agent-question: one rule for a well-formed ticket, and one for a row id and a stream's + cursor**, in lockstep with the Python pack. The packs answered a mangled ticket differently: this one accepted a + stray character after a payload and answered 403 for a part that is too short, where the twin answered 400. 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 `Last-Event-ID` went through `Number()` (`1.0`, `1e3` and `0x10` 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; + above 2^53-1 the id is carried exactly, as a `BigInt`. The shared vectors are `ask-person-vectors.json` version 3 + (146 cases) and `agent-question-vectors.json` version 4 (111 cases), byte-identical with the Python pack. + **Upgrade note:** none for a ticket the pack issued or an id it returned. + +6. **REST automation and the host: an entry's flags as the Java engine reads them, the upload bound in bytes, a + limit on a request body, and the engines' error body where the host answered its own**, in lockstep with the + Python pack. + - 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`. `rest.yaml` is read + with the boolean words of the Python pack's reader and the engine's, so the single letters `y` and `n` are + text. + - The upload bound counted a text field by the length of its text; each field counts as the bytes of its part in + the body. A body past the bound is let go by unread, so the client takes the 413 instead of a broken + connection. + - `: ping` was written into the body of a stream that is not Server-Sent Events when the idle timer fired a + moment before the clock reached the deadline. A keep-alive is written only when a keep-alive interval has + passed. + - 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 host's catch-all 500 with + no record, and a stream was destroyed. + - A request body had no limit. The host reads at most 16 MiB into memory, as the Python pack does: a body over + it is 413 `Request body exceeds 16777216 bytes` in the engines' error body, and an envelope on + `POST /api/event` without REST automation. + - A part of an upload that is multipart itself is 400 + `Upload takes text fields and files, not a nested multipart part`; it was delivered as a text field, or as a + file of that type. An upload whose parts do not follow the boundary its content type declares is a 400. + + **Upgrade note:** an entry whose flag is written as anything but `true` or `false` stops the start - write `true` + or `false`. A request body over 16 MiB is refused; a file upload keeps its own bound, `rest.upload.max.bytes`. + ### Changed 1. **The agent-question app reads the question record and writes nothing: the backend of the React UI (RFC-0014