diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 300bb29a6..66d5de885 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -46,6 +46,7 @@ these rules. | `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | | `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, issue #2010) | | `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, issue #2010) | +| `record-encrypted-v1.cases.json` | cases | `tests/encrypted_record_conformance.rs` | — (pending: the Go guest does not use typed records yet) | | `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | | `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | | `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | @@ -92,8 +93,8 @@ fixtures described below. It ends with the fresh artifact exchange in both directions (`test:conformance:exchange`, which also needs the deterministic EQL guest). Set no fixture-update variables when checking conformance. -The task runs the single-value cases in native Rust only, because the Go -runner of that profile is pending. +The task runs the single-value cases and the encrypted-record cases in native +Rust only, because the Go runners of those profiles are pending. The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface @@ -207,6 +208,28 @@ The native runner is `single_value_conformance` in the Rust crate. with the typed interface. The Go runner is pending. The Go runner will be written with the single-value calls of the Go SDK (issue #2010). +## An encrypted record as typed values + +The [encrypted-record contract](encrypted-records-contract.md) defines +`record-encrypted-v1` in `v1/record-encrypted-v1.cases.json`. A binding +asks for an encrypted record as an `EncryptedRecord`, and moves it to its +language and back as a frame. + +Each case encrypts rows under a plan, writes +the record as a frame, and checks the frame's form. It then reads the frame +back, after a change where the case has one. It decrypts the frame, or +checks the refusal at the stage the case names. The cases cover: + +- every output kind, and a passthrough field of each value kind +- a batch, and an empty batch +- both null modes, and a `"null": "sql"` field left out +- one sealed value under `c`: a list, a map, or an empty one is refused +- the refusals, with the field, the output, and the row they name + +The native runner is `encrypted_record_conformance` in the Rust crate, and +`test:conformance` runs it. The Go runner is pending until the Go guest uses +typed records. + ## `record-reads-v1` contract The [read contract](read-contract.md) defines cases in `v1/record-reads-v1.cases.json` for diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 90b570655..096f5b668 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -12,6 +12,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | | Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures | +| An encrypted record as typed values, moved across a binding as a frame | The [encrypted-record profile](encrypted-records-contract.md), run by native Rust (`v1/record-encrypted-v1.cases.json`: every output kind, a passthrough of each value kind, a batch, both null modes, the refusal of a list, a map or an empty container under `c`, and the refusals at each stage with their field, output and row); `packages/stack-encrypt/src/dynamic/record/encrypted/tests/mod.rs` (a property test of any record through its frame and back, reading any frame without a panic, a field that names a target type, one field's frame, and the owned API); `packages/recipher-frame/src/serde/raw/tests/mod.rs` (a raw frame node written and read as it is) | The Go runner, once the Go guest uses typed records; Python and TypeScript runners | | Fresh cross-language storage | `.github/workflows/tests-golang.yml` exports fresh Go EQL rows for Rust, the storage-only `Json` documents among them; initial scalar artifact exchange; fixed storage-blob vectors read by both Rust (`opaque_blob.rs`) and Go (`TestOpaqueReadsARustWrittenBlob`); the [exchange profile](exchange-contract.md): values, records, blobs and EQL rows written fresh and opened in both Rust/Go directions, with producer, engine, backend and storage versions in the report | Python/TypeScript pairs and backends when their runners exist; supported released versions once the compatibility policy is defined; fresh exchange of searchable JSON documents, and of `Json` documents from Rust to Go; a SQL lane storing one language's fresh rows through the other | | JSON queries, extraction and tampering | `packages/stack-encrypt/tests/json_tree_vectors.rs`; `packages/eql/tests/encryption/tests/json_tree.rs`; `languages/golang/encrypt/json_tree_test.go`, `json_postgres_test.go` | Formal operation profile; JSON vectors consumed by all runners | | Element and predicate matching | Go `json_elements_test.go`, `json_match_test.go` and corresponding PostgreSQL tests; Rust/SQL predicate suites | Map exact supported grammar and documented semantic differences to case IDs | diff --git a/conformance/stack-encrypt/encrypted-records-contract.md b/conformance/stack-encrypt/encrypted-records-contract.md new file mode 100644 index 000000000..66c074cc1 --- /dev/null +++ b/conformance/stack-encrypt/encrypted-records-contract.md @@ -0,0 +1,177 @@ +# Encrypted-record profile + +`record-encrypted-v1` is the conformance profile for an encrypted record as +typed values, and for the frame that a language binding moves it in. The +cases are in `v1/record-encrypted-v1.cases.json`. The profile is an +experimental test contract. + +A binding asks `record::encrypt` for an `EncryptedRecord`, or a batch of +them, and gives one back to `record::decrypt`. It moves the record to its +language and back as a frame, with `EncryptedRecord::to_frame` and +`EncryptedRecord::from_frame`. The cases fix the form of that frame, so +every binding builds and reads the same values. + +## Terms + +- A frame is one value written as bytes, in the format that Stack Encrypt + reads. +- An encrypted record has one entry for each field. Each field has one + entry for each output. +- An output is one of these: + - `c`, the sealed value + - an index term: `eq`, `match`, `ore`, `ope`, or `ore_block` + - `passthrough`, a field's value stored without encryption + - `target`, the value of a field that names a target type +- A sealed value is the encrypted form of one scalar. Its bytes are stable. +- A refusal is an error that Stack Encrypt returns for a value or a frame + it does not accept. + +## Runners + +The Rust runner is +`packages/stack-encrypt/tests/encrypted_record_conformance.rs`. The Go +runner is pending: the Go guest does not use typed records yet. The Python +and TypeScript runners are pending too. A missing runner is not a passing +result. + +## Cases + +Each case has these keys: + +| Key | Meaning | +|---|---| +| `id` | The name of the case | +| `plan` | The plan, in the [declaration grammar](declaration-grammar.md) | +| `batch` | Whether the rows are a batch. Without a batch, `rows` has one row. | +| `rows` | The rows to encrypt, as values | +| `frame` | The frame form that the encrypted record must have | +| `mutation` | A change to the frame before it is read back | +| `opened` | The rows that the frame, read back, decrypts to | +| `expected_error` | The `stage` of the refusal, and its `code` and payload `fields` | + +A case has `opened` or `expected_error`, never both. + +### Values + +`rows` and `opened` write a value in one of these ways: + +| Form | The value | +|---|---| +| `{"type": ..., "text": ...}` | A scalar, as the [value profile](values-contract.md#cases) defines it | +| an array of values | A list | +| `{"$object": {...}}` | A map of values | +| `null` | A null | + +A row leaves out a field that it does not have. + +### Frame nodes + +`frame` and the `value` of a mutation write a node of the frame in one of +these ways: + +| Form | The node | +|---|---| +| `"$sealed"` | The bytes of a sealed value | +| `"$bytes"` | Any bytes, such as a term. `frame` only. | +| `{"$value": }` | The frame of a value, such as a passthrough field's value | +| `{"$hex": "..."}` | These bytes | +| `{"$passthrough": }` | A passthrough node of the frame, around another node. Mutations only. | +| other text | That text | +| `null` | A null | +| an array | An array of nodes | +| another object | An object of nodes | + +In a mutation, `"$sealed"` is the bytes of the first sealed value in the +frame that the runner wrote. + +Objects compare by key. The order of the keys in the corpus file is not +significant. The order of a frame's keys is Stack Encrypt's. The runner +does not check it. + +### Mutations + +A mutation has a `path`, an `op`, and, for `set`, a `value`. Each step of +the path is a key of an object, or a position in an array, counted from 0. + +- `set` puts `value` at the path. It adds the key when the object has none. +- `remove` takes the key at the path out of its object. +- `duplicate` writes the entry at the path a second time. +- An empty path sets the whole frame. + +## Required behavior + +For each case, the runner does this: + +1. It reads the plan, and encrypts the rows as one `EncryptedRecord`, or as + a batch of them. +2. It writes the record as a frame. Where the case has `frame`, the frame + has that form. +3. It applies the mutation, where the case has one. +4. It parses the frame, reads it back as a record, and decrypts the record. +5. For a case with `opened`, every step succeeds. With no mutation, the + record read back writes the same frame again. The record decrypts to + the `opened` rows. +6. For a case with `expected_error`, the step that its `stage` names is + refused, with the `code`, and with a payload equal to `fields`. Every + step before it succeeds. + +| Stage | The step that is refused | +|---|---| +| `encrypt` | `record::encrypt`, before any key is requested | +| `frame` | Parsing the frame. The case has no `code` or `fields`. | +| `read` | Reading the frame as a record | +| `decrypt` | `record::decrypt`, before any key is retrieved | + +The cases cover these things: + +- Every output kind: a sealed value, each index term, an index term alone, + and a passthrough field. +- A passthrough field of each value kind, and a passthrough that is a list + or a map. +- A batch, and an empty batch. +- A field with `"null": "sql"` and no value. It has no entry, and decrypts + as a null. +- A field with `"null": "sealed"` and no value. It is sealed. +- A `"null": "sql"` field that the frame leaves out. It decrypts as a null. +- Index terms left out of the frame. `decrypt` does not read them. +- The refusals, listed in the next table. + +| Refusal | Stage | Reason | +|---|---|---| +| A sealed field whose value is a list, a map, or an empty one | `encrypt` | `not_one_value` | +| A frame that is not an object, or not an array of objects | `read` | `not_an_object` | +| A field that is not an object of outputs, a null included | `read` | `outputs_not_map` | +| A key that is not an output, such as `eql` | `read` | `not_an_output` | +| Anything under `c` but one sealed value's bytes | `read` | `not_sealed` | +| A term that is not bytes | `read` | `not_passthrough` | +| A field name given twice | `frame` | none | +| A sealed field with no `c` | `decrypt` | `no_ciphertext_node` | +| A passthrough of another type than its field declares | `decrypt` | `field_type` | +| A refusal of a row of a batch | any | the refusal's reason, with the row | + +## Refusals + +The code of an `encrypt` refusal is `stack_encrypt::dynamic_source`. The +code of a `read` or `decrypt` refusal is `stack_encrypt::dynamic_record`. +The payload has these fields, where they apply: + +| Field | Meaning | +|---|---| +| `reason` | What was wrong, such as `not_an_output` or `not_sealed` | +| `field` | The field at fault | +| `output` | The output at fault, such as `c` or `eq` | +| `row` | The row of a batch, counted from 0 | +| `found` | The kind of a frame, or a row, that is not an object | + +No refusal contains a value, or a key that is not an output. + +## Scope and remaining work + +The profile does not cover these: + +- A field that names a target type. The EQL profile covers target values, + and the native tests cover their `target` output. +- One field's frame alone (`EncryptedField::to_frame` and `from_frame`). + The native tests cover it. +- The stored tree, `StackCipherText`. Other profiles cover it. +- Frames exchanged between languages. That needs a second runner. diff --git a/conformance/stack-encrypt/v1/record-encrypted-v1.cases.json b/conformance/stack-encrypt/v1/record-encrypted-v1.cases.json new file mode 100644 index 000000000..668f38c46 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-encrypted-v1.cases.json @@ -0,0 +1,2894 @@ +{ + "version": 1, + "profile": "record-encrypted-v1", + "required_capabilities": ["records", "encrypted-records", "refusals"], + "cases": [ + { + "id": "every-output", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "frame": { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + }, + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "passthrough-every-kind", + "plan": { + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "id": { + "type": "bool", + "text": "true" + } + }, + { + "id": { + "type": "int8", + "text": "-8" + } + }, + { + "id": { + "type": "int16", + "text": "-16" + } + }, + { + "id": { + "type": "int32", + "text": "-32" + } + }, + { + "id": { + "type": "int64", + "text": "-64" + } + }, + { + "id": { + "type": "int128", + "text": "-128" + } + }, + { + "id": { + "type": "uint8", + "text": "8" + } + }, + { + "id": { + "type": "uint16", + "text": "16" + } + }, + { + "id": { + "type": "uint32", + "text": "32" + } + }, + { + "id": { + "type": "uint64", + "text": "64" + } + }, + { + "id": { + "type": "uint128", + "text": "128" + } + }, + { + "id": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": { + "type": "float64", + "text": "-0.25" + } + }, + { + "id": { + "type": "string", + "text": "text" + } + }, + { + "id": { + "type": "string", + "text": "" + } + }, + { + "id": { + "type": "bytes", + "text": "00ff" + } + }, + { + "id": { + "type": "bytes", + "text": "" + } + }, + { + "id": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + }, + { + "id": { + "type": "decimal", + "text": "12.50" + } + }, + { + "id": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + }, + { + "id": { + "type": "null", + "text": "" + } + } + ], + "frame": [ + { + "id": { + "passthrough": { + "$value": { + "type": "bool", + "text": "true" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int8", + "text": "-8" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int16", + "text": "-16" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int32", + "text": "-32" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int64", + "text": "-64" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int128", + "text": "-128" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint8", + "text": "8" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint16", + "text": "16" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint32", + "text": "32" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "64" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint128", + "text": "128" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "float32", + "text": "1.5" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "float64", + "text": "-0.25" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "string", + "text": "text" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "string", + "text": "" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "bytes", + "text": "00ff" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "bytes", + "text": "" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "date", + "text": "2024-02-29" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "decimal", + "text": "12.50" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "null", + "text": "" + } + } + } + } + ], + "opened": [ + { + "id": { + "type": "bool", + "text": "true" + } + }, + { + "id": { + "type": "int8", + "text": "-8" + } + }, + { + "id": { + "type": "int16", + "text": "-16" + } + }, + { + "id": { + "type": "int32", + "text": "-32" + } + }, + { + "id": { + "type": "int64", + "text": "-64" + } + }, + { + "id": { + "type": "int128", + "text": "-128" + } + }, + { + "id": { + "type": "uint8", + "text": "8" + } + }, + { + "id": { + "type": "uint16", + "text": "16" + } + }, + { + "id": { + "type": "uint32", + "text": "32" + } + }, + { + "id": { + "type": "uint64", + "text": "64" + } + }, + { + "id": { + "type": "uint128", + "text": "128" + } + }, + { + "id": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": { + "type": "float64", + "text": "-0.25" + } + }, + { + "id": { + "type": "string", + "text": "text" + } + }, + { + "id": { + "type": "string", + "text": "" + } + }, + { + "id": { + "type": "bytes", + "text": "00ff" + } + }, + { + "id": { + "type": "bytes", + "text": "" + } + }, + { + "id": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + }, + { + "id": { + "type": "decimal", + "text": "12.50" + } + }, + { + "id": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + }, + { + "id": { + "type": "null", + "text": "" + } + } + ] + }, + { + "id": "passthrough-lists-and-maps", + "plan": { + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "id": [ + { + "type": "string", + "text": "a" + }, + [] + ] + }, + { + "id": { + "$object": { + "k": { + "type": "uint32", + "text": "1" + }, + "empty": { + "$object": {} + } + } + } + }, + { + "id": [] + }, + { + "id": { + "$object": {} + } + } + ], + "frame": [ + { + "id": { + "passthrough": { + "$value": [ + { + "type": "string", + "text": "a" + }, + [] + ] + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "$object": { + "k": { + "type": "uint32", + "text": "1" + }, + "empty": { + "$object": {} + } + } + } + } + } + }, + { + "id": { + "passthrough": { + "$value": [] + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "$object": {} + } + } + } + } + ], + "opened": [ + { + "id": [ + { + "type": "string", + "text": "a" + }, + [] + ] + }, + { + "id": { + "$object": { + "k": { + "type": "uint32", + "text": "1" + }, + "empty": { + "$object": {} + } + } + } + }, + { + "id": [] + }, + { + "id": { + "$object": {} + } + } + ] + }, + { + "id": "batch", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "35" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "frame": [ + { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + }, + { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + } + ], + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "35" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "empty-batch", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [], + "frame": [], + "opened": [] + }, + { + "id": "sql-null", + "plan": { + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "eq"], + "type": "string", + "null": "sql" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "frame": { + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "1" + } + } + } + }, + "opened": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ] + }, + { + "id": "sealed-null", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq"], + "type": "uint32", + "null": "sealed" + } + }, + "batch": false, + "rows": [ + { + "age": null + } + ], + "frame": { + "age": { + "c": "$sealed", + "eq": "$bytes" + } + }, + "opened": [ + { + "age": null + } + ] + }, + { + "id": "sql-null-field-left-out", + "plan": { + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "eq"], + "type": "string", + "null": "sql" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "email": { + "type": "string", + "text": "a@example.com" + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "mutation": { + "path": ["email"], + "op": "remove" + }, + "opened": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ] + }, + { + "id": "index-terms-left-out", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "eq"], + "op": "remove" + }, + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "list-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"] + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": [ + { + "type": "string", + "text": "a" + } + ], + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "map-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"] + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": { + "$object": { + "k": { + "type": "string", + "text": "a" + } + } + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "empty-list-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"] + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": [], + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "empty-map-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"] + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": { + "$object": {} + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "typed-array-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"], + "type": "array" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": [ + { + "type": "uint32", + "text": "1" + } + ], + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "typed-object-under-c", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"], + "type": "object" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "doc": { + "$object": {} + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc" + } + } + }, + { + "id": "list-under-c-in-a-batch", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"] + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "doc": { + "type": "string", + "text": "one" + }, + "id": { + "type": "uint64", + "text": "1" + } + }, + { + "doc": [ + { + "type": "string", + "text": "a" + } + ], + "id": { + "type": "uint64", + "text": "2" + } + } + ], + "expected_error": { + "stage": "encrypt", + "code": "stack_encrypt::dynamic_source", + "fields": { + "reason": "not_one_value", + "field": "doc", + "row": 1 + } + } + }, + { + "id": "frame-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [], + "op": "set", + "value": "text" + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "found": "string" + } + } + }, + { + "id": "batch-row-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [1], + "op": "set", + "value": { + "$value": { + "type": "uint32", + "text": "5" + } + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "row": 1, + "found": "uint32" + } + } + }, + { + "id": "field-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "outputs_not_map", + "field": "age" + } + } + }, + { + "id": "field-given-as-null", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age"], + "op": "set", + "value": null + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "outputs_not_map", + "field": "age" + } + } + }, + { + "id": "unknown-output-key", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "foo"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_output", + "field": "age" + } + } + }, + { + "id": "eql-is-not-an-output-key", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "eql"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_output", + "field": "age" + } + } + }, + { + "id": "bytes-under-c-that-are-not-sealed", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": { + "$hex": "00ff" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "age", + "output": "c" + } + } + }, + { + "id": "text-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": "not sealed" + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "age", + "output": "c" + } + } + }, + { + "id": "list-of-sealed-values-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": ["$sealed"] + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "map-of-sealed-values-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": { + "k": "$sealed" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "empty-container-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": ["empty_seq", "$sealed"] + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "passthrough-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": { + "$passthrough": { + "$value": { + "type": "uint32", + "text": "99" + } + } + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "age", + "output": "c" + } + } + }, + { + "id": "term-not-bytes", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "eq"], + "op": "set", + "value": "not bytes" + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_passthrough", + "field": "age", + "output": "eq" + } + } + }, + { + "id": "read-refusal-in-a-batch-names-the-row", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [1, "age", "foo"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "stage": "read", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_output", + "field": "age", + "row": 1 + } + } + }, + { + "id": "repeated-field-name", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age"], + "op": "duplicate" + }, + "expected_error": { + "stage": "frame" + } + }, + { + "id": "missing-ciphertext", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "remove" + }, + "expected_error": { + "stage": "decrypt", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "no_ciphertext_node", + "field": "age" + } + } + }, + { + "id": "decrypt-refusal-in-a-batch-names-the-row", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [1, "age", "c"], + "op": "remove" + }, + "expected_error": { + "stage": "decrypt", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "no_ciphertext_node", + "field": "age", + "row": 1 + } + } + }, + { + "id": "passthrough-of-another-kind", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"], + "type": "uint64" + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["id", "passthrough"], + "op": "set", + "value": { + "$value": { + "type": "string", + "text": "x" + } + } + }, + "expected_error": { + "stage": "decrypt", + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "field_type", + "field": "id" + } + } + } + ] +} diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 258d39793..084debad4 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -612,6 +612,7 @@ mod tests { row: None, reason: Reason::NoCiphertextNode, found: None, + output: None, }, ), ( @@ -642,6 +643,26 @@ mod tests { ); } + /// A stored record's refusal reaches the host with every field of its + /// payload, the output at fault among them. + #[test] + fn a_stored_record_refusal_carries_its_output_to_the_host() { + use stack_encrypt::dynamic::{Error, Reason}; + let error = Error::Record { + field: Some("age".to_string()), + row: Some(1), + reason: Reason::NotSealed, + found: None, + output: Some("c".to_string()), + }; + assert_eq!(fail_dynamic(&error), STATUS_ENCODING); + let recorded = stack_guest_abi::last_error::take().expect("an error is recorded"); + let text = String::from_utf8_lossy(&recorded); + for part in ["output", "not_sealed", "field", "age", "row"] { + assert!(text.contains(part), "the recorded error carries {part}"); + } + } + #[test] fn term_errors_are_derivation_failures() { // An empty context never reaches a term — it is `STATUS_ENCODING` diff --git a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs index ea52886ec..1ea9d2dff 100644 --- a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs +++ b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs @@ -175,10 +175,15 @@ async fn a_batch_of_documents_round_trips_in_one_request() { .iter() .map(|text| BTreeMap::from([("profile", text.as_str())])) .collect(); - let sealed = record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) - .unwrap() - .await - .unwrap(); + let sealed = record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets, + ) + .unwrap() + .await + .unwrap(); assert_eq!( calls.lock().unwrap().generate.len(), 1, @@ -331,7 +336,7 @@ async fn a_document_does_not_open_under_another_column() { let (cipher, calls) = common::cipher().await; let keyset = cipher.default_keyset(); let text = documents()[0].to_string(); - let sealed = record::encrypt_with( + let sealed = record::encrypt_with::( &keyset, frame(BTreeMap::from([("profile", text.as_str())])), &plan(), @@ -383,7 +388,12 @@ async fn text_that_is_not_a_document_is_refused_before_any_key() { let text = case["text"].as_str().unwrap(); let code = case["reason"].as_str().unwrap(); let source = BTreeMap::from([("profile", text)]); - let error = match record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) { + let error = match record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets, + ) { Err(error) => error, Ok(_) => panic!("{text:?} was accepted"), }; @@ -399,7 +409,13 @@ async fn text_that_is_not_a_document_is_refused_before_any_key() { } // A value of another kind is not a document either. let source = BTreeMap::from([("profile", 7u32)]); - assert!(record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets).is_err()); + assert!(record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets + ) + .is_err()); assert!( calls.lock().unwrap().generate.is_empty(), "no key was requested" diff --git a/packages/recipher-frame/CHANGELOG.md b/packages/recipher-frame/CHANGELOG.md index c1db7722a..b6c8393ad 100644 --- a/packages/recipher-frame/CHANGELOG.md +++ b/packages/recipher-frame/CHANGELOG.md @@ -9,6 +9,12 @@ ### Added - `OwnedFrame` is re-exported from `vitaminc-aead`, with the rest of the frame. +- `Entries` is re-exported from `vitaminc-aead`, beside `Elements`: what `Frame::entries` returns. +- `serde::raw` writes and reads one frame node as it is. + It is for a value that serde has no model for, such as a date, a timestamp, a decimal, a UUID, or a passthrough. + Use it with `#[serde(with = "recipher_frame::serde::raw")]` on a `Buffer` field, or call `serialize`, `serialize_bytes`, and `deserialize` from a `with` module of your own. + Writing checks that the bytes are one well-formed node, and counts the node's depth from where it is written. + The storage profile and every other serde format refuse a raw node, so it never becomes another value by mistake. ## [0.10.0] - 2026-11-19 diff --git a/packages/recipher-frame/src/lib.rs b/packages/recipher-frame/src/lib.rs index 0ec153c12..ec29db060 100644 --- a/packages/recipher-frame/src/lib.rs +++ b/packages/recipher-frame/src/lib.rs @@ -43,8 +43,8 @@ pub use transport::{decode_ciphertext, encode_ciphertext, CodecError}; /// `vitaminc-aead` next to the leaf codec they share, and are re-exported /// here so a binding that depends on this crate has the whole transport. pub use vitaminc_aead::frame::{ - Elements, FrameError, FrameWriteError, OwnedFrameContainer, OwnedFrameSink, ARRAY, MAX_DEPTH, - OBJECT, PASSTHROUGH, + Elements, Entries, FrameError, FrameWriteError, OwnedFrameContainer, OwnedFrameSink, ARRAY, + MAX_DEPTH, OBJECT, PASSTHROUGH, }; /// The leaf tag table, which lives with the leaf codec in `vitaminc-aead`. pub use vitaminc_aead::tags; diff --git a/packages/recipher-frame/src/serde.rs b/packages/recipher-frame/src/serde.rs index a1ee184ce..c43e8ee2a 100644 --- a/packages/recipher-frame/src/serde.rs +++ b/packages/recipher-frame/src/serde.rs @@ -149,6 +149,8 @@ use vitaminc_protected::Buffer; use crate::write::{write, AsTransport}; +pub mod raw; + // ============================================================================= // Errors // ============================================================================= @@ -750,12 +752,25 @@ impl<'de> de::Deserializer<'de> for &mut Deserializer<'de> { } } + /// A raw node ([`raw`]) is handed over as its bytes, in the transport + /// format only. Any other newtype is read as the value inside it. fn deserialize_newtype_struct>( self, - _name: &'static str, + name: &'static str, visitor: V, ) -> Result { - visitor.visit_newtype_struct(self) + if name != raw::TOKEN { + return visitor.visit_newtype_struct(self); + } + if self.profile != Profile::Transport { + return Err(Error::new( + "a raw frame node is not read from a storage blob", + )); + } + let start = self.pos; + self.skip()?; + let node = self.buf.get(start..self.pos).ok_or_else(malformed_frame)?; + raw::handing_over(|| visitor.visit_borrowed_bytes(node)) } fn deserialize_struct>( diff --git a/packages/recipher-frame/src/serde/raw.rs b/packages/recipher-frame/src/serde/raw.rs new file mode 100644 index 000000000..e118e9c5d --- /dev/null +++ b/packages/recipher-frame/src/serde/raw.rs @@ -0,0 +1,153 @@ +//! One frame node, written and read as it is. +//! +//! serde has no data model for some frame nodes: a date, a timestamp, a +//! decimal, a UUID, or a passthrough. To keep such a node as frame bytes, +//! put `#[serde(with = "recipher_frame::serde::raw")]` on a field whose +//! type is [`Buffer`]. Or call [`serialize`] and [`deserialize`] from a +//! `with` module of your own. The node crosses as its bytes, +//! and serde never reads inside it. +//! +//! - Writing, the bytes must be exactly one well-formed frame node. The +//! node's own depth counts towards the frame's depth limit +//! ([`MAX_DEPTH`](vitaminc_aead::frame::MAX_DEPTH)), from where it is +//! written. +//! - Reading takes the next node of the frame, whatever it is, as its bytes. +//! The frame was checked when it was parsed, so the node is well formed. +//! - Only this crate's transport format writes or reads a raw node. Another +//! serde format, and the storage profile, refuse it, so a raw node never +//! becomes some other value by mistake. +//! - An error never repeats the node's bytes. +//! +//! ``` +//! use serde::{Deserialize, Serialize}; +//! use vitaminc_protected::{Buffer, Controlled}; +//! +//! #[derive(Serialize, Deserialize)] +//! struct Row { +//! name: String, +//! #[serde(with = "recipher_frame::serde::raw")] +//! value: Buffer, +//! } +//! +//! // A date, which serde has no model for, as a frame node. +//! let date = recipher_frame::to_frame(vitaminc_aead::plaintext::Raw( +//! Some(vitaminc_aead::plaintext::Logical::Date), +//! vitaminc_aead::plaintext::Physical::Int(vitaminc_aead::plaintext::Int::I32(19_000)), +//! ))?; +//! let row = Row { name: "dob".into(), value: date }; +//! let bytes = recipher_frame::serde::to_vec(&row)?; +//! let back: Row = recipher_frame::serde::from_slice(bytes.risky_ref())?; +//! assert_eq!(back.value.risky_ref(), row.value.risky_ref()); +//! # Ok::<(), Box>(()) +//! ``` + +use std::cell::Cell; +use std::fmt; + +use ::serde::de::{self, Deserializer, Visitor}; +use ::serde::ser::{self, Serialize, Serializer}; +use vitaminc_aead::Frame; +use vitaminc_protected::{Buffer, Controlled}; + +/// The name a raw node is written and read under. Only this crate's +/// reader and writer know it. +pub(crate) const TOKEN: &str = "$recipher_frame::serde::raw"; + +thread_local! { + /// Set while this crate's writer takes a raw node's bytes, or its reader + /// hands them over. A raw node refuses to be written or read when it is + /// not set, so another serde format never sees one as plain bytes. + static HANDING_OVER: Cell = const { Cell::new(false) }; +} + +/// Run `f` while a raw node is being handed over. +pub(crate) fn handing_over(f: impl FnOnce() -> T) -> T { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + HANDING_OVER.with(|flag| flag.set(self.0)); + } + } + let _reset = Reset(HANDING_OVER.with(|flag| flag.replace(true))); + f() +} + +fn is_handing_over() -> bool { + HANDING_OVER.with(Cell::get) +} + +/// The message of a raw node that another format was asked to write or +/// read. +const ONLY_HERE: &str = "a raw frame node is written and read only by recipher_frame::serde"; + +/// Write `node`, the bytes of one frame node, as it is. +/// +/// # Errors +/// +/// Through `serializer`'s error, in these cases: +/// +/// - The bytes are not exactly one well-formed node. +/// - The node would nest deeper than a frame allows where it is written. +/// - The serializer is the storage profile's, or another format's. +pub fn serialize(node: &Buffer, serializer: S) -> Result { + serialize_bytes(node.risky_ref(), serializer) +} + +/// [`serialize`] for a node held in a slice. +/// +/// # Errors +/// +/// As [`serialize`]. +pub fn serialize_bytes(node: &[u8], serializer: S) -> Result { + serializer.serialize_newtype_struct(TOKEN, &Node(node)) +} + +/// Read the next node as it is, into a [`Buffer`] that is wiped when it is +/// dropped. +/// +/// # Errors +/// +/// Through `deserializer`'s error: the deserializer is the storage +/// profile's, or another format's. +pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_newtype_struct(TOKEN, NodeVisitor) +} + +/// A raw node's bytes. Only this crate's writer takes them. +struct Node<'a>(&'a [u8]); + +impl Serialize for Node<'_> { + fn serialize(&self, serializer: S) -> Result { + if !is_handing_over() { + return Err(::custom(ONLY_HERE)); + } + serializer.serialize_bytes(self.0) + } +} + +/// Takes a raw node's bytes from this crate's reader. +struct NodeVisitor; + +impl<'de> Visitor<'de> for NodeVisitor { + type Value = Buffer; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a frame node") + } + + fn visit_bytes(self, bytes: &[u8]) -> Result { + if !is_handing_over() { + return Err(E::custom(ONLY_HERE)); + } + // The reader hands over a node of a frame it has parsed, so this + // holds; it is checked again so the value is one node whatever + // handed it over. + Frame::parse(bytes).map_err(|_| E::custom("not one frame node"))?; + let mut node = Buffer::with_capacity(bytes.len()); + node.extend_from_slice(bytes); + Ok(node) + } +} + +#[cfg(test)] +mod tests; diff --git a/packages/recipher-frame/src/serde/raw/tests/mod.rs b/packages/recipher-frame/src/serde/raw/tests/mod.rs new file mode 100644 index 000000000..1ebd699a0 --- /dev/null +++ b/packages/recipher-frame/src/serde/raw/tests/mod.rs @@ -0,0 +1,265 @@ +use quickcheck_macros::quickcheck; +use serde::{Deserialize, Serialize}; +use vitaminc_aead::frame::{ARRAY, MAX_DEPTH, OBJECT, PASSTHROUGH}; +use vitaminc_aead::plaintext::{Int, Logical, Physical, Raw}; +use vitaminc_aead::to_frame; +use vitaminc_protected::{Buffer, Controlled}; + +use crate::serde::{from_slice, to_vec}; + +/// A row whose `value` is a raw node. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Row { + name: String, + #[serde(with = "crate::serde::raw")] + value: Buffer, +} + +fn buffer(bytes: &[u8]) -> Buffer { + let mut out = Buffer::new(); + out.extend_from_slice(bytes); + out +} + +fn row(value: &[u8]) -> Row { + Row { + name: "n".to_owned(), + value: buffer(value), + } +} + +/// A frame of `depth` nested arrays around a null: `depth` levels below +/// its root. +fn nested(depth: usize) -> Vec { + let mut out = Vec::new(); + for _ in 0..depth { + out.extend([ARRAY, 1, 0, 0, 0]); + } + out.extend(to_frame(None::).expect("a null").risky_ref()); + out +} + +/// Frames of nodes that serde has no model for, and of nodes that it has. +fn nodes() -> Vec> { + let frame = |value: Buffer| value.risky_ref().to_vec(); + let date = Raw(Some(Logical::Date), Physical::Int(Int::I32(19_000))); + let mut passthrough = vec![PASSTHROUGH]; + passthrough.extend(frame(to_frame("clear").expect("text"))); + vec![ + frame(to_frame(date).expect("a date")), + passthrough, + frame(to_frame(None::).expect("a null")), + frame(to_frame(vec![1u32, 2]).expect("an array")), + frame(to_frame(std::collections::BTreeMap::from([("k", "v")])).expect("an object")), + nested(MAX_DEPTH - 1), + ] +} + +#[test] +fn a_node_is_written_as_it_is_and_read_back_as_it_is() { + for node in nodes() { + let written = to_vec(&row(&node)).expect("written"); + let mut expected = vec![OBJECT, 2, 0, 0, 0]; + expected.extend(to_vec_fields(&node)); + assert_eq!(written.risky_ref().as_slice(), expected.as_slice()); + let back: Row = from_slice(written.risky_ref()).expect("read"); + assert_eq!(back.value.risky_ref().as_slice(), node.as_slice()); + assert_eq!(back.name, "n"); + } +} + +/// The two entries of a [`Row`], as the writer lays them out. +fn to_vec_fields(node: &[u8]) -> Vec { + let mut out = Vec::new(); + out.extend(4u32.to_le_bytes()); + out.extend(b"name"); + out.extend(to_frame("n").expect("text").risky_ref()); + out.extend(5u32.to_le_bytes()); + out.extend(b"value"); + out.extend(node); + out +} + +#[test] +fn bytes_that_are_not_one_node_are_refused_without_repeating_them() { + let text = to_frame("forged-secret") + .expect("text") + .risky_ref() + .to_vec(); + let mut two = text.clone(); + two.extend(&text); + let truncated = &text[..text.len() - 1]; + for bad in [&[][..], truncated, &two, &[0xEE][..]] { + let error = to_vec(&row(bad)).expect_err("refused"); + let message = error.to_string(); + assert!(message.contains("raw frame node"), "{message}"); + assert!(!message.contains("forged"), "{message}"); + assert_eq!(error.field(), Some("value")); + } +} + +/// A raw node at depth 1 may be at most `MAX_DEPTH - 1` levels deep. +#[test] +fn the_depth_limit_counts_the_node_where_it_is_written() { + assert!(to_vec(&row(&nested(MAX_DEPTH - 1))).is_ok()); + assert!(to_vec(&row(&nested(MAX_DEPTH))).is_err()); +} + +#[test] +fn the_storage_profile_refuses_a_raw_node() { + let node = to_frame(1u32).expect("a number"); + assert!(crate::storage::to_vec(&row(node.risky_ref())).is_err()); + + let written = to_vec(&row(node.risky_ref())).expect("written"); + let mut blob = crate::storage::HEADER.to_vec(); + blob.extend(written.risky_ref()); + assert!(crate::storage::from_slice::(&blob).is_err()); +} + +#[test] +fn another_format_refuses_a_raw_node() { + let node = to_frame(1u32).expect("a number"); + let error = serde_json::to_string(&row(node.risky_ref())).expect_err("refused"); + assert!(error.to_string().contains("raw frame node"), "{error}"); + assert!(serde_json::from_str::(r#"{"name":"n","value":[1]}"#).is_err()); + assert!(serde_json::from_str::(r#"{"name":"n","value":"AQ=="}"#).is_err()); +} + +#[quickcheck] +fn any_bytes_are_written_as_one_node_or_refused(bytes: Vec) -> bool { + match to_vec(&row(&bytes)) { + Ok(written) => { + let back: Row = from_slice(written.risky_ref()).expect("what was written reads"); + back.value.risky_ref().as_slice() == bytes.as_slice() + } + Err(_) => vitaminc_aead::Frame::parse(&bytes).is_err(), + } +} + +#[quickcheck] +fn any_frame_reads_as_a_row_or_is_refused(bytes: Vec) -> bool { + let _ = from_slice::(&bytes); + true +} + +/// A value that serde writes through one of its own calls, never as bytes. +#[derive(Clone, Copy, Debug)] +enum NotBytes { + Bool, + I8, + I16, + I32, + I64, + U8, + U16, + U32, + U64, + F32, + F64, + Char, + Str, + None, + Some, + Unit, + UnitStruct, + UnitVariant, + NewtypeStruct, + NewtypeVariant, + Seq, + Map, +} + +impl NotBytes { + const ALL: [NotBytes; 22] = [ + NotBytes::Bool, + NotBytes::I8, + NotBytes::I16, + NotBytes::I32, + NotBytes::I64, + NotBytes::U8, + NotBytes::U16, + NotBytes::U32, + NotBytes::U64, + NotBytes::F32, + NotBytes::F64, + NotBytes::Char, + NotBytes::Str, + NotBytes::None, + NotBytes::Some, + NotBytes::Unit, + NotBytes::UnitStruct, + NotBytes::UnitVariant, + NotBytes::NewtypeStruct, + NotBytes::NewtypeVariant, + NotBytes::Seq, + NotBytes::Map, + ]; +} + +impl Serialize for NotBytes { + fn serialize(&self, s: S) -> Result { + use serde::ser::{SerializeMap, SerializeSeq}; + match self { + NotBytes::Bool => s.serialize_bool(true), + NotBytes::I8 => s.serialize_i8(1), + NotBytes::I16 => s.serialize_i16(1), + NotBytes::I32 => s.serialize_i32(1), + NotBytes::I64 => s.serialize_i64(1), + NotBytes::U8 => s.serialize_u8(1), + NotBytes::U16 => s.serialize_u16(1), + NotBytes::U32 => s.serialize_u32(1), + NotBytes::U64 => s.serialize_u64(1), + NotBytes::F32 => s.serialize_f32(1.0), + NotBytes::F64 => s.serialize_f64(1.0), + NotBytes::Char => s.serialize_char('x'), + NotBytes::Str => s.serialize_str("x"), + NotBytes::None => s.serialize_none(), + NotBytes::Some => s.serialize_some(&1u8), + NotBytes::Unit => s.serialize_unit(), + NotBytes::UnitStruct => s.serialize_unit_struct("U"), + NotBytes::UnitVariant => s.serialize_unit_variant("E", 0, "V"), + NotBytes::NewtypeStruct => s.serialize_newtype_struct("N", &1u8), + NotBytes::NewtypeVariant => s.serialize_newtype_variant("E", 0, "V", &1u8), + NotBytes::Seq => s.serialize_seq(Some(0))?.end(), + NotBytes::Map => s.serialize_map(Some(0))?.end(), + } + } +} + +/// Writes `NotBytes` where a raw node's bytes go. +struct RawOf(NotBytes); + +impl Serialize for RawOf { + fn serialize(&self, s: S) -> Result { + s.serialize_newtype_struct(crate::serde::raw::TOKEN, &self.0) + } +} + +#[test] +fn a_raw_node_takes_bytes_and_nothing_else() { + for value in NotBytes::ALL { + let error = to_vec(&RawOf(value)).expect_err("refused"); + let message = error.to_string(); + assert!( + message.contains("holds its bytes and nothing else"), + "{value:?}: {message}" + ); + } +} + +#[test] +fn another_format_still_refuses_a_raw_node_after_one_is_written() { + let node = to_frame(1u32).expect("a number"); + to_vec(&row(node.risky_ref())).expect("written"); + let error = serde_json::to_string(&row(node.risky_ref())).expect_err("refused"); + assert!(error.to_string().contains("raw frame node"), "{error}"); +} + +#[test] +fn another_format_says_it_expected_a_frame_node() { + let Err(error) = serde_json::from_str::(r#"{"name":"n","value":[1]}"#) else { + panic!("a raw node read from JSON"); + }; + assert!(error.to_string().contains("a frame node"), "{error}"); +} diff --git a/packages/recipher-frame/src/write.rs b/packages/recipher-frame/src/write.rs index 435ea985e..d865db0cc 100644 --- a/packages/recipher-frame/src/write.rs +++ b/packages/recipher-frame/src/write.rs @@ -32,9 +32,10 @@ use vitaminc_aead::frame::{FrameWriteError, ARRAY, MAX_DEPTH, OBJECT}; use vitaminc_aead::leaf::{self, Form, ScalarError}; use vitaminc_aead::plaintext::{Float, Int, Physical}; use vitaminc_aead::tags::{self, STORAGE_MAP, STORAGE_SOME}; +use vitaminc_aead::Frame; use vitaminc_protected::{Buffer, Controlled}; -use crate::serde::{At, Error, Profile}; +use crate::serde::{raw, At, Error, Profile}; use crate::storage::{distinct, Invalid, MapKey}; /// A [`Profile`] as a type, so the writer is compiled once for each @@ -428,12 +429,33 @@ impl<'o, P: Profiled> ser::Serializer for Writer<'o, P> { ) -> Result<(), Error> { self.scalar(Physical::Text(variant)) } + /// A raw node ([`raw`]) is written as its bytes, in + /// the transport format only. The bytes are first checked to be one + /// node that fits the depth left. Any other newtype is written as the + /// value inside it. fn serialize_newtype_struct( self, - _name: &'static str, + name: &'static str, value: &T, ) -> Result<(), Error> { - value.serialize(self) + if name != raw::TOKEN { + return value.serialize(self); + } + if P::PROFILE != Profile::Transport { + return Err(Error::new( + "a raw frame node is not written in a storage blob", + )); + } + self.check_depth()?; + let start = self.out.len(); + raw::handing_over(|| value.serialize(Raw { out: self.out }))?; + let node = self.out.risky_ref().get(start..).unwrap_or_default(); + match Frame::parse_nested(node, self.depth) { + Ok((_, [])) => Ok(()), + _ => Err(Error::new( + "a raw frame node is not one well-formed node within the depth limit", + )), + } } fn serialize_newtype_variant( self, @@ -935,6 +957,141 @@ impl ser::Serializer for TextKeyWriter<'_> { } } +/// Takes a raw node's bytes onto the end of the frame, and refuses any +/// other value: a raw node holds bytes and nothing else. +struct Raw<'o> { + out: &'o mut Buffer, +} + +/// The refusal of anything but bytes in a raw node. +fn not_raw() -> Error { + Error::new("a raw frame node holds its bytes and nothing else") +} + +impl ser::Serializer for Raw<'_> { + type Ok = (); + type Error = Error; + type SerializeSeq = ser::Impossible<(), Error>; + type SerializeTuple = ser::Impossible<(), Error>; + type SerializeTupleStruct = ser::Impossible<(), Error>; + type SerializeTupleVariant = ser::Impossible<(), Error>; + type SerializeMap = ser::Impossible<(), Error>; + type SerializeStruct = ser::Impossible<(), Error>; + type SerializeStructVariant = ser::Impossible<(), Error>; + + fn serialize_bytes(self, v: &[u8]) -> Result<(), Error> { + self.out.extend_from_slice(v); + Ok(()) + } + fn serialize_bool(self, _: bool) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i8(self, _: i8) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i16(self, _: i16) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i32(self, _: i32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i64(self, _: i64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u8(self, _: u8) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u16(self, _: u16) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u32(self, _: u32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u64(self, _: u64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_f32(self, _: f32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_f64(self, _: f64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_char(self, _: char) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_str(self, _: &str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_none(self) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_some(self, _: &T) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit(self) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit_struct(self, _: &'static str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_newtype_struct( + self, + _: &'static str, + _: &T, + ) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: &T, + ) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_seq(self, _: Option) -> Result { + Err(not_raw()) + } + fn serialize_tuple(self, _: usize) -> Result { + Err(not_raw()) + } + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } + fn serialize_map(self, _: Option) -> Result { + Err(not_raw()) + } + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Err(not_raw()) + } + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7ab0bf090..3fa579609 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **An encrypted record as typed values** (#2029). A language binding asks + for the encrypted record as typed values, and moves it to its language + and back as a frame. No binding walks a tree or renames a key itself. + - `dynamic::record::EncryptedRecord` has one `EncryptedField` for each + field, in the plan's order. A field with `"null": "sql"` and no value + has no entry. A field has its outputs under Stack Encrypt's keys: + - `c`, a `Ciphertext` + - `eq`, `match`, `ore`, `ope`, and `ore_block`, each a `TermBytes` + - `passthrough`, a `PassthroughFrame` + - `target`, the bytes that a target type returned + - `record::encrypt` and `encrypt_with` return the form the caller names: + `StackCipherText`, `EncryptedRecord`, or `Vec` for a + batch (`EncryptedForm`). `record::decrypt` and `decrypt_with` take any + of them (`StoredForm`). So does the owned API, through `Planned`. + - A typed record has one sealed value under `c`. A sealed field whose + value is a list or a map is refused before any key is requested. An + empty list or map is refused too. The new reason is `not_one_value`. + The stored tree still takes such a value. + - Three pairs of functions move a record, a batch, or one field as a + frame: + - `EncryptedRecord::to_frame` and `EncryptedRecord::from_frame` + - `EncryptedRecord::batch_to_frame` and `batch_from_frame` + - `EncryptedField::to_frame` and `EncryptedField::from_frame` + + They use `recipher_frame::serde`. `c` is the sealed + value's stable bytes. A term and a target value are their bytes. A + passthrough is its frame node, as it is. + - The frame is a transport form, not a storage format. Store the bytes + inside it. + - Reading a frame checks its structure only. A refusal names the field, + the output, and the row of a batch, where there is one. Three new + reasons say what was wrong: + - `not_an_output`: a key that is not an output + - `not_sealed`: anything under `c` but one sealed value's bytes + - `batch_shape`: one record where a batch is asked for, or a batch + where one record is + - `Error::Record` has a new field, `output`: the key of the output at + fault, such as `c` or `eq`. `Error::output` returns it, and the payload + has it as `output`. A typed record sets it. `decrypt` and + `check_record` leave it `None` for the stored tree, so their payloads + do not change. Code that builds an `Error::Record` must set the new + field. + - A call that does not name its form, and passes the result only to + `decrypt`, now needs one: `record::encrypt::(..)`, + or a type on the variable. - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` @@ -1806,6 +1851,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **The message for `Reason::Unframeable` no longer says "passthrough".** + The message was "a passthrough value nests deeper, or holds a longer + value, than a frame carries". The message is now "a value nests deeper, + or holds a longer value, than a frame carries". The reason is also given + for a value to encrypt, and for a stored record written as a frame. The + name `unframeable` is unchanged. + - **The `Debug` text of `OpaqueBlob` and `JsonPlaintext` has changed.** Both types now derive vitaminc's `OpaqueDebug`, as the crate's other secret types do. The text starts with the type's full path and masks the diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 064f5c2b0..d2eb2d578 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -135,6 +135,31 @@ and never needs the field's type. Anything else of another type is refused with the reason `field_type`, and JavaScript's `undefined` with the reason `undefined`. A field that declares no type takes its value as it is. +A binding asks for the record as a +[`crate::dynamic::record::EncryptedRecord`]: `Planned::new(&plan, +row).encrypt_into(&keyset)` and [`crate::dynamic::record::encrypt`] return +the form the caller names, and a batch is a `Vec`. +[`crate::dynamic::record::EncryptedRecord::to_frame`] writes the record +as a frame, in a buffer that is wiped when it is dropped. The frame keeps +Stack Encrypt's keys. Each field is an object of its outputs: + +- `c` is the sealed value's bytes. +- An index term, and a `target` value, is its bytes. +- A passthrough field's value is the value itself. +- A field with `"null": "sql"` and no value has no entry. + +The binding builds its language's value from this frame, as it does for a +decrypted value. So in JavaScript the record `{ email, id }` is +`{ email: { c: Uint8Array, eq: Uint8Array }, id: { passthrough: 7n } }`. +The binding walks no tree and renames no key. + +A typed record has one sealed value under `c`. A sealed field whose +value is a list or a map is refused before any key is requested, with the +reason `not_one_value`. + +The frame is how the record crosses to the language, not how it is +stored. Store the bytes inside the frame. + ### Derive a query term A query is planned before any value exists: @@ -170,6 +195,19 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. +A binding reads the record back from its language's value as a frame. +[`crate::dynamic::record::EncryptedRecord::from_frame`] returns the record +to decrypt, and `decrypt` takes it as it takes the stored tree. Reading +the frame checks its structure only: `decrypt` checks that the record fits +the plan. + +- For a column that contains SQL `NULL`, leave the field out. That works + only for a field with `"null": "sql"`. +- The binding does not have to send the index terms. Decrypt reads only + `c`, `passthrough`, and `target`. +- A key that is not an output is refused with the reason `not_an_output`. + The error names the field, and the row of a batch. + ### One value as one ciphertext A record is not the only stored form. Rust's `keyset.encrypt(value)` diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 3a5648e0b..6db880537 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -599,9 +599,20 @@ mod tests { row: Some(2), reason: Reason::NotAnObject, found: Some(crate::dynamic::Found::Sealed), + output: None, }), json!({ "reason": "not_an_object", "row": 2, "found": "sealed" }), ), + ( + Box::new(Error::Record { + field: Some("email".to_owned()), + row: Some(1), + reason: Reason::NotSealed, + found: None, + output: Some("c".to_owned()), + }), + json!({ "field": "email", "reason": "not_sealed", "row": 1, "output": "c" }), + ), ( Box::new(Error::SourceFailed { field: Some(name()), diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 23771176e..f42ebaaec 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -45,6 +45,8 @@ //! language is the same bytes. The one step that stays dynamic is //! dispatching a value whose type is known only at run time to the typed //! term operation, which [`IndexSpec`](crate::target::IndexSpec)'s `Index` impls do. +//! * [`record::EncryptedRecord`] — an encrypted record as typed outputs. A +//! binding moves it to its language and back as a frame. //! * [`read_json`] and [`json_frame`] — a `json` field's document, from //! the JSON text a binding hands over and back to it. //! * [`TargetResolver`] — the EQL types a build holds, installed by the host diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 8f38d5a04..6e694c8bb 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -81,9 +81,10 @@ use std::sync::Arc; use zeroize::Zeroize; use super::query::{field_operators, find, query_term, QueryTerm}; +use super::record::encrypted::form::{Shape, Shaped}; use super::record::{ - self, name_target, open_record, shape_record, write_record, Absent, Context, FieldPlan, Plan, - Rows, Verb, + self, in_form, name_target, open_record, shape_batch, shape_row, write_record, Absent, Context, + EncryptedForm, EncryptedRecord, FieldPlan, Plan, Rows, StoredForm, Verb, }; use super::target::{NoTargets, TargetResolver}; use super::{Error, Op, Reason, TermBytes}; @@ -96,9 +97,7 @@ use crate::target::{ Indexes, OptionalContext, Owned, Pending, }; use crate::target::{Step, YIELD_EVERY}; -use crate::{ - CipherRef, CipherText, Encrypt, KeysetCipher, Label, NonEmpty, PlanError, StackCipherText, -}; +use crate::{CipherRef, Encrypt, KeysetCipher, Label, NonEmpty, PlanError, StackCipherText}; use vitaminc_aead::frame::{Frame, OwnedFrame}; /// The resolver of a build without EQL types, for [`Plan::field`]. @@ -345,83 +344,96 @@ impl Plan { } } -/// A record under a plan encrypts to the stored row: every field under its -/// own context, the caller's scope and then its bindings after the plan's -/// own. The value is an [`OwnedFrame`], or a [`Frame`] borrowed from bytes -/// the caller keeps. The borrowed form reads the frame in place; the owned -/// form consumes it. -impl<'p, V, R> EncryptTarget> for StackCipherText -where - V: Encrypt + 'p, - for<'x> &'x V: Encrypt, - Planned<'p, Plan, V, R>: Zeroize, - R: TargetResolver + 'p, -{ - type ContextInput = OptionalContext; - fn encryption<'s, K: 'static>( - ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput> - where - Planned<'p, Plan, V, R>: 's, - { - Encryption::from_build( - contexts::caller_leaf(), - move |source: &Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { - encrypt_record( - cipher, - source.plan, - &source.value, - &source.resolver, - context, +/// A record under a plan encrypts to a stored record, in the form that the +/// caller names. The form is the stored tree ([`StackCipherText`]), one +/// typed record ([`EncryptedRecord`]), or a batch of them +/// (`Vec`). Every field is sealed under its own context, +/// then the caller's scope, and then its bindings after the plan's own. +/// +/// The value is an [`OwnedFrame`], or a +/// [`Frame`] borrowed from bytes the caller keeps. The borrowed form reads +/// the frame in place; the owned form consumes it. +macro_rules! encrypts_to { + ($form:ty) => { + impl<'p, V, R> EncryptTarget> for $form + where + V: Encrypt + 'p, + for<'x> &'x V: Encrypt, + Planned<'p, Plan, V, R>: Zeroize, + R: TargetResolver + 'p, + { + type ContextInput = OptionalContext; + fn encryption<'s, K: 'static>( + ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput> + where + Planned<'p, Plan, V, R>: 's, + { + Encryption::from_build( + contexts::caller_leaf(), + move |source: &Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { + encrypt_record( + cipher, + source.plan, + &source.value, + &source.resolver, + context, + ) + }, ) - }, - ) - } - fn owned_encryption<'s, K: 'static>( - ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput, Owned> - where - Planned<'p, Plan, V, R>: 's, - { - Encryption::from_owned_build( - contexts::caller_leaf(), - move |source: Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { - let Planned { - plan, - value, - resolver, - } = source; - encrypt_record(cipher, plan, value, &resolver, context) - }, - ) - } + } + fn owned_encryption<'s, K: 'static>( + ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput, Owned> + where + Planned<'p, Plan, V, R>: 's, + { + Encryption::from_owned_build( + contexts::caller_leaf(), + move |source: Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { + let Planned { + plan, + value, + resolver, + } = source; + encrypt_record(cipher, plan, value, &resolver, context) + }, + ) + } + } + }; } -/// The record lowered under the plan extended by the caller's context, or -/// the refusal. -fn encrypt_record<'a, K: 'static>( +encrypts_to!(StackCipherText); +encrypts_to!(EncryptedRecord); +encrypts_to!(Vec); + +/// The record lowered under the plan extended by the caller's context, in +/// the form `T`, or the refusal. +fn encrypt_record<'a, K: 'static, T: EncryptedForm>( cipher: &'a KeysetCipher<'_, K>, plan: &Plan, value: impl Encrypt, resolver: &(impl TargetResolver + ?Sized), context: OptionalContext, -) -> Pending<'a, StackCipherText, K> { +) -> Pending<'a, T, K> { let plan = match plan.under_caller(context.into_inner()) { Ok(plan) => plan, Err(error) => return Pending::failed(cipher, wrap(error)), }; - match Planned::with_resolver(&*plan, value, resolver).run_encrypt(cipher) { - Ok(pending) => pending, + match Planned::with_resolver(&*plan, value, resolver).run_encrypt(cipher, T::SHAPE) { + Ok(pending) => in_form(pending), Err(error) => Pending::failed(cipher, wrap(error)), } } -/// A stored row under a plan decrypts to its values, under the caller's -/// scope and bindings. A row from another keyset than the one the call +/// A stored record under a plan, in any of its forms ([`StoredForm`]), +/// decrypts to its values, under the caller's scope and bindings. A row from another keyset than the one the call /// names is refused before any key is retrieved. The opening is a closure /// the cipher runs later, which owns the plan, the row and the resolver, /// so the resolver is `Send + Sync + 'static` here where the encrypt side /// borrows it. -impl<'p, R> DecryptSource for Planned<'p, Plan, StackCipherText, R> +impl<'p, S, R> DecryptSource for Planned<'p, Plan, S, R> where + S: StoredForm, R: TargetResolver + Send + Sync + 'static, { type ContextInput = OptionalContext; @@ -470,13 +482,15 @@ where pub(super) fn run_encrypt<'a, K: 'static>( self, cipher: &'a KeysetCipher<'_, K>, - ) -> Result, Error> { + form: Shape, + ) -> Result, Error> { let Planned { plan, value, resolver, } = self; let rows = record::source_rows(value, plan)?; + record::check_form(&rows, plan, form)?; let extend = plan.declared_context(); let shape = plan.shape(); // Every target field of every row, in row-major order, run by the @@ -515,7 +529,7 @@ where cipher .run(description, values, extend) .zip(eql) - .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) + .try_map(move |(values, eql)| shape_row(form, values, eql, &shape, &absent)) } Rows::Batch(rows) => { let rows = rows @@ -566,10 +580,10 @@ where .zip(per_row) .map(|(values, (absent, count))| { let own: Vec> = eql.by_ref().take(count).collect(); - shape_record(values, own, &shape, &absent) + shape_row(form, values, own, &shape, &absent) }) .collect::, _>>() - .map(CipherText::Sequence) + .and_then(|rows| shape_batch(form, rows)) }) }; built_in_chunks(cipher, groups, row, finish) @@ -578,8 +592,9 @@ where } } -impl<'p, 'r, R> Planned<'p, Plan, StackCipherText, &'r R> +impl<'p, 'r, S, R> Planned<'p, Plan, S, &'r R> where + S: StoredForm, R: TargetResolver + ?Sized, { /// Lower the plan and open the stored row, or batch of rows, through @@ -613,7 +628,7 @@ where resolver, } = self; let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); - let rows = record::record_rows(value, plan)?; + let rows = record::stored_rows(value.into_stored(), plan)?; let extend = plan.declared_context(); let shape = plan.shape(); let cipher = cipher_ref.cipher(); diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 30acdc750..56dfcb5c8 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -143,6 +143,51 @@ //! `"c"` subtree with a passthrough carrying forged plaintext and have it //! reported as a successful decrypt. The encrypt-side refusal is what makes //! that a round-trip invariant rather than data loss. +//! +//! # An encrypted record as a type +//! +//! [`encrypt`] returns the record in the form the caller names, and +//! [`decrypt`] takes any of them back: +//! +//! - [`StackCipherText`], the stored tree. +//! - [`EncryptedRecord`], one record of typed outputs. +//! - `Vec`, a batch of them. +//! +//! An [`EncryptedRecord`] has one [`EncryptedField`] for each field, in the +//! plan's order. A field has its outputs under Stack Encrypt's keys: `c`, +//! `eq`, `match`, `ore`, `ope`, `ore_block`, `passthrough`, and `target`. A +//! field with `"null": "sql"` and no value has no entry. +//! +//! A typed record has one sealed value under `c`. A sealed field whose +//! value is a list or a map, an empty one included, is refused before any +//! key is requested ([`Reason::NotOneValue`]). The stored tree takes such a +//! value as it is. +//! +//! A language binding moves a typed record to its language and back as a +//! frame, with [`EncryptedRecord::to_frame`] and +//! [`EncryptedRecord::from_frame`]. It builds its language's value from the +//! frame, as it does for any value. So it walks no tree and renames no +//! key. Take a plan that seals and indexes `email`, and passes `id` +//! through. A row sealed from `{ "email": "ada@example.com", "id": "u-7" }` +//! has this frame: +//! +//! ```text +//! { "email": { "c": , "eq": }, "id": { "passthrough": "u-7" } } +//! ``` +//! +//! - `c` is the sealed value's stable bytes +//! ([`Ciphertext::to_bytes`](crate::Ciphertext::to_bytes)). +//! - A term, and a `target` value, is its bytes. +//! - `passthrough` is the field's value, as it is. +//! +//! The frame is a transport form, not a storage format. A binding stores +//! the bytes inside it. The sealed value's bytes and a term's bytes are +//! stable. The frame around them can change between releases, as any frame +//! can. +//! +//! Reading a frame checks its structure only. [`decrypt`] checks whether the +//! record fits a plan. It ignores outputs that the plan does not open, as it +//! does for the stored tree. use std::collections::BTreeSet; use std::fmt; @@ -171,6 +216,11 @@ use crate::{ }; use vitaminc_aead::IntoContext as _; +pub(super) mod encrypted; +use encrypted::form::{Shape, Shaped, Stored}; +use encrypted::in_row; +pub use encrypted::{EncryptedField, EncryptedForm, EncryptedRecord, StoredForm}; + /// The map key a target field's EQL value rides under in a stored record: /// wire format, like the output keys (see the /// [module docs](self#the-stored-record-is-wire-format)). @@ -1666,15 +1716,22 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// awaited, however many rows and fields there are. Its failure is the /// engine's [`Error`](crate::Error). /// -/// The result is per record a map of `field → { output-key → node }` (see -/// the [module docs](self#the-stored-record-is-wire-format)): `"c"` first, -/// then each term in the order the plan named its indexes. A batch is a -/// sequence of such maps. +/// The caller names the form of the result `T` ([`EncryptedForm`]): +/// +/// - [`StackCipherText`]: for each record, a map from each field to a map +/// of its outputs (see the +/// [module docs](self#the-stored-record-is-wire-format)). `"c"` is first, +/// then each term in the order the plan named its indexes. A batch is a +/// sequence of such maps. +/// - [`EncryptedRecord`]: one record of typed outputs, for a source that is +/// one record. +/// - `Vec`: a batch of them, for a source that is a batch. /// /// # Examples /// /// ``` -/// use stack_encrypt::dynamic::{record, frame::OwnedFrame}; +/// use stack_encrypt::dynamic::record::{self, EncryptedRecord}; +/// use stack_encrypt::dynamic::frame::OwnedFrame; /// use stack_encrypt::{AsProtectedRef, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { @@ -1696,7 +1753,12 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// // map writes it; a binding's codec writes the same bytes. /// let row = std::collections::BTreeMap::from([("age", 34u32)]); /// let frame = OwnedFrame::of(&row)?; -/// let sealed = record::encrypt(&keyset, &frame, &plan)?.await?; +/// let sealed: EncryptedRecord = record::encrypt(&keyset, &frame, &plan)?.await?; +/// +/// // A language binding builds its value from the record's frame. Here +/// // the frame is read straight back. +/// let stored = sealed.to_frame()?; +/// let sealed = EncryptedRecord::from_frame(stored.frame())?; /// /// // Only the ciphertext comes back, as the record's frame; the term is /// // one-way. @@ -1715,14 +1777,19 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// declares its kind and the kind check comes first. Decided here, before /// the pending exists. A failure of the pending itself is the engine's. /// +/// For a typed form, also [`Error::Source`] with [`Reason::BatchShape`] for +/// a batch given for one [`EncryptedRecord`], or one record for a batch, +/// and with [`Reason::NotOneValue`] for a sealed field whose value is a list +/// or a map, naming the field and the row of a batch. +/// /// A plan with a target field needs the resolver that built it: /// [`encrypt_with`]. This runs under [`NoTargets`], so such a plan is /// refused ([`Error::Target`]). -pub fn encrypt<'a, K: 'static>( +pub fn encrypt<'a, T: EncryptedForm, K: 'static>( cipher: &'a KeysetCipher<'_, K>, source: impl Encrypt, plan: &Plan, -) -> Result, Error> { +) -> Result, Error> { encrypt_with(cipher, source, plan, &NoTargets) } @@ -1743,13 +1810,23 @@ pub fn encrypt<'a, K: 'static>( /// /// As [`encrypt`], plus [`Error::Target`] for a target value of another /// kind than the type takes, or a name the resolver refuses. -pub fn encrypt_with<'a, K: 'static>( +pub fn encrypt_with<'a, T: EncryptedForm, K: 'static>( cipher: &'a KeysetCipher<'_, K>, source: impl Encrypt, plan: &Plan, resolver: &(impl TargetResolver + ?Sized), -) -> Result, Error> { - Planned::with_resolver(plan, source, resolver).run_encrypt(cipher) +) -> Result, Error> { + Planned::with_resolver(plan, source, resolver) + .run_encrypt(cipher, T::SHAPE) + .map(in_form) +} + +/// A record path's result, as the form `T` the caller asked for. The path +/// shapes its result as `T` asked, so another form is a defect here. +pub(super) fn in_form<'a, T: EncryptedForm, K: 'static>( + pending: Pending<'a, Shaped, K>, +) -> Pending<'a, T, K> { + pending.try_map(|shaped| T::from_shaped(shaped).ok_or(crate::Error::ResponseShape)) } /// Derive the EQL query value of one target field for one plaintext: the @@ -1849,6 +1926,11 @@ pub(super) fn name_target(error: TargetError, field: &str) -> TargetError { /// Decrypt a record — or a batch — produced by [`encrypt`] under the same /// plan. /// +/// `record` is in any of the forms [`encrypt`] returns ([`StoredForm`]): +/// the stored tree, one [`EncryptedRecord`], or a batch of them. A typed +/// record is checked against the plan as the stored tree is. A refusal of a +/// row of a typed batch names the row. +/// /// Only the `"c"` and `"passthrough"` outputs participate: terms are /// one-way. The stored tree is checked and read here, with no cipher: that /// is [`check_record`], and it is where [`Error::Record`] comes from. What @@ -1897,7 +1979,7 @@ pub(super) fn name_target(error: TargetError, field: &str) -> TargetError { /// refused ([`Error::Target`]). pub fn decrypt<'a, K: 'static>( cipher_ref: impl Into>, - record: StackCipherText, + record: impl StoredForm, plan: &Plan, expected: Option