diff --git a/docs/dev/pointers.md b/docs/dev/pointers.md index 803f8d380..c9f016329 100644 --- a/docs/dev/pointers.md +++ b/docs/dev/pointers.md @@ -254,6 +254,9 @@ to re-run the step, and never degrades to the preview. `onEvict` is where the ca - **Budget.** `valueStoreBudgetMB` (DevTools Settings → Output pointers, default 1024), capped at half of `navigator.storage.estimate().quota`. Each eviction is `{ subsystem: "value-store", kind: "evict", reason, key, bytes, detail.source }`; a body the whole budget cannot hold is `kind: "refuse"`, and the fetch still answers with its preview. +- **Code reads a pointer's value faked** (ruling 133; docs/spec/SECRET_HANDLES.md, "What the worker serves to code is + faked"): `derefWhole` fakes every read before any pipe runs, so a `dereference` or a pipe from code runs over the + session's fakes. The model's own dereference tool passes no mask and reads as before. Nothing READS a stored value yet: `python_exec` opening one is slice 5. Until then the one reader is the worker's TEST-ONLY `globalThis.__mlValues` (`rows()`, `read(key)`, reachable only through `serviceWorker.evaluate`), which diff --git a/docs/dev/python-sandbox.md b/docs/dev/python-sandbox.md index ef6973c49..a58acbf08 100644 --- a/docs/dev/python-sandbox.md +++ b/docs/dev/python-sandbox.md @@ -54,6 +54,9 @@ charge) are [`docs/spec/ML_TABLE.md`](../spec/ML_TABLE.md); this is where they l `pd.read_csv` with the decided `sep`, header and names. It then pops the buffer, and the worker deletes any name left in `finally`. The background still refuses a stored key unless the sender is entitled to it: a run active on its tab holds it, or the worker disclosed it to that tab (`page:`). +- **A cell reads registered values as fakes** (ruling 133; docs/spec/SECRET_HANDLES.md, "What the worker serves to code + is faked"): `ml.table` and every wire answer are faked, and a stored table's carrier may be Arrow where the store + holds Parquet (`table-fake.ts` rebuilds one that holds a value). **A returned DataFrame larger than its 200-row preview becomes a stored table** (slice 6): diff --git a/docs/spec/ML_TABLE.md b/docs/spec/ML_TABLE.md index 5800edb56..4bc0e71a4 100644 --- a/docs/spec/ML_TABLE.md +++ b/docs/spec/ML_TABLE.md @@ -233,6 +233,10 @@ wait for the kept-bytes store (§10, step 3), and ask until then. As built: delimiter. A reader errno (`EACCES`, `EFBIG`, `ENOENT`) is the call's error code. The worker binds the bytes once as a bytearray (`bindTableBytes`, under `_ml_wbuf_`), the frame builder takes them, and they are dropped after the cell if it never did. +- **Faked** (ruling 133, SECRET_HANDLES.md, "What the worker serves to code is faked"). Every answer's strings, and a + stored table's bytes, reach the cell with each registered value replaced by the session's fake: delimited text and + Arrow in place, a Parquet table that holds a value as an Arrow IPC stream (`table-fake.ts`), or refused naming a + column that cannot carry a fake. - **The frame** is built in the cell by `_ml_table_frame` (`python-runtime.ts`): Arrow and Parquet through pyarrow, a delimited body re-read by `pd.read_csv` with the delimiter and header already decided (so pandas cannot disagree with the JS reader), rows and HTML as the old loader built them. The source facts go on `df.attrs`. diff --git a/docs/spec/SECRET_HANDLES.md b/docs/spec/SECRET_HANDLES.md index d344b7e85..a38e733a5 100644 --- a/docs/spec/SECRET_HANDLES.md +++ b/docs/spec/SECRET_HANDLES.md @@ -317,7 +317,8 @@ on real captured output in its PR. which one; a registered value at rest in the value store behind a pointer (a `fetch_url` page's whole text, a stored table) until PR 2 scrubs it where it is written: every model-bound read of it (a `@tool:` read, a pipe's head, range or grep, the output of a script that called `ml.dereference`) crosses the scrub, so what remains is the value at rest - and an approved script that reads it and transforms it before printing; a registered value inside an answer's `data` + (code reads it faked since ruling 133, so what a script transforms before printing is the fake: "What the worker + serves to code is faked (ruling 133)" below); a registered value inside an answer's `data` to a page (anything not under an error key) is not scrubbed, since the data is the handler's answer and only the error text is the worker's own; `GET_CONFIG`'s answer to a page is not run through the registry, by design, since what keeps a secret out of it is `publicConfig`'s fixed key list (`redteam-lifetimes-config.test.mjs`, @@ -1682,3 +1683,301 @@ the pin. None is scheduled; the red team gets this section as its target before The red team's properties are rows 5 and 8, that a page-started caller reaches none of it, and that no reader of a masked file exists outside the list in row 2. + +### What the worker serves to code is faked (ruling 133) + +**The ruling** (Shane, 2026-11-29, in the coordinator's session). What the worker serves to code reaches it with each +registered value replaced by its same-length fake (ruling 101's `RDCT…`, per name), before code sees it. Code is every +script the worker answers: a Python cell, an approved `exec` in an isolated world or the page's main world, and a +survey. The scrub matches a value, not a value changed: a cell that printed a value reversed, split or encoded put it in +the model's tool result unmarked (redteam-e4's probe table, every row). Now code never holds the value, so anything it +transforms is the fake. BUILT. + +**A read of the live page stays raw.** Model-written `exec` reading the page sees the page's own text, unfaked, and a +page-built run's page still holds the real rows it hoisted. The worker serves neither, so neither is covered. + +**A page-hosted run's pointers are not faked** (ruled (b), coordinator, 2026-12-01). A run whose loop lives in the page +(`window.ml.agent`, `ml-agent-run.ts`) keeps its pointers in the page, holding what the page was answered: a `fetch_url` +answer's `data` to a page is not scrubbed (the scrub's known limits above). So code that run executes in the page's main +world reads them unfaked. The same read in a run the worker hosts is faked ("Where the mask sits", 4). e4's row 1h pins +both. + +**The inputs.** All of these are faked: +- `ml.table` of a page table, of a URL in the run's fetch cache, of a stored whole (`@tool:` past the preview), or of a + Google Sheet. +- `ml.dereference` of any pointer, a stored whole text included. +- A stored table's columns, and a page's hoisted tables. +- Every string a read-only member answers (`ml.ps`, `ml.info`, `ml.models`, `ml.config`, `ml.settings`, + `ml.capabilities`, `ml.serverTools`, `ml.getModel`, a cached `ml.fetch`). Here the configured server URL counts as a + form of the config field `window-ml-server`. + +Files under `/files`, `@file:` and `ml.fs` were already faked by rulings 101 and 132, with the same fake. + +**The fake.** `sessionFakeForms(key)` (`sw-fake-key.ts`) gives the forms with their fakes, and `secret-fake.ts` applies +them. An occurrence becomes its form's fake, and any other match becomes `*`. Byte length and valid UTF-8 are kept. One +value gives one fake throughout a session. + +The key is the run's session. A wire client with no run (a cell a page started) uses `page:` +(`fakeKeyOf`, `ml-wire-serve.ts`), and a page-hosted run's column read uses `page:`. No session key can equal +either, so their fakes are their own. + +The value store keeps the real bytes. The fake is made where a value is served, so a read past the preview (row 250,000 +of 300,000) is faked like the preview. + +Three helpers apply it. `fakeStrings` fakes many strings in one call. `fakeValue` fakes a value's strings, an object's +keys included, and its bytes value by value; with `wire`, it reads ML_WIRE form (`{ $bytes }`, the `{ "$": … }` wrap). +`fakeToken` fakes a pointer's value (`worker-readonly-ml.ts`), all but its image, which is pixels. + +**Who is served, and through what.** + +| Code | Reaches values through | +| --- | --- | +| a Python cell: a worker-built run's `python_exec`, a page's `ml.pythonExec` (a page script, or a page-built run's tool), the Python bench | the wire (`onMlCall` → `serveWireCall` → `answerOf`), and the offscreen document's read of a stored table | +| a survey (the read-only dialect in the worker) | `workerReadonlyMl`: its members, `dereference` through `derefWhole`, a stored table's columns through `columnsFor` | +| an approved `exec` in an isolated world | `iso-channel.ts`: `deref` (`wholeDerefFor`, `derefWhole`), `columns` (`readStoredColumns`), `settings`, `sh`, `fs` | +| an approved `exec` in the page's main world | its pre-reads (`preReadsFor` with `whole` false: the resolver's preview) and `VALUE_COLUMNS` (`readStoredColumns`) | + +**Where the mask sits.** Each value is faked where it leaves the worker's hands, and the wire's answer is a catch-all +behind those places. + +1. *`workerReadonlyMl`'s members* (`fakedMember`). Each answer is faked synchronously for a member that answers + synchronously (`_fetchCached`): `getModel`, `config`, `models`, `capabilities`, `serverTools`, `ps`, `info`, + `_fetchCached`, `settings`. The forms are read once before the members are built. A survey and the wire share this + host, and an isolated exec's `settings` is faked the same way. The pure members (`pipe`, `jsonPath`, `schema`, + `range`) answer only from the code's own arguments. +2. *`derefWhole`*. It fakes every read before any pipe runs: a stored whole text, an in-memory pointer, a table's + preview and meta, an attached file. The run's resolver takes a `mask` (`tokenSink`'s fourth argument), which it + applies to the pointer's value before `derefPipe` reads it. So a `grep` for the value finds no line, a pipe cannot be + used to test the value one character at a time, and `lines a-b` counts over the text code reads. The model's + dereference tool passes no mask, and its read is unchanged. A survey, the wire and an isolated exec read through + `derefWhole`. +3. *`readStoredColumns`* (`sw-values.ts`). It takes the forms as a required argument, and each of its three callers + passes its run's: a survey's `columnsFor`, an isolated exec's `columns`, and `VALUE_COLUMNS`. The decode stays cached + as stored, and the cells are faked on each read. The column names are the caller's own, so they are not faked. +4. *`preReadsFor`'s main-world branch* (`sw-run-host.ts`). The resolver's preview is faked as `derefWhole`'s read is. +5. *The wire's answer* (`ml-wire-serve.ts` `answerOf`, through `ctx.fake`, `sw-ml-wire.ts` `wireFake`). This covers the + first answer and the one after an `ask`: every string in the value in wire form, values and object keys alike, and a + pointer answer's label. + - This is what fakes the `table` member's rows and HTML: a page table, the fetch cache, a Sheet, a pointer's rows, a + page's hoisted rows. It also fakes any member added later without being listed. + - A value that 1 or 2 already faked passes unchanged. A fake can match a form only if the person registered the fake + itself, and it is then faked again, which reveals nothing. + - A stored table's key crosses as it is and is read in 6. +6. *The offscreen document's table read* (`table-answer.ts`, `tableAnswerBytes`, the `value` branch, through + `table-fake.ts` `fakeStoredTable`). The forms come from `FILES_SECRET_FORMS` under the client's key. The store keeps + what the server sent: delimited text, Arrow (file or stream) or Parquet. + - *Delimited text* is faked in place with `fakeSecretBytes`. + - *Arrow* is faked in place. apache-arrow's IPC reader hands out views onto the bytes it was given, and every fake + has its value's byte length (a fake is drawn at the form's UTF-8 length, and a match that is not an occurrence + becomes as many `*` bytes), so each value is overwritten where it lies and no offset moves. A match never spans two + cells: text values are joined by NUL with no form holding NUL, and bytes are faked value by value, so a value split + across two adjacent cells is not faked in either, which is the stated limit below, and no cell is changed by a + match in its neighbour. Every column is decided by its Arrow TYPE (`table-fake.ts` `ARROW`), each type in exactly + one list: + - searched as text, joined, in place: Utf8, LargeUtf8; + - searched as bytes, value by value, in place: Binary, LargeBinary, FixedSizeBinary; + - searched, and a value in one refuses the read: Utf8View, BinaryView (their short values sit inside the views); + - visited through their children, so each of the types above nested under them is handled as it is at the top: + List, LargeList, FixedSizeList, Struct, Map, Union, and a Dictionary through its dictionary; + - not searched: Null, Int, Float, Bool, Decimal, Date, Time, Timestamp, Interval, Duration (a stated limit, below); + - any other type (run-end-encoded, a type added later) refuses the read. + Nothing is decoded into rows or encoded again. + - *Parquet* is handed over as it is when no string or binary cell holds a registered value: its string and binary + columns are decoded with `hyparquet` and checked. When a cell does hold one, the whole table is decoded, faked, and + handed to the cell as an Arrow IPC stream built from the decoded columns. The cell gets a table either way, never + the file, so the change of carrier is not seen. The stream is built from typed arrays (`makeData`), because + apache-arrow's builders compile code with `new Function`, which the extension's CSP forbids. + - Faking inside the cell's interpreter is not an option: an approved cell runs any Python and could replace the + masker first. +7. *A page-started cell's tables* (`sw-python.ts` `hoistedAsRead`). The worker hands back each hoisted table's data + faked with the cell's fakes (`tablesRead`), and the page shows those in `inputTables` (`ml-python.ts`), not its own + read. A stored table's preview, which the page held and the cell never read, is not shown. + +*Joining.* `fakeStrings` and the Arrow values are faked in one call over their text joined by U+0000, then split. A +registered value may contain U+0000 (the registry refuses no character), so the join is made only when no form contains +U+0000, and the split's count is checked. If either check fails, each string is faked alone. Arrow values are copied +back by their offsets, not by a split, so a value holding a NUL byte keeps its place. + +*Binary cells.* An Arrow Binary column, and a Parquet `BYTE_ARRAY` column with no string annotation (read as bytes, +`utf8: false`), are faked value by value with `fakeSecretBytes`. Bytes cannot be joined, since any byte may occur. + +*Where a fake cannot be put.* The read is refused, and nothing is served unfaked, in these cases: +- A Parquet table holds a value and has a column with no lossless Arrow form here: a decimal, a date or time, an INT96, + a fixed-length array, an integer of another width, or a nested or repeated column. +- An Arrow column's values were not read where they lie (a compressed body), a view type holds a value, or a column is + of a type in none of the lists above. +- Either format has a column name, nested ones included, that holds a value. +- Metadata holds a value: an Arrow schema's or a field's metadata (key or value), or a Parquet file's key-value metadata + (pandas' own among it). They reach the cell in the schema, where a fake cannot be put without rewriting it, so they + are searched and refuse rather than being faked. + +The refusal reads "ml.table(): column is , which cannot be served with registered values replaced, +so this table is not read." + +The same table holding no value reads as it is. The configured server URL is a form in every configured session, so "a +session with no forms" is not the condition: a cell that holds a value is. + +*Object keys.* Two keys of one object can fake to the same text: two distinct values under 8 bytes, of one length, both +read as the same `*` run. They are not merged, and neither is dropped. The answer fails with "the answer has two keys at + that read the same once registered values are replaced, so it is not read" (`FakedKeysClash`). A table's column +names are a list, so two such names are both kept, as written. + +*Unreadable forms.* Every read in the list above fails with "the registered secrets could not be read, so this read is +withheld.", and no value crosses, as for an attached file. + +**Dependencies.** None new: `hyparquet` and `apache-arrow` are already dependencies. Each is imported where a table is +read, but esbuild without code splitting puts both into `dist/offscreen.js`, as it does into `background.js`. That +bundle is 997 KB at this branch, against 270 KB on main at f750ae30 (measured 2026-11-30). The code is evaluated only +when a stored table is read, but the bytes are part of the offscreen document's load: it starts about 20 to 30 ms +later, read from the medians of six alternating runs on a shared machine (the PR's body has the figures). + +**The cost** (measured 2026-11-30, Node on this laptop; 300,000 rows × 3 string columns and 1 integer column; F, the +session's form count, is 2): + +| Source | What is done | Total | +| --- | --- | --- | +| delimited text | one `fakeSecretBytes` over the bytes | linear in size, one search | +| Arrow file or stream | the string values faked in place | about 0.07 s | +| Parquet, no cell holding a value | the string columns decoded and checked; the file handed over | the decode | +| Parquet, a cell holding a value | decode, fake, an Arrow IPC stream | about 0.32 s | + +Joined faking costs about 0.3 µs a cell and is nearly flat in F (the 2026-11-29 measurement, `fakeSecretText` over +300,000 joined cells: 91 ms at F = 1, 117 ms at F = 200). The Arrow handed over in place of a Parquet file is +uncompressed and transferred to the Python worker, not copied. + +A binary column in a cell (measured 2026-12-01, the built extension in Chromium on this laptop, three runs each; 300,000 +rows, a binary column holding the value in one row and a string column, F = 2): + +| `ml.table` of it, in the cell | With the value registered | With nothing registered | Faking a row | +| --- | --- | --- | --- | +| Parquet, a BYTE_ARRAY column | 4.2 s | 1.7 s | about 8.5 µs | +| Arrow, a Binary column | 2.3 s | 1.6 s | about 2.3 µs | + +The whole `python_exec` step on the Parquet table, measured from the run (two runs each), takes 8.6 s with the value +registered and 6.1 s without; a cell that prints one line takes 4.3 s, with or without pandas imported. So faking is +about a third of that step, not most of it. On a runner about 1.75 times slower, such a cell crosses `python_exec`'s +15 s default and detaches, and the tool's answer is then the detach notice, not the cell's output. No runner's speed was +measured against this one, so whether CI's does is not known; the rows on these tables pass `expect_ms` so that it +does not decide them. + +A text read whole (a `dereference` with no pipe, a stored text) is faked twice, once by `derefWhole`'s mask and once by +the wire's answer. Measured 2026-12-01, Node on this laptop, F = 2, median of five runs of 20: + +| One faked megabyte | Per fake | +| --- | --- | +| ASCII, no match | 0.8 ms | +| one non-ASCII character, no match | 1.8 ms | +| mixed text with 100 matches | 2.6 ms | + +A whole dereference of a stored megabyte through the wire, including the read and the copy, costs about 8 to 10 ms a +call (191 calls in a cell, ASCII and one non-ASCII character). Most of a fake is `byteString`, the bytes as one +character per byte for the native search. It first built that string from character codes, at about 12 ms a megabyte +and so 24 ms a call, and `tests/ml-wire.test.mjs`'s loop of unpiped dereferences ran past its 30 s cap on CI. It now +decodes natively: all-ASCII bytes as they are, any other bytes widened to UTF-16 code units 0 to 255. + +**A cell a page started** (`ml.pythonExec` from a page script). The page supplied its hoisted rows, and it gets back the +cell's `stdout`, `value` and `inputTables` as the cell saw them: the fakes. Nothing is restored on the way back, for two +reasons: +- The worker cannot tell a page's own `pythonExec` from a page-built agent run's python tool. Both are `PYTHON_EXEC` + from the page, and the run's loop, with its model, lives in the page (e4's rows 5 and 6). Exempting rows the page sent + would leave row 5's escape open. +- Restoring would mean replacing each fake in page-bound output with its value. A page that shows the cell a fake it got + elsewhere (a masked `/files` read printed back, a fake from an earlier answer) would then get the value back: a + decoder for every fake. + +**The cost (stated).** +- A page's own data that equals a registered value is computed on the fake. A page that needs its own rows exactly reads + them itself, since it has them. +- A value under 8 bytes, and any match that is not an occurrence, reads as `*` at its length. So two distinct short + values of one length compare equal in code, and a join, a group or a `set` on them merges them. +- A fake in code's output draws no pill and has no count line. Ruling 101 gives a fake no marker, so the person sees + `RDCT…` in a result with nothing marking it. Marking it for the person is an open design, owner to be assigned by the + coordinator. Finding a fake by matching text would break the pill's rule (a pill only at a recorded cut), since code + that learned a session's fake can print it and forge a pill. +- A Parquet or Arrow table that holds a value and has a column of a type listed above, or a column name that holds a + value, cannot be read by code at all. +- A page with an approved origin can test a list of strings against the registered values in one call. Its own + `ml.pythonExec` hoists a table of candidates and prints it; each candidate that equals a registered form comes back + as a fake, and one under 8 bytes as `*` at its length. The page learns that the candidate is registered, never under + which name: a fake is `RDCT` and characters drawn from an HMAC, with nothing of the name in it. Two candidates that + are different forms of one value get different fakes, so the page does not learn that they belong together. Each + call's fakes are its own (`page:`, a new handle per cell), so a fake is not compared across calls. Attempts + are not bounded. The scrub's known limits state the one-guess form (a page's own text quoted back in an error); this + form tests a whole list per call, with no model in the loop. It stays a stated limit (Shane, 2026-12-01), and e4's + oracle row pins it. A registry value is at least 8 characters (`REGISTRY_MIN_VALUE`), so a candidate equal to one + always comes back as a fake; a `*` comes back only for a config field's shorter form (the server's host name, from 4 + characters, or the model filter's) or a GitHub token. + +**Known limits.** This replaces, for code, "an approved script that reads it and transforms it before printing" (the +scrub's known limits above). Code reads every worker-served input faked, so a value it transforms is the fake. What +reaches code unfaked: +- A value no form matches: a value split across two cells or two answers, or a spelling not among its forms. +- A value held as a number, a decimal, a date or a boolean (an all-digit registered value in a number column, say): + these columns are not searched, since the scrub matches text and such a cell is not text. A cell that prints one still + crosses the output scrub, which matches its printed text. +- An error's text. It crosses through `forPage`, not through the fake, and holds only what the worker or the code wrote. +- The live page, as stated above. + +A value under 8 bytes reads as `*`. + +**`ml.sh`.** Unchanged. `ml.sh.run`'s head and `ml.sh.read`'s range are already scrubbed to `[REDACTED:]` markers +as they cross into the script (`sw-shell-call.ts` `scrubbedHead`, `forModel`; `shRead`, `scrubRange` then `forModel`, +and a binary range's bytes by `bytewise` substitution). They are counted in the answer's `scrubbed`. Their answers pass +the wire's mask, but a marker is not a form, so the mask finds nothing there and the markers stay. + +**Upgrade.** Nothing stored changes. A value stored before this is read faked, and a pointer minted before this still +resolves: the resolver's mask is an optional fourth argument. + +**Rows.** +- e4's red-team rows, written failing first, in `tests/e2e/redteam-code-reads-fakes.spec.mjs`. Every cell that reads + the 300,000-row table passes `expect_ms` and fails on a detached answer, with the answer in the message. + - 1a a page's own table reaches a worker cell as the fake; + - 1b a URL in the run's fetch cache reaches a worker cell as the fake; + - 1c a stored whole past the preview reaches a worker cell as the fake (row 250,000 of 300,000); + - 1d a stored whole text through an awaited `ml.dereference` reaches a worker cell as the fake; + - 1e the read-only members' strings reach a worker cell as the fake; + - 1f a page-built run's python tool reads hoisted rows as the fake; + - 1g an approved exec in an isolated world reads a pointer's value and columns as the fake; + - 1h (stated limit) a page-hosted run's pointers are not faked: its main world reads the raw value, and the same read + in a worker-hosted run is the fake; + - 2 a stored table as delimited text, an Arrow file, an Arrow stream and Parquet is faked past the preview, and its + other columns are untouched; + - 3 a typed Parquet (a Decimal past float64's precision) is served exactly or refused naming the column and type; + - 3b the same Parquet in a session with no forms reads as it is, every column exact; + - 4 a Parquet BYTE_ARRAY column and an Arrow Binary column are faked value by value, other rows untouched (the cell's + output is attached to the result); + - 4b a registered value holding U+0000: every string is still faked, and the cell count is unchanged; + - 5 a stored text read whole greps empty for the value, and its lines agree with the unfaked text; + - 7 unreadable forms: every input fails, and no text of the value crosses; + - 8 a page-started cell's stdout, value and `inputTables` carry the fake, and a fake the page sends back is not + restored; + - 9 (guard) a cell cannot climb into the worker's JavaScript, so the mask is the only path to the value; + - 10 the spec states the live-page limit, and a page's own exec still reads the live DOM unmasked; + - 11 (stated limit) a page's own `ml.pythonExec` hoists a candidate list and learns which candidates are registered. +- e4's per-type rows in `tests/redteam-arrow-types.test.mjs`, one per Arrow type id, enumerated from the library: + - every concrete class reports one of the base ids this table decides, and the ids this library can write are exactly + the decided ones (no type 22 exists here, and a Union cannot enter a schema, so no cell can receive one); + - text types (Utf8, LargeUtf8): the cell is the fake, its neighbours and the buffer's length untouched, the value's + bytes gone; + - bytes types (Binary, LargeBinary, FixedSizeBinary): each value faked at its own length; + - view types (Utf8View, BinaryView): a value in one refuses the read, naming the column and the type, never the value, + and a clean one is served as it is; + - containers (List, LargeList, FixedSizeList, Struct, Map): a value nested in one is faked, at any depth; + - a Dictionary is faked through its dictionary: every entry, and the rows that use them; + - unsearched types (Null, ints, floats, Bool, Decimal, dates, times, timestamps, durations, intervals) are + byte-identical. +- The builder's rows are in `tests/code-reads-fakes.test.mjs`: + - joining with and without U+0000 in a form; + - the wire form; + - two object keys that fake to the same text refused with the path, and two such column names kept; + - an answer with nothing registered in it byte-identical to today's; + - every `readStoredColumns` caller passes forms, every wire answer passes the mask, and each of `workerReadonlyMl`'s + members is wrapped; + - `ml.sh` markers unchanged; + - a pipe on a pointer runs over the fake; + - Arrow faked in place in each carrier, a dictionary's values, a Binary column, and a column named with a value + refused (a compressed body is not tested: no codec is registered here to write one); + - Parquet handed over as it is when clean, as Arrow when not, and refused naming a Decimal column; + - the upgrade. +- `byteString` (`tests/secret-mask.test.mjs`): one character per byte on both paths, 0x80 to 0x9f, a leading 0xfe 0xff, + and a megabyte each of ASCII, ASCII with one high byte, and mixed text. diff --git a/scripts/test.mjs b/scripts/test.mjs index c2739fd19..92d43b9fc 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -77,7 +77,7 @@ const GENRES = { // of what a page or the model reads, as each crossing applies it and over a ranged read, and the input that takes one. secrets: { about: "secrets: the registry, the scrub at each crossing and over a ranged read, and the secret input", - files: ["secret-registry.test.mjs", "secret-scrub-crossings.test.mjs", "secret-scrub-range.test.mjs", "secret-input.test.mjs", "secret-mask.test.mjs"], + files: ["secret-registry.test.mjs", "secret-scrub-crossings.test.mjs", "secret-scrub-range.test.mjs", "secret-input.test.mjs", "secret-mask.test.mjs", "code-reads-fakes.test.mjs"], }, // `/files` (FILE_ATTACHMENTS.md, "`/files/` read by range, and `ml.fs`"): the ranged reader over the shelf, the // offscreen document's source for it, the synchronous channel Python's mount is served over, and the mount itself. diff --git a/src/agent/agent-host.ts b/src/agent/agent-host.ts index 02386f342..e6346e933 100644 --- a/src/agent/agent-host.ts +++ b/src/agent/agent-host.ts @@ -81,7 +81,7 @@ export interface RunAgentHostDeps { tryReadonly?(name: string, args: Record, live?: LiveOutput, call?: { seq: number; step: number }): Promise; /** Receives this run's pointer resolver at start, so the host can answer a page-side `ml.dereference` * (the loop, and the store, live here; the tool runs in the page). See background's derefByRun. */ - tokenSink?(resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits) => DerefRead): void; + tokenSink?(resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: import("../pointers/token-pipe").TokenValue) => import("../pointers/token-pipe").TokenValue) => DerefRead): void; /** Receives the run's context snapshot function (agent-loop.ts `contextSink`), for `ml.current` in a read-only * survey evaluated in the worker (sw-readonly.ts). */ contextSink?(snapshot: (extra?: { model?: string | null; log?: readonly import("../log/run-log").RunLogEvent[] }) => import("./current-context").CurrentSnapshot): void; diff --git a/src/agent/agent-loop.ts b/src/agent/agent-loop.ts index 0bfd85840..feec6ecad 100644 --- a/src/agent/agent-loop.ts +++ b/src/agent/agent-loop.ts @@ -339,7 +339,7 @@ export interface AgentLoopOptions { tools: ToolMeta[]; maxSteps?: number | (() = /** Called once at run start with a resolver for this run's `@tool:` pointers. The host binds it into the * ToolContext so `ml.dereference` inside an approved exec reads THIS run's outputs — and only while a * tool of this run is executing. The loop owns the store, so it is the only place that can hand this out. */ - tokenSink?: (resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits) => DerefRead) => void; + tokenSink?: (resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: TokenValue) => TokenValue) => DerefRead) => void; /** Called once at run start with a way to SNAPSHOT this run's context, for `ml.current` in a read-only `exec` * (docs/spec/CURRENT_CONTEXT.md). The same arrangement as `tokenSink`, for the same reason: the loop is the only * thing holding the messages and what it recorded about each, so it hands out the reader. The host adds what @@ -787,7 +787,9 @@ export async function runAgentLoop(task: string, opts: AgentLoopOptions, deps: A }; // Hand the resolver to the host (see tokenSink). Throws exactly what the tool would return, so a failed // read inside exec surfaces the same MemoryFault / pipe error the model sees from the tool itself. - opts.tokenSink?.((ref: string, pipe?: string | string[], limits?: PipeLimits): DerefRead => { + // `mask` is code's (worker-readonly-ml.ts `derefWhole`, ruling 133): the value faked before any pipe reads it, so + // the pipe, the meta and the answer all read the fake. + opts.tokenSink?.((ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: TokenValue) => TokenValue): DerefRead => { // An attached file: what it is, and the key of what code reads, never the text: a text file's bytes as // attached (`data`, which derefWhole masks), a PDF's read document. The read is the worker's (derefWhole), // which can wait on the store; a caller that cannot is refused there (preReadsFor). @@ -798,8 +800,9 @@ export async function runAgentLoop(task: string, opts: AgentLoopOptions, deps: A const file = { name: f.name, type: f.type, bytes: f.bytes, turn: f.turn, ...(isTextFile(f) ? { lines: f.lines } : { pages: f.pages }) }; return { value: `${fileRef(f)} ${quoteName(f.name)}: attached by the person. ${fileKindSaid(f)}.`, meta: { id: f.id, tool: "attached", kind: "text", step: 0, value: isTextFile(f) ? f.data : f.doc, file } }; } - const { value: v, matched, score } = tokenStore.resolveRef(ref, opts.labelMatch); - if (!v) throw new Error(memoryFault(ref, tokenStore.nearest(ref), seq)); + const { value: found, matched, score } = tokenStore.resolveRef(ref, opts.labelMatch); + if (!found) throw new Error(memoryFault(ref, tokenStore.nearest(ref), seq)); + const v = mask ? mask(found) : found; // A soft label match travels BESIDE the value, never inside it: the caller here is a script that will // parse/split/pipe what it gets back, so a note appended to the value would corrupt the data. const warning = matched diff --git a/src/background.ts b/src/background.ts index dd2b94363..bb123b524 100644 --- a/src/background.ts +++ b/src/background.ts @@ -43,6 +43,7 @@ import { handleRunLogDump } from "./sw/sw-run-log"; import { handleRunStateDump } from "./sw/sw-run-state"; import { releaseSessionValues, startValueSweeps, valueHolders, readStoredColumns } from "./sw/sw-values"; // where a table larger than its preview lives (docs/spec/POINTER_VALUES.md) // what the system decided on its own (docs/dev/housekeeping.md) import { costCalls } from "./sw/sw-prices"; +import { sessionFakeForms } from "./sw/sw-fake-key"; // code reads a stored table faked (ruling 133) import { PendingApprovalDescriptor, pendingApprovals, externallyResolvable, externalApprovals, resolveApproval, fetchConsent, credFetchGrants, senderTrust, serverToolKey, tabGrants } from "./sw/sw-consent"; import { syncPresence, isVisible, presence, injectRunTools, injectPageScripts, SITE_REQUESTS_KEY } from "./sw/sw-presence"; import { isExtensionSender, senderFacts, editSiteAccess, pageRefusal, agentRefusal, readSiteLists, selfApprovalFacts, senderSelfApproves, siteLevels, siteSchemaReady, upgradeNotice, dismissUpgradeNotice } from "./sw/sw-site-access"; @@ -1049,7 +1050,9 @@ function route(message: any, sender: chrome.runtime.MessageSender, sendResponse: sendResponse({ error: "That stored table was not named by the running script." }); return; } try { - const r = await readStoredColumns(key, names, { ...(typeof message.delimiter === "string" ? { delimiter: message.delimiter } : {}), ...(message.headerless ? { headerless: true } : {}) }, plan); + // Faked as code reads it (ruling 133), with the run's session's fakes, or the tab's for a page-hosted run. + const forms = await sessionFakeForms(viaPage ? `page:${tabId}` : runId).catch(() => null); + const r = await readStoredColumns(key, names, { ...(typeof message.delimiter === "string" ? { delimiter: message.delimiter } : {}), ...(message.headerless ? { headerless: true } : {}) }, forms, plan); sendResponse(r); } catch (e) { sendResponse({ error: (e as Error)?.message || String(e) }); } })(); diff --git a/src/ml/ml-python.ts b/src/ml/ml-python.ts index 81a5bef43..db526fdfe 100644 --- a/src/ml/ml-python.ts +++ b/src/ml/ml-python.ts @@ -64,12 +64,20 @@ export const pythonExec = async function(this: MlApi, code: string, { image = nu // A returned DataFrame → the UI renders a real table. Past its preview it carries the whole frame's row count, and // the value-store key its pointer will name. if (r.table) extra.resultTable = { ...r.table, ...(r.valueKey ? { value: r.valueKey } : {}) }; - const read = hoisted.flatMap((h) => h.answer ? [{ src: h.src, answer: h.answer }] : []); + // What the cell READ, which the worker hands back faked (ruling 133, `tablesRead`, one per table sent), never what this + // page hoisted: a table it did not hand back is left out. + const asRead = (r as { tablesRead?: (LoadedTable["data"] | null)[] }).tablesRead; + const read = hoisted.flatMap((h, i) => { + if (!h.answer) return []; + const data = asRead ? asRead[i] : h.answer.data; + return data ? [{ src: h.src, answer: { ...h.answer, data, ...(data === h.answer.data ? {} : { preview: undefined }) } }] : []; + }); if (read.length) extra.inputTables = read.map(({ src, answer: l }) => ({ name: src, source: l.source, ...(l.data.kind === "rows" ? { columns: l.data.columns, rows: l.data.rows } : l.data.kind === "value" ? { columns: l.data.columns, rows: l.preview ?? [], ...(l.rowCount != null ? { rowCount: l.rowCount } : {}) } : { html: true }), })); - return Object.keys(extra).length ? { ...r, ...extra } : r; + const { tablesRead: _read, ...answer } = r as typeof r & { tablesRead?: unknown }; + return Object.keys(extra).length ? { ...answer, ...extra } : answer; }; /** diff --git a/src/offscreen.ts b/src/offscreen.ts index 232a785cd..70090eb05 100644 --- a/src/offscreen.ts +++ b/src/offscreen.ts @@ -53,6 +53,8 @@ import { b64ToBytes, bytesToB64, type PdfMessage, type PdfReadReply, type PdfRen import { importTestCode } from "./python/pkg-install-test"; import { attachFiles, detachFiles, filesMessage, readWholeFile, setFilesReader } from "./python/files-host"; import { ML_TABLE_FILE_MAX, tableAnswerBytes } from "./python/table-answer"; +import { fakeKeyOf } from "./sw/ml-wire-serve"; +import type { FakedForm } from "./secret-fake"; import { createFilesSource } from "./python/files-source"; import { RangedReader } from "./session/ranged-reader"; import { AgentFiles } from "./session/agent-files"; @@ -216,7 +218,7 @@ type PendingEntry = typeof pending extends Map ? E : never; // document's to stamp — the worker never sees it (LANE_1_PR2_DESIGN.md "Who stamps the handle"). An // `ask` first answer is NOT relayed down: the cell's `send` stays pending until the later `ML_ANSWER` // push, matched by `client`, arrives here. -const wireByClient = new Map void; runMsgId: number; principal: string; calls: Map }>(); // state: plumbing — one in-flight cell each +const wireByClient = new Map void; runMsgId: number; principal: string; fakeKey: string; calls: Map }>(); // state: plumbing — one in-flight cell each /** * Post a wire call's final answer to the cell that made it. An `ml.table` answer over a stored table or a `/files/` file @@ -234,6 +236,11 @@ async function postWireAnswer(client: string, seq: number, answer: unknown): Pro ? await tableAnswerBytes(answer, { stored: async (key) => { const { row, blob } = await store().get(key); return { format: row.format, buffer: await blob.arrayBuffer() }; }, file: (path) => readWholeFile(entry.principal, path, ML_TABLE_FILE_MAX), + forms: async () => { + const got = await chrome.runtime.sendMessage({ type: "FILES_SECRET_FORMS", session: entry.fakeKey }) as { forms?: FakedForm[] | null } | undefined; + if (!Array.isArray(got?.forms)) throw new Error("the secrets could not be read"); + return got.forms; + }, }) : { answer }; const mlAnswer = { seq, answer: ready.answer, ...(ready.buffer ? { buffer: ready.buffer } : {}) }; @@ -725,7 +732,7 @@ function runInWorker(code: string, image: string | null, hardened: boolean, stre // THE `ml` WIRE: the handle stays HERE. The worker is told only that this run has a wire and which // run's namespace it is — never `client` (LANE_1_PR2_DESIGN.md, "Who stamps the handle"). if ((inside && Array.isArray(libraries?.libraries) && libraries.libraries.length) || libraries?.library) libraryPrincipals.add(principal); - if (wire) wireByClient.set(wire.client, { post: (m, transfer) => { try { w.postMessage(m, transfer ?? []); } catch { /* worker gone */ } }, runMsgId: id, principal, calls: new Map() }); + if (wire) wireByClient.set(wire.client, { post: (m, transfer) => { try { w.postMessage(m, transfer ?? []); } catch { /* worker gone */ } }, runMsgId: id, principal, fakeKey: fakeKeyOf(wire, wire.client), calls: new Map() }); // A leased cell always streams to this document, which keeps its tail; the chunks go on only for a `streamId`. w.postMessage({ id, code, image, hardened, stream: stream || cell !== undefined, ...(wire ? { wire: true, run: wire.run } : {}), ...(env ? { env: true } : {}), ...(complete ? { complete } : {}), ...(bench?.persist ? { persist: true } : {}), ...(bench?.reset ? { benchReset: true } : {}), ...(inside ? { inside: true } : {}), // The person's approved tier 3 libraries ride an inside run; a library op (its card's shape, its load after diff --git a/src/python/table-answer.ts b/src/python/table-answer.ts index 9693f9463..b5c265f9c 100644 --- a/src/python/table-answer.ts +++ b/src/python/table-answer.ts @@ -5,6 +5,8 @@ import { binaryKind } from "../sw/body-read"; import { hasHeaderRow, looksArrowFile, looksParquet, parseDelimited, sniffDelimiter } from "../table/table-data"; import type { TableSource } from "../contract"; import { WireError } from "../sw/ml-wire-serve"; +import { fakeStoredTable, TableNotFaked } from "./table-fake"; +import { fakeSecretText, type FakedForm } from "../secret-fake"; type Cell = string | number | boolean | null; @@ -31,10 +33,12 @@ export const ML_TABLE_FILE_MAX = 64 * 1024 * 1024; /** How much of a file's head decides its delimiter and header: enough lines for `sniffDelimiter` and `hasHeaderRow`. */ const HEAD_BYTES = 64 * 1024; -/** What the relay needs of the offscreen document: a stored value's bytes and format, and a whole `/files/` file. */ +/** What the relay needs of the offscreen document: a stored value's bytes and format, a whole `/files/` file, and the + * cell's forms with their fakes (FILES_SECRET_FORMS), which throws when they cannot be read. */ export interface TableAnswerDeps { stored(key: string): Promise<{ format: string; buffer: ArrayBuffer }>; file(path: string): Promise; + forms(): Promise; } type Answer = { seq?: number; value?: { source?: unknown; data?: Record } & Record; error?: unknown } & Record; @@ -55,11 +59,20 @@ export async function tableAnswerBytes(answer: unknown, deps: TableAnswerDeps): if (!a || !data || (data.kind !== "value" && data.kind !== "file")) return { answer }; const fail = (code: string, message: string) => ({ answer: { seq: a.seq, error: { code, message } } }); if (data.kind === "value") { + // A stored table reaches the cell faked (ruling 133): read here, from the store, which keeps what the server sent. + let forms: readonly FakedForm[]; + try { forms = await deps.forms(); } catch { return fail("Failed", "ml.table: the registered secrets could not be read, so this read is withheld."); } try { - const { format, buffer } = await deps.stored(String(data.key)); + const stored = await deps.stored(String(data.key)); + const { format, buffer } = await fakeStoredTable(stored.format, stored.buffer, forms); const { key: _key, ...rest } = data; return { answer: { ...a, value: { ...a.value, data: { ...rest, format } } }, buffer }; } catch (e) { + if (e instanceof TableNotFaked) { + const label = (a.value?.source as { label?: unknown } | undefined)?.label; + // The source is the code's own text, faked too, so the refusal holds no registered value. + return fail("Failed", `ml.table(${JSON.stringify(fakeSecretText(typeof label === "string" ? label : String(data.label ?? ""), forms))}): ${e.message}`); + } return fail("Failed", `ml.table could not read the stored table: ${(e as Error)?.message ?? e}`); } } diff --git a/src/python/table-fake.ts b/src/python/table-fake.ts new file mode 100644 index 000000000..a9bf908e7 --- /dev/null +++ b/src/python/table-fake.ts @@ -0,0 +1,277 @@ +// table-fake.ts — a stored table's bytes made ready for a Python cell with each registered value replaced by the session's fake (ruling 133, "Where the mask sits", 6). + +// The offscreen document reads a stored table's bytes from the store and hands them to the cell, which reads them with +// pyarrow or pandas. A fake keeps its value's byte length, so the bytes are faked where they lie, never rebuilt, except +// for a Parquet table that holds a value: its pages may be compressed, so it is decoded and handed over as Arrow IPC. +// Faking inside the cell's interpreter is not an option: an approved cell runs any Python and could replace the masker +// first. Each decoder is imported when a table is read, so the offscreen bundle loads neither until then. + +import { fakeSecretBytes, fakeSecretText, fakeStrings, type FakedForm } from "../secret-fake"; + +/** A table that holds a registered value in a place a fake cannot be put: the column, and why. */ +export class TableNotFaked extends Error { + constructor(column: string, what: string) { super(`column ${column} is ${what}, which cannot be served with registered values replaced, so this table is not read.`); this.name = "TableNotFaked"; } +} + +/** Arrow's type ids (apache-arrow's `Type` enum, the base id a concrete type reports) by what this module does with + * a column of that type. Every id is in exactly one list; an id in none (a run-end-encoded column, a type added + * later) refuses the read. */ +const ARROW = { + /** Text, faked in place over the values joined: Utf8, LargeUtf8. */ + text: new Set([5, 20]), + /** Bytes, faked in place value by value: Binary, LargeBinary, FixedSizeBinary. */ + bytes: new Set([4, 19, 15]), + /** View types, whose short values sit inside the views: searched, and a value in one refuses the read. */ + views: new Set([23, 24]), + /** Containers, whose children are visited: List, Struct, Union, FixedSizeList, Map, LargeList; a Dictionary (-1) + * is visited through its dictionary. */ + containers: new Set([12, 13, 14, 16, 17, 21, -1]), + /** Not searched (a stated limit: the scrub matches text, and a printed number still crosses the output scrub): + * Null, Int, Float, Bool, Decimal, Date, Time, Timestamp, Interval, Duration. */ + unsearched: new Set([1, 2, 3, 6, 7, 8, 9, 10, 11, 18]), +} as const; + +/** + * Fake the values of a variable-width column in place: each value's bytes, `offsets[i]` to `offsets[i + 1]`. Text is + * faked over the values joined by NUL bytes, in one call, unless a form holds NUL; bytes value by value, since any + * byte may occur in them (ruling 133, "Binary cells"). A fake keeps its value's length, so no offset moves. + * @param values the column's value bytes, changed in place + * @param offsets the value offsets + * @param from the first value's index + * @param to one past the last value's index + * @param forms the session's forms with their fakes + * @param text whether the values are text + * @returns how many matches were faked + */ +export function fakeSpans(values: Uint8Array, offsets: ArrayLike, from: number, to: number, forms: readonly FakedForm[], text: boolean): number { + const at = (i: number) => Number(offsets[i]); + if (to <= from) return 0; + if (!text || forms.some((f) => f.find.includes("\u0000"))) { + let n = 0; + for (let i = from; i < to; i++) n += fakeSecretBytes(values.subarray(at(i), at(i + 1)), forms); + return n; + } + const base = at(from), count = to - from; + const joined = new Uint8Array(at(to) - base + count - 1); + for (let i = from, w = 0; i < to; i++) { + joined.set(values.subarray(at(i), at(i + 1)), w); + w += at(i + 1) - at(i) + 1; + } + const n = fakeSecretBytes(joined, forms); + if (!n) return 0; + for (let i = from, w = 0; i < to; i++) { + const len = at(i + 1) - at(i); + values.set(joined.subarray(w, w + len), at(i)); + w += len + 1; + } + return n; +} + +/** Whether faking changes any of `strings`. */ +const anyFaked = (strings: readonly string[], forms: readonly FakedForm[]): boolean => { + const out = fakeStrings(strings, forms); + return out.some((s, i) => s !== strings[i]); +}; + +/** One node of a decoded Arrow column, as apache-arrow's `Data` holds it. */ +interface ArrowData { + type: { typeId: number; byteWidth?: number; toString(): string }; + offset: number; length: number; + values?: Uint8Array; valueOffsets?: ArrayLike; + children?: ArrowData[]; + dictionary?: { data: ArrowData[] }; +} + +/** An Arrow field as the schema holds it: its name, its metadata, and its children's. */ +interface ArrowField { name: string; metadata?: Map; type: { children?: readonly ArrowField[] } } + +/** + * Refuse a table whose column names or metadata hold a registered value: they reach the cell in the schema, where a + * fake cannot be put without rewriting it. + * @param names every column name, nested ones included + * @param metadata every metadata key and value, the schema's and each field's + * @param forms the session's forms with their fakes + * @throws {TableNotFaked} naming the first such name, or saying the metadata holds one + */ +function refuseHeldNames(names: readonly string[], metadata: readonly string[], forms: readonly FakedForm[]): void { + const faked = fakeStrings(names, forms); + const named = names.findIndex((n, i) => faked[i] !== n); + if (named >= 0) throw new TableNotFaked(JSON.stringify(faked[named]), "named with a registered value"); + if (anyFaked(metadata, forms)) throw new TableNotFaked("metadata", "a schema's or a field's metadata holding a registered value"); +} + +/** + * Fake an Arrow IPC table (file or stream) in place. Every column is decided by its TYPE ({@link ARROW}): text and + * bytes are faked where they lie, nested ones included; a view type that holds a value, a column of a type in no list, + * and a column whose values the reader did not read where they lie (a compressed body) refuse the read, as does a + * column name or a metadata string that holds a value. Numbers, decimals, dates and booleans are not searched. + * @param buffer the IPC bytes, changed in place + * @param forms the session's forms with their fakes + * @throws {TableNotFaked} as above + */ +export async function fakeArrow(buffer: ArrayBuffer, forms: readonly FakedForm[]): Promise { + const { tableFromIPC, makeVector } = await import("apache-arrow"); + const table = tableFromIPC(new Uint8Array(buffer)); + const names: string[] = [], metadata: string[] = []; + const meta = (m: Map | undefined) => { for (const [k, v] of m ?? []) metadata.push(k, v); }; + const walk = (fields: readonly ArrowField[]) => { for (const f of fields) { names.push(f.name); meta(f.metadata); if (f.type.children) walk(f.type.children); } }; + meta(table.schema.metadata); + walk(table.schema.fields as unknown as ArrowField[]); + refuseHeldNames(names, metadata, forms); + const seen = new Set(); + const visit = (d: ArrowData, column: string): void => { + if (seen.has(d)) return; + seen.add(d); + const id = d.type.typeId; + if (ARROW.text.has(id) || ARROW.bytes.has(id)) { + if (!d.values) return; + if (d.values.buffer !== buffer) throw new TableNotFaked(column, `${d.type} stored compressed`); + // A fixed-size binary has no offsets: value i is the `byteWidth` bytes at i × `byteWidth`. + const width = d.type.byteWidth ?? 0; + const offsets = id === 15 ? Float64Array.from({ length: d.offset + d.length + 1 }, (_, i) => i * width) : d.valueOffsets; + if (offsets) fakeSpans(d.values, offsets, d.offset, d.offset + d.length, forms, ARROW.text.has(id)); + } else if (ARROW.views.has(id)) { + const got = [...makeVector(d as never)].map((v) => v == null ? "" : typeof v === "string" ? v : new TextDecoder().decode(v as Uint8Array)); + if (anyFaked(got, forms)) throw new TableNotFaked(column, String(d.type)); + } else if (!ARROW.containers.has(id) && !ARROW.unsearched.has(id)) { + throw new TableNotFaked(column, `${d.type}, a type this read does not search`); + } + for (const c of d.children ?? []) visit(c, column); + for (const c of d.dictionary?.data ?? []) visit(c, column); + }; + table.schema.fields.forEach((f, i) => { + for (const d of table.getChildAt(i)?.data ?? []) visit(d as unknown as ArrowData, f.name); + }); +} + +/** A Parquet leaf as this module reads it: its name, its Arrow kind, or why it has none. */ +type ParquetColumn = { name: string; nullable: boolean } & ({ kind: "bool" | "int32" | "int64" | "float" | "double" | "utf8" | "binary" } | { kind: null; what: string }); + +/** + * What a top-level Parquet column becomes in Arrow: only the types that carry losslessly here. Anything else (a + * decimal, a date or time, an INT96, a fixed-length array, a nested or repeated column) has no kind, and its Parquet + * type is what a refusal names. + */ +function parquetKind(e: import("hyparquet").SchemaElement, leaf: boolean): ParquetColumn { + const base = { name: e.name, nullable: e.repetition_type !== "REQUIRED" }; + const logical = e.logical_type?.type, converted = e.converted_type; + const what = logical ?? converted ?? e.type ?? "a nested group"; + if (!leaf || e.repetition_type === "REPEATED") return { ...base, kind: null, what: logical ?? converted ?? "a nested or repeated column" }; + const plainInt = (bits: number) => !logical && !converted || logical === "INTEGER" && (e.logical_type as { bitWidth: number; isSigned: boolean }).bitWidth === bits && (e.logical_type as { isSigned: boolean }).isSigned || converted === `INT_${bits}`; + switch (e.type) { + case "BOOLEAN": return { ...base, kind: "bool" }; + case "INT32": return plainInt(32) ? { ...base, kind: "int32" } : { ...base, kind: null, what }; + case "INT64": return plainInt(64) ? { ...base, kind: "int64" } : { ...base, kind: null, what }; + case "FLOAT": return logical || converted ? { ...base, kind: null, what } : { ...base, kind: "float" }; + case "DOUBLE": return logical || converted ? { ...base, kind: null, what } : { ...base, kind: "double" }; + case "BYTE_ARRAY": + if (converted === "UTF8" || logical === "STRING") return { ...base, kind: "utf8" }; + return logical || converted ? { ...base, kind: null, what } : { ...base, kind: "binary" }; + default: return { ...base, kind: null, what }; + } +} + +/** + * A Parquet table faked: the bytes as they are when no string or binary cell holds a registered value (the common + * case, whatever the forms), and otherwise the table decoded, faked, and written as an Arrow IPC stream, with every + * column carried exactly (ruling 133, "Where the mask sits", 6). Built from the decoded columns directly: apache-arrow's + * builders compile code, which an extension page may not. + * @param buffer the Parquet bytes + * @param forms the session's forms with their fakes + * @returns the bytes to hand over, and their format + * @throws {TableNotFaked} when a value is held and a column has no lossless Arrow form here, or a name holds a value + */ +export async function fakeParquet(buffer: ArrayBuffer, forms: readonly FakedForm[]): Promise<{ format: "parquet" | "arrow-stream"; buffer: ArrayBuffer }> { + const { parquetMetadata, parquetSchema, parquetReadObjects } = await import("hyparquet"); + const meta = parquetMetadata(buffer); + const tree = parquetSchema(meta); + const columns = tree.children.map((c) => parquetKind(c.element, !c.children.length)); + const names = columns.map((c) => c.name); + // Every name in the schema, nested ones included, and the file's key-value metadata (pandas' own among it). + const everyName: string[] = []; + const walk = (n: typeof tree) => { for (const c of n.children) { everyName.push(c.element.name); walk(c); } }; + walk(tree); + refuseHeldNames(everyName, (meta.key_value_metadata ?? []).flatMap((kv) => [kv.key, kv.value ?? ""]), forms); + const texty = columns.filter((c) => c.kind === "utf8" || c.kind === "binary" || c.kind === null); + if (!texty.length) return { format: "parquet", buffer }; + const read = async (cols: string[]) => (await parquetReadObjects({ file: buffer, columns: cols, utf8: false })) as Record[]; + // First the columns that can hold a value: when none does, the file is handed over as it is. + const rows = await read(texty.map((c) => c.name)); + const holds = (c: ParquetColumn): boolean => { + const cells = rows.map((r) => r[c.name]); + if (c.kind === "utf8") return anyFaked(cells.map((v) => typeof v === "string" ? v : ""), forms); + if (c.kind === "binary") return cells.some((v) => v instanceof Uint8Array && fakeSecretBytes(v.slice(), forms) > 0); + // A column with no Arrow form here, read as text: a value in it refuses the read below. + const text = JSON.stringify(cells, (_k, v) => typeof v === "bigint" ? String(v) : v instanceof Uint8Array ? new TextDecoder().decode(v) : v); + return fakeSecretText(text, forms) !== text; + }; + if (!texty.some(holds)) return { format: "parquet", buffer }; + const odd = columns.find((c) => c.kind === null) as (ParquetColumn & { kind: null }) | undefined; + if (odd) throw new TableNotFaked(odd.name, odd.what); + const all = await read(names); + return { format: "arrow-stream", buffer: await arrowStreamOf(columns as (ParquetColumn & { kind: string })[], all, forms) }; +} + +/** + * Decoded Parquet rows as an Arrow IPC stream, with every string faked: each column's `Data` made from typed arrays + * (`makeData`), never through a builder. + */ +async function arrowStreamOf(columns: (ParquetColumn & { kind: string })[], rows: Record[], forms: readonly FakedForm[]): Promise { + const A = await import("apache-arrow"); + const n = rows.length; + const enc = new TextEncoder(); + const fields: InstanceType[] = []; + const children: unknown[] = []; + for (const c of columns) { + const cells = rows.map((r) => r[c.name]); + const valid = new Uint8Array(Math.ceil(n / 8)); + let nulls = 0; + cells.forEach((v, i) => { if (v == null) nulls++; else valid[i >> 3] |= 1 << (i & 7); }); + const common = { length: n, nullCount: nulls, nullBitmap: nulls ? valid : undefined }; + let type: InstanceType, data: unknown; + if (c.kind === "utf8" || c.kind === "binary") { + const parts = c.kind === "utf8" + ? fakeStrings(cells.map((v) => typeof v === "string" ? v : ""), forms).map((s) => enc.encode(s)) + : cells.map((v) => { const b = v instanceof Uint8Array ? v.slice() : new Uint8Array(0); fakeSecretBytes(b, forms); return b; }); + const offsets = new Int32Array(n + 1); + parts.forEach((p, i) => { offsets[i + 1] = offsets[i] + p.length; }); + const bytes = new Uint8Array(offsets[n]); + parts.forEach((p, i) => bytes.set(p, offsets[i])); + type = c.kind === "utf8" ? new A.Utf8() : new A.Binary(); + data = A.makeData({ type: type as never, ...common, valueOffsets: offsets, data: bytes }); + } else if (c.kind === "bool") { + const bits = new Uint8Array(Math.ceil(n / 8)); + cells.forEach((v, i) => { if (v === true) bits[i >> 3] |= 1 << (i & 7); }); + type = new A.Bool(); + data = A.makeData({ type: type as never, ...common, data: bits }); + } else { + const [T, Arr] = c.kind === "int32" ? [new A.Int32(), Int32Array] : c.kind === "int64" ? [new A.Int64(), BigInt64Array] : c.kind === "float" ? [new A.Float32(), Float32Array] : [new A.Float64(), Float64Array]; + const out = new (Arr as Int32ArrayConstructor)(n) as unknown as { [i: number]: number | bigint }; + cells.forEach((v, i) => { if (v != null) out[i] = c.kind === "int64" ? BigInt(v as bigint) : Number(v); }); + type = T; + data = A.makeData({ type: type as never, ...common, data: out as never }); + } + fields.push(new A.Field(c.name, type, c.nullable)); + children.push(data); + } + const schema = new A.Schema(fields); + const struct = A.makeData({ type: new A.Struct(fields), length: n, nullCount: 0, children: children as never }); + const bytes = A.tableToIPC(new A.Table([new A.RecordBatch(schema, struct)]), "stream"); + return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; +} + +/** + * A stored table's bytes made ready for a cell, faked (ruling 133): delimited text in place, Arrow in place, Parquet + * as it is or as Arrow (see {@link fakeParquet}). Any other format passes as it is: the cell refuses to read it. + * @param format the stored row's format + * @param buffer its bytes, which may be changed in place + * @param forms the session's forms with their fakes + * @returns what to hand over + * @throws {TableNotFaked} when a value cannot be faked where it is + */ +export async function fakeStoredTable(format: string, buffer: ArrayBuffer, forms: readonly FakedForm[]): Promise<{ format: string; buffer: ArrayBuffer }> { + if (format === "csv" || format === "tsv") { fakeSecretBytes(new Uint8Array(buffer), forms); return { format, buffer }; } + if (format === "arrow-file" || format === "arrow-stream") { await fakeArrow(buffer, forms); return { format, buffer }; } + if (format === "parquet") return fakeParquet(buffer, forms); + return { format, buffer }; +} diff --git a/src/secret-fake.ts b/src/secret-fake.ts index 44aadbe92..2581d7df2 100644 --- a/src/secret-fake.ts +++ b/src/secret-fake.ts @@ -221,6 +221,92 @@ export function fakeSecretText(text: string, forms: readonly FakedForm[]): strin return fakeSecretBytes(bytes, forms) ? new TextDecoder().decode(bytes) : text; } +/** What {@link fakeStrings} joins its strings on, when no form contains it. */ +const JOINT = "\u0000"; + +/** + * Many strings masked as {@link fakeSecretText} masks one, in one call over them joined by U+0000 and split again + * (ruling 133, "Joining"): a call per string costs a search per form, the joined call about one search in all. A + * registered value may contain U+0000, so the join is made only when no form does, and the split's count is checked; + * either failing, each string is masked alone. + * @param strings the strings + * @param forms the session's forms with their fakes + * @returns the strings masked, in order + */ +export function fakeStrings(strings: readonly string[], forms: readonly FakedForm[]): string[] { + if (!strings.length) return []; + if (!forms.some((f) => f.find.includes(JOINT))) { + const parts = fakeSecretText(strings.join(JOINT), forms).split(JOINT); + if (parts.length === strings.length) return parts; + } + return strings.map((s) => fakeSecretText(s, forms)); +} + +/** Two keys of one object read the same once registered values are replaced, so the object cannot be served + * (ruling 133, "Object keys"). */ +export class FakedKeysClash extends Error { + constructor(path: string) { super(`the answer has two keys at ${path || "its top"} that read the same once registered values are replaced, so it is not read`); this.name = "FakedKeysClash"; } +} + +/** Bytes masked as {@link fakeSecretBytes} masks them, in a copy. */ +const fakedBytes = (b: Uint8Array, forms: readonly FakedForm[]): Uint8Array => { const c = b.slice(); fakeSecretBytes(c, forms); return c; }; + +/** Base64 to bytes and back, for a wire-form `{ $bytes }`. */ +const fromBase64 = (s: string): Uint8Array => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); +const toBase64 = (b: Uint8Array): string => { let bin = ""; for (let i = 0; i < b.length; i += 0x8000) bin += String.fromCharCode(...b.subarray(i, i + 0x8000)); return btoa(bin); }; + +/** Whether `v` is a plain object: a prototype of null or of some realm's `Object.prototype`. */ +const isPlain = (v: object): boolean => { const p = Object.getPrototypeOf(v); return p === null || Object.getPrototypeOf(p) === null; }; + +/** + * A value served to code with every registered value replaced by its session fake (ruling 133): each string in it, an + * object's keys included, through {@link fakeStrings} in one call, and each byte view through {@link fakeSecretBytes}, + * value by value. Arrays and plain objects are copied; numbers, booleans, null, bigints and any other object pass as + * they are. With `wire`, `v` is in ML_WIRE form: a `{ $bytes }` tag's bytes are masked as bytes, except the object a + * `{ "$": … }` wrap holds, which is data. + * @param v the value + * @param forms the session's forms with their fakes + * @param wire whether `v` is in wire form + * @returns the copy + * @throws {FakedKeysClash} when two keys of one object read the same once faked + */ +export function fakeValue(v: T, forms: readonly FakedForm[], wire = false): T { + const isBytesTag = (o: Record, keys: string[], wrapped: boolean) => wire && !wrapped && keys.length === 1 && keys[0] === "$bytes" && typeof o.$bytes === "string"; + const isWrap = (o: Record, keys: string[], wrapped: boolean) => wire && !wrapped && keys.length === 1 && keys[0] === "$" && !!o.$ && typeof o.$ === "object" && !Array.isArray(o.$); + const strings: string[] = []; + const collect = (x: unknown, wrapped: boolean): void => { + if (typeof x === "string") { strings.push(x); return; } + if (!x || typeof x !== "object" || ArrayBuffer.isView(x)) return; + if (Array.isArray(x)) { for (const y of x) collect(y, false); return; } + if (!isPlain(x)) return; + const o = x as Record, keys = Object.keys(o); + if (isBytesTag(o, keys, wrapped)) return; + const wrap = isWrap(o, keys, wrapped); + for (const k of keys) { if (!wrap) strings.push(k); collect(o[k], wrap); } + }; + collect(v, false); + const faked = fakeStrings(strings, forms); + let i = 0; + const build = (x: unknown, wrapped: boolean, path: string): unknown => { + if (typeof x === "string") return faked[i++]; + if (!x || typeof x !== "object") return x; + if (ArrayBuffer.isView(x)) return fakedBytes(new Uint8Array(x.buffer, x.byteOffset, x.byteLength), forms); + if (Array.isArray(x)) return x.map((y, n) => build(y, false, `${path}[${n}]`)); + if (!isPlain(x)) return x; + const o = x as Record, keys = Object.keys(o); + if (isBytesTag(o, keys, wrapped)) return { $bytes: toBase64(fakedBytes(fromBase64(o.$bytes as string), forms)) }; + const wrap = isWrap(o, keys, wrapped); + const out: Record = Object.getPrototypeOf(o) === null ? Object.create(null) : {}; + for (const k of keys) { + const key = wrap ? k : faked[i++]; + if (Object.prototype.hasOwnProperty.call(out, key)) throw new FakedKeysClash(path); + Object.defineProperty(out, key, { value: build(o[k], wrap, wrap ? path : `${path}.${key}`), enumerable: true, writable: true, configurable: true }); + } + return out; + }; + return build(v, false, "") as T; +} + /** One slot in a written content: a fake (its form's place) or a marker (its text). */ export interface Slot { at: number; end: number; form?: number; marker?: string } diff --git a/src/secret-mask.ts b/src/secret-mask.ts index e30e483c1..90f23a54d 100644 --- a/src/secret-mask.ts +++ b/src/secret-mask.ts @@ -17,15 +17,28 @@ const GITHUB_TOKEN_MAX = 266; const utf8 = new TextEncoder(); +/** Decodes all-ASCII bytes, which read the same as one character per byte, natively. */ +const asciiDecoder = new TextDecoder(); + +/** Decodes bytes widened to UTF-16 code units, natively. A `latin1` decoder is windows-1252, which is not one character + * per byte for 0x80 to 0x9f. */ +const utf16Decoder = new TextDecoder("utf-16le"); + /** - * Bytes as a string of one character per byte (codes 0 to 255), so a native string search finds byte offsets. + * Bytes as a string of one character per byte (codes 0 to 255), so a native string search finds byte offsets. Every read + * served to code is faked through here (ruling 133), so both paths are native: all-ASCII bytes decode as they are, and any + * other bytes are widened to code units 0 to 255 (no surrogate, no byte order mark) and decoded as UTF-16. Building a + * megabyte from character codes cost about 13 ms; these cost about 0.5 and 1.5 ms. * @param b the bytes * @returns the string, `b.length` long */ export function byteString(b: Uint8Array): string { - let s = ""; - for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)); - return s; + let ascii = true; + for (let i = 0; i < b.length; i++) if (b[i] > 0x7f) { ascii = false; break; } + if (ascii) return asciiDecoder.decode(b); + const wide = new Uint16Array(b.length); + wide.set(b); + return utf16Decoder.decode(wide); } /** ASCII letters lowered and nothing else, so a folded string keeps every byte's offset. */ diff --git a/src/sw/ml-wire-serve.ts b/src/sw/ml-wire-serve.ts index 7face6296..ac7d12885 100644 --- a/src/sw/ml-wire-serve.ts +++ b/src/sw/ml-wire-serve.ts @@ -176,8 +176,9 @@ async function fail(seq: number, code: MlWireErrorCode, message: string, scrub: return { seq, error: { code, message: await scrub(message), ...(task !== undefined ? { task } : {}) } }; } -/** Run a member and turn its result, or its throw, into the answer. */ -async function answerOf(seq: number, name: string, member: WireMember, args: unknown[], scrub: (s: string) => Promise): Promise { +/** Run a member and turn its result, or its throw, into the answer: its value or pointer through `fake` (ruling 133), + * whose throw fails the call, so nothing it could not mask crosses. */ +async function answerOf(seq: number, name: string, member: WireMember, args: unknown[], scrub: (s: string) => Promise, fake: WireServeContext["fake"]): Promise { let result: unknown; try { result = await member.run(...args); @@ -186,9 +187,9 @@ async function answerOf(seq: number, name: string, member: WireMember, args: unk return fail(seq, "Failed", `ml.${name}: ${(e as Error)?.message || String(e)}`, scrub); } const p = result && typeof result === "object" ? (result as { [POINTER]?: MlWirePointer })[POINTER] : undefined; - if (p) return { seq, pointer: { ...p } }; try { - return { seq, value: toWire(result) }; + if (p) return { seq, pointer: fake ? fake({ ...p }) as MlWirePointer : { ...p } }; + return { seq, value: fake ? fake(toWire(result)) : toWire(result) }; } catch (e) { return fail(seq, (e as WireError).code ?? "Failed", `ml.${name}: ${(e as Error).message}`, scrub); } @@ -234,6 +235,10 @@ export interface WireServeContext { argsMeter?: WireArgsMeter; /** Scrub an error's text before it crosses (sw-scrub.ts `forPage` in the worker). */ scrub: (text: string) => Promise; + /** Every answer's value or pointer, in wire form, with each registered value replaced by the session's fake + * (ruling 133; secret-fake.ts `fakeValue`), the first answer and the one after an `ask` alike. A throw fails the + * call with its message. Absent: the answer crosses as the member gave it. */ + fake?: (v: unknown) => unknown; /** Told the member of each call that names one the client has, for the cell's recorded facts (CELL_FACTS.md). It * only counts: nothing it does changes the answer. */ onCall?: (name: string) => void; @@ -279,10 +284,10 @@ export async function serveWireCall(req: Partial | null | undefin } ctx.onCall?.(name); const member = ctx.members[name]; - if (!member.gate) return answerOf(seq, name, member, args, ctx.scrub); + if (!member.gate) return answerOf(seq, name, member, args, ctx.scrub, ctx.fake); let decision: WireGateDecision; try { decision = await member.gate(args); } catch (e) { return fail(seq, "Denied", `ml.${name}: ${(e as Error)?.message || String(e)}`, ctx.scrub); } - if ("allow" in decision) return answerOf(seq, name, member, args, ctx.scrub); + if ("allow" in decision) return answerOf(seq, name, member, args, ctx.scrub, ctx.fake); if ("deny" in decision) return fail(seq, "Denied", `ml.${name}: ${decision.deny}`, ctx.scrub); // The call waits on the person; the client suspends on it, and the answer follows when they decide. A card unanswered // past the cap fails the call, and an approval that lands after the client closed (the cell ended, the worker @@ -292,7 +297,7 @@ export async function serveWireCall(req: Partial | null | undefin void Promise.race([decision.decided, timedOut]).then( (ok) => ok === "timeout" ? fail(seq, "Denied", `ml.${name}: the card went unanswered`, ctx.scrub) : !ctx.isOpen() ? null - : ok ? answerOf(seq, name, member, args, ctx.scrub) : fail(seq, "Denied", `ml.${name}: the person declined`, ctx.scrub), + : ok ? answerOf(seq, name, member, args, ctx.scrub, ctx.fake) : fail(seq, "Denied", `ml.${name}: the person declined`, ctx.scrub), (e) => fail(seq, "Denied", `ml.${name}: ${(e as Error)?.message || String(e)}`, ctx.scrub), ).then((a) => { clearTimeout(timer); if (a && ctx.isOpen()) ctx.later(a); }); return { seq, ask: { card: decision.ask } }; @@ -326,6 +331,17 @@ export interface WireClient { const clients = new Map(); // state: plumbing — one in-flight cell each +/** + * The key a client's fakes are derived under: its run's session, or `page:` for a client with no run, a + * namespace no session hash takes, so a page's fakes are its own (ruling 133, "The fake"). + * @param client the client + * @param handle its handle + * @returns the key + */ +export function fakeKeyOf(client: Pick, handle: string): string { + return client.run ?? `page:${handle}`; +} + /** The open client a handle names, or undefined: unknown, or closed when its code finished. */ export const wireClient = (handle: string): WireClient | undefined => clients.get(handle); diff --git a/src/sw/sw-ml-wire.ts b/src/sw/sw-ml-wire.ts index 038c228a2..47791f735 100644 --- a/src/sw/sw-ml-wire.ts +++ b/src/sw/sw-ml-wire.ts @@ -12,18 +12,19 @@ import type { MlWireAnswer, MlWireRequest } from "../contract"; import { ML_READONLY_METHODS, mlFacade } from "../readonly-exec/policy"; -import { workerReadonlyMl, derefWhole, type RunDeref } from "./worker-readonly-ml"; +import { workerReadonlyMl, derefWhole, FORMS_UNREADABLE, type RunDeref } from "./worker-readonly-ml"; +import { sessionFakeForms } from "./sw-fake-key"; +import { fakeValue, FakedKeysClash, type FakedForm } from "../secret-fake"; import { pipeStages } from "../pointers/token-pipe"; import { FILE_PREFIX } from "../pointers/token-prefixes"; import type { PipeLimits } from "../pointers/text-pipe"; import { MAX_STRING, PIPE_CHARS_PER_STEP, STEP_BUDGET } from "../readonly-exec/limits"; import { derefByRun, isWorkerRun, runControllers, sessionTokens, turnByRun } from "./sw-runs"; -import { surveySettings } from "./sw-change-setting"; import { shPut, shRead, shRun, type ShAnswer, type ShCallContext } from "./sw-shell-call"; import { forPage } from "./sw-scrub"; import { tableMemberFor } from "./sw-ml-table"; import { isOffscreenSender } from "./sw-offscreen"; -import { serveWireCall, wirePointer, WireError, wireClient, deliverIfOpen, type WireMember, type WireClient, type WireFrom, type WireArgsMeter } from "./ml-wire-serve"; +import { serveWireCall, wirePointer, WireError, wireClient, deliverIfOpen, fakeKeyOf, type WireMember, type WireClient, type WireFrom, type WireArgsMeter } from "./ml-wire-serve"; /** The largest value a call answers in full, as JSON characters; past it, a pointer read answers its pointer instead. * One megabyte: chrome serialises each message as JSON, and a cell awaiting more than this wants a pipe, not the bytes. */ @@ -43,18 +44,19 @@ function senderIs(from: WireFrom, sender: chrome.runtime.MessageSender): boolean * The members a client's realm has. `full` adds `sh.run`/`sh.read`/`sh.put` for a client a running step of its run opened; the * other gated members (a live fetch, `chat`, `click`) come with the consent path, each with its own gate. * @param client the client + * @param forms its forms with their fakes, for the members that answer what the worker holds (null: they answer nothing) * @returns its members, by name */ -function membersFor(client: WireClient): Record { +function membersFor(client: WireClient, forms: readonly FakedForm[] | null): Record { const deref = client.run ? derefByRun.get(client.run) : undefined; // `ml.settings`: only for a client bound to a run the worker built. The run is the handle's, which the worker opened. - const host = { ...workerReadonlyMl(client.tabUrl(), deref, client.run ?? ""), ...(client.run && isWorkerRun(client.run) ? { settings: surveySettings } : {}) }; + const host = workerReadonlyMl(client.tabUrl(), deref, client.run ?? "", forms, !!client.run && isWorkerRun(client.run)); const facade = mlFacade(host, undefined, undefined, undefined, "worker") ?? {}; const out: Record = Object.create(null); for (const name of ML_READONLY_METHODS) { const fn = facade[name]; if (typeof fn !== "function") continue; - out[name] = { run: name === "dereference" && deref ? dereferenceOverWire(deref, client.run!, meterOf(client)) : fn as (...a: unknown[]) => unknown }; + out[name] = { run: name === "dereference" && deref ? dereferenceOverWire(deref, client.run!, meterOf(client), forms) : fn as (...a: unknown[]) => unknown }; } // ml.sh: an approved (full) client of a run, opened by one of its steps, and only while that run runs. Bound to the run // and step the HANDLE records, never to anything in the request; each call is judged or asked inside that step @@ -134,13 +136,13 @@ function argsMeterOf(client: WireClient): WireArgsMeter { * @param limits the client's budget, which the pipe charges * @returns the member's function */ -function dereferenceOverWire(deref: RunDeref, run: string, limits: PipeLimits): (...a: unknown[]) => unknown { +function dereferenceOverWire(deref: RunDeref, run: string, limits: PipeLimits, forms: readonly FakedForm[] | null): (...a: unknown[]) => unknown { return async (ref: unknown, opts?: unknown) => { const o = opts && typeof opts === "object" ? opts as { pipe?: unknown } : {}; const pipe = o.pipe ?? null; if (pipe !== null && typeof pipe !== "string" && !(Array.isArray(pipe) && pipe.every((x) => typeof x === "string"))) throw new WireError("BadRequest", "dereference's pipe is a string or an array of strings"); - const read = await derefWhole(run, deref, String(ref ?? ""), pipeStages(pipe as string | string[] | null), limits); + const read = await derefWhole(run, deref, String(ref ?? ""), pipeStages(pipe as string | string[] | null), limits, forms); const value = { text: read.value, ...(read.meta ? { meta: read.meta } : {}), ...(read.warning ? { warning: read.warning } : {}) }; const size = JSON.stringify(value).length; if (size <= WIRE_VALUE_CAP) return value; @@ -178,7 +180,25 @@ export function onMlCall(message: Partial, sender: chrome.runtime sendResponse({ seq, error: { code: "Refused", message: "this sender cannot call ml over the wire" } }); return true; } - serveWireCall(message, { run: client.run, members: membersFor(client), argsMeter: argsMeterOf(client), later: (a) => deliverLater(handle, a), isOpen: () => wireClient(handle) !== undefined, scrub, onCall: (n) => client.calls.set(n, (client.calls.get(n) ?? 0) + 1) }) + // WHAT CODE IS SERVED IS FAKED (ruling 133): the members that answer what the worker holds, and every answer as it + // leaves, with the fakes of the client's run's session, or of the client itself when it has no run (a cell a page + // started), whose key no session hash can equal. Forms that cannot be read fail every answer. + sessionFakeForms(fakeKeyOf(client, handle)).catch(() => null) + .then((forms) => serveWireCall(message, { run: client.run, members: membersFor(client, forms), argsMeter: argsMeterOf(client), later: (a) => deliverLater(handle, a), isOpen: () => wireClient(handle) !== undefined, scrub, fake: wireFake(forms), onCall: (n) => client.calls.set(n, (client.calls.get(n) ?? 0) + 1) })) .then(sendResponse, async (e) => sendResponse({ seq, error: { code: "Failed", message: await scrub(String((e as Error)?.message || e)) } })); return true; } + +/** + * The wire's catch-all mask (ruling 133, "Where the mask sits", 5): every string of an answer in wire form, values and + * keys, faked; or, with no forms, a refusal of every answer. + * @param forms the client's forms with their fakes, or null when they could not be read + * @returns the mask `serveWireCall` applies + */ +export function wireFake(forms: readonly FakedForm[] | null): (v: unknown) => unknown { + return (v) => { + if (!forms) throw new WireError("Failed", FORMS_UNREADABLE); + try { return fakeValue(v, forms, true); } + catch (e) { throw e instanceof FakedKeysClash ? new WireError("Failed", e.message) : e; } + }; +} diff --git a/src/sw/sw-python.ts b/src/sw/sw-python.ts index 6b29a71b5..abeb31036 100644 --- a/src/sw/sw-python.ts +++ b/src/sw/sw-python.ts @@ -8,7 +8,7 @@ import { recordHousekeeping, sessionArea } from "./sw-housekeeping"; import { ensureOffscreen, forgetOffscreen, isOffscreenSender } from "./sw-offscreen"; import { secretFormsNow } from "./sw-scrub"; import { maskName } from "../secret-mask"; -import type { FakedForm } from "../secret-fake"; +import { fakeValue, type FakedForm } from "../secret-fake"; import { sessionFakeForms } from "./sw-fake-key"; import { activeRuns, attachedFilesOf, execReads, isWorkerRun, onSessionRelease, pageValueSession, runControllers, type ReleaseReason } from "./sw-runs"; import { valueHolders, budgetBytes as valueBudgetBytes, claimValue } from "./sw-values"; @@ -16,7 +16,7 @@ import { PY_PACKAGE_LOADS } from "../python/python-env"; import { defineJob } from "../job-registry"; import { pyCodeCovers } from "./grant-extract"; import { pythonCellInDialect } from "../agent/python-dialect"; -import { openWireClient } from "./ml-wire-serve"; +import { fakeKeyOf, openWireClient } from "./ml-wire-serve"; import { hoistKey, tableOpts } from "../python/table-answer"; import type { HoistedAnswer, TableAnswer, TableReadOpts } from "../python/table-answer"; import { recordRunLog } from "./sw-run-log"; @@ -211,6 +211,22 @@ export function hoistedTables(v: unknown): Map | undefine return out.size ? out : undefined; } +/** + * Each hoisted table's data as a page-started cell read it: faked with the cell's fakes (ruling 133), in the order the + * page sent them. A table the page could not read, or every table when the forms cannot be read, is null. + * @param sent `payload.hoisted`, already checked by {@link hoistedTables} + * @param tables the checked tables, by `hoistKey` + * @param key the cell's fake key (ml-wire-serve.ts `fakeKeyOf`) + * @returns the data, one entry per table sent + */ +export async function hoistedAsRead(sent: { src: string; opts?: unknown }[], tables: ReadonlyMap, key: string): Promise<(TableAnswer["data"] | null)[]> { + const forms = await sessionFakeForms(key).catch(() => null); + return sent.map((h) => { + const a = tables.get(hoistKey(h.src, tableOpts(h.opts))); + return forms && a && "data" in a ? fakeValue(a.data, forms) : null; + }); +} + /** PYTHON_EXEC through the router: the caller is read off the sender, which the browser sets. */ export function pythonExec(message: any, sender: chrome.runtime.MessageSender, sendResponse: (r: any) => void): void { const ownSurface = isExtensionSender(sender); @@ -364,7 +380,10 @@ export async function runPython(payload: any, requestId: string | undefined, cal if ((res as { markSet?: unknown } | undefined)?.markSet === true && caller.wireRun) recordRunLog(caller.wireRun, { subsystem: "python", kind: "outside-mark", reason: "outside-cell", detail: { principal } }); if (key && caller.disclose && caller.tabId != null) claimValue(key, pageValueSession(caller.tabId)); caller.onCellFacts?.({ wire: wire?.calls() ?? [], markSet: (res as { markSet?: unknown } | undefined)?.markSet === true }); - return { data: res }; + // A page-started cell's tables as the cell read them, faked (ruling 133), for the page's `inputTables`: what the + // page hoisted is its own read, which the cell never saw. + const tablesRead = hoisted && wire ? await hoistedAsRead(payload.hoisted, hoisted, fakeKeyOf({ run: null }, wire.handle)) : undefined; + return { data: tablesRead && res && typeof res === "object" ? { ...res, tablesRead } : res }; } catch (err) { return { error: (err as Error)?.message || String(err) }; } finally { diff --git a/src/sw/sw-run-host.ts b/src/sw/sw-run-host.ts index 30a0e49e3..d8828e74b 100644 --- a/src/sw/sw-run-host.ts +++ b/src/sw/sw-run-host.ts @@ -10,7 +10,8 @@ import { namesJsBridge } from "../python/bridge-names"; import { evalReadonlyInWorker } from "./sw-readonly"; import { surveySh, guardSurvey } from "./sw-survey-sh"; import { endPythonTurn, markPythonBridged, pythonRunBridged } from "./sw-python"; -import { workerReadonlyMl, derefWhole } from "./worker-readonly-ml"; +import { workerReadonlyMl, derefWhole, fakedMember, fakeToken, FORMS_UNREADABLE } from "./worker-readonly-ml"; +import { sessionFakeForms } from "./sw-fake-key"; import { pipeStages } from "../pointers/token-pipe"; import { recordRunLog, runLog } from "./sw-run-log"; import { forModel, forModelHistory, forPage, forLive, forPerson, forStored, forTurn, redactedNote, withAsIs } from "./sw-scrub"; @@ -37,7 +38,7 @@ import { extractGrants, fetchUrlLiterals, tabGrantsForCall } from "./grant-extra import { parseInfo } from "../resource/resource-capacity"; import { cdpClick, cdpShadowResolve, cdpKeyType, cdpEval, releaseDebugger } from "./sw-cdp"; import { grantsFor, dropCallGrants, serverToolKey, pendingApprovals, grantCredFetch, grantOnceFetch, consentFetch, fetchConsent, resolveApproval } from "./sw-consent"; -import { settingBeforeCard, settingCard, settingFacts, settingMeasureDeps, holdSettingChange, releaseSettingChange, noteSettingDeclined, watchSetting, settingEntries, surveySettings, settingChangedElsewhere, type SettingChange } from "./sw-change-setting"; +import { settingBeforeCard, settingCard, settingFacts, settingMeasureDeps, holdSettingChange, releaseSettingChange, noteSettingDeclined, watchSetting, settingEntries, settingChangedElsewhere, type SettingChange } from "./sw-change-setting"; import { ASK_POLICY_CAUSE, BROKEN_POLICY_CAUSE, navOnlyWhy, startLeftWhy, judgeCall, fetchFacts, navigateFacts, actFacts, noteAct, dropActs, actsOf, rememberFetchUrls, withPolicies, addRunPolicy, askWhyOf, askedByPolicy, withoutAsked, takeArchiveNotice } from "./sw-policies"; import { checkProposals, recordedFetches, measureBreadth, breadthNote, measureActBreadth, actBreadthNote, measureSettingBreadth, measureSettingRows, settingBreadthNote, recordedSettingKeys, type PolicyProposal, type SettingBreadth } from "./policy-proposal"; import { approveManifest, checkManifestProposal, draftCardNote, type CheckedManifest } from "./sw-manifest-proposal"; @@ -192,9 +193,12 @@ function thrownKey(e: unknown): string { async function preReadsFor(runId: string, js: string, whole: boolean): Promise { const fn = derefByRun.get(runId); if (!fn) return []; + // The main world's preview is faked as `derefWhole`'s read is (ruling 133); forms that cannot be read fail each read. + const forms = whole ? null : await sessionFakeForms(runId).catch(() => null); return Promise.all(namedReads(expandPointers(js).code).map(async ({ ref, pipe }): Promise => { try { - const r = whole ? await derefWhole(runId, fn, ref, pipeStages(pipe ?? null)) : fn(ref, pipe); + if (!whole && !forms) throw new Error(FORMS_UNREADABLE); + const r = whole ? await derefWhole(runId, fn, ref, pipeStages(pipe ?? null)) : fn(ref, pipe, undefined, (v) => fakeToken(v, forms!)); // What the person attached is not read into the page's own world, for the reason a stored text is not read // whole there; the resolver's answer for a file is its description, which must not pass for its text. if (!whole && r.meta?.file) return { ref, pipe, error: "An attached file is read only in an isolated world, which this page has none of. Read it with the dereference tool instead." }; @@ -1431,13 +1435,15 @@ function hostTurn(message: any, tabId: number, sendResponse: (r: any) => void, t // ml.fs, for a script that names it: reads of THIS run's session, on a channel of this exec's own // in the offscreen document (sw-fs-call.ts), closed when the exec ends. const fsCall = execNames(js).fs ? fsCallFor(runId) : undefined; + // What the worker serves the script reaches it faked (ruling 133): its stored columns and settings. + const forms = await sessionFakeForms(runId).catch(() => null); const out = await runIsolatedExec({ tabId, runId, js, how: route.how, reason: route.reason, reads, onStream, documentId: execDoc, sh: !!sh, fs: !!fsCall, // What the world may ask for while it runs: re-pipes of what it was sent, those stored tables, ml.sh and ml.fs. - serve: isoServer(runId, reads, { deref: wholeDerefFor(runId), holders: valueHolders, columns: readStoredColumns, ...(sh ? { sh } : {}), ...(fsCall ? { fs: fsCall.fs } : {}) }), + serve: isoServer(runId, reads, { deref: wholeDerefFor(runId), holders: valueHolders, columns: (key, names, opts, plan) => readStoredColumns(key, names, opts, forms, plan), ...(sh ? { sh } : {}), ...(fsCall ? { fs: fsCall.fs } : {}) }), // Made only for a script that names it, as a survey's is (tryReadonly below). // The person's settings, read now, for a script that names them in a run the worker built. - ...(p.builtBy === "worker" && execNames(js).settings ? { settings: async () => settingEntries(await getConfig()) } : {}), + ...(p.builtBy === "worker" && execNames(js).settings ? { settings: fakedMember("settings", async () => settingEntries(await getConfig()), forms) as () => Promise> } : {}), ...(snap && execNames(js).current ? { current: async () => withTasks(withPolicies(withRuntime(await withEnv(await withUserWatches(snap({ model: modelNow(), log: eventsForRun(await runLog.all(), runId) })), tabId, !!p.autoApproveReadonly, !byWorker())), runId), runId) } : {}), }).finally(() => fsCall?.end()); // A reading taken after a wait for the person is not simultaneous with one taken before: say so. @@ -1860,10 +1866,12 @@ function hostTurn(message: any, tabId: number, sendResponse: (r: any) => void, t : undefined; // The prompt's own condition for naming `ml.sh` (a run the worker built, offered it at its start): a budget trip then names it. const shellOffered = byWorker() && !!p.shell; + // What the survey's members serve reaches it faked (ruling 133), with this run's session's fakes. + const surveyForms = await sessionFakeForms(runId).catch(() => null); const w = await guardSurvey(sh, () => evalReadonlyInWorker(args, { ...(snap ? { current: () => current ?? snap({ model: modelNow(), log }) } : {}), // ml.settings: a free read, only in a run the worker built (decided from its record, never the script). - ml: { ...workerReadonlyMl(tabPageUrl.get(tabId) ?? "", derefByRun.get(runId), runId), ...(byWorker() ? { settings: surveySettings } : {}), ...(sh ? { sh: sh.host } : {}) }, + ml: { ...workerReadonlyMl(tabPageUrl.get(tabId) ?? "", derefByRun.get(runId), runId, surveyForms, byWorker()), ...(sh ? { sh: sh.host } : {}) }, live, signal: abortCtl.signal, ...(shellOffered ? { shell: true } : {}), diff --git a/src/sw/sw-runs.ts b/src/sw/sw-runs.ts index cc56682cd..f587d26c9 100644 --- a/src/sw/sw-runs.ts +++ b/src/sw/sw-runs.ts @@ -557,7 +557,7 @@ export const releaseRunTab = (tabId: number, runId: string): void => { // Pointer resolvers for background-hosted runs, keyed by runId — handed over by the loop at start (tokenSink) // so a page-side tool's `ml.dereference` can read THIS run's captured outputs. Deleted when the run ends. -export const derefByRun = new Map DerefRead>(); +export const derefByRun = new Map(); /** The pointer reads sent with a run's in-flight approved `exec` (named-reads.ts): a stored table's columns are read * for that call only when its key is among them (VALUE_COLUMNS). Set and cleared around the one call. */ export const execReads = new Map(); // state: plumbing diff --git a/src/sw/sw-values.ts b/src/sw/sw-values.ts index d742a69fb..e4a7efd65 100644 --- a/src/sw/sw-values.ts +++ b/src/sw/sw-values.ts @@ -9,6 +9,7 @@ import { ValueStore, ValueTooLarge, ValueMissing, type ValueFormat, type ValueRow } from "../pointers/value-store"; import type { StoredReadPlan } from "../table/table-plan"; import { cachedStoredColumns } from "../table/table-decode-cache"; +import { fakeValue, type FakedForm } from "../secret-fake"; import type { FetchedBody } from "./sw-fetch"; import { recordHousekeeping } from "./sw-housekeeping"; import { DEFAULT_CONFIG } from "../contract/contract-config"; @@ -167,14 +168,22 @@ export async function valueHolders(key: string): Promise { } /** Named columns of a stored table, every row up to the plan's limit, from the worker's decode of the bytes as stored - * (decoded on the first read, `table-decode-cache.ts`). The store is asked first on every read, so a value that is gone - * throws the store's ValueMissing (with its reason) even while its decode is cached; the decoder's error for an - * unknown column or an oversized read. */ -export async function readStoredColumns(key: string, names: string[], opts: { delimiter?: string; headerless?: boolean }, plan: StoredReadPlan = {}): Promise<{ rowCount: number; columns: Record }> { + * (decoded on the first read, `table-decode-cache.ts`), as code reads them: each registered value in a cell replaced + * by the session's fake (ruling 133). The decode is cached as stored; the fake is made on each read. The store is asked + * first on every read, so a value that is gone throws the store's ValueMissing (with its reason) even while its decode + * is cached; the decoder's error for an unknown column or an oversized read. + * @param forms the reading run's session's forms with their fakes (`sessionFakeForms`), or null when they could not be + * read, and then nothing is read */ +export async function readStoredColumns(key: string, names: string[], opts: { delimiter?: string; headerless?: boolean }, forms: readonly FakedForm[] | null, plan: StoredReadPlan = {}): Promise<{ rowCount: number; columns: Record }> { + if (!forms) throw new Error("the registered secrets could not be read, so this read is withheld."); const s = values(); if (!s) throw new Error("there is no value store in this context"); const { row, blob } = await s.get(key); - return cachedStoredColumns(row.blob ?? row.key, () => blob.arrayBuffer(), row.format, names, opts, plan); + const read = await cachedStoredColumns(row.blob ?? row.key, () => blob.arrayBuffer(), row.format, names, opts, plan); + // The column names are the caller's own, so only the cells are faked: a list per column, never an object's keys. + const columns: Record = {}; + for (const [name, cells] of Object.entries(read.columns)) columns[name] = fakeValue(cells, forms); + return { rowCount: read.rowCount, columns }; } /** A session is gone: release what it held, except the rows named in `keep`. */ diff --git a/src/sw/worker-readonly-ml.ts b/src/sw/worker-readonly-ml.ts index cfd93b392..96b2fbecd 100644 --- a/src/sw/worker-readonly-ml.ts +++ b/src/sw/worker-readonly-ml.ts @@ -8,7 +8,7 @@ import type { DerefRead, DerefValue } from "../contract/contract-pointers"; import { DerefText } from "../tools/deref-read"; -import { pipeStages, derefPipe, TokenStore } from "../pointers/token-pipe"; +import { pipeStages, derefPipe, TokenStore, type TokenValue } from "../pointers/token-pipe"; import { mlPipe, type PipeLimits } from "../pointers/text-pipe"; import { fileSections } from "../pointers/file-pointer"; import { lineCount } from "../attached-files"; @@ -22,38 +22,54 @@ import { valueHolders, readStoredColumns, readStoredText } from "./sw-values"; import { workerFetchCached } from "./worker-tools"; import { sessionFakeForms } from "./sw-fake-key"; import { maskName } from "../secret-mask"; -import { fakeSecretText, type FakedForm } from "../secret-fake"; +import { fakeSecretText, fakeValue, type FakedForm } from "../secret-fake"; +import { surveySettings } from "./sw-change-setting"; import type { StoredColumnReader } from "../table/table-data"; -/** A run's pointer resolver, as the loop hands it to the host (`tokenSink`). */ -export type RunDeref = (ref: string, pipe?: string | string[], limits?: PipeLimits) => DerefRead; +/** A run's pointer resolver, as the loop hands it to the host (`tokenSink`). `mask`, when given, is applied to the + * pointer's value before any pipe reads it (ruling 133: code reads a pointer faked). */ +export type RunDeref = (ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: TokenValue) => TokenValue) => DerefRead; /** - * Read a pointer through the run's resolver, over the WHOLE of a stored text when its row names one (fetch_url past its - * preview; docs/spec/POINTER_VALUES.md, slice 9) and over what the row holds otherwise. The resolver is synchronous and - * holds only the preview, so the whole is read here, where the caller can wait. A whole that is gone throws the store's - * reason, never the preview. - * @param runId the run, which must hold the stored value + * A pointer's value as code reads it (ruling 133): every string in it faked (what the model saw, the fuller capture, + * the call, the label, the LaTeX and the table preview, its column names and dtypes' keys alike) in one call. The image + * is pixels, never text, and is left as it is. + * @param v the value + * @param forms the session's forms with their fakes + * @returns the faked copy + */ +export function fakeToken(v: TokenValue, forms: readonly FakedForm[]): TokenValue { + const { image, ...rest } = v; + return { ...fakeValue(rest, forms), ...(image !== undefined ? { image } : {}) } as TokenValue; +} + +/** + * Read a pointer through the run's resolver, as CODE reads it: faked (ruling 133), each registered value replaced by + * the session's fake before any pipe runs, so a `grep` for the value finds no line and `lines a-b` counts over the text + * code reads. Over the WHOLE of a stored text when its row names one (fetch_url past its preview; POINTER_VALUES.md, + * slice 9) and over what the row holds otherwise. The resolver is synchronous and holds only the preview, so the whole + * is read here, where the caller can wait. A whole that is gone throws the store's reason, never the preview; forms that + * cannot be read throw, and nothing is read. + * @param runId the run, which must hold the stored value, and whose session's fakes are used * @param deref the run's pointer resolver * @param ref the pointer * @param stages the pipe, as stages * @param limits the caller's budget for the pipe's line stages (text-pipe.ts `PipeLimits`), or none; with no stages it * is charged the size of the text read (`charge`), since nothing else would charge that copy - * @returns what the resolver answers, with the whole text in place of the preview + * @param known the session's forms when the caller already read them (null: they could not be read); absent, read here + * @returns what the resolver answers, faked, with the whole text in place of the preview */ -export async function derefWhole(runId: string, deref: RunDeref, ref: string, stages: string[], limits?: PipeLimits): Promise { - const base = deref(ref); +export async function derefWhole(runId: string, deref: RunDeref, ref: string, stages: string[], limits?: PipeLimits, known?: readonly FakedForm[] | null): Promise { + const forms = known !== undefined ? known : await sessionFakeForms(runId).catch(() => null); + if (!forms) throw new Error(FORMS_UNREADABLE); + const mask = (v: TokenValue): TokenValue => fakeToken(v, forms); + const base = deref(ref, undefined, undefined, mask); const key = base.meta?.value, meta = base.meta; // An attached file is read here, every time, from the run's held rows: a PDF's read document as its `` // sections (what the dereference tool reads), a text file as attached (`data`, the resolver's key), with `lines` - // counted over the masked text read here. The key stays here; the caller gets the file. - // Every caller here is CODE, which reads the file as the `/files` mount of the run's session gives it: its text - // masked before any pipe runs, each secret's occurrence as the session's fake, and its name as a listing shows it (FILE_ATTACHMENTS.md, "Names under `/files`", rule 5). The model's - // dereference tool does not come here. + // counted over the masked text read here. The key stays here; the caller gets the file, its name as a listing + // shows it (FILE_ATTACHMENTS.md, "Names under `/files`", rule 5). The model's dereference tool does not come here. if (key && meta?.file) { - let forms: FakedForm[]; - try { forms = await sessionFakeForms(runId); } - catch { throw new Error("the registered secrets could not be read, so this file's text is withheld."); } const stored = await readStoredText(key, runId, !stages.length && limits?.charge ? limits.charge : undefined); const body = fakeSecretText(meta.file.lines != null ? stored : fileSections(JSON.parse(stored) as PdfDoc), forms); const { value: _key, ...rest } = meta; @@ -61,40 +77,64 @@ export async function derefWhole(runId: string, deref: RunDeref, ref: string, st return { value: derefPipe({ id: meta.id, tool: meta.tool, kind: "text", out: body, t: 0, step: 0 }, "out", stages, limits), meta: { ...rest, file } }; } if (!key || !meta || meta.table || meta.kind === "table" || TokenStore.slotOf(ref) === "in") { - if (stages.length) return deref(ref, stages, limits); + if (stages.length) return deref(ref, stages, limits, mask); limits?.charge?.(base.value.length); return base; } // An unpiped read copies the whole text with no stage to charge it, so the caller's budget is charged its size // here, before the copy (the blob's byte count, which is the character count for the ASCII a megabyte usually is). - const whole = await readStoredText(key, runId, !stages.length && limits?.charge ? limits.charge : undefined); + const whole = fakeSecretText(await readStoredText(key, runId, !stages.length && limits?.charge ? limits.charge : undefined), forms); return { ...base, value: derefPipe({ id: meta.id, tool: meta.tool, kind: meta.kind, out: whole, t: 0, step: meta.step }, "out", stages, limits) }; } /** A stored table's columns, read from the worker's value store for the run that holds it: what `VALUE_COLUMNS` answers * a page, without the round trip. A key the run does not hold reads nothing. */ -function columnsFor(runId: string, read: DerefRead): StoredColumnReader | undefined { +function columnsFor(runId: string, read: DerefRead, forms: readonly FakedForm[] | null): StoredColumnReader | undefined { const key = read.meta?.table ? read.meta.value : undefined; const table = read.meta?.table; if (!key || !table) return undefined; return async (names, plan) => { const holders = await valueHolders(key); if (holders && !holders.includes(runId)) throw new Error("That stored table is not held by this run."); - return await readStoredColumns(key, names, { ...(table.delimiter ? { delimiter: table.delimiter } : {}), ...(table.headerless ? { headerless: true } : {}) }, plan) as Awaited>; + return await readStoredColumns(key, names, { ...(table.delimiter ? { delimiter: table.delimiter } : {}), ...(table.headerless ? { headerless: true } : {}) }, forms, plan) as Awaited>; }; } +/** Why a read served to code fails when the session's forms cannot be read: nothing unfaked crosses (ruling 133). */ +export const FORMS_UNREADABLE = "the registered secrets could not be read, so this read is withheld."; + /** - * Build the read-only `ml` for one survey of one run. + * A member whose answer reaches code faked (ruling 133): each registered value in it replaced by the session's fake, + * synchronously for a member that answers synchronously. With no forms (they could not be read) it answers nothing. + * @param name the member, for the refusal + * @param fn the member + * @param forms the session's forms with their fakes, or null when they could not be read + * @returns the member, faked + */ +export function fakedMember(name: string, fn: (...a: never[]) => unknown, forms: readonly FakedForm[] | null): (...a: unknown[]) => unknown { + return (...a: unknown[]) => { + if (!forms) throw new Error(`ml.${name}: ${FORMS_UNREADABLE}`); + const r = (fn as (...a: unknown[]) => unknown)(...a); + return r instanceof Promise ? r.then((v) => fakeValue(v, forms)) : fakeValue(r, forms); + }; +} + +/** + * Build the read-only `ml` for one survey of one run. Every member that answers what the worker holds (the box, the + * config, the run's fetches, its pointers) answers it faked with `forms` (ruling 133); the pure ones (`pipe`, + * `jsonPath`, `schema`, `range`) answer only from the code's own arguments. * @param tabUrl the run's tab as the browser reports it, for `config()`'s one page-dependent field * @param deref the run's pointer resolver; absent before the loop has handed it over, and then `dereference` is absent * too, so a survey naming a pointer is decided by the page leg, which refuses it * @param runId the run, which a stored table's column read must be held by + * @param forms the session's forms with their fakes (`sessionFakeForms`), or null when they could not be read, and then + * every such member answers nothing + * @param settings whether `ml.settings` is offered: only to a run the worker built * @returns the members the dialect's worker facade picks from */ -export function workerReadonlyMl(tabUrl: string, deref?: RunDeref, runId = ""): Record { +export function workerReadonlyMl(tabUrl: string, deref: RunDeref | undefined, runId: string, forms: readonly FakedForm[] | null, settings = false): Record { const base = workerMl(tabUrl); - const ml: Record = { + const served: Record unknown> = { getModel: async () => (await getConfig()).model, config: base.config, models: base.models, @@ -102,22 +142,26 @@ export function workerReadonlyMl(tabUrl: string, deref?: RunDeref, runId = ""): serverTools: base.serverTools, ps: () => listLoadedModels(), info: () => fetchOllamaInfo(), - pipe: mlPipe, - jsonPath: mlJsonPath, - schema: mlSchema, - range: mlRange, // The run's own fetches, made by its `fetch_url` in the worker: a re-read is free and never egresses. Only the // default mode is cached; any other misses, and the dialect defers it to the page. _fetchCached: (url: unknown, mode?: { credentials?: boolean; rendered?: boolean; format?: string }) => mode?.credentials || mode?.rendered || mode?.format === "html" ? undefined : workerFetchCached(runId, String(url)), + ...(settings ? { settings: surveySettings } : {}), + }; + const ml: Record = { + pipe: mlPipe, + jsonPath: mlJsonPath, + schema: mlSchema, + range: mlRange, }; + for (const [name, fn] of Object.entries(served)) ml[name] = fakedMember(name, fn, forms); if (deref) { // The page's `ml.dereference`, with the store read in-process. Its advisory has // nowhere to go: the dialect's console is the script's, and a warning written into it would read as output. const dereference = async (ref: unknown, opts: { pipe?: string | string[] | null } = {}): Promise => { - const read = await derefWhole(runId, deref, String(ref ?? ""), pipeStages(opts?.pipe ?? null)); + const read = await derefWhole(runId, deref, String(ref ?? ""), pipeStages(opts?.pipe ?? null), undefined, forms); const again = (stages: string | string[]): Promise => dereference(ref, { pipe: stages }); - return new DerefText(read.value, read.meta, again, read.readColumns ?? columnsFor(runId, read)); + return new DerefText(read.value, read.meta, again, read.readColumns ?? columnsFor(runId, read, forms)); }; ml.dereference = dereference; } diff --git a/tests/code-reads-fakes.test.mjs b/tests/code-reads-fakes.test.mjs new file mode 100644 index 000000000..5ebf7baaa --- /dev/null +++ b/tests/code-reads-fakes.test.mjs @@ -0,0 +1,344 @@ +// code-reads-fakes.test.mjs — what the worker serves to code is faked (ruling 133, SECRET_HANDLES.md, "What the worker +// serves to code is faked"): the joined fake and its fallbacks, the wire's catch-all, the members a survey and a cell +// read, a pointer read before its pipe, a stored table's columns, and a stored table's bytes in each carrier. The +// red-team rows, one per input and code kind, are e4's (tests/e2e/redteam-code-reads-fakes.spec.mjs). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { IDBFactory, IDBKeyRange } from "fake-indexeddb"; +import { tableFromArrays, tableToIPC, tableFromIPC, vectorFromArray, Utf8, Binary, Int64, Int32, Dictionary } from "apache-arrow"; +import { parquetWriteBuffer } from "hyparquet-writer"; + +// The worker's chrome, as much as the registry, the session's fakes and the value store read. +const NAME = "DB_PASS"; +const VALUE = "hunter2-correct-horse"; +const local = { ml_secret_registry: [{ name: NAME, value: VALUE }] }; +const changed = []; +/** Register `entries` as the person would: stored, and the change delivered to the worker's listeners. */ +const register = (entries) => { + const old = local.ml_secret_registry; + local.ml_secret_registry = entries; + for (const f of changed) f({ ml_secret_registry: { oldValue: old, newValue: entries } }, "local"); +}; +globalThis.indexedDB = new IDBFactory(); +globalThis.IDBKeyRange = IDBKeyRange; +globalThis.chrome = { + runtime: { id: "ext-id", getURL: (p) => p, onMessage: { addListener() {} } }, + storage: { + sync: { get: async (d) => ({ ...(d ?? {}) }), set: async () => {} }, + local: { + get: async (k) => { + if (typeof k === "string") return k in local ? { [k]: local[k] } : {}; + if (Array.isArray(k)) return Object.fromEntries(k.filter((x) => x in local).map((x) => [x, local[x]])); + return Object.fromEntries(Object.entries(k ?? {}).map(([x, d]) => [x, x in local ? local[x] : d])); + }, + set: async (o) => { Object.assign(local, o); }, remove: async () => {}, + }, + session: { get: async () => ({}), set: async () => {}, remove: async () => {} }, + onChanged: { addListener: (f) => changed.push(f) }, + }, + alarms: { create() {}, onAlarm: { addListener() {} } }, +}; + +const { fakeStrings, fakeValue, fakeSecretText, FakedKeysClash, deriveFakes, sessionFakeKey } = await import("../src/secret-fake.ts"); +const { sessionFakeForms } = await import("../src/sw/sw-fake-key.ts"); +const { derefWhole, workerReadonlyMl, fakeToken, FORMS_UNREADABLE } = await import("../src/sw/worker-readonly-ml.ts"); +const { serveWireCall, fakeKeyOf, wirePointer } = await import("../src/sw/ml-wire-serve.ts"); +const { wireFake } = await import("../src/sw/sw-ml-wire.ts"); +const { storeHeld, readStoredColumns } = await import("../src/sw/sw-values.ts"); +const { fakeStoredTable, TableNotFaked } = await import("../src/python/table-fake.ts"); +const { pipeStages, TokenStore } = await import("../src/pointers/token-pipe.ts"); +const { runAgentLoop } = await import("../src/agent/agent-loop.ts"); + +/** The session's fake for `VALUE`: `RDCT` and letters and digits, its length (ruling 101). */ +const FAKE = new RegExp(`RDCT[A-Za-z0-9]{${VALUE.length - 4}}`); +/** Fixed forms for the pure rows: the value, and a short one that reads as `*`. */ +const master = Uint8Array.from({ length: 32 }, (_, i) => i); +const FORMS = await deriveFakes(await sessionFakeKey(master, "s1"), [{ name: NAME, index: 0, find: VALUE }, { name: "PIN", index: 0, find: "ab12" }, { name: "PIN2", index: 0, find: "cd34" }]); +const fakeOf = FORMS[0].fake; + +// --- joining, and its fallbacks --- + +test("many strings are faked in one joined call, each as it would be alone", () => { + const strings = [`x ${VALUE} y`, "plain", "", VALUE, `${VALUE}${VALUE}`, "ab12 and cd34"]; + assert.deepEqual(fakeStrings(strings, FORMS), strings.map((s) => fakeSecretText(s, FORMS))); + assert.equal(fakeStrings(strings, FORMS)[3], fakeOf); +}); + +test("a form holding U+0000, and a string holding U+0000, fall back to one call a string: every string still faked, the count unchanged", () => { + const nul = [...FORMS, { name: "NUL", index: 0, find: "with\u0000nul", fake: undefined }]; + const strings = ["a with\u0000nul b", VALUE, "c"]; + const out = fakeStrings(strings, nul); + assert.equal(out.length, 3); + assert.equal(out[0], "a ******** b"); + assert.equal(out[1], fakeOf); + const held = ["has\u0000inside", VALUE]; + assert.deepEqual(fakeStrings(held, FORMS), [held[0], fakeOf], "a string holding the joint splits wrong, so each is faked alone"); +}); + +// --- a value as code is served it --- + +test("fakeValue fakes strings and keys at any depth and bytes value by value; numbers, booleans and null pass", () => { + const v = { [VALUE]: [VALUE, 1, true, null, { k: `p ${VALUE}` }], bytes: new TextEncoder().encode(VALUE) }; + const out = fakeValue(v, FORMS); + assert.deepEqual(Object.keys(out), [fakeOf, "bytes"]); + assert.deepEqual(out[fakeOf], [fakeOf, 1, true, null, { k: `p ${fakeOf}` }]); + assert.equal(new TextDecoder().decode(out.bytes), fakeOf); + assert.equal(new TextDecoder().decode(v.bytes), VALUE, "the input is not changed"); +}); + +test("in wire form a { $bytes } tag is faked as bytes, and the object a { $ } wrap holds is data, its keys faked", () => { + const b64 = btoa(VALUE); + const out = fakeValue({ a: { $bytes: b64 }, w: { $: { $bytes: VALUE } } }, FORMS, true); + assert.equal(atob(out.a.$bytes), fakeOf); + assert.deepEqual(out.w, { $: { $bytes: fakeOf } }, "the wrapped dict's key is data and not a form; its value is faked as text"); +}); + +test("two keys that fake to the same text are refused with the path; two such column names in a list are both kept", () => { + assert.throws(() => fakeValue({ t: { ab12: 1, cd34: 2 } }, FORMS), (e) => e instanceof FakedKeysClash && /at \.t that read the same/.test(e.message)); + assert.deepEqual(fakeValue({ columns: ["ab12", "cd34"] }, FORMS), { columns: ["****", "****"] }); +}); + +test("an answer holding nothing registered is byte for byte what it was", () => { + const v = { columns: ["a", "b"], rows: [["x", 1], [null, 2.5]], nested: { $: { $bytes: "AA==" } } }; + assert.equal(JSON.stringify(fakeValue(v, FORMS, true)), JSON.stringify(v)); +}); + +test("an ml.sh answer's markers are not forms, so the wire's mask leaves them", () => { + const answer = { head: `password = [REDACTED:${NAME}]`, scrubbed: { [NAME]: 1 } }; + assert.deepEqual(wireFake(FORMS)(answer), answer); +}); + +// --- the wire's catch-all --- + +/** Serve one call of `member` with the mask, as sw-ml-wire.ts does. */ +const serve = (member, fake, extra = {}) => serveWireCall({ seq: 1, call: "m", args: [], run: null }, { run: null, members: { m: member }, later: extra.later ?? (() => {}), isOpen: () => true, scrub: async (s) => s, fake, ...extra }); + +test("every wire answer passes the mask: a value, a pointer's label, and the answer after an ask", async () => { + const a = await serve({ run: () => ({ rows: [[VALUE]] }) }, wireFake(FORMS)); + assert.deepEqual(a.value, { rows: [[fakeOf]] }); + const p = await serve({ run: () => wirePointer({ token: "@tool:abc", label: VALUE, size: 9 }) }, wireFake(FORMS)); + assert.equal(p.pointer.label, fakeOf); + let later; + const asked = await serve({ run: () => VALUE, gate: async () => ({ ask: "card", decided: Promise.resolve(true) }) }, wireFake(FORMS), { later: (x) => { later = x; } }); + assert.ok("ask" in asked); + await new Promise((r) => setTimeout(r, 20)); + assert.equal(later.value, fakeOf, "the final answer is faked as the first is"); +}); + +test("forms that cannot be read fail every answer, and none of the value crosses", async () => { + const a = await serve({ run: () => ({ rows: [[VALUE]] }) }, wireFake(null)); + assert.equal(a.error.code, "Failed"); + assert.match(a.error.message, /withheld/); + assert.ok(!JSON.stringify(a).includes(VALUE)); +}); + +test("a client with no run fakes under its own key, which no session hash equals", () => { + assert.equal(fakeKeyOf({ run: "run-1" }, "mlw-1"), "run-1"); + assert.equal(fakeKeyOf({ run: null }, "mlw-1"), "page:mlw-1"); +}); + +// --- structural: every door --- + +test("STRUCTURAL every readStoredColumns caller passes forms, every serveWireCall caller a mask, and each served member of workerReadonlyMl is faked", async () => { + const src = (p) => readFileSync(new URL(`../src/${p}`, import.meta.url), "utf8"); + for (const p of ["background.ts", "sw/sw-run-host.ts", "sw/worker-readonly-ml.ts"]) { + // Each call is one line, and the forms ride it. + const lines = src(p).split("\n").filter((l) => /readStoredColumns\(/.test(l)); + assert.ok(lines.length, p); + for (const l of lines) assert.match(l.slice(l.indexOf("readStoredColumns(")), /\bforms\b/, `${p}: ${l.trim().slice(0, 160)}`); + } + const calls = [...src("sw/sw-ml-wire.ts").matchAll(/serveWireCall\(message, \{([^}]*)\}/g)]; + assert.ok(calls.length >= 1); + for (const c of calls) assert.match(c[1], /fake: wireFake\(forms\)/); + // With no forms, each member that answers what the worker holds answers nothing; the pure ones still answer. + const ml = workerReadonlyMl("https://a.example/", undefined, "", null, true); + const pure = new Set(["pipe", "jsonPath", "schema", "range"]); + for (const [name, fn] of Object.entries(ml)) { + if (pure.has(name)) continue; + await assert.rejects(async () => fn("x"), (e) => e.message === `ml.${name}: ${FORMS_UNREADABLE}`, name); + } + assert.deepEqual(Object.keys(ml).filter((n) => !pure.has(n)).sort(), ["_fetchCached", "capabilities", "config", "getModel", "info", "models", "ps", "serverTools", "settings"]); +}); + +// --- a pointer read, before its pipe --- + +/** A run's resolver over one captured value, as the loop hands it to the host. */ +async function resolverOver(value) { + const tokenStore = new TokenStore(); + tokenStore.note(value); + let deref; + await runAgentLoop("t", { tools: [], maxSteps: () => 1, toolTokens: true, runHash: "r", tokenStore, tokenSink: (fn) => { deref = fn; } }, { + callModel: async () => ({ content: "done", tool_calls: [] }), + runTool: async () => ({ result: "" }), + autoApprove: () => null, + buildMessages: (task) => [{ role: "user", content: task }], + pushAssistant: (m, msg) => m.push({ role: "assistant", ...msg }), + pushToolResult: () => {}, + }); + return deref; +} + +test("code's read of an in-memory pointer is faked before the pipe: a grep for the value finds no line; the label and a table's preview are faked too", async () => { + const out = `line 0\n${VALUE} here\nline 2\n`; + const deref = await resolverOver({ id: "abc1234", tool: "fetch_url", kind: "text", out, label: `the ${VALUE} page`, t: 0, step: 1, + table: { columns: [VALUE], rows: [[VALUE]], shape: [1, 1], dtypes: { [VALUE]: "str" } } }); + const r = await derefWhole("code-fakes-1", deref, "@tool:abc1234", []); + assert.match(r.value, new RegExp(`^line 0\\n${FAKE.source} here\\nline 2\\n$`)); + assert.match(r.meta.label, FAKE); + assert.ok(!JSON.stringify(r.meta).includes(VALUE), JSON.stringify(r.meta)); + assert.equal((await derefWhole("code-fakes-1", deref, "@tool:abc1234", pipeStages(`grep ${VALUE}`))).value, "", "the pipe reads the fake"); + assert.equal((await derefWhole("code-fakes-1", deref, "@tool:abc1234", pipeStages("grep RDCT"))).value.split("\n").length, 1, "and finds the fake where the value was"); + assert.equal(deref("@tool:abc1234").value, out, "the model's read, which passes no mask, is unchanged"); +}); + +test("one value gives one fake throughout a session; another session's is different", async () => { + const [a, b, c] = await Promise.all([sessionFakeForms("code-fakes-2"), sessionFakeForms("code-fakes-2"), sessionFakeForms("code-fakes-3")]); + const at = (forms) => forms.find((f) => f.find === VALUE).fake; + assert.equal(at(a), at(b)); + assert.notEqual(at(a), at(c)); +}); + +test("fakeToken leaves an image's pixels as they are", () => { + const image = `data:image/png;base64,${btoa("ab12ab12")}`; + assert.equal(fakeToken({ id: "x", tool: "t", kind: "text", out: VALUE, image, t: 0, step: 0 }, FORMS).image, image); +}); + +// --- a stored table's columns --- + +test("a stored table's columns reach code faked; forms that cannot be read read nothing", async () => { + const row = await storeHeld(new Blob([`id,token\n1,${VALUE}\n2,filler\n`]), "csv", "t.csv", "code-fakes-4"); + const forms = await sessionFakeForms("code-fakes-4"); + const r = await readStoredColumns(row.key, ["token", "id"], {}, forms); + assert.match(r.columns.token[0], FAKE); + assert.equal(r.columns.token[1], "filler"); + assert.deepEqual(r.columns.id, [1, 2]); + await assert.rejects(readStoredColumns(row.key, ["token"], {}, null), /withheld/); +}); + +// --- a stored table's bytes, in each carrier --- + +const N = 2000, AT = 1500; +const token = Array.from({ length: N }, (_, i) => (i === AT ? VALUE : "filler")); +const order = Array.from({ length: N }, (_, i) => BigInt(i)); +const bufOf = (u8) => u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength); + +test("Arrow, file and stream: string values faked in place, other columns and every offset untouched", async () => { + const t = tableFromArrays({ order: vectorFromArray(order, new Int64()), token: vectorFromArray(token, new Utf8()) }); + for (const kind of ["file", "stream"]) { + const bytes = bufOf(tableToIPC(t, kind)); + const size = bytes.byteLength; + const out = await fakeStoredTable(`arrow-${kind}`, bytes, FORMS); + assert.equal(out.buffer, bytes, "the same bytes, changed where they lie"); + assert.equal(out.buffer.byteLength, size); + const back = tableFromIPC(new Uint8Array(out.buffer)); + assert.equal(back.getChild("token").get(AT), fakeOf, kind); + assert.equal(back.getChild("token").get(0), "filler"); + assert.equal(back.getChild("order").get(AT), BigInt(AT)); + } +}); + +test("Arrow: a dictionary's values and a Binary column are faked; a registered value holding NUL still fakes the column", async () => { + const dict = tableFromArrays({ tok: vectorFromArray(token, new Dictionary(new Utf8(), new Int32())) }); + const d = await fakeStoredTable("arrow-stream", bufOf(tableToIPC(dict, "stream")), FORMS); + assert.equal(tableFromIPC(new Uint8Array(d.buffer)).getChild("tok").get(AT), fakeOf); + const bin = tableFromArrays({ blob: vectorFromArray(token.map((x) => new TextEncoder().encode(x)), new Binary()) }); + const b = await fakeStoredTable("arrow-file", bufOf(tableToIPC(bin, "file")), FORMS); + assert.equal(new TextDecoder().decode(tableFromIPC(new Uint8Array(b.buffer)).getChild("blob").get(AT)), fakeOf); + const nul = [...FORMS, { name: "NUL", index: 0, find: "with\u0000nul" }]; + const t = tableFromArrays({ token: vectorFromArray(token, new Utf8()) }); + const n = await fakeStoredTable("arrow-file", bufOf(tableToIPC(t, "file")), nul); + const col = tableFromIPC(new Uint8Array(n.buffer)).getChild("token"); + assert.equal(col.get(AT), fakeOf); + assert.equal(col.length, N); +}); + +test("Arrow: a column named with a registered value is refused, naming it by its fake", async () => { + const t = tableFromArrays({ [VALUE]: vectorFromArray(["a"], new Utf8()) }); + await assert.rejects(fakeStoredTable("arrow-file", bufOf(tableToIPC(t, "file")), FORMS), (e) => e instanceof TableNotFaked && e.message.includes(fakeOf) && !e.message.includes(VALUE)); +}); + +test("Arrow: a value split across two adjacent cells is faked in neither, and no cell is changed by its neighbour", async () => { + const half = VALUE.length / 2; + const cells = ["filler", VALUE.slice(0, half), VALUE.slice(half), "filler"]; + const t = tableFromArrays({ token: vectorFromArray(cells, new Utf8()) }); + const out = await fakeStoredTable("arrow-file", bufOf(tableToIPC(t, "file")), FORMS); + assert.deepEqual([...tableFromIPC(new Uint8Array(out.buffer)).getChild("token")], cells, "each cell as a read of it alone, which matches nothing"); + const whole = tableFromArrays({ token: vectorFromArray(["x", VALUE, "y"], new Utf8()) }); + const w = await fakeStoredTable("arrow-file", bufOf(tableToIPC(whole, "file")), FORMS); + assert.deepEqual([...tableFromIPC(new Uint8Array(w.buffer)).getChild("token")], ["x", fakeOf, "y"], "the neighbours of a faked cell are untouched"); +}); + +test("Arrow: a FixedSizeBinary column is faked value by value; metadata holding a value refuses the read", async () => { + const { FixedSizeBinary, Field, Schema, Table, RecordBatch, makeData, Struct } = await import("apache-arrow"); + const width = new TextEncoder().encode(VALUE).length; + const values = new Uint8Array(width * 3); + values.set(new TextEncoder().encode("x".repeat(width)), 0); + values.set(new TextEncoder().encode(VALUE), width); + values.set(new TextEncoder().encode("y".repeat(width)), width * 2); + const type = new FixedSizeBinary(width); + const field = new Field("fsb", type, false); + const ipcOf = (schema) => bufOf(tableToIPC(new Table([new RecordBatch(schema, makeData({ type: new Struct(schema.fields), length: 3, nullCount: 0, children: [makeData({ type, length: 3, nullCount: 0, data: values })] }))]), "file")); + const out = await fakeStoredTable("arrow-file", ipcOf(new Schema([field])), FORMS); + const col = tableFromIPC(new Uint8Array(out.buffer)).getChild("fsb"); + assert.equal(new TextDecoder().decode(col.get(1)), fakeOf); + assert.equal(new TextDecoder().decode(col.get(0)), "x".repeat(width)); + await assert.rejects(fakeStoredTable("arrow-file", ipcOf(new Schema([field], new Map([["note", `a ${VALUE}`]]))), FORMS), (e) => e instanceof TableNotFaked && /metadata/.test(e.message) && !e.message.includes(VALUE)); + const tagged = new Field("fsb", type, false, new Map([[VALUE, "1"]])); + await assert.rejects(fakeStoredTable("arrow-file", ipcOf(new Schema([tagged])), FORMS), (e) => e instanceof TableNotFaked && /metadata/.test(e.message)); +}); + +test("Parquet: key-value metadata holding a value refuses the read, even when no cell holds one", async () => { + const pq = parquetWriteBuffer({ columnData: [{ name: "token", data: ["filler"], type: "STRING" }], kvMetadata: [{ key: "note", value: `a ${VALUE}` }] }); + await assert.rejects(fakeStoredTable("parquet", pq, FORMS), (e) => e instanceof TableNotFaked && /metadata/.test(e.message) && !e.message.includes(VALUE)); +}); + +test("Parquet: handed over as it is when no cell holds a value; as an Arrow stream, faked, when one does", async () => { + const clean = parquetWriteBuffer({ columnData: [{ name: "order", data: order, type: "INT64" }, { name: "token", data: token.map(() => "filler"), type: "STRING" }] }); + const c = await fakeStoredTable("parquet", clean, FORMS); + assert.deepEqual([c.format, c.buffer], ["parquet", clean]); + const held = parquetWriteBuffer({ columnData: [ + { name: "order", data: order, type: "INT64" }, { name: "ratio", data: token.map((_, i) => i / 4), type: "DOUBLE" }, + { name: "flag", data: token.map((_, i) => i === AT), type: "BOOLEAN" }, { name: "token", data: token, type: "STRING" }, + { name: "blob", data: token.map((x) => new TextEncoder().encode(x)), type: "BYTE_ARRAY" }, + ] }); + const h = await fakeStoredTable("parquet", held, FORMS); + assert.equal(h.format, "arrow-stream"); + const back = tableFromIPC(new Uint8Array(h.buffer)); + assert.equal(back.numRows, N); + assert.equal(back.getChild("token").get(AT), fakeOf); + assert.equal(new TextDecoder().decode(back.getChild("blob").get(AT)), fakeOf); + assert.equal(back.getChild("order").get(AT), BigInt(AT)); + assert.equal(back.getChild("ratio").get(AT), AT / 4); + assert.equal(back.getChild("flag").get(AT), true); + assert.equal(back.getChild("flag").get(0), false); +}); + +test("Parquet: a Decimal column is refused by name and type when a cell holds a value, and served as it is when none does", async () => { + const typed = (labels) => parquetWriteBuffer({ + columnData: [{ name: "amount", data: labels.map(() => 123456789012345678901234567890n) }, { name: "label", data: labels }], + schema: [{ name: "root", num_children: 2 }, + { name: "amount", type: "FIXED_LEN_BYTE_ARRAY", type_length: 16, converted_type: "DECIMAL", scale: 10, precision: 38, repetition_type: "REQUIRED" }, + { name: "label", type: "BYTE_ARRAY", converted_type: "UTF8", repetition_type: "REQUIRED" }], + }); + await assert.rejects(fakeStoredTable("parquet", typed(token), FORMS), (e) => e instanceof TableNotFaked && /column amount is DECIMAL/.test(e.message)); + const clean = typed(token.map(() => "filler")); + assert.equal((await fakeStoredTable("parquet", clean, FORMS)).buffer, clean); +}); + +test("delimited text is faked in place", async () => { + const bytes = bufOf(new TextEncoder().encode(`a,b\n1,${VALUE}\n`)); + const out = await fakeStoredTable("csv", bytes, FORMS); + assert.equal(new TextDecoder().decode(out.buffer), `a,b\n1,${fakeOf}\n`); +}); + +// --- upgrade --- + +test("UPGRADE: a value stored before this is read faked, and a resolver called the old way (no mask) still answers", async () => { + const row = await storeHeld(new Blob([`id,token\n1,${VALUE}\n`]), "csv", "old.csv", "code-fakes-5"); + const r = await readStoredColumns(row.key, ["token"], {}, await sessionFakeForms("code-fakes-5")); + assert.match(r.columns.token[0], FAKE); + const deref = await resolverOver({ id: "def5678", tool: "fetch_url", kind: "text", out: VALUE, t: 0, step: 1 }); + assert.equal(deref("@tool:def5678").value, VALUE); + register([{ name: NAME, value: VALUE }]); +}); diff --git a/tests/dereference.test.mjs b/tests/dereference.test.mjs index c89dede00..38c6f4bed 100644 --- a/tests/dereference.test.mjs +++ b/tests/dereference.test.mjs @@ -836,7 +836,7 @@ test("a read-only survey in the worker reads an attached file: its pages by pipe const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); const { evalReadonlyInWorker } = await import("../src/sw/sw-readonly.ts"); const { deref, pdf } = await heldFiles("deref-file-d"); - const ml = workerReadonlyMl("https://a.example/", deref, "deref-file-d"); + const ml = workerReadonlyMl("https://a.example/", deref, "deref-file-d", []); const r = await evalReadonlyInWorker({ js: `const v = await ml.dereference("@file:${pdf.id}", { pipe: "pages 3 | grep revenue" }); return [v.text, v.file.pages, v.file.name, v.type]` }, { ml }); assert.equal(r.kind, "answered", JSON.stringify(r)); assert.match(r.result, /revenue 30/); diff --git a/tests/e2e/redteam-code-reads-fakes.spec.mjs b/tests/e2e/redteam-code-reads-fakes.spec.mjs new file mode 100644 index 000000000..671b1a12d --- /dev/null +++ b/tests/e2e/redteam-code-reads-fakes.spec.mjs @@ -0,0 +1,672 @@ +// redteam-code-reads-fakes.spec.mjs — RED TEAM (e4) for ruling 133, written BEFORE the code: what the worker +// serves to code reaches it with each registered value replaced by its same-length session fake (RDCT…), so a cell +// that prints the value, reverses it, splits it or encodes it transforms the FAKE and never the value. Every row +// here fails while the worker still hands code the real bytes, and passes once the fake is what arrives. +// +// The claim each row makes is about what the CODE holds: the printed value is the fake (RDCT…, the value's +// length), and neither it nor its reversal carries a window of the real value. The input's own fixture is asserted +// first (the tool reached it, the far row reads), so a row whose setup broke fails in its setup lines rather than +// hiding behind the expected one. +// +// Code kinds, as the spec's table names them: a worker-built run's `python_exec` (the wire), a page-built run's +// python tool (hoisted rows), a page-started `ml.pythonExec`, an approved `exec` naming a pointer (an isolated +// world, which reads through `derefWhole` and `readStoredColumns`), and a page-built run's `exec` (the page's own +// main world, whose pre-reads are the resolver's preview). Each reads the same registered value from a different +// door. +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import { tableFromArrays, tableToIPC, vectorFromArray, Utf8, Binary, Int64 } from "apache-arrow"; +import { parquetWriteBuffer } from "hyparquet-writer"; +import { launchExtension, configureExtension, waitForMl } from "./harness.mjs"; +import { startFakeLlm } from "./fake-llm.mjs"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const HAS_PYODIDE = existsSync(join(HERE, "../../dist/pyodide/pyodide.mjs")); + +const SECRET = "FAKE_SECRET_Q7x2Lm9Z"; +/** The fake every row looks for: ruling 101's prefix, the value's own length. */ +const FAKE_PREFIX = "RDCT"; +const BIG_ROWS = 300_000; +/** Past MAX_TABLE_ROWS (200,000): only the store can answer this row, so its read proves the fake sits at the store. */ +const SECRET_ROW = 250_000; +const SECRET_BYTES = new TextEncoder().encode(SECRET); + +test.describe.configure({ mode: "default", timeout: 300_000 }); + +/** Rows of the table fixtures: the same data in every carrier, the value at one far row. */ +function bigRows() { + const order = new Array(BIG_ROWS); + const region = new Array(BIG_ROWS); + const token = new Array(BIG_ROWS); + for (let i = 0; i < BIG_ROWS; i++) { + order[i] = BigInt(i); + region[i] = ["north", "south", "east", "west"][i % 4]; + token[i] = i === SECRET_ROW ? SECRET : "filler"; + } + return { order, region, token }; +} + +/** The fixture files, built once. */ +function buildFixtures() { + const { order, region, token } = bigRows(); + const csv = ["order,region,token"]; + for (let i = 0; i < BIG_ROWS; i++) csv.push(`${order[i]},${region[i]},${token[i]}`); + const table = tableFromArrays({ + order: vectorFromArray(order, new Int64()), + region: vectorFromArray(region, new Utf8()), + token: vectorFromArray(token, new Utf8()), + }); + const parquet = Buffer.from(parquetWriteBuffer({ columnData: [ + { name: "order", data: order, type: "INT64" }, + { name: "region", data: region, type: "STRING" }, + { name: "token", data: token, type: "STRING" }, + ] })); + // A stored TEXT whose value sits on one far line: a grep must find nothing, the other lines must read the same. + const textLines = new Array(20_000); + for (let i = 0; i < textLines.length; i++) textLines[i] = i === 10_000 ? `${SECRET} on one line` : `line ${i}`; + // A short text past the preview cut, with the value in the PREVIEW the page's main world gets. + const previewText = `${SECRET}\n` + "preview filler line\n".repeat(400); + // Every Parquet primitive the decoder reads, plus a DECIMAL past float64's precision: a type the read must carry + // losslessly or refuse, naming the column. + const typed = Buffer.from(parquetWriteBuffer({ + columnData: [ + { name: "order", data: order }, + { name: "flag", data: token.map((_, i) => i === SECRET_ROW) }, + { name: "ratio", data: token.map((_, i) => (i === SECRET_ROW ? 0.5 : 0.25)) }, + { name: "amount", data: token.map(() => 123456789012345678901234567890n) }, + { name: "label", data: token }, + ], + schema: [ + { name: "root", num_children: 5 }, + { name: "order", type: "INT64", repetition_type: "REQUIRED" }, + { name: "flag", type: "BOOLEAN", repetition_type: "REQUIRED" }, + { name: "ratio", type: "DOUBLE", repetition_type: "REQUIRED" }, + { name: "amount", type: "FIXED_LEN_BYTE_ARRAY", type_length: 16, converted_type: "DECIMAL", scale: 10, precision: 38, repetition_type: "REQUIRED" }, + { name: "label", type: "BYTE_ARRAY", converted_type: "UTF8", repetition_type: "REQUIRED" }, + ], + })); + // A binary column: Parquet BYTE_ARRAY with no string annotation, and the same as an Arrow Binary column. + const blob = token.map((t) => new TextEncoder().encode(t)); + const binaryParquet = Buffer.from(parquetWriteBuffer({ columnData: [ + { name: "order", data: order, type: "INT64" }, + { name: "blob", data: blob, type: "BYTE_ARRAY" }, + ] })); + const binaryArrow = tableFromArrays({ + order: vectorFromArray(order, new Int64()), + blob: vectorFromArray(blob, new Binary()), + }); + return { + csv: csv.join("\n"), + arrowFile: Buffer.from(tableToIPC(table, "file")), + arrowStream: Buffer.from(tableToIPC(table, "stream")), + parquet, + typed, + binaryParquet, + binaryArrow: Buffer.from(tableToIPC(binaryArrow, "file")), + text: textLines.join("\n"), + previewText, + }; +} + +async function startDataServer(fx) { + const pageHtml = `fake probe` + + `
token
${SECRET}
`; + const routes = { + "/probe.html": [pageHtml, "text/html"], + "/secret.csv": [`id,token\n1,${SECRET}\n`, "text/csv"], + "/big.csv": [fx.csv, "text/csv"], + "/big.arrow": [fx.arrowFile, "application/vnd.apache.arrow.file"], + "/big.arrows": [fx.arrowStream, "application/vnd.apache.arrow.stream"], + "/big.parquet": [fx.parquet, "application/octet-stream"], + "/typed.parquet": [fx.typed, "application/octet-stream"], + "/binary.parquet": [fx.binaryParquet, "application/octet-stream"], + "/binary.arrow": [fx.binaryArrow, "application/vnd.apache.arrow.file"], + "/big.txt": [fx.text, "text/plain"], + "/preview.txt": [fx.previewText, "text/plain"], + }; + const srv = createServer((req, res) => { + const hit = routes[(req.url || "/").split("?")[0]]; + if (!hit) { res.writeHead(404); return res.end("no"); } + res.writeHead(200, { "content-type": hit[1], "cache-control": "no-store" }); + res.end(hit[0]); + }); + await new Promise((r) => srv.listen(0, "127.0.0.1", r)); + return { url: `http://127.0.0.1:${srv.address().port}`, stop: () => new Promise((r) => srv.close(r)) }; +} + +let ext, bare, fake, data, page, tabId, barePage, bareTab; + +async function configure(E, { forms = true } = {}) { + await configureExtension(E.sw, { + chatUrl: fake.url, apiKey: "", apiFormat: "openai", model: "fake-model", + modelFilter: "", debugMode: "off", autoApprovePython: true, autoApproveReadonly: true, + pageApprovalDomains: [new URL(data.url).origin], + }); + if (forms) await E.sw.evaluate((v) => chrome.storage.local.set({ ml_secret_registry: [{ name: "PROBE_SECRET", value: v }] }), SECRET); + await new Promise((r) => setTimeout(r, 500)); +} + +/** Resolve every approval the run raises, until it has produced `n` answers or the deadline passes. */ +async function drainApprovals(E, n, before, timeout) { + const deadline = Date.now() + timeout; + while (Date.now() < deadline && fake.calls().length - before < n) { + for (const g of await E.sw.evaluate(() => globalThis.__mlApprovals.list())) { + await E.sw.evaluate((key) => globalThis.__mlApprovals.resolve(key, true), g.key); + } + await new Promise((r) => setTimeout(r, 200)); + } +} + +/** + * Drive one run the WORKER built and return the TOOL messages the model received, in order. A worker-built run's + * `python_exec` and `ml.table` are the worker's tools and the wire; its `exec` naming a pointer runs in an isolated + * world. + */ +async function workerRun(steps, { E = ext, id = tabId, timeout = 150_000 } = {}) { + const before = fake.calls().length; + fake.setScript([...steps, { content: "done" }]); + await E.sw.evaluate(({ id: tab }) => globalThis.__mlStartUserRunForTest(tab, { task: "fake probe", hud: "quiet", surface: "overlay" }, { approvalRouting: "both" }), { id }); + await drainApprovals(E, steps.length + 1, before, timeout); + const msgs = fake.calls().at(-1)?.messages ?? []; + return msgs.filter((m) => m.role === "tool" && typeof m.content === "string").map((m) => m.content).slice(-steps.length); +} + +/** Drive one run the PAGE built: its python tool runs the cell on the page, its `exec` runs in the main world. */ +async function pageRun(steps, { target = page, E = ext, timeout = 150_000 } = {}) { + const before = fake.calls().length; + fake.setScript([...steps, { content: "done" }]); + const run = target.evaluate(() => window.ml.agent("Probe.", { + env: false, approvalRouting: "both", toolTokens: true, extraTools: [window.ml.pythonTool()], + // The page owns its own run, so it answers its own gates here: what this file probes is what the worker + // SERVES the cell once it runs, not who signed the card. + approve: async () => ({ approved: true }), + })); + await drainApprovals(E, steps.length + 1, before, timeout); + await run.catch(() => {}); + const msgs = fake.calls().at(-1)?.messages ?? []; + return msgs.filter((m) => m.role === "tool" && typeof m.content === "string").map((m) => m.content).slice(-steps.length); +} + +/** Every 8-character window of `s`, its 8-character reversal, and `s` itself. */ +function forbidden(s) { + const out = [s, [...s].reverse().join("").slice(0, 8)]; + for (let i = 0; i + 8 <= s.length; i++) out.push(s.slice(i, i + 8)); + return out; +} + +/** The value printed after `prefix`, on a line of the cell's output. */ +function printed(content, prefix) { + const m = new RegExp(`^${prefix}:([^\\n]*)$`, "m").exec(content); + return m ? m[1] : null; +} + +/** A cell reading the 300,000-row table must answer ATTACHED: a detached one carries no stdout, which a row would read as an unexplained setup failure. */ +function assertAttached(content, label) { + expect(String(content), `setup (${label}): the cell answered attached, not detached; it said: ${String(content).slice(0, 400)}`).not.toMatch(/^\s*Detached:/); +} + +/** + * What code must hold: an RDCT fake of the value's length, and neither the print nor its reversal carrying any + * window of the real value. + */ +function assertFake(content, prefix, label, value = SECRET) { + const v = printed(content, prefix); + expect(v, `${label}: the cell printed ${prefix}; it answered ${JSON.stringify(String(content).slice(0, 400))}`).not.toBeNull(); + expect(v, `${label}: the value reaches code as an RDCT fake, got ${JSON.stringify(v)}`).toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(v.length, `${label}: the fake keeps the value's length`).toBe(new TextEncoder().encode(value).length); + const rev = printed(content, `${prefix}R`); + expect(rev, `${label}: the cell printed ${prefix}R`).not.toBeNull(); + for (const w of forbidden(value)) { + expect(v, `${label}: the print carries no window of the value`).not.toContain(w); + expect(rev, `${label}: the reversal carries no window of the value`).not.toContain(w); + } + expect(content, `${label}: the raw value never reaches the model`).not.toContain(value); +} + +test.beforeAll(async () => { + fake = await startFakeLlm({ model: "fake-model" }); + data = await startDataServer(buildFixtures()); + ext = await launchExtension(); + await configure(ext); + bare = await launchExtension(); // no registry: row 3's "with no forms" and row 9's control + await configure(bare, { forms: false }); + page = await ext.context.newPage(); + await page.goto(`${data.url}/probe.html`); + await waitForMl(page); + tabId = await ext.sw.evaluate(async (u) => (await chrome.tabs.query({})).find((t) => t.url?.startsWith(u))?.id, data.url); + barePage = await bare.context.newPage(); + await barePage.goto(`${data.url}/probe.html`); + await waitForMl(barePage); + bareTab = await bare.sw.evaluate(async (u) => (await chrome.tabs.query({})).find((t) => t.url?.startsWith(u))?.id, data.url); +}); + +test.afterAll(async () => { + await ext?.close(); + await bare?.close(); + await fake?.stop(); + await data?.stop(); +}); + +// --- row 1: each input, through the worker's wire ------------------------------------------------------------- + +test("1a a page's own table reaches a worker cell as the fake", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + expect(await page.evaluate((v) => document.querySelector("table").innerText.includes(v), SECRET), "setup: the page's table holds the value").toBe(true); + const [py] = await workerRun([{ tool: "python_exec", args: { code: + `df = ml.table("table")\nv = str(df["token"].iloc[0])\nprint("V:" + v)\nprint("VR:" + v[::-1])` } }]); + assertFake(py, "V", "1a"); +}); + +test("1b a URL in the run's fetch cache reaches a worker cell as the fake", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/secret.csv`; + const [fetched, py] = await workerRun([ + { tool: "fetch_url", args: { url } }, + { tool: "python_exec", args: { code: + `df = ml.table(${JSON.stringify(url)})\nv = str(df["token"].iloc[0])\nprint("V:" + v)\nprint("VR:" + v[::-1])` } }, + ]); + expect(fetched, "setup: the fetch reached the tool").toContain("secret.csv"); + assertFake(py, "V", "1b"); +}); + +test("1c a stored whole past the preview reaches a worker cell as the fake (row 250,000 of 300,000)", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.csv`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "big" } }, + { tool: "python_exec", args: { code: + `df = ml.table('@tool:"big"')\nv = str(df["token"].iloc[${SECRET_ROW}])\no = str(df["order"].iloc[${SECRET_ROW}])\n` + + `print("V:" + v)\nprint("VR:" + v[::-1])\nprint("O:" + o)`, expect_ms: 120000 } }, + ]); + assertAttached(py, "1c"); + expect(printed(py, "O"), "setup: the far row's other column reads as the fixture").toBe(String(SECRET_ROW)); + assertFake(py, "V", "1c"); +}); + +test("1d a stored WHOLE TEXT through an awaited ml.dereference reaches a worker cell as the fake", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.txt`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "the text" } }, + { tool: "python_exec", args: { code: + `t = (await ml.dereference('@tool:"the text"'))["text"]\nn = t.find(" on one line")\n` + + `v = t[n-${SECRET.length}:n] if n > 0 else "NOTFOUND"\n` + + `print("V:" + v)\nprint("VR:" + v[::-1])\nprint("H:" + t.split("\\n")[0])` } }, + ]); + expect(printed(py, "H"), `setup: the whole text was read, not the preview; it answered ${JSON.stringify(String(py).slice(0, 300))}`).toBe("line 0"); + assertFake(py, "V", "1d"); +}); + +test("1e the read-only members' strings reach a worker cell as the fake (ps names the configured server)", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + fake.setResident([{ model: fake.url, name: fake.url, size: 1e9, size_vram: 1e9, context_length: 4096, expires_at: null }]); + const [py] = await workerRun([{ tool: "python_exec", args: { code: + `ps = await ml.ps()\nv = str(ps[0]["model"])\n` + + `print("V:" + v)\nprint("VR:" + v[::-1])\nprint("W:" + v)` } }]); + assertFake(py, "V", "1e", fake.url); + expect(printed(py, "W"), "one value gives one fake within a cell").toBe(printed(py, "V")); +}); + +test("1f a page-BUILT run's python tool reads hoisted rows as the fake", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const [py] = await pageRun([{ tool: "python_exec", args: { code: + `df = ml.table("table")\nv = str(df["token"].iloc[0])\nprint("V:" + v)\nprint("VR:" + v[::-1])`, mode: "readonly" } }]); + assertFake(py, "V", "1f"); +}); + +test("1g an approved exec in an isolated world reads a pointer's value and columns as the fake", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.csv`; + const [, exec] = await workerRun([ + { tool: "fetch_url", args: { url, token: "iso big" } }, + { tool: "exec", args: { js: + `const t = @tool:"iso big".table;\nconst c = await t.col("token");\n` + + `const v = String(c[${SECRET_ROW}]);\nreturn "V:" + v + "|VR:" + [...v].reverse().join("") + "|O:" + c.length` } }, + ]); + // The tool result is the returned string (possibly JSON-quoted): read the field out of it. + const text = exec.replace(/\\"/g, '"'); + expect(text, "setup: the exec's column read answered with the whole column").toContain(`|O:${BIG_ROWS}`); + const v = /V:([^|"\\]*)/.exec(text)?.[1]; + expect(v, `setup: the exec printed its value: ${text.slice(0, 300)}`).toBeTruthy(); + expect(v, "1g: an isolated exec holds the fake").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(v.length, "1g: the fake keeps the value's length").toBe(SECRET.length); + for (const w of forbidden(SECRET)) expect(text, "1g: no window of the value crosses").not.toContain(w); +}); + +test("1h (stated limit) a PAGE-hosted run's pointers are not faked: its main world reads the raw value, and the same read in a WORKER-hosted run is the fake", async () => { + // SECRET_HANDLES.md, "A page-hosted run's pointers are not faked": a run whose loop lives in the page keeps its + // pointers in the page, holding what the page was answered (a fetch_url's data to a page is not scrubbed). So code + // the page's main world runs reads them unfaked. The worker's scrub still stands between that read and the model: + // what the model is sent carries no window of the value. + const url = `${data.url}/preview.txt`; + const ask = (token) => `const t = @tool:${JSON.stringify(token)}.text;\n` + + `const hit = t.includes(${JSON.stringify(SECRET)});\n` + + `const i = hit ? t.indexOf(${JSON.stringify(SECRET)}) : -1;\n` + + `return "RAW:" + (hit ? "yes" : "no") + ":" + (i >= 0 ? t.slice(i, i + ${SECRET.length}) : "NONE")`; + const [, exec] = await pageRun([ + { tool: "fetch_url", args: { url, token: "preview text" } }, + { tool: "exec", args: { js: ask("preview text") } }, + ]); + const text = exec.replace(/\\"/g, '"'); + expect(text, `setup: the page's exec answered: ${text.slice(0, 300)}`).toContain("RAW:yes"); + expect(text, "1h (stated limit): the page-hosted run's main world holds the value — the test's premise, which the spec states").not.toContain(`RAW:yes:${SECRET}`); + for (const w of forbidden(SECRET)) expect(text, "1h: what reaches the model carries no window of the value, however raw the page's world").not.toContain(w); + + // Beside it: the same read in a run the worker hosts. Its exec (an isolated world, an approved page) is served the + // FAKE, so the value is not even findable there. + const [, wExec] = await workerRun([ + { tool: "fetch_url", args: { url, token: "worker text" } }, + { tool: "exec", args: { js: ask("worker text") } }, + ]); + const wText = wExec.replace(/\\"/g, '"'); + expect(wText, `setup: the worker-hosted exec answered: ${wText.slice(0, 300)}`).toContain("RAW:no"); + expect(wText, "1h: a worker-hosted run's code reads the fake, so the value is not in what it reads").not.toContain(SECRET); +}); + +// --- row 2: a stored table in each carrier, read past the preview ----------------------------------------------- + +for (const [label, path] of [["delimited", "big.csv"], ["an Arrow FILE", "big.arrow"], ["an Arrow STREAM", "big.arrows"], ["Parquet", "big.parquet"]]) { + test(`2 a stored table as ${label} is faked past the preview, and its other columns are untouched`, async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/${path}`; + const token = `fmt ${label}`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token } }, + { tool: "python_exec", args: { code: + `df = ml.table('@tool:${JSON.stringify(token)}')\n` + + `v = str(df["token"].iloc[${SECRET_ROW}])\n` + + `print("V:" + v)\nprint("VR:" + v[::-1])\n` + + `print("O:" + str(df["order"].iloc[${SECRET_ROW}]))\nprint("R:" + str(df["region"].iloc[${SECRET_ROW}]))\n` + + `print("N:" + str(df.shape[0]))`, expect_ms: 120000 } }, + ]); + assertAttached(py, `2 ${label}`); + expect(printed(py, "O"), `setup (${label}): the far row reads`).toBe(String(SECRET_ROW)); + expect(printed(py, "R"), `setup (${label}): the other string column is the fixture's`).toBe("north"); + expect(printed(py, "N"), `setup (${label}): every row crossed`).toBe(String(BIG_ROWS)); + assertFake(py, "V", `2 ${label}`); + }); +} + +// --- row 3: a Parquet column of each type, carried losslessly or refused by name -------------------------------- + +/** The Decimal as the fixture's unscaled integer over 10^10, written out. */ +const DECIMAL_TEXT = "12345678901234567890.1234567890"; + +test("3 a typed Parquet (Decimal past float64's precision) is served exactly or refused naming the column and type", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/typed.parquet`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "typed" } }, + { tool: "python_exec", args: { code: + `try:\n df = ml.table('@tool:"typed"')\n` + + ` print("OK:" + str(df.shape[0]))\n` + + ` print("F:" + str(df["flag"].iloc[${SECRET_ROW}]))\n` + + ` print("D:" + str(df["ratio"].iloc[${SECRET_ROW}]))\n` + + ` print("M:" + str(df["amount"].iloc[${SECRET_ROW}]))\n` + + ` print("L:" + str(df["label"].iloc[${SECRET_ROW}]))\nexcept Exception as e:\n print("ERR:" + str(e).replace("\\n", " "))`, expect_ms: 120000 } }, + ]); + assertAttached(py, "3"); + expect(py, "setup: the cell answered one way or the other").toMatch(/^(OK|ERR):/m); + if (printed(py, "OK") == null) { + // Refused: the column and its type are named, and nothing crosses. + const err = printed(py, "ERR") ?? ""; + expect(err, "3: the refusal names the column").toMatch(/amount/i); + expect(err, "3: the refusal names the type").toMatch(/decimal/i); + expect(py, "3: no text crosses a refused read").not.toContain(SECRET); + return; + } + // Served: every column is the source's value, exactly, and the string column is the fake. + expect(printed(py, "OK"), "3: every row crossed").toBe(String(BIG_ROWS)); + expect(printed(py, "F"), "3: the boolean is exact").toBe("True"); + expect(printed(py, "D"), "3: the double is exact").toBe("0.5"); + expect(printed(py, "M"), "3: the Decimal keeps every digit").toBe(DECIMAL_TEXT); + assertFake(py, "L", "3"); +}); + +test("3b the same typed Parquet in a session with NO forms reads as it is, every column exact", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/typed.parquet`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "typed bare" } }, + { tool: "python_exec", args: { code: + `df = ml.table('@tool:"typed bare"')\n` + + `print("M:" + str(df["amount"].iloc[${SECRET_ROW}]))\n` + + `print("L:" + str(df["label"].iloc[${SECRET_ROW}]))\nprint("N:" + str(df.shape[0]))`, expect_ms: 120000 } }, + ], { E: bare, id: bareTab }); + assertAttached(py, "3b"); + expect(printed(py, "N"), "setup: every row crossed with no forms").toBe(String(BIG_ROWS)); + expect(printed(py, "M"), "3b: the Decimal keeps every digit").toBe(DECIMAL_TEXT); + expect(printed(py, "L"), "3b: with no forms the string is the value itself").toBe(SECRET); +}); + +// --- row 4: binary columns, and a registered value holding U+0000 ---------------------------------------------- + +for (const [label, path] of [["a Parquet BYTE_ARRAY column", "binary.parquet"], ["an Arrow Binary column", "binary.arrow"]]) { + test(`4 a ${label} is faked value by value, other rows untouched`, async ({}, testInfo) => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/${path}`; + const token = `bin ${label}`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token } }, + { tool: "python_exec", args: { code: + `df = ml.table('@tool:${JSON.stringify(token)}')\n` + + `b = bytes(df["blob"].iloc[${SECRET_ROW}])\n` + + `o = bytes(df["blob"].iloc[0])\n` + + `print("V:" + b.decode("latin-1").replace("\\n", " "))\n` + + `print("L:" + str(len(b)))\nprint("O:" + o.decode("latin-1"))\nprint("N:" + str(df.shape[0]))`, expect_ms: 120000 } }, + ]); + // CI keeps only the page snapshot of a failed row: carry the cell's own output with it, and in each setup + // message, so a row that printed nothing says why (a deadline, a refusal, an exception in the cell). + await testInfo.attach("cell", { body: String(py), contentType: "text/plain" }); + assertAttached(py, label); + const cell = (() => { const s = String(py); return s.length > 4000 ? `${s.slice(0, 4000)}…[${s.length} chars]` : s; })(); + expect(printed(py, "O"), `setup (${label}): another row reads as the fixture; the cell said: ${cell}`).toBe("filler"); + expect(printed(py, "N"), `setup (${label}): every row crossed; the cell said: ${cell}`).toBe(String(BIG_ROWS)); + expect(printed(py, "L"), `setup (${label}): the cell is a byte string; the cell said: ${cell}`).toBe(String(SECRET_BYTES.length)); + const v = printed(py, "V") ?? ""; + expect(v, "4: the bytes reach code as the fake").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(v.length, "4: the fake keeps the byte length").toBe(SECRET_BYTES.length); + for (const w of forbidden(SECRET)) expect(v, "4: no window of the value crosses").not.toContain(w); + expect(py, "4: the value never reaches the model").not.toContain(SECRET); + }); +} + +test("4b a registered value holding U+0000: every string is still faked, and the cell count is unchanged", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.csv`; + try { + await ext.sw.evaluate((v) => chrome.storage.local.set({ ml_secret_registry: [ + { name: "PROBE_SECRET", value: v }, + { name: "PROBE_NUL", value: "with\u0000nul" }, + ] }), SECRET); + await new Promise((r) => setTimeout(r, 500)); + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "nul big" } }, + { tool: "python_exec", args: { code: + `df = ml.table('@tool:"nul big"')\nv = str(df["token"].iloc[${SECRET_ROW}])\n` + + `print("V:" + v)\nprint("VR:" + v[::-1])\n` + + `print("N:" + str(df.shape[0]))\nprint("R:" + str(df["region"].iloc[${SECRET_ROW}]))`, expect_ms: 120000 } }, + ]); + assertAttached(py, "4b"); + expect(printed(py, "N"), "setup: the split kept every cell").toBe(String(BIG_ROWS)); + expect(printed(py, "R"), "setup: the other column is the fixture's").toBe("north"); + assertFake(py, "V", "4b"); + } finally { + await ext.sw.evaluate((v) => chrome.storage.local.set({ ml_secret_registry: [{ name: "PROBE_SECRET", value: v }] }), SECRET); + } +}); + +// --- row 5: derefWhole of a stored text ----------------------------------------------------------------------- + +test("5 a stored text read whole greps empty for the value, and its lines agree with the unfaked text", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.txt`; + const [, py] = await workerRun([ + { tool: "fetch_url", args: { url, token: "lines text" } }, + { tool: "python_exec", args: { code: + `t = (await ml.dereference('@tool:"lines text"'))["text"]\n` + + `print("G:" + ("found" if ${JSON.stringify(SECRET)} in t else "empty"))\n` + + `print("A:" + t.split("\\n")[0])\nprint("B:" + t.split("\\n")[2])\n` + + `print("C:" + str(len(t.split("\\n"))))` } }, + ]); + expect(printed(py, "A"), "setup: the text read starts where the fixture does").toBe("line 0"); + expect(printed(py, "B"), "setup: its third line is the fixture's").toBe("line 2"); + expect(printed(py, "C"), "setup: every line crossed").toBe("20000"); + expect(printed(py, "G"), "5: a grep of the value finds no line").toBe("empty"); + expect(py, "5: no window of the value crosses").not.toContain(SECRET); +}); + +// --- row 7: forms unreadable: each read fails closed ----------------------------------------------------------- + +test("7 unreadable forms: every input fails, and no text of the value crosses", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const url = `${data.url}/big.txt`; + try { + // A fault at the fake's derivation: sign rejects, so no session can have forms. Changing the registry forgets + // every session's cached fakes, so the next read derives again and meets the fault. Restored in `finally`. + await ext.sw.evaluate((v) => chrome.storage.local.set({ ml_secret_registry: [ + { name: "PROBE_SECRET", value: v }, + { name: "PROBE_FAULT", value: "fault-surface-value" }, + ] }), SECRET); + await new Promise((r) => setTimeout(r, 300)); + const took = await ext.sw.evaluate(() => { + globalThis.__origSign = crypto.subtle.sign.bind(crypto.subtle); + crypto.subtle.sign = () => Promise.reject(new Error("redteam fault: no sign")); + return crypto.subtle.sign.toString().includes("redteam fault"); + }); + expect(took, "setup: the fault is in place").toBe(true); + const [py, , deref] = await workerRun([ + { tool: "python_exec", args: { code: + `try:\n df = ml.table("table")\n print("V:" + str(df["token"].iloc[0]))\nexcept Exception as e:\n print("ERR:" + str(e).replace("\\n", " "))` } }, + { tool: "fetch_url", args: { url, token: "fault text" } }, + { tool: "python_exec", args: { code: + `try:\n t = (await ml.dereference('@tool:"fault text"'))["text"]\n print("V:" + t[:40])\nexcept Exception as e:\n print("ERR:" + str(e).replace("\\n", " "))` } }, + ]); + for (const [content, label] of [[py, "7 the page table"], [deref, "7 the stored text"]]) { + expect(content, `${label}: no text of the value crosses`).not.toContain(SECRET); + expect(content, `${label}: the read did not serve a value`).not.toMatch(/^V:/m); + expect(content, `${label}: the read failed and said so`).toMatch(/ERR:|error|withheld|could not/i); + } + } finally { + await ext.sw.evaluate(() => { + if (globalThis.__origSign) { crypto.subtle.sign = globalThis.__origSign; delete globalThis.__origSign; } + }); + await ext.sw.evaluate((v) => chrome.storage.local.set({ ml_secret_registry: [{ name: "PROBE_SECRET", value: v }] }), SECRET); + } +}); + +// --- row 8: a cell a page started ----------------------------------------------------------------------------- + +test("8 a page-started cell's stdout, value and inputTables carry the fake; a fake the page sends back is not restored", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const code = `df = ml.table("table")\nv = str(df["token"].iloc[0])\nprint("RAW:" + v)\nprint("REV:" + v[::-1])\nreturn v`; + try { + const first = await page.evaluate((c) => window.ml.pythonExec(c), code); + expect(first.ok, `setup: the page's cell ran: ${JSON.stringify(first.error)}`).toBe(true); + const shown = /^RAW:([^\n]*)$/m.exec(first.stdout)?.[1]; + expect(shown, "setup: the cell printed its value").toBeTruthy(); + expect(shown, "8: the page gets the fake in stdout").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(shown.length, "8: the fake keeps the value's length").toBe(SECRET.length); + expect(first.stdout, "8: no window of the value in stdout").not.toContain(SECRET); + expect(JSON.stringify(first.value), "8: the returned value is the fake").toContain(shown); + expect(JSON.stringify(first.inputTables), "8: the input table's cell is the fake").toContain(shown); + // The page puts the fake it got back into the table it hoists: what comes back is that same fake, never the value. + await page.evaluate((fakeValue) => { document.querySelector("#t td").textContent = fakeValue; }, shown); + const second = await page.evaluate((c) => window.ml.pythonExec(c), code); + expect(second.ok, `setup: the second cell ran: ${JSON.stringify(second.error)}`).toBe(true); + expect(second.stdout, "8: the fake the page sent in comes back as the fake").toContain(`RAW:${shown}`); + expect(second.stdout, "8: the fake is not restored to the value").not.toContain(SECRET); + } finally { + await page.evaluate((v) => { document.querySelector("#t td").textContent = v; }, SECRET); + } +}); + +// --- the guard: the cell's own realm reaches no storage and no network ----------------------------------------- + +test("9 GUARD a cell cannot climb into the worker's JavaScript, so the mask is the only path to the value", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + const [refused, control] = await workerRun([ + // The route a lifted realm would need: the browser's own globals, storage and fetch included. + { tool: "python_exec", args: { code: + `import js\ng = js.globalThis\n` + + `names = ["chrome", "fetch", "XMLHttpRequest", "WebSocket", "indexedDB", "caches", "navigator", "postMessage"]\n` + + `print("PRESENT:" + str([n for n in names if bool(js.Reflect.get(g, n))]))` } }, + // The same run's legitimate read of the same cell's table. + { tool: "python_exec", args: { code: + `df = ml.table("table")\nv = str(df["token"].iloc[0])\nprint("V:" + v)\nprint("VR:" + v[::-1])` } }, + ]); + expect(refused, "9: the cell asking for the browser's JavaScript is refused").toMatch(/may not reach the browser's JavaScript|outside the read-only Python dialect/i); + expect(refused, "9: the refused cell never ran, so no realm read storage").not.toMatch(/^PRESENT:/m); + assertFake(control, "V", "9"); +}); + +// --- the stated limit: a read of the live page stays raw, and the spec says so -------------------------------- + +test("10 the spec states the live-page limit, and a page's own exec still reads the live DOM unmasked", async () => { + const spec = readFileSync(join(HERE, "../../docs/spec/SECRET_HANDLES.md"), "utf8"); + const paragraphs = spec.split(/\n\s*\n/).filter((p) => /live page/i.test(p)); + expect(paragraphs.some((p) => /raw|unfaked|not covered|not faked/i.test(p)), "the spec states a read of the live page stays raw").toBe(true); + // The limit itself: the page's own reader holds the real text, and no worker answer is involved. + expect(await page.evaluate((v) => document.querySelector("table").innerText.includes(v), SECRET), "a page's own read of the live DOM is the page's text").toBe(true); +}); + +// --- the oracle: a page's own cell tests a whole candidate list per call, and today that is a stated limit ---------- + +test("11 ORACLE: a page's own ml.pythonExec hoists a candidate list and today learns which candidates are registered", async () => { + test.skip(!HAS_PYODIDE, "needs the bundled Pyodide"); + // SECRET_HANDLES.md, "The cost (stated)": an approved page's own cell can test strings against the registered + // values. Each candidate equal to a registered form comes back as a fake; the page learns THAT it is registered, + // never under which name, never that two forms belong together, and a later call's fakes are its own. Whether the + // page's own rows stay faked is Shane's decision; this row pins today's behaviour, as the spec says it does. + const B64 = Buffer.from(SECRET).toString("base64"); // another form of the same value (valueForms' base64) + const GH = "ghp_" + "Zq7".repeat(12); // a GitHub token: the mask stars it whole, registered or not + const CANDIDATES = [SECRET, B64, "ORDINARY_STRING_99", "A1b2C3", GH]; + const code = `df = ml.table("table")\nvals = [str(x) for x in df["token"]]\n` + + `for i, v in enumerate(vals):\n print("C" + str(i) + ":" + v)\nreturn vals`; + const lineOf = (out, i) => new RegExp(`^C${i}:([^\\n]*)$`, "m").exec(String(out))?.[1] ?? null; + try { + await page.evaluate((cands) => { + const tb = document.querySelector("#t tbody"); + tb.innerHTML = cands.map(() => "").join(""); + [...tb.querySelectorAll("td")].forEach((td, i) => { td.textContent = cands[i]; }); + }, CANDIDATES); + const first = await page.evaluate((c) => window.ml.pythonExec(c), code); + expect(first.ok, `setup: the page's cell ran: ${JSON.stringify(first.error)}`).toBe(true); + const [c0, c1, c2, c3, c4] = [0, 1, 2, 3, 4].map((i) => lineOf(first.stdout, i)); + expect(c0, `setup: the cell printed its first candidate: ${String(first.stdout).slice(0, 300)}`).not.toBeNull(); + // The registered candidate, in two of its forms: each a fake of its own length, and of a different value. + expect(c0, "11: a registered candidate is the fake").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(c0.length, "11: the fake keeps the candidate's length").toBe(SECRET.length); + expect(c1, "11: another form of the same value is a fake too").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(c1.length, "11: that fake keeps its own form's length").toBe(B64.length); + expect(c1, "11: two forms of one value do not share a fake, so the page cannot tell they belong together").not.toBe(c0); + // The page's other rows and what the mask knows. + expect(c2, "11: an unregistered candidate is unchanged").toBe("ORDINARY_STRING_99"); + // Values under 8 characters cannot be registered at all (secret-registry.ts REGISTRY_MIN_VALUE, entryRefusal), + // so no form is that short: the `*` a short candidate could show would need a registered value to match, and + // the one `*` mask a page list does meet is the token below. + expect(c3, "11: a short unregistered candidate is unchanged").toBe("A1b2C3"); + expect(c4, "11: a GitHub token reads as `*` at its length, registered or not").toBe("*".repeat(GH.length)); + // Nothing of the registered NAME, or a marker, reaches the page's code or its answer. + expect(first.stdout, "11: no name-bearing marker or name reaches the page").not.toContain("[REDACTED"); + expect(first.stdout, "11: no name-bearing marker or name reaches the page").not.toContain("PROBE_SECRET"); + for (const w of forbidden(SECRET)) expect(first.stdout, "11: no window of the value reaches the page's cell").not.toContain(w); + expect(JSON.stringify(first.value), "11: the value the cell returns carries the same fakes").toContain(c0); + // A second call is its own key (`page:`): the same candidates get different fakes. + const second = await page.evaluate((c) => window.ml.pythonExec(c), code); + expect(second.ok, `setup: the second cell ran: ${JSON.stringify(second.error)}`).toBe(true); + const s0 = lineOf(second.stdout, 0), s1 = lineOf(second.stdout, 1); + expect(s0, "11: a second call's fake is its own, not the first call's").toMatch(new RegExp(`^${FAKE_PREFIX}`)); + expect(s0, "11: a second call's fake differs for the same candidate").not.toBe(c0); + expect(s1, "11: ...for each form").not.toBe(c1); + } finally { + await page.evaluate((v) => { + const tb = document.querySelector("#t tbody"); + tb.innerHTML = ""; + tb.querySelector("td").textContent = v; + }, SECRET); + } +}); diff --git a/tests/readonly-current.test.mjs b/tests/readonly-current.test.mjs index ea09550e7..f1d4eab77 100644 --- a/tests/readonly-current.test.mjs +++ b/tests/readonly-current.test.mjs @@ -386,16 +386,16 @@ function oneCapture(value = '{"rows":[1,2,3]}') { test("WORKER ML: only reads; nothing that spends, mutates, egresses or reads the page", async () => { const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); - const without = Object.keys(workerReadonlyMl("https://a.example/")).sort(); + const without = Object.keys(workerReadonlyMl("https://a.example/", undefined, "", [])).sort(); assert.deepEqual(without, ["_fetchCached", "capabilities", "config", "getModel", "info", "jsonPath", "models", "pipe", "ps", "range", "schema", "serverTools"]); - assert.deepEqual(Object.keys(workerReadonlyMl("https://a.example/", oneCapture().deref)).sort(), [...without, "dereference"].sort(), + assert.deepEqual(Object.keys(workerReadonlyMl("https://a.example/", oneCapture().deref, "", [])).sort(), [...without, "dereference"].sort(), "dereference exists only when the host hands over the run's store"); }); test("WORKER ML: a pointer read is answered in the worker from the run's store, pipe stages included", async () => { const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); const c = oneCapture(); - const ml = workerReadonlyMl("https://a.example/", c.deref); + const ml = workerReadonlyMl("https://a.example/", c.deref, "", []); const run = (js) => evalReadonlyInWorker({ js }, { ml }); const a = await run("return @tool:abc1234.json.rows.length"); assert.deepEqual([a.kind, a.result], ["answered", "3"]); @@ -408,7 +408,7 @@ test("WORKER ML: a pointer read is answered in the worker from the run's store, test("WORKER ML ADVERSARIAL: a pointer's value is data; no realm, no constructor, no write back into the store", async () => { const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); const c = oneCapture(); - const ml = workerReadonlyMl("https://a.example/", c.deref); + const ml = workerReadonlyMl("https://a.example/", c.deref, "", []); for (const js of [ `(await ml.dereference("x")).constructor`, `(await ml.dereference("x")).pipe.constructor("return this")()`, `ml.dereference.constructor("return this")()`, `(await ml.dereference("x"))["__proto__"]`, @@ -420,7 +420,7 @@ test("WORKER ML ADVERSARIAL: a pointer's value is data; no realm, no constructor test("WORKER ML ADVERSARIAL: what the worker does not carry defers to the page, where it is refused; a read then a page reach returns nothing", async () => { const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); - const ml = workerReadonlyMl("https://a.example/", oneCapture().deref); + const ml = workerReadonlyMl("https://a.example/", oneCapture().deref, "", []); for (const js of [`ml.chat("x")`, `ml.setModel("m")`, `ml.fetch("https://b.example/")`, `ml.agent("x")`, `ml.pythonExec("1")`, `ml._fetchCached("u")`, `ml.unload()`]) { assert.equal((await evalReadonlyInWorker({ js }, { ml })).kind, "needs-page", `worker: ${js}`); await assert.rejects(evalReadonly(js, doc(), ml), (e) => outOfDialect(e) && !(e instanceof NeedsPage), `page: ${js}`); @@ -432,7 +432,7 @@ test("WORKER ML ADVERSARIAL: what the worker does not carry defers to the page, test("WORKER ML HALTING: a survey that re-reads a pointer forever is stopped by the step budget", { timeout: 10_000 }, async () => { const { workerReadonlyMl } = await import("../src/sw/worker-readonly-ml.ts"); const c = oneCapture(); - const ml = workerReadonlyMl("https://a.example/", c.deref); + const ml = workerReadonlyMl("https://a.example/", c.deref, "", []); const r = await evalReadonlyInWorker({ js: `let n = 0; while (true) { await ml.dereference("x"); n++ } return n` }, { ml }); assert.notEqual(r.kind, "needs-page"); assert.ok(r.kind === "refused" || /^Error:/.test(r.result), JSON.stringify(r)); diff --git a/tests/redteam-arrow-types.test.mjs b/tests/redteam-arrow-types.test.mjs new file mode 100644 index 000000000..479a620b3 --- /dev/null +++ b/tests/redteam-arrow-types.test.mjs @@ -0,0 +1,270 @@ +// redteam-arrow-types.test.mjs — RED TEAM (e4): one row per Arrow type, enumerated from the library, not sampled. +// +// ruling 133 ("Where the mask sits", 6) serves a stored table's bytes to a cell with every registered value replaced by +// the session's fake, and src/python/table-fake.ts decides each column by its TYPE id. This file pins that decision for +// EVERY type id this library can write: +// +// - text (Utf8, LargeUtf8) and bytes (Binary, LargeBinary, FixedSizeBinary) are faked where they lie: the cell's fake, +// its neighbours and every other cell untouched, the buffer the same length, the value's bytes gone from it; +// - a view type (Utf8View, BinaryView) that HOLDS a value refuses the read, naming the column and its type and never +// the value — its short values sit inside the views, where a fake cannot be put; a clean view is served as it is; +// - containers (List, LargeList, FixedSizeList, Struct, Map, and a Dictionary through its dictionary) are searched +// through their children, so a value nested at any depth is faked as at the top; +// - the unsearched types (Null, the ints, floats, Bool, Decimal, dates, times, timestamps, durations, intervals) are +// served byte-identical: a STATED LIMIT. A printed number still crosses the output scrub, and the only way a +// registered value lands in such a column is a table someone already wrote with the value in it. +// +// Every type id the library can produce is in exactly one of those groups (the first two rows enumerate them). An id in +// NONE (a run-end-encoded column, a type added later) refuses the read; that branch is an AUDIT row, because this +// apache-arrow cannot write one: there is no type id 22 (RunEndEncoded), and a Union (14) — a container — has a type but +// cannot enter a Schema here, so no cell can receive one (the reason sits with the enumeration row). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as A from "apache-arrow"; +import { + tableFromArrays, tableToIPC, tableFromIPC, vectorFromArray, makeData, makeVector, Field, Schema, Table, + RecordBatch, Struct, Null, Int32, Int64, Float64, Bool, Decimal, DateMillisecond, TimeSecond, + TimestampMillisecond, DurationMillisecond, IntervalYearMonth, IntervalDayTime, IntervalMonthDayNano, + Utf8, LargeUtf8, Binary, LargeBinary, FixedSizeBinary, Utf8View, BinaryView, List, LargeList, FixedSizeList, + Map_, Dictionary, DenseUnion, SparseUnion, +} from "apache-arrow"; + +const { deriveFakes, sessionFakeKey } = await import("../src/secret-fake.ts"); +const { fakeStoredTable, TableNotFaked } = await import("../src/python/table-fake.ts"); + +const NAME = "DB_PASS"; +const VALUE = "hunter2-correct-horse"; +const FRONT = VALUE.slice(0, 6); +/** The session's fake for VALUE: `RDCT` and letters and digits, its length (ruling 101 / 133). */ +const FORMS = await deriveFakes(await sessionFakeKey(Uint8Array.from({ length: 32 }, (_, i) => i), "s1"), [{ name: NAME, index: 0, find: VALUE }]); +const FAKE = FORMS[0].fake; +const enc = new TextEncoder(); + +/** The IPC bytes of a table, as their own ArrayBuffer (what a stored row holds). */ +const ipc = (t) => { const u8 = tableToIPC(t, "file"); return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength); }; +/** The table a cell reads after the bytes are faked, with a copy of the bytes from BEFORE the faking and after it. */ +async function faked(t, forms = FORMS) { + const bytes = ipc(t); + const before = Buffer.from(bytes); + const out = await fakeStoredTable("arrow-file", bytes, forms); + return { out, back: tableFromIPC(new Uint8Array(out.buffer)), before, after: Buffer.from(out.buffer) }; +} +/** Every text a cell can decode out of a table, dictionary values included. */ +const decodedStrings = (t) => { + const out = []; + for (let i = 0; i < t.numCols; i++) { + for (const d of t.getChildAt(i).data) { + if (d.dictionary) out.push(...[...makeVector(d.dictionary)].map(String)); + try { out.push(...[...makeVector(d)].map((v) => typeof v === "string" ? v : v instanceof Uint8Array ? new TextDecoder().decode(v) : String(v))); } catch { /* a type makeVector cannot walk: its own row asserts its cells */ } + } + } + return out; +}; +const holdsValue = (strings) => strings.some((s) => s.includes(VALUE) || s.includes(FRONT)); + +// --- one fixture per type id, and the decision each is written for --- + +/** The `x` column of a one-column table holding, where the type can, VALUE at row 1. */ +const col = (v) => tableFromArrays({ x: v }); +const str = (T) => () => col(vectorFromArray(["filler", VALUE, "tail"], new T())); +const bytes = (T) => () => col(vectorFromArray([enc.encode("x"), enc.encode(VALUE), enc.encode("y")], new T())); +/** A flat Int32 payload (an interval's values), which no `vectorFromArray` can build. */ +const flat = (T, data, n = 2) => () => { + const type = new T(); + const d = makeData({ type, length: n, nullCount: 0, data: Int32Array.from(data) }); + const f = new Field("x", type, false); + return new Table([new RecordBatch(new Schema([f]), makeData({ type: new Struct([f]), length: n, nullCount: 0, children: [d] }))]); +}; +const fsb = () => { + const width = enc.encode(VALUE).length; + const values = new Uint8Array(width * 3); + values.set(enc.encode("x".repeat(width)), 0); + values.set(enc.encode(VALUE), width); + values.set(enc.encode("y".repeat(width)), width * 2); + const type = new FixedSizeBinary(width); + const f = new Field("x", type, false); + return new Table([new RecordBatch(new Schema([f]), makeData({ type: new Struct([f]), length: 3, nullCount: 0, children: [makeData({ type, length: 3, nullCount: 0, data: values })] }))]); +}; +const listOf = (T) => () => { + const item = new Field("item", new Utf8(), true); + return col(vectorFromArray([["a"], [VALUE]], T === FixedSizeList ? new T(1, item) : new T(item))); +}; +const dict = () => col(vectorFromArray([VALUE, "a"], new Dictionary(new Utf8(), new Int32()))); +const mapType = () => new Map_(new Field("entries", new Struct([new Field("key", new Utf8(), false), new Field("value", new Utf8(), true)]), false), false); +const unionType = (T) => new T([new Field("a", new Utf8(), true)], [0]); + +/** id → [what this module must do with a column of it, a table holding VALUE in it where it can]. */ +const TYPE = { + 1: ["unsearched", () => col(vectorFromArray([null, null], new Null()))], + 2: ["unsearched", () => col(vectorFromArray([7n, 8n], new Int64()))], + 3: ["unsearched", () => col(vectorFromArray([1.5, 2.5], new Float64()))], + 4: ["bytes", bytes(Binary)], + 5: ["text", str(Utf8)], + 6: ["unsearched", () => col(vectorFromArray([true, false], new Bool()))], + 7: ["unsearched", () => col(vectorFromArray([Buffer.alloc(16, 1), Buffer.alloc(16, 2)], new Decimal(38, 10)))], + 8: ["unsearched", () => col(vectorFromArray([new Date(0), new Date(1)], new DateMillisecond()))], + 9: ["unsearched", () => col(vectorFromArray([1, 2], new TimeSecond()))], + 10: ["unsearched", () => col(vectorFromArray([1n, 2n], new TimestampMillisecond()))], + 11: ["unsearched", () => col(vectorFromArray([[1], [2]], new IntervalYearMonth()))], + 12: ["containers", listOf(List)], + 13: ["containers", () => col(vectorFromArray([{ name: "a" }, { name: VALUE }]))], + 14: ["containers", null], // a Union: its type is here, its IPC writer is not (see the enumeration row) + 15: ["bytes", fsb], + 16: ["containers", listOf(FixedSizeList)], + 17: ["containers", () => col(vectorFromArray([new Map([["k", "a"]]), new Map([["k", VALUE]])], mapType()))], + 18: ["unsearched", () => col(vectorFromArray([1n, 2n], new DurationMillisecond()))], + 19: ["bytes", bytes(LargeBinary)], + 20: ["text", str(LargeUtf8)], + 21: ["containers", listOf(LargeList)], + 23: ["views", bytes(BinaryView)], + 24: ["views", str(Utf8View)], + "-1": ["containers", dict], +}; + +// --- the enumeration: every type the library exposes, and the id it reports --- + +test("concrete types: every class in the library reports one of the base ids this table decides", () => { + // Every concrete type apache-arrow 21 exposes, with the base id its column reports. + const item = () => new Field("item", new Utf8(), true); + const families = [ + [new Null(), 1], [new A.Int8(), 2], [new A.Int16(), 2], [new A.Int32(), 2], [new A.Int64(), 2], + [new A.Uint8(), 2], [new A.Uint16(), 2], [new A.Uint32(), 2], [new A.Uint64(), 2], + [new A.Float16(), 3], [new A.Float32(), 3], [new Float64(), 3], [new Binary(), 4], [new Utf8(), 5], [new Bool(), 6], + [new A.Decimal(38, 10), 7], [new A.DateDay(), 8], [new DateMillisecond(), 8], + [new TimeSecond(), 9], [new A.TimeMillisecond(), 9], [new A.TimeMicrosecond(), 9], [new A.TimeNanosecond(), 9], + [new A.TimestampSecond(), 10], [new TimestampMillisecond(), 10], [new A.TimestampMicrosecond(), 10], [new A.TimestampNanosecond(), 10], + [new IntervalYearMonth(), 11], [new IntervalDayTime(), 11], [new IntervalMonthDayNano(), 11], + [new List(item()), 12], [new Struct([]), 13], + [new DenseUnion([item()], [0]), 14], [new SparseUnion([item()], [0]), 14], [new A.FixedSizeBinary(4), 15], + [new FixedSizeList(1, item()), 16], [new Map_(new Field("entries", new Struct([])), false), 17], + [new A.DurationSecond(), 18], [new DurationMillisecond(), 18], [new A.DurationMicrosecond(), 18], [new A.DurationNanosecond(), 18], + [new LargeBinary(), 19], [new LargeUtf8(), 20], [new LargeList(item()), 21], [new BinaryView(), 23], [new Utf8View(), 24], + [new Dictionary(new Utf8(), new A.Int32()), -1], + ]; + const seen = new Set(); + for (const [t, id] of families) { + assert.equal(t.typeId, id, `${t.constructor.name} reports base id ${id}`); + seen.add(id); + } + for (const id of seen) assert.ok(String(id) in TYPE, `base id ${id} has a row in this file`); + assert.deepEqual([...seen].sort((a, b) => a - b), [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24], + "a base id this library has and the table does not decide is a gap, and one more is the group's own audit"); + // The ids in no list: 22 (RunEndEncoded) does not exist here; a Union (14) is a container but cannot be written. + assert.equal(A.Type.RunEndEncoded, undefined, "a run-end-encoded column cannot be constructed here, so its refusal cannot be driven"); + for (const T of [DenseUnion, SparseUnion]) assert.equal(unionType(T).typeId, 14); +}); + +test("each fixture reports the type id it stands for, and the ids this library can write are exactly the decided ones", () => { + const written = {}; + for (const [id, [, make]] of Object.entries(TYPE)) { + if (!make) continue; + const d = make().getChildAt(0).data[0]; + assert.ok(d, `type ${id}'s fixture produced a column`); + assert.equal(String(d.type.typeId), id, `the fixture for ${id} is of that type`); + written[id] = true; + } + assert.deepEqual(Object.keys(written).sort((a, b) => Number(a) - Number(b)), + ["-1", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20", "21", "23", "24"], + "the ids this library writes are exactly the ids this file decides, a Union (14) aside"); + for (const T of [DenseUnion, SparseUnion]) { + const type = unionType(T); + assert.equal(type.typeId, 14, `a ${T.name} is a container by id`); + // The type exists, and the library cannot put a column of it into a Schema (its `children` are type ids where + // fields belong), so no table — and no cell — can ever hold one; the container branch would visit its children. + assert.throws(() => new Schema([new Field("x", type, true)]), (e) => /children/.test(e.message), + `apache-arrow 21 cannot hold a ${T.name} column in a table, so no cell can receive one`); + } +}); + +// --- text and bytes are faked where they lie --- + +test("text types (Utf8, LargeUtf8): the cell is the fake, its neighbours and the buffer's length untouched, the value's bytes gone", async () => { + for (const id of [5, 20]) { + const { after, before, back } = await faked(TYPE[id][1]()); + assert.equal(back.getChild("x").get(1), FAKE, `type ${id}: the cell holding the value reads as its fake`); + assert.deepEqual([back.getChild("x").get(0), back.getChild("x").get(2)], ["filler", "tail"], `type ${id}: neighbours untouched`); + assert.equal(after.length, before.length, `type ${id}: the bytes are faked where they lie`); + assert.ok(!after.includes(Buffer.from(VALUE)), `type ${id}: the value's bytes are gone from the buffer`); + assert.ok(!holdsValue(decodedStrings(back)), `type ${id}: no cell decodes to the value`); + } +}); + +test("bytes types (Binary, LargeBinary, FixedSizeBinary): each value faked value by value, at its own length", async () => { + for (const id of [4, 19, 15]) { + const { after, before, back } = await faked(TYPE[id][1]()); + const cell = back.getChild("x").get(1); + assert.equal(new TextDecoder().decode(cell), FAKE, `type ${id}: the value's bytes read as its fake`); + assert.equal(cell.length, enc.encode(VALUE).length, `type ${id}: the fake keeps the value's length`); + assert.equal(after.length, before.length, `type ${id}: the bytes are faked where they lie`); + assert.ok(!after.includes(Buffer.from(VALUE)), `type ${id}: the value's bytes are gone from the buffer`); + } +}); + +// --- a view type holding a value refuses; a clean one is served --- + +test("view types (Utf8View, BinaryView): a value in one refuses the read, naming the column and the type, never the value", async () => { + for (const [id, name] of [[23, "BinaryView"], [24, "Utf8View"]]) { + await assert.rejects(() => fakeStoredTable("arrow-file", ipc(TYPE[id][1]()), FORMS), (e) => { + assert.ok(e instanceof TableNotFaked, `type ${id}: refused as a table that cannot be faked`); + assert.ok(e.message.includes(name) && e.message.includes("x"), `type ${id}: the message names the column and the type — ${e.message}`); + assert.ok(!e.message.includes(VALUE) && !e.message.includes(FRONT), `type ${id}: the message never carries the value`); + return true; + }); + } +}); + +test("a clean view type is served as it is: there is nothing in it to fake", async () => { + for (const [id, T] of [[23, BinaryView], [24, Utf8View]]) { + const cells = T === Utf8View ? ["a", "b"] : [enc.encode("a"), enc.encode("b")]; + const { after, before } = await faked(col(vectorFromArray(cells, new T()))); + assert.ok(after.equals(before), `type ${id}: the bytes are handed over unchanged`); + } +}); + +// --- containers are searched through their children --- + +test("containers (List, LargeList, FixedSizeList, Struct, Map): a value nested in one is faked, at any depth", async () => { + const shapes = { + List: listOf(List), + LargeList: listOf(LargeList), + FixedSizeList: listOf(FixedSizeList), + Struct: () => col(vectorFromArray([{ name: "a" }, { name: VALUE }])), + "Map value": () => col(vectorFromArray([new Map([["k", "a"]]), new Map([["k", VALUE]])], mapType())), + "Map key": () => col(vectorFromArray([new Map([["k", "a"]]), new Map([[VALUE, "v"]])], mapType())), + "List": () => col(vectorFromArray([[{ name: "a" }], [{ name: VALUE }]], new List(new Field("item", new Struct([new Field("name", new Utf8(), true)]), true)))), + "Struct": () => col(vectorFromArray([{ tags: ["a"] }, { tags: [VALUE] }], new Struct([new Field("tags", new List(new Field("item", new Utf8(), true)), true)]))), + }; + for (const [label, make] of Object.entries(shapes)) { + const { back, after } = await faked(make()); + const strings = decodedStrings(back); + assert.ok(strings.some((x) => x.includes(FAKE)), `${label}: the nested value reads as its fake — ${JSON.stringify(strings)}`); + assert.ok(!holdsValue(strings), `${label}: nothing decodes to the value`); + assert.ok(!after.includes(Buffer.from(VALUE)), `${label}: the value's bytes are gone from the buffer`); + } +}); + +test("a Dictionary is faked through its dictionary: every entry, and the rows that use them", async () => { + const { back, after } = await faked(dict()); + const strings = decodedStrings(back); + assert.ok(strings.some((x) => x.includes(FAKE)), `the dictionary entry reads as its fake — ${JSON.stringify(strings)}`); + assert.ok(!holdsValue(strings), "no dictionary entry holds the value"); + assert.equal(back.getChild("x").get(0), FAKE, "the row that uses the entry reads its fake"); + assert.equal(back.getChild("x").get(1), "a", "a row on a clean entry is untouched"); + assert.ok(!after.includes(Buffer.from(VALUE)), "the value's bytes are gone from the buffer"); +}); + +// --- the unsearched types: served byte-identical (stated limit) --- + +test("unsearched types (Null, ints, floats, Bool, Decimal, dates, times, timestamps, durations, intervals): bytes identical", async () => { + const extra = { + "IntervalDayTime": flat(IntervalDayTime, [1, 2, 3, 4, 5, 6]), + "IntervalMonthDayNano": flat(IntervalMonthDayNano, [1, 2, 3, 4, 5, 6, 7, 8]), + "Decimal holding the value's own bytes": () => col(vectorFromArray([Buffer.alloc(16, 1), Buffer.from(VALUE).subarray(0, 16)], new Decimal(38, 10))), + }; + const shapes = { ...Object.fromEntries(Object.entries(TYPE).filter(([, [kind]]) => kind === "unsearched").map(([id, [, make]]) => [`type ${id}`, make])), ...extra }; + for (const [label, make] of Object.entries(shapes)) { + const { after, before } = await faked(make()); + assert.ok(after.equals(before), `${label}: the column is not searched, so its bytes are handed over as they are (a stated limit)`); + } +}); diff --git a/tests/secret-mask.test.mjs b/tests/secret-mask.test.mjs index 40da3fe1d..c89138583 100644 --- a/tests/secret-mask.test.mjs +++ b/tests/secret-mask.test.mjs @@ -3,7 +3,7 @@ // two mounts". The reader's use of it (the widened window, a match across reads) is in ranged-reader.test.mjs. import { test } from "node:test"; import assert from "node:assert/strict"; -import { maskSecretBytes, maskOverlap, maskName, MASK_BYTE } from "../src/secret-mask.ts"; +import { maskSecretBytes, maskOverlap, maskName, MASK_BYTE, byteString } from "../src/secret-mask.ts"; const enc = (s) => new TextEncoder().encode(s); const dec = (b) => new TextDecoder().decode(b); @@ -98,3 +98,29 @@ test("an empty find is ignored", () => { assert.equal(maskName("plain.txt", [{ find: "", put: "[X]" }]), "plain.txt"); assert.equal(maskName("a-s3-b", [{ find: "", put: "[X]" }, { find: "s3", put: "[Y]" }]), "a-[Y]-b"); }); + +// --- byteString: one character per byte --- + +test("byteString is one character per byte on both of its paths: all-ASCII bytes, and bytes with any above 0x7f", () => { + const perByte = (b) => Array.from(b, (c) => String.fromCharCode(c)).join(""); + const all = Uint8Array.from({ length: 256 }, (_, i) => i); + const enc = new TextEncoder(); + const cases = { + "empty": new Uint8Array(0), + "every ASCII byte": all.subarray(0, 128), + "every byte": all, + "0x80 to 0x9f, which windows-1252 maps elsewhere": all.subarray(0x80, 0xa0), + "a high byte between ASCII": Uint8Array.from([0x41, 0x80, 0x42]), + "a high byte last": Uint8Array.from([0x41, 0x42, 0xff]), + "0xfe 0xff and 0xff 0xfe first, which a UTF-16 decoder could read as a byte order mark": Uint8Array.from([0xfe, 0xff, 0xff, 0xfe, 0x41]), + "UTF-8 of two-, three- and four-byte characters": enc.encode("café ✓ 😀"), + "a megabyte of ASCII": enc.encode("a".repeat(1_000_000)), + "a megabyte of ASCII with one high byte": enc.encode("a".repeat(999_998) + "é"), + "a megabyte of mixed text": enc.encode("café ✓ 😀 ".repeat(70_000)), + }; + for (const [label, b] of Object.entries(cases)) { + const s = byteString(b); + assert.equal(s.length, b.length, label); + assert.ok(s === perByte(b), label); + } +}); diff --git a/tests/table-answer.test.mjs b/tests/table-answer.test.mjs index a6b58b24b..c30527d44 100644 --- a/tests/table-answer.test.mjs +++ b/tests/table-answer.test.mjs @@ -10,6 +10,7 @@ const fileAnswer = (data = {}) => ({ seq: 4, value: { source: { kind: "file", la const deps = (file, stored) => ({ file: async (p) => { if (typeof file === "function") return file(p); return file; }, stored: async (k) => { if (!stored) throw new Error("no such value"); return stored(k); }, + forms: async () => [], }); // --- answers that carry no bytes ---