diff --git a/docs/plans/2026-12-01-one-walk-records-and-host-built-types.md b/docs/plans/2026-12-01-one-walk-records-and-host-built-types.md new file mode 100644 index 000000000..b0f20b50d --- /dev/null +++ b/docs/plans/2026-12-01-one-walk-records-and-host-built-types.md @@ -0,0 +1,2330 @@ +# One walk for a record, and host-built stored types + +Status: draft, 1 December 2026, updated 6 December 2026. The decisions in +[Decisions](#decisions) are Dan Draper's. The steps are a proposal. + +A spike of the encrypt, decrypt, and query paths is in draft PR #2043. That +PR is not for merging. The table in [Groundwork](#groundwork) says which +groundwork pull requests exist. No other step is built. + +Code is cited as it stands on `next` at `b939de404`. The answers of 5 and 6 +December 2026 cite `next` at `bf69526db`. + +## Contents + +- [Summary](#summary) +- [Terms](#terms) +- [Decisions](#decisions) +- [Why](#why) +- [The design](#the-design) +- [What was checked](#what-was-checked) +- [Checks to make first](#checks-to-make-first) +- [Crate layout](#crate-layout) +- [Groundwork](#groundwork) +- [Phase 1: the record path](#phase-1-the-record-path) +- [Phase 2: queries](#phase-2-queries) +- [What does not change](#what-does-not-change) +- [Checks that must move with the code](#checks-that-must-move-with-the-code) +- [What this changes elsewhere](#what-this-changes-elsewhere) +- [Not in this plan](#not-in-this-plan) +- [Open questions](#open-questions) + +## Summary + +Today Stack Encrypt seals a record one field at a time and builds the +record's tree by hand afterwards. A field that is stored as an EQL type is +formatted in Rust by a resolver, for every language. A query comes back in a +form of its own. + +After this plan: + +- A record is walked once. Each field's ciphertext and terms come from that + walk, and the result is one `StackCipherText`. +- The tree has a node for a term. +- The tree crosses to Go and TypeScript in the transport codec. Each + language reads the tree with one deserializer. The deserializer calls a + visitor. +- A stored type, such as EQL's `TextEq`, is defined in the language that + uses it. Its visitor builds the stored value from the tree. `eql-codegen` + writes these types from the EQL catalog. +- Stack Encrypt has no resolver. Its record form and its query form do not + name EQL. The Go SDK has one encryption guest, not two. +- A query is a tree of terms, read by the same deserializer. +- A target is declared once. That one declaration encrypts it, decrypts it, + and gives its query terms. +- A value with an index is walked once. Today each operation walks it. +- A Rust struct and a record from a language binding use field + declarations of the same kind. A struct's record reads its fields with + closures. A plan's record reads them by name. +- The two crates have a layout a reader can follow: the three calls at the + top, and one place for each index. + +Rust still does the sealing, the term derivation, and the context binding. +The format of a stored type is written once for each language. + +## Terms + +| Term | Meaning | +|---|---| +| Stack Encrypt, `stack-encrypt` | The Rust library that encrypts values and derives search terms | +| EQL | Encrypt Query Language: the SQL library that stores and queries encrypted values in PostgreSQL | +| Language binding | The interface between the Rust code and Go or TypeScript | +| Record | A set of named fields encrypted together, such as one database row | +| Plan | The description of a record that a language binding sends as data: its fields, and each field's indexes and context | +| Target | The type a plaintext is encrypted into, such as `Ciphertext` or an EQL type | +| Walk | One pass over a value. It reports each scalar, map, and sequence, in order, to a sink | +| Sink | What a walk reports to. A sink stages what an operation needs from the value | +| Declaration | A value that says how a plaintext becomes a target: a sink for the walk, and a finishing step. See [A declaration](#a-declaration) | +| Term | The bytes an index derives from a value, such as an equality term. A record stores terms beside the ciphertext, and a query sends them | +| Leaf | One sealed scalar in the encrypted tree | +| JSON tree | The stored form of a JSON document that can be searched: one entry for each node, with selectors and tokens. It is EQL's `JsonSearch`. The code in `stack-encrypt` calls it the JSON index | +| Opaque JSON | A JSON document stored as one ciphertext of its JSON text, with no index. It is EQL's `Json` | +| `StackCipherText` | The encrypted tree: leaves, maps, sequences, and passthrough values. Step 1.3 adds a node for a term | +| AAD | Additional authenticated data: bytes that a leaf is sealed under and must be opened under. Here they come from the leaf's context and its place in the tree | +| Resolver | The code in `eql-bindings` that builds an EQL type's stored form in Rust today, for every language | +| Deserializer and visitor | In Go or TypeScript, the deserializer reads the tree and calls the visitor for each node. The visitor builds the value | +| Spike | Code written to test the design, in draft PR #2043. It is not for merging | +| G1 to G9 | The nine groundwork pull requests. See [Groundwork](#groundwork) | + +## Decisions + +Decisions by Dan Draper: + +- Encryption works as serde does. Any plaintext structure gives one + `StackCipherText`. A record is a `Map`, and a batch of records is a + `Sequence` of `Map`. +- One walk of a record reproduces what is stored today. No stored format + changes. The one exception is the prefix on an EQL value's `c`, below. +- A record's plan implements `EncryptTarget`. The plan builds an interim + step with the combinators, and the cipher seals that step. +- The tree crosses to a language binding in the transport codec. +- Each language defines its stored types, and builds them from the tree with + a deserializer and a visitor. The resolvers are removed. +- A term is a node of its own in the tree. The node contains bytes only. The + map key above the node says what kind of term it is. +- A query comes back as a `StackCipherText` too. That is the second phase. +- The public API may change. +- Decrypt needs only what opens. A stored value that has no term still + decrypts. Decided on 5 December 2026. +- A match filter is built the same way in every EQL type. Text that cuts + no token is stored with the empty filter, in `TextMatch` as in + `TextSearch`. Decided on 5 December 2026. +- `vitaminc-prf` and `vitaminc-ore` move into this repository. Decided on 5 + December 2026. +- A conversion is declared for one direction at a time: `convert_into` for + what encrypt returns, and `convert_from` for what decrypt takes. Decrypt + has an input type of its own. One declaration still gives the fields and + their contexts for both directions. Decided on 5 December 2026. +- The JSON scheme can move from `stack-encrypt` to EQL at the end of phase + 2, if the standard declarations can declare a JSON document. Decided on 5 + December 2026. +- `zip` leaves a side that opens nothing out of what decrypt takes. A + declaration says in its type whether it opens, so a term that opens can + be added later. Decided on 5 December 2026. +- A plan says which of two forms a null takes: a value that is missing + from the stored record, or a null that is sealed. The two are different + stored forms. The choice has nothing to do with a database, so the first + form is named `"omitted"`, not `"sql"`. The second keeps the name + `"sealed"`. Decided on 5 December 2026. +- On encrypt, a record with no entry for a field is a null for an + `"omitted"` field, as it is today. For any other field it is an error. + Decided on 5 December 2026. +- The Go SDK's struct tag becomes `null=omitted`. `null=sql` stays for a + time as a deprecated spelling. Decided on 5 December 2026. +- A record of a Rust struct is built from closures, with no field names. + The closure reads the field and gives its type. A plan's record still + reads fields by name. Decided on 6 December 2026. +- The Go SDK needs no code generator. It reads the fields of a struct while + the program runs, as `encoding/json` does. The call is + `cipher.Encrypt(ctx, users, &rows)`. A stored struct can also have a + method that says how it is sealed, and the compiler then checks each + field. Decided on 5 December 2026. +- An SDK mirrors the Rust API as closely as is idiomatic in its language. + The Go principle "Generate code with a Go tool" is dropped. The rule that + no call takes a context is dropped too. In Go the encryption context is + given with `Scope` and `Bind`. Decided on 5 December 2026. +- The next EQL release waits until this plan is done. What the plan no + longer needs is deleted, with no deprecation. Decided on 5 December 2026. +- An EQL value's `c` is written with the prefix `rc:1:`, in place of + `stack-encrypt:1:`. A reader accepts both, so every stored value still + opens. Decided on 5 December 2026. +- On decrypt, the stored `i` of an EQL value has to match the plan's label, + as in the Go SDK today. The label is independent of the name of the + database column, so a renamed column does not stop old rows from opening. + Decided on 5 December 2026. +- On decrypt, a term that the declaration has no index for is ignored. A + field that the declaration does not name is ignored too, unless the + declaration asks for it to be refused. Decided on 5 December 2026. +- The form that crosses to a language binding is not frozen. Only the + stored format is. Decided on 5 December 2026. +- Decrypt opens the fields that a stored record has. The output type + decides what a missing field means. The record path does not refuse a + record for a field that is not there. Stack Encrypt does not model the + database: EQL and an ORM adapter do. Decided on 5 December 2026. + +Decisions from the spike, made between 2 December 2026 and 5 December 2026: + +- A target says how it is encrypted with a declaration: a sink for one walk + of the value, and a finishing step. The combinators become adapters over + that one trait, as the standard library's iterator adapters are. A + declaration is the interim step that the third decision names. +- One declaration of a field seals the field, opens it, and gives its query + terms. +- A record's plan builds a declaration at run time. The derive writes one + at compile time. Both use the same adapters. +- `plaintext.encrypt_into::()` is to `EncryptTarget` what `collect` is + to `FromIterator`. The impl of `EncryptTarget` says which plaintext + types a target takes. +- The JSON tree is one operation in a declaration. +- Today's combinators are removed when every target has moved: + `Encryption`, `Decryption`, and `KeysetCipher::run`. +- The encrypt sink has no context. One function derives each leaf's + additional authenticated data (AAD) from the leaf's place in the tree. +- A value staged for encryption is a `Node`. Only + `target::Pending` is called `Pending`. +- `Cipher` is the only cipher trait. A tree is sealed with a closure, as it + is opened. `AsyncCipher` is deleted. +- The AES-256-GCM cipher moves into `vitaminc-aead`, and + `vitaminc-normalize` moves into this repository. Nothing here then depends + on `vitaminc-encrypt` 0.10. +- The AES-256-GCM cipher then moves into `stack-encrypt`, as crate-private + functions, not a trait. The stored layout of a leaf moves with it. + `vitaminc-aead` then has no encryption primitive and no key. It has the + tree format, the walk, and the `Cipher` trait. The move into + `stack-encrypt` was decided on 5 December 2026, after #2044 had moved the + cipher into `vitaminc-aead`. +- `cargo deny` and `cargo vet` cover `stack-encrypt` before the cipher moves + there, so that its AES dependencies stay checked. +- The two crates get the layout in [Crate layout](#crate-layout). +- `encrypt_tree` and `decrypt_tree` are removed. `run_decryption` is + private. +- The readability refactor of the dynamic record path (#2042) merges first. + +**The prefix on `c`.** An EQL value's `c` is a prefix followed by base64 of +the sealed leaf. Today the prefix is `stack-encrypt:1:` +(`packages/eql/crates/eql-bindings/src/encryption.rs:135`). No decision +record chose it, and production data has it. + +The prefix becomes `rc:1:` for every value that is written. A reader +accepts both prefixes, so every stored value still opens. The two prefixes +differ from their first character, so a reader cannot mistake one for the +other. + +The change is one-way for software that is already released. A reader from +before the change does not open a value with the new prefix. So the change +takes two releases: + +1. The first release accepts both prefixes, and still writes the old one. +2. The second release writes `rc:1:`. + +A program upgrades every reader to the first release before any writer +moves to the second. No stored value is encrypted again. + +## Why + +### A record is sealed field by field + +A whole value is already one walk: `StackCipherText` implements +`EncryptTarget` for any source +(`packages/stack-encrypt/src/target/operations.rs:1717`). A record is not +one walk. The dynamic record path builds one operation for each field, and +`shape_record` builds the `Map` by hand. Three costs follow: + +- **The source is copied.** `into_raw_fields` writes each field's value into + a frame of its own, so that each field can be walked alone. +- **Types are erased and recovered.** `lift` boxes each field's output, and + `shape_record` uses `FieldShape` to take the output back out. +- **Terms lose their type.** `shape_record` stores each term as a + passthrough node of bytes (`bytes_node`, + `packages/stack-encrypt/src/dynamic/record.rs:713`). + +The pieces for one walk exist in `vitaminc-aead`: `Sink`, `Tee` +(`packages/vitaminc-aead/src/plaintext/tee.rs`), `EncryptSink::root` +(`packages/vitaminc-aead/src/encrypt_sink.rs:273`), and `Either` +(`packages/vitaminc-aead/src/typed.rs:856`). The first decision record of +`vitaminc-aead` says "Encrypt-plus-terms is `Tee(EncryptSink, Terms)` with +no special wrapper". Stack Encrypt runs each piece alone, once for each +field. + +### A field is described three times, and its value is walked for each operation + +A field with an index has three descriptions today: + +- its encryption, an `Encryption` built from the combinators + (`packages/stack-encrypt/src/target/operations.rs:92`); +- its decryption, a `Decryption` (`operations.rs:108`); +- its query, the index's `query_operation` + (`packages/stack-encrypt/src/target/index.rs:292`). + +Only tests check that the three agree. + +Each operation also walks the value for itself. `indexed` joins a ciphertext +operation with one operation for each index (`index.rs:1019`), and each of +them reads the plaintext. The spike counted the walks of one value with an +equality index. There were two. + +### A stored type is built in Rust for every language + +A plan field can name a type such as `TextEq`. A resolver then runs the +type's Rust code and returns finished JSON bytes +(`packages/stack-encrypt/src/dynamic/target.rs:560`, +`packages/eql/crates/eql-bindings/src/encryption/targets.rs:887`). Three +things follow from the resolver: + +- every entry point has a second form that takes a resolver; +- the Go SDK builds, embeds, and releases a second guest with the EQL types; +- Stack Encrypt's record form and query form name EQL. + +A language cannot define a stored type of its own. A language can only name +a type that Rust has. + +### A query has its own output form + +`dynamic::query_term` returns a `QueryTerm` +(`packages/stack-encrypt/src/dynamic/query.rs:281`). A `QueryTerm`'s operand +has one of four fixed shapes (`:290`). The answer crosses through serde. +Each language SDK has a second reader for the answer, such as Go's +`parseQueryTerm` (`languages/golang/encrypt/query.go:197`). A query with +more structure than those four shapes has no form to use. + +## The design + +| Part | Where it runs | What it does | +|---|---|---| +| The walk | Rust, `stack-encrypt` | Visits the record once. The record's declaration gives each field the sinks its plan asks for | +| Sealing | Rust | One key request for the whole call, then one sealed tree | +| The tree | `vitaminc-aead` | `Single`, `Sequence`, `Map`, the two empty markers, `Passthrough`, and a new term node | +| The crossing | `recipher-frame`, with its Go and TypeScript halves | The transport codec. The codec has no stability guarantee, so it can change | +| The deserializer | Go and TypeScript | Reads the transport bytes and calls a visitor for each node | +| The stored type | Go and TypeScript | A visitor that builds the stored value, and a function that returns the sealed leaf to decrypt | + +A stored type is three things in the host language: + +1. The outputs the type asks for. They become the field's entry in the + plan. For `TextEq` the outputs are `c` and `eq`. +2. A visitor that reads the field's map and builds the value. +3. A function that returns the sealed leaf from a stored value, for decrypt. + For a type that stores its context, such as an EQL type's `i`, the + function first checks that context against the plan's label. + +The field's context is the plan's, as it is today. The resolver uses the +plan's parts under the field's label +(`packages/eql/crates/eql-bindings/src/encryption/targets.rs:448`). So a +plain field `email` under `users` has the same context as the EQL type +`TextEq` for `users.email`. So the two have the same equality term. + +An EQL value stores its context in `i`, and that `i` is built from the +plan's label. On decrypt, the stored `i` has to match the plan's label. A +value whose `i` differs is refused with `ContextMismatch`, as the Go SDK +refuses it today (`packages/stack-encrypt/src/target/context.rs:999`). The +host type makes that check. + +The label and the name of a database column are independent. The label +comes from the declaration, such as a Go struct tag. So a column can be +renamed in the database, and old rows still open: neither the label nor +`i` changes. + +A changed name in the declaration is a different act. It changes the label, +so old rows stop opening. The Go SDK's guide says not to do it +(`languages/golang/cmd/stashgen/README.md:95`). + +A match term is the same only when the plan field asks for the options that +the type fixes. That is why step 1.1 comes first. The experiments checked +equality and match only. The order types, `TextSearch`, and the JSON types +are in the checks to make first. + +### A declaration + +A declaration is a value that says how a plaintext becomes a target. It has +two parts: + +1. **A sink.** The plaintext is walked into it once. The sink stages what + the target needs: the plaintext tree to seal, and the normalized scalar + of each term. Nothing is sealed or keyed. The sink has no context. +2. **A finishing step.** It is handed what the walk staged, the cipher, and + one context. It requests the keys, seals the leaves, keys the terms, and + builds the target. + +A declaration is built as an iterator is built. An operation starts one. +Each adapter returns a small struct that is a declaration too. + +| Kind | Name | What it declares | +|---|---|---| +| Operation | `ciphertext()` | Seal the value | +| Operation | `equality()`, and one for each other index | Derive the index's term | +| Operation | `passthrough()` | Keep the value in the clear | +| Operation | `json_document(options)` | Seal a document as a JSON tree | +| Adapter | `a.zip(b)` | Both, from one walk, under one context | +| Adapter | `a.convert_into(to)`, `a.try_convert_into(to)` | Convert what encrypt returns | +| Adapter | `a.convert_from(from)` | Convert what decrypt takes into the parts that `a` opens | +| Adapter | `a.accepting::<C>()` | Take a context that converts to the one `a` needs | +| Adapter | `a.under(own)` | Run under a context of its own | +| Record | `record::<User>().field(select, a)` | A record of a Rust struct. The closure `select` reads one field, and `a` is that field's declaration. No field has a name | +| Adapter | `a.entry("email")` | Read the entry of that name from a record. A plan from a language binding uses it | +| Adapter | `a.under_field("email")` | Run `a` under the record's context, then its own name. For a record whose context is one of its fields | +| Adapter | `fields.context_from("tenant")` | Read the record's context from its entry `tenant`, keep that entry in the clear, and hand the context to each field | +| Adapter | `fields.record()` | On encrypt, refuse an entry that no field takes | +| Collection | `Option<A>` | A part that a field has or does not have | +| Collection | `Fields<A>` | The fields of a record, collected from an iterator | + +**A field.** A value stored as a ciphertext with an equality term is one +declaration. The spike calls it `indexed_equality()`, and it does what +today's `indexed(Equality)` does +(`packages/stack-encrypt/src/target/declaration.rs:507` in the spike): + +```rust +fn indexed_equality() -> impl Declaration<Output = Encrypted<EqualityTerm>> { + ciphertext() // seal the value + .accepting::<CallerContext>() // take the context the term takes + .zip(equality()) // and derive its equality term + // Encrypt returns a pair: (StackCipherText, EqualityTerm). + // `convert_into` makes the pair the stored type. + .convert_into(|(ciphertext, terms)| Encrypted { ciphertext, terms }) + // Decrypt takes the parts that open. An equality term opens + // nothing, so `zip` leaves it out. `convert_from` gives the + // ciphertext from a stored value. + .convert_from(|stored: Encrypted<EqualityTerm>| stored.ciphertext) +} +``` + +`zip` joins two declarations, and encrypt returns a pair. The two +conversions are separate: + +- `convert_into` changes only what encrypt returns. Here it turns the pair + into a named type. +- `convert_from` changes only what decrypt takes. Here it takes a stored + value apart, and gives the ciphertext. Decrypt never reads the term. + +Each declaration says, in its type, whether it has something to open. +`zip` reads that from its two sides: + +- when both sides open, decrypt takes a pair; +- when one side opens, decrypt takes that side's part alone. + +Every index today is one-way, so a term has no part. A later index could +store something that opens: the similarity work opens an embedding to +filter on the client. Such a term would say that it opens. It would then +have a part in the pair. Nothing else would change. + +A small prototype of `zip` and the two conversions compiled on Rust 1.94.1. +It had no position marker such as `Right<Here>` in any signature. It did +not cover `Option`, `Fields`, or `under`. + +A second prototype did the same for the query lookup. Each index says +whether it has an index for each operator, in one line for each operator. +`zip` reads that from its two sides. So `field.query::<Eq>()` needs no +position marker either. + +Two mistakes still do not compile: a query for an operator that no index +has, and a `zip` of two indexes for one operator. + +The spike has one adapter for both, `convert(to, from)`, and `map` for a +conversion with no way back. Step 1.4 builds the two separate adapters. + +**A record of a Rust struct.** A struct of two fields is one expression. +The derive writes it. `label(..)` stands for a field's own label: + +```rust +struct User { email: String, age: i32 } + +struct EncryptedUser { + email: Encrypted<EqualityTerm>, + age: StackCipherText, +} + +record::<User>() + .field(|u| &u.email, indexed_equality().under(label("users/email"))) + .field(|u| &u.age, ciphertext().under(label("users/age"))) + .convert_into(|(email, age)| EncryptedUser { email, age }) + .convert_from(|stored: EncryptedUser| (stored.email, stored.age)) + .plaintext_from(|(email, age)| User { email, age }) +``` + +No field has a name. Each closure reads one field of the struct, and gives +the compiler that field's type. So the sealed value always has the type +that the compiler checked. `field` takes the closure with the field's +declaration, so the two cannot get out of order. The name `plaintext_from` +is proposed. + +Each field's declaration is still a sink. Its trait has no plaintext type. +Only the record has the struct's type. + +On encrypt, each closure is called once. Its field is then walked into its +declaration's sink. The `email` value goes to both the ciphertext's sink +and the equality term's sink. In the finishing step, each field takes the +caller's context under its own label. One key request covers both +ciphertexts. + +On decrypt, `convert_from` takes an `EncryptedUser` apart, and each +ciphertext opens under its field's context. `plaintext_from` builds the +`User` from the opened fields. + +One mistake stays possible. `plaintext_from` takes the fields by position. +Two fields of the same type can be exchanged there, and the code compiles. +`next` has the same limit: `Decryption::zip` and `map` build a struct from +a tuple (`packages/stack-encrypt/src/target/operations.rs:1471`). + +Fields of distinct types cannot be exchanged. A struct is safe when each +field has a type of its own, such as `Email` for one and `Name` for +another. + +A prototype of a record built this way compiled and ran on Rust 1.94.1. It +did not cover a record whose context is one of its fields, or a batch. + +The spike built a struct's record by name, with `entry` and `record`. A +name is a string that a person writes, so a hand-written declaration could +check one field's type and seal another field's value. + +**A plan.** A plan builds a record at run time, from field declarations of +the same kind. A plan has no Rust struct, so it reads each field by name. +Each field's label and name come from the plan: + +```rust +plan.fields().iter() + .map(|field| { + // `label` is the plan's label. With the field's identity it + // gives the field's own label, such as `users/email`. + let own = join(label, field.identity())?; + Ok(planned(field)?.under(own).entry(field.name())) + }) + .collect::<Result<Fields<_>, _>>()? + .record() +``` + +`planned(field)` is the field's declaration. The plan says whether the +field has a ciphertext, a term, and a value in the clear. So the +declaration has each of the three as an `Option`. In the spike, +`fields_under_label` builds the record and `planned` builds a field +(`packages/stack-encrypt/src/dynamic/record/one_sink.rs:588` and `:504`). + +`zip` cannot join a plan's fields. Each `zip` makes a new type, and the +number of a plan's fields is known only at run time. So every field of a +plan has one type, with an `Option` for each part a field may lack. The +fields are then collected into a `Fields`, as a `Vec` is collected from an +iterator. + +**One declaration serves three calls.** + +| Call | Trait | What the declaration gives | +|---|---|---| +| Encrypt | `Declaration` | The sink and the finishing step | +| Decrypt | `Open` | `Open` has an input type of its own: the parts of the stored target that open. Those parts are taken apart under the one context, and one key request follows. Each tree is then opened, and its plaintext is walked into the sink of the output. That sink is a frame for a binding, or a Rust type | +| Query | `Answers<Op>` | `field.query::<Eq>()` is the declaration of the term that a query sends for `Eq`, under the field's own context | + +**One structure, two conversions.** The fields, their names, and each +field's context are declared once, and both directions use them. A +conversion is declared for one direction: + +- A declaration with `convert_into` and no `convert_from` encrypts and + gives its query terms. It does not decrypt, and the compiler says so. A + query type is declared this way: a query term has nothing to open. +- A declaration with `convert_from` decrypts. Its input can be smaller than + what encrypt returns. A field with an index can decrypt from its + ciphertext alone. + +A separate declaration for decrypt was considered. It would state each +field's label and entry name a second time. A mismatch between the two +would fail only at run time, as an AEAD error. One structure cannot +disagree with itself. + +**What the compiler checks.** + +- **One context for each target.** `zip` asks both sides to name the same + context type. +- **The plaintext's type.** `EncryptTarget<S>` is this design's + `FromIterator<A>`. `plaintext.encrypt_into::<T>()` is its + `collect::<B>()`. A target's impl says which plaintext types it takes. For + a field of a struct's record, the closure in `field(|u| &u.email, ..)` + gives the compiler the field's type, and reads the value. +- **The operator.** A declaration with no index that answers `Eq` has no + `query::<Eq>()`. Two indexes that both answer one operator do not + compile either. Today that second case is refused at run time. + +A record from a language binding has no Rust type, so its checks are made +during the walk, as they are today. + +## What was checked + +Three experiments ran. The first two are on local branches. The third is +draft PR #2043. None of them is for merging. + +**One walk of a record.** Four tests, with no change to a trait in +`vitaminc-aead`: + +| Test | Result | +|---|---| +| A field planned in `Tee(EncryptSink, Terms)` under its own root | The equality term is today's term, byte for byte. Today's `record::decrypt` opens the result | +| One walk of a whole record through a record sink | Every field is planned. No field is copied into a frame first. Today's decrypt opens the result | +| One walk of a batch | Each row is planned as its own root, and each row opens alone | +| A control | A field planned under another field's root does not open | + +**Stored types built in Go and TypeScript.** The types are `TextEq`, +`TextMatch`, and their two query types, each written in both languages: + +| Check | Result | +|---|---| +| Go's and TypeScript's stored values against Rust's | The same bytes, once `c` is set aside. `c` is sealed under a new key each time. For `TextMatch`, Go sent EQL's match options through a test-only call, because Go's plan cannot send them yet (step 1.1) | +| Rust's decryption of a value Go built | The value opens | +| A plan with no EQL type, on a value Rust built | The value opens, from the leaf inside `c` | +| Query values against Rust's | The same bytes, with nothing set aside | +| TypeScript on a tree the Go guest recorded | The same bytes, under the same test seed | +| Every truncation of a recorded tree | Refused in both languages. None panics or throws | + +The Go half needed no change in Rust. A plan field that lists +`outputs: ["c", "eq"]` already comes back as a map with those two keys. + +**One declaration for encrypt, decrypt, and query (#2043).** The spike is +built on #2042. The spike's code is in four files of +`packages/stack-encrypt/src`: `target/declaration.rs`, +`target/declaration/open.rs`, `target/declaration/query.rs`, and +`dynamic/record/one_sink.rs`. + +Each row compares the declaration with today's code, on the same input. + +| Call | Case | Result | +|---|---|---| +| Encrypt | A ciphertext with an equality term | The same term, key requests, and contexts. One walk of the value. Today's combinators make two | +| Encrypt | A Rust struct of two fields | The same term. Each field is under its own context | +| Encrypt | A frame from a binding, through the struct's declaration | The same term. No field is copied first | +| Encrypt | A record of a plan: with a context field, with a label, and with nothing to seal | The same fields, outputs, term, and number of keys. Today's decrypt opens it | +| Encrypt | A JSON document: as JSON text, as a Rust struct, and as a map from a binding | The same selectors and number of entries. Today's decrypt opens it | +| Decrypt | A ciphertext with its term | Opens, with the same key requests and contexts | +| Decrypt | A stored struct | Opens into a Rust struct that derives `Decrypt`, and into a frame | +| Decrypt | A record of a plan, for the same three plans | The same plaintext and number of keys as today's decrypt | +| Query | A field of a struct | The term the record stores, and today's query term | +| Query | A field of a plan | Today's `query_term`, and the term the record stores | + +Each of these is refused, in every call it applies to: + +- a field the declaration does not name, and a missing field; +- a changed context field, and another context; +- a ciphertext moved to another field's place; +- an operator that the field's index has no term for; +- a query of a plan whose context is a field. Today's code refuses it too. + +The compiler refuses each of these. Each was tried by hand: + +- a pair whose sides name two context types; +- a number, for a target that takes text; +- a record field whose type does not fit the field's target; +- a query of a declaration with no index; +- an operator that the index does not answer; +- two indexes that both answer one operator. + +The spike needed two additions to `vitaminc-aead`, and no change to `Sink`, +`MapSink`, or `SeqSink`: + +- `Option<S>` is a sink when `S` is one, so a field can have a sink or none. +- `EncryptSink::into(place)` writes its tree into a place the caller lends. + +The spike does not cover: + +- match terms, order terms, and an operator whose query term is not the + stored term; +- nulls, batches, and a plan's scopes and bindings with values; +- the JSON queries, and the opening of a JSON document; +- a derive that writes declarations; +- `contexts()` without a run, and the kinds of error. Every refusal in the + spike is `Error::Aead`. + +The spike differs from today's code in four ways. Step 1.4 fixes the first +three: + +- **Decrypt refuses a stored field that has no term.** Today's decrypt + ignores terms. This is wrong: a field with an index would not decrypt + from its ciphertext alone. The cause is that `Open::retrieve` takes the + whole stored output, term included + (`target/declaration/open.rs:69` in the spike). The spike rebuilds that + output from the stored map, and refuses a map with no `eq` + (`dynamic/record/one_sink.rs:567`). The term is then never read + (`open.rs:221`). Step 1.4 changes `Open` to take only the parts that + open. +- **On encrypt, the value is walked before the context is checked.** Today + the context is checked first. Decrypt is not affected: the spike checks + the context before anything opens (`open.rs:196`). Step 1.4 checks the + caller's context before the walk. See [The order of the + checks](#the-order-of-the-checks). +- **A typed `JsonPlaintext` is written to text and parsed again.** Today's + JSON operation reads it in place. The spike also turns a map from a + language binding into a frame, and then into a `serde_json::Value` + (`target/declaration.rs:472`). Step 1.4 removes both copies. A typed + `JsonPlaintext` contains a parsed document. `next` hands that document + to the JSON tree directly. +- **A function that returns a declaration has to state the type of its + query term in its return type.** This is open question 24. + +### The order of the checks + +These are the checks of a context, in the spike and today. Each runs before +a key is requested: + +- no scope or binding is empty; +- a field with a term has a scope to derive the term under; +- the key descriptor fits in a ZeroKMS request; +- for a record whose context is a field: the field is present, with a label + as its value. + +In the spike's encrypt, `run` walks the value first. These checks run +afterwards, in the finishing step (`target/declaration.rs:231`). The +effects of that order: + +- **Security.** When the context is refused, nothing is sealed or returned. + No key is requested either. This is as today. But the plaintext has + already been copied into the staged value. The staged value is wiped + when it is dropped. +- **Speed.** A call that is refused for its context pays for one walk. + Other calls are unchanged. +- **Correctness.** When both the plaintext and the context are wrong, the + error is about the plaintext. Today it is about the context. + +A context read from a record's field can only be checked after the walk, +because the walk is what reads it. Every other check can come first. So +step 1.4 checks the caller's context before the walk, and checks a context +field after it. + +### A row that comes back in part + +A database query can select some columns of a row. So a stored record can +reach decrypt with some of its fields missing. + +Today decrypt goes through the plan's fields +(`packages/stack-encrypt/src/dynamic/record.rs:942`): + +- a missing field that is `"null": "sql"` opens as a null; +- any other missing field is refused with `FieldMissing`. + +The spike refuses any record whose number of fields differs, with +`Error::Aead` (`target/declaration/open.rs:590`). + +The rule for this plan: decrypt opens the fields that are there. The output +has an entry for each of them, and none for a missing field. The output +type then decides: + +- A frame for a language binding has the entries that were opened. The + SDK's generated code decides what a missing one means. +- A Rust type can refuse a missing field, take it as an `Option`, or use a + type with a state for "not selected". A refusal is a shape mismatch, + `Error::OpenedType`, not an AEAD error + (`packages/stack-encrypt/docs/adr/0010-what-a-stored-value-authenticates.md`). + +A type that maps a row for an ORM is the place for a "not selected" state. +Stack Encrypt does not define one. + +**The two forms of a null.** A plan field's `"null"` says which form a +null takes when the field is encrypted +(`packages/stack-encrypt/src/dynamic/record/plan.rs:82`): + +| Today's name | New name | The stored form | +|---|---|---| +| `"sealed"` | `"sealed"` | A null is sealed like a value, padded to the width of the field's type. The stored record does not show that the value is a null | +| `"sql"` | `"omitted"` | A null gives no entry. The stored record has nothing for the field | + +So a value that is missing is one stored form. A null that was encrypted +is another. That difference is what the plan has to say. + +The difference is not about a database, although `"sql"` names one. So the +form that stores nothing is named `"omitted"`. + +A plan has no type like Rust's `Option`. A record with no entry for a field +is the way a binding gives no value. So encrypt keeps today's rule +(`packages/stack-encrypt/src/dynamic/record/source.rs:162`): + +- for an `"omitted"` field, a record with no entry is a null, so nothing + is stored; +- for any other field, a record with no entry is refused with + `FieldMissing`. + +The mode is an instruction for encrypt. Decrypt does not need it: an entry +that is there opens, to a null if a null was sealed, and a missing entry +gives nothing. + +Today decrypt reads the mode, and opens a missing `"sql"` field as a null +(`dynamic/record.rs:961`). With the rule above, the SDK does that. An SDK +reads the database row itself. So the SDK has the facts: which columns were +null, and which were not selected. + +Three comments call part of the plan's form a frozen wire format +(`dynamic/record/plan.rs:104`, `dynamic/kind.rs:11`, and +`dynamic/mod.rs:143`). The plan's form is not frozen, so the comments are +corrected with this change. + +Two cases are still refused by Stack Encrypt: + +- a record whose context is one of its fields, when that field is missing. + No other field can open without it; +- a leaf that does not open. + +The rule changes two things that a caller gets today. Step 1.4's pull +requests keep behaviour unchanged, so the rule is not one of them. It is a +pull request of its own, after the plan builds its declaration: + +- a missing field that is not `"null": "sql"` is no longer refused by the + record path. The plaintext type still refuses it when the type cannot + take a missing field; +- a missing field no longer opens as a null. The SDK decides what a + missing field means. + +Neither of the first two experiments checked these: + +- The JSON search types, the order terms, and `TextSearch`. +- Null fields, scopes, bindings, and a context field. +- One seal of a tree whose fields have their own key descriptors. +- The conversion of a value to its declared type inside the walk. +- The host-built types on the tree that one walk builds. +- Speed, and fuzzing of the two new deserializers. + +## Checks to make first + +Three checks decide which types step 1.6 covers, and whether step 1.7 can +remove the resolver. Steps 1.1 to 1.5 do not wait for them. + +| Check | What is known | +|---|---| +| A JSON search type built in Go or TypeScript | The hard case. `packages/eql/crates/eql-bindings/src/v4/json_tree.rs` is 1,050 lines, about 880 of them outside tests. Today's tree has nothing to build the type from. See below | +| The order types: `ob`, `op`, and `between` with its two terms | A second kind of term, and a query of two terms. The check needs only today's tree and the experiment's deserializer | +| `TextSearch` | Its filter is the filter of `TextMatch`, with one difference: text that cuts no token. See below. The check needs only today's tree and the experiment's deserializer | + +Each check is done when the host type builds the bytes Rust builds. + +### The JSON check + +The JSON check has to change Stack Encrypt before a host type can be tried. +The reason is the route a JSON document takes to a stored type today. + +A scalar type has a route through the tree. The type's plan field lists +the outputs the type is made of. `TextEq` asks for `outputs: ["c", "eq"]`, and +the field comes back as a map with those two keys. The host type reads the +map. + +A JSON document has no such route: + +- **A plan cannot list the JSON tree as an output.** A `json` field has to + name a target that stores a document, such as `JsonSearch`. A plan that + lists the index as an output is refused with `JsonIndexPending` + (`packages/stack-encrypt/src/refusal.rs:923`, + `packages/stack-encrypt/src/dynamic/kind.rs:116`). +- **The target builds the stored value in Rust.** The JSON tree code returns one + document: a key header `h`, the entries `sv`, and the containment + projection `q`. Rust's EQL type is that document's JSON with `v` and `i` + added (`packages/eql/crates/eql-bindings/src/v4/json_tree.rs:481`). The + resolver returns the result as finished JSON bytes. The document is never + a node of the tree. +- **A JSON operator needs the target too.** A query reads the index's + options from the field's target, and a field with no target has none + (`packages/stack-encrypt/src/dynamic/query.rs:833`). + +So the check has two parts, in this order: + +1. Stack Encrypt admits the JSON tree as an output of a plain `json` field, + and returns the document in the tree. The check has to say what form the + document has there. No node of today's tree fits a document. A document + is not one sealed leaf with terms beside it: each entry in `sv` has a + ciphertext of its own (`json_tree.rs:125`). +2. A Go or TypeScript type builds the stored value from that form, and the + check compares the value with Rust's. + +If the JSON check fails, step 1.6 still covers every other type. Step 1.7 +and phase 2 then wait, and this plan is revised with what the check found. + +### The `TextSearch` check + +`TextSearch` and `TextMatch` build a filter the same way. Both use EQL's +match options (`packages/eql/crates/eql-bindings/src/encryption.rs:472` and +`:517`), and both write the positions as the same list (`:443`). The two +filters have one JSON schema +(`packages/eql/crates/eql-bindings/src/v4/mod.rs:126`). + +The types differ only for text that cuts no token: empty text, one letter, +or separators alone. + +| Type | Text that cuts no token | +|---|---| +| `TextMatch` | Refused with `EmptyTermText` (`encryption.rs:434`) | +| `TextSearch` and `TextSearchOre` | Stored with an empty filter (`encryption.rs:498`) | + +The rustdoc gives a reason (`v4/mod.rs:104`). `=` and `<` still find a +search value through `hm` and its order term. A `TextMatch` value with an +empty filter is a row that no operator can find. + +That difference is wrong. A match filter is built the same way in every EQL +type, whatever other terms the type has. A rule that depends on the other +terms would tie the match operator to them. A query would then have to +combine two terms, and that breaks the usual pattern of an EQL query. + +The one rule is that both types store the empty filter. Stack Encrypt +already stores such text that way +(`packages/stack-encrypt/src/sem/mod.rs:1357`). The refusal is in +`eql-bindings` alone. + +The rule changes no query. EQL finds a stored filter only when it contains +the query's filter. A query that Stack Encrypt builds never has an empty +filter: the query refuses text that cuts no token (`v4/mod.rs:113`). So no +such query finds a stored empty filter. + +A query operand built by hand needs a second change. Before G8, an +`eql_v4.query_text_match` operand with `"bf": []` was accepted, where the +search query domains raise on such an operand. With stored empty filters, +that operand would find the `TextMatch` values that store one. So G8 also +makes `query_text_match` raise on an empty filter. A match query's filter +is then never empty, in any type and from any producer. + +G8 of the groundwork changes the Rust types, so the host types have one +rule to copy. The check then covers a value that is built from three +terms. + +## Crate layout + +`stack-encrypt` and `vitaminc-aead` are hard to follow today. The numbers +are from branch `spike/one-sink`. + +| | `stack-encrypt` | `vitaminc-aead` | +|---|---:|---:| +| Source files | 68 | 35 | +| Lines of code and docs | 45,700 | 9,400 | +| Public top-level modules | 18 | 8 | +| Names re-exported at the crate root | 97 | 63 | +| Pairs of top-level modules that use each other | 14 | 5 | + +In `stack-encrypt`, `target` uses 12 of the other top-level modules, so +there is no order to read the crate in. One word names several places: +`contexts.rs`, `target/context.rs`, and `dynamic/context.rs`. One index is +in three modules: the equality index is in `target/index.rs`, `op/mod.rs`, +and `sem/mod.rs`. + +### The rules + +Each rule is a test that can be applied to any file. + +1. **The three calls are top-level modules:** `encrypt`, `decrypt`, and + `query`. The first file of each has the call a reader is following. +2. **A type is with its data. Its methods are with the call they + provide.** The `KeysetCipher` struct is in `cipher/`. Its encrypt methods + are in `encrypt/mod.rs`, its decrypt methods in `decrypt/mod.rs`, and its + query methods in `query/mod.rs`. Today its methods are in seven `impl` + blocks in six files. +3. **The declaration design is laid out as `core::iter` is:** a `traits/` + folder, an `operations/` folder, and an `adapters/` folder with one file + for each adapter. +4. **One index is in one place:** its operation, its term, and the + operators it answers. +5. **A module uses only the modules below it.** +6. **A test block longer than about 300 lines moves to a sibling + `tests.rs`.** +7. **The derive's output names one module, `__private`.** The derive has 78 + paths into `target::` today. With one module, a later move does not + change the derive. + +### `stack-encrypt` + +``` +lib.rs the crate docs: the three calls. 29 names at the root. + +encrypt/ a plaintext becomes encrypted +decrypt/ an encrypted value becomes a plaintext +query/ a typed query becomes an encrypted query term + +index/ each index: its operation, its term, what it answers +operator/ the operators a query can ask (Eq, Lt, Matches, ..) +cipher/ the client, its keysets, the key requests of one call, and + the AES-256-GCM functions that seal and open a leaf +sealed/ what is stored: Ciphertext, StackCipherText, the sealed leaf + and its stored layout +context/ every context type +value/ the plaintext types this crate adds + +dynamic/ what a language binding calls: frames in, frames out, + and the plan that describes a record as data + +error/ Error, and the refusals of a caller's input +__private the names the derive's output uses (hidden) +``` + +That is 11 public modules. + +``` +encrypt/ + mod.rs the keyset's encrypt methods, EncryptInto, run + traits/ + declaration.rs Declaration + target.rs EncryptTarget<S>, and record() + operations/ + ciphertext.rs ciphertext(), with its finishing step + passthrough.rs passthrough() + adapters/ one file each: zip, convert_into, convert_from, accepting, + under, entry, record, fields, option, under_field, + context_from + targets.rs EncryptTarget for Ciphertext and StackCipherText + collections.rs Vec<S> into Vec<T>, and Option<S> into Option<T> + +decrypt/ + mod.rs the keyset's and the cipher's decrypt methods, DecryptFrom + traits.rs Open, DecryptSource + targets.rs DecryptSource for Ciphertext and StackCipherText + collections.rs Vec<T> into Vec<P>, and Option<T> into Option<P> + +query/ + mod.rs FieldQuery and its encrypt call, Answers, + the keyset's JSON query methods + checks.rs what a query is refused for, before any term exists + field_reference/ mod.rs, json.rs, predicate_checks.rs + +index/ + mod.rs Index, Indexes, IndexSpec, Encrypted<Terms>, indexed() + supports.rs which operators an index answers + equality.rs Equality, equality(), EqualityTerm + matching/ Match, matching(), MatchTerms; tokenize.rs + order.rs Ore, Ope, OreBlock, their operations and terms + json/ the JSON tree: json_document(), its walk, its seal, its queries + term_error.rs + +cipher/ + mod.rs builder.rs + keyset.rs KeysetCipher: the struct, how it is made, its state + keyset_cache.rs + pending/ Pending: mod.rs, combine.rs, request.rs, dispatch.rs, future.rs + audit.rs credential.rs randomness.rs + aes/ seal() and open() for one leaf, the nonce, and the two + backends: aws_lc.rs and rust_crypto.rs + +sealed/ ciphertext.rs, tree.rs, leaves.rs, transcode.rs, leaf_layout.rs +context/ mod.rs, input.rs, descriptor.rs, label.rs, display.rs, testing.rs +value/ mod.rs, json.rs, blob.rs + +dynamic/ + mod.rs record.rs + plan/ mod.rs, kind.rs, target.rs, declaration.rs, check.rs, + source.rs, error.rs + query/ mod.rs, json.rs, field_handle.rs + term.rs json.rs frame_context.rs cipher_directed.rs + +error/ mod.rs, refusal.rs, found.rs +``` + +Three points about `encrypt/`: + +- **The entry points are in `mod.rs`.** They are `keyset.encrypt`, + `keyset.encrypt_with_context`, `value.encrypt_into`, and + `value.encrypt_into_with_context`. `encrypt_tree` is the same call as + `encrypt_into_with_context::<StackCipherText>`, so it is removed. + `encrypt_tree` is used in 80 places, so removing it is a pull request of + its own. +- **An index's operation is with its index.** `equality()` and + `json_document()` are in `index/`. So `encrypt` names no index, and a new + index adds no file to it. The standard library does the same: the + iterator over a string's characters is in `core::str`. +- **The impls for the built-in targets are in `targets.rs`.** The + standard library keeps `FromIterator for Vec` with `Vec`, because `Vec` + is above `iter`. Here `Ciphertext` is below `encrypt`: the `ciphertext()` + operation names the type it builds. An impl beside the type would make + `sealed` and `encrypt` use each other. + +`decrypt/` is small, because the adapters are shared. Each adapter's file in +`encrypt/adapters/` has its `Open` impl too. + +The operators are a top-level module, renamed from `op`. They cannot be +inside `query/`. Each index says which operators it answers, so `index` uses +the operators, and `query` uses `index`. + +### `vitaminc-aead` + +``` +lib.rs the verbs and the Cipher trait. About 26 names at the root. + +plaintext/ how a value describes itself + mod.rs Encrypt, EncryptRef, Scalar, Sink, SeqSink, MapSink + kinds.rs value_kind.rs path.rs depth.rs + sources/ std.rs, date.rs, decimal.rs, timestamp.rs, uuid.rs + adapters/ tee.rs, lent.rs, either.rs, option.rs +encrypt/ mod.rs: encrypt(); sink.rs: EncryptSink; shape.rs +seal/ mod.rs: Cipher, Node::seal, open_with; node.rs: Node +decrypt/ mod.rs: decrypt(); walk.rs; target.rs: Decrypt, FromScalar; + sinks/: one file for each sink +leaf/ mod.rs: scalars as bytes; tags.rs +frame/ as today +aad.rs +``` + +`typed.rs` (1,647 lines) is the decrypt side. It is split into `decrypt/`. + +The AES cipher and the stored layout of a leaf are not in this tree. They +move to `stack-encrypt` in step 1.4. + +### The order of the modules + +A module uses only the modules to its left: + +``` +context, value < sealed < cipher < operator < index < encrypt, decrypt < query < dynamic +``` + +`error` is the exception: every module may use it. + +| | Today | After | +|---|---:|---:| +| `stack-encrypt`: pairs of modules that use each other | 14 | 1 | +| `vitaminc-aead` | 5 | 2 | + +The pair that stays in `stack-encrypt` is `error` and `index`. + +### The crate root + +A name is at the root of `stack-encrypt` if a typical program needs it for +one of five things: + +- to build a client; +- to call encrypt or decrypt; +- to name what it encrypts into; +- to pass a context; +- to handle an error. + +| Group | Names | +|---|---| +| The client | `StackCipher`, `StackCipherBuilder`, `KeysetCipher`, `kms` | +| The calls | `EncryptInto`, `DecryptFrom`, `Pending` | +| What a program encrypts into | `Ciphertext`, `StackCipherText`, `Encrypted`, `OpaqueBlob` | +| Traits for a program's own types | `EncryptTarget`, `DecryptSource`, `Encrypt`, `Decrypt` | +| Contexts | `Label`, `CallerContext`, `IntoContext`, `NonEmpty`, `nonempty!` | +| Secrets | `Protected`, `Controlled` | +| Audit and credentials | `AuditMetadata`, `Audited`, `WithCredential` | +| Errors | `Error`, `ErrorPayload`, `diagnostic` | +| Other | `VERSION` | + +That is 29 names. The other 68 of today's 97 are reached through a module: + +| Goes to | Names | +|---|---| +| `index::` | `Equality`, `Match`, `Ope`, `Ore`, `OreBlock`, `Json`, `Index`, `Indexes`, `IndexSpec`, `TermSet`, `Orderable` | +| `query::` | `FieldReference`, `FieldQuery`, `BetweenQuery`, `Needs`, `QueryInput`, `Ready`, `ScopeInput` | +| `context::` | `Descriptor`, `Describe`, `Description`, `LabelError`, `Context`, `ContextPiece`, `IntoAad`, `IntoPrfContext`, `PrfContext`, `MaybeEmpty`, `EmptyError`, `nonempty_bytes!`, and the nine types that show contexts | +| `cipher::` | `NoKms`, `WithKeySource`, `WithAuthStrategy`, `KeySource`, `OwnIdentity`, `CipherRef`, `PendingFuture`, `Request`, `Responses`, `AuditValue` | +| `sealed::` | `SealedValue`, `LeafBytesError`, `CipherText`, `Node`, `PassthroughFrame` | +| `decrypt::` | `DecryptField`, `Decryptable` | +| `value::` | `BlobError`, `OpaqueEncode`, `OpaqueDecode` | +| `dynamic::` | `PlanError`, and the re-exports `Buffer`, `ProtectedRef`, and `AsProtectedRef` | +| No re-export | `EncryptRef`, `ScalarTarget`, `DecodeError`, `Unspecified`. A program takes them from `vitaminc-aead` | +| Deleted with today's combinators | `Encryption`, `Decryption` | + +`Buffer`, `ProtectedRef`, and `AsProtectedRef` come from +`vitaminc-protected`. The functions a binding calls take them, so `dynamic` +re-exports them. A binding's author then gets the matching version with no +second dependency. + +### Renames + +| Old | New | Reason | +|---|---|---| +| The `target` module | Removed | "Target" is a glossary word for a type. The module has 13 files on about six subjects | +| `sem` | `index` | The glossary has "index" and "term". It has no "SEM" | +| `op` | `operator` | The whole word | +| `contexts` | `context::display` | It shows contexts | +| `json/derive.rs` | Four files in `index/json/` | In this crate "derive" means the macro | +| `typed`, `encrypt_sink`, `container`, and `walk`, in `vitaminc-aead` | `decrypt`, `encrypt::sink`, `seal::node`, and `decrypt::walk` | Each new name says what the file has | + +### What the layout costs + +- **Public paths change.** `sem::*` becomes `index::*`. `json::*` becomes + `index::json::*`. `field_reference` becomes `query::field_reference`. + `eql-bindings` uses all three. +- **The root loses 68 names.** +- **Both designs exist for a time.** Today's combinators stay in + `target/operations.rs` until they are deleted. Only new code goes into + `encrypt/`. + +## Groundwork + +These pull requests do not change how a record is encrypted. Only G8 +changes a result that a caller gets. + +They can start now. Each is labelled G, for groundwork, and a number. G1 +to G3 have merged into `next`. The others are based on it. + +| | What | State | +|---|---|---| +| G1 | The readability refactor of the dynamic record path | #2042, merged | +| G2 | The AES-256-GCM cipher moves into `vitaminc-aead` | #2044, merged | +| G3 | `vitaminc-normalize` moves into this repository | #2052, merged | +| G4 | Long test blocks move to `tests.rs` files | #2055, draft | +| G5 | The layout of `vitaminc-aead` | #2061, draft, stacked on #2055 | +| G6 | The layout of the shared modules of `stack-encrypt` | Not started | +| G7 | `vitaminc-prf` and `vitaminc-ore` move into this repository | #2057, draft: `cargo vet` needs three crates covered | +| G8 | `TextMatch` stores the empty filter for text that cuts no token | #2054, draft | +| G9 | The prefix on `c` becomes `rc:1:`, and a reader accepts both prefixes | #2056, draft: the reader. The writer follows a release later | + +**G2, the AES cipher.** `vitaminc-aead` gets the parts of `vitaminc-encrypt` +0.10 that this repository calls, behind an `aes` feature. The pull request +also makes these changes: + +- The leaf format types become private to `vitaminc-aead`. The deprecated + `Aad` and `AadPiece` names are removed. +- The AES backend no longer frees a copy of the plaintext without wiping + it. A seal that fails wipes its buffer. +- A compiler flag chooses the RustCrypto backend for tests on a native + target. A Cargo feature did this before. CI runs the workspace's tests + with every feature on, so a feature would have changed the backend for + every test. +- CI runs the tests of `vitaminc-aead` on `wasm32-wasip1`. That is the + target of the Go guests. +- `aws-lc-rs` gets an audit in the `cargo vet` store, and the publisher of + `aws-lc-sys` is trusted. + +The cipher does not stay in `vitaminc-aead`. Its only caller outside tests +is `stack-encrypt`. For each leaf, `stack-encrypt` builds an `Aes256Cipher` +from that leaf's data key (`leaf_cipher`, +`packages/stack-encrypt/src/cipher.rs`). So `stack-encrypt` wraps a one-key +cipher inside a cipher of its own. Its own cipher picks a key for each +leaf. + +Each new `Aes256Cipher` also seeds a random number generator from system +entropy, once for each leaf. Step 1.4 moves the cipher into `stack-encrypt`. + +**G3, `vitaminc-normalize`.** The crate comes with its git history, at the +code of its 0.10.0 release, as `vitaminc-aead` did +(`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). The move +changes no library code. One test changes, because it read the Debug output +of an error that `vitaminc-aead` prints differently here. + +The crate's own changes are not in this step. They follow from the +`vitaminc-aead` changes in the first pull request of step 1.4, so they go +there. Every user of the API that changes is in this repository. + +#2052 also added the crate to the `cargo vet` and `cargo deny` store. + +**G4 to G6, the layout.** Each is a move with no change in behaviour: + +1. The long test blocks. +2. `vitaminc-aead`. +3. `error`, `context`, `value`, and `sealed`. +4. `cipher/`. +5. `index/`, renamed from `sem`. +6. `__private`, with the derive. + +The rest of the layout comes with step 1.4: `encrypt/`, `decrypt/`, +`query/`, and `dynamic/plan/`. + +**G7, the two crates of terms.** Equality terms are derived with +`vitaminc-prf`. The order term sink is in `vitaminc-ore`. + +Both crates come with their git history, at the code of their 0.10.0 +release, as G3 did. This repository uses both at 0.10.0 from crates.io +today (`Cargo.toml:172`). Both depend on `vitaminc-aead` and +`vitaminc-normalize`. Those two crates are already here. + +The order schemes `clww-ore` and `ore-rs` come from `cipherstash/ore.rs` +and depend on both crates. So the `[patch.crates-io]` table of each +workspace that resolves them adds both, as it does for `vitaminc-normalize`. +The EQL timing generator pins `vitaminc-ore` at `=0.10.0` +(`packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml:20`), so its +table changes too. The `cargo vet` and `cargo deny` store covers both +crates. + +The move changes no library code. The changes to their sinks come with +step 1.4. + +**G8, one rule for a match filter.** `TextMatch` stores text that cuts no +token with the empty filter, as `TextSearch` and `TextSearchOre` do. The +three types then have one filter type, `BloomFilter`. The type +`SearchBloomFilter` is removed: it has not been in a release. A match query +of such text is still refused. + +In EQL v4's SQL, `query_text_match` raises on an empty filter, as the +search query domains do. + +G8 is the one groundwork item that changes a result. A Go program gets +`ErrTerm` today when it stores such text in a `TextMatch` field. After G8, +the value is stored. + +## Phase 1: the record path + +| Step | What | Depends on | +|---:|---|---| +| 1.1 | Go's plan carries match options | Nothing | +| 1.2 | The tree codec takes any leaf | Nothing | +| 1.3 | A term node, and a length on a passthrough node | #2003, 1.2 | +| 1.4 | One walk: declarations | The groundwork. A plan's declaration writes term nodes once 1.3 is in | +| 1.5 | A deserializer and a visitor in Go and TypeScript | #2003, 1.3 | +| 1.6 | The stored types in each language | 1.1, 1.5, and each type's check above | +| 1.7 | The resolver removed | 1.6 done for every EQL v4 type | +| 1.8 | The Go SDK without a generator | 1.6 | + +PR #2003 moves vitaminc's two Go packages into this repository. Both are +public: + +- `languages/golang/encrypt/frame` is the codec. It has + `MarshalCipherText`, `UnmarshalCipherText`, and the storage profile. +- `languages/golang/encrypt/value` is the value types. + +Every Go step here is written against `encrypt/frame`. Step 1.5 adds the +reader and the visitor to it. vitaminc's `vcencrypt` is to be deleted. +After that, nothing outside this repository reads the tree. + +### 1.1 Go's plan carries match options + +The match options decide the filter, and the tree does not record them. EQL +fixes its own: 3-grams, downcase, short words, `k` = 6, and `m` = 2048 +(`packages/eql/crates/eql-bindings/src/encryption.rs:398`). A bare `"match"` +in a plan means `k` = 3 and `m` = 256. For the text "Ada Lovelace" that is +59 positions against 27. So the type that reads a filter must be the type +that asks for it. + +Rust's plan accepts the options in an object form +(`packages/stack-encrypt/src/dynamic/record/plan.rs:1055`). Go's plan +cannot send them, for two reasons: + +- Go has no option to give. `MatchOption` is an interface with no + implementation, and `encrypt.Match` ignores its arguments + (`languages/golang/encrypt/term.go:53` and `:63`). +- `Plan.Wire()` writes each output as a string + (`languages/golang/internal/record/record.go:544`). + +The step makes three changes: + +- Go's public API defines the match options. +- Go's plan model keeps the options and writes the object form. +- The comment on `MatchOption` is corrected. The comment says the guest + derives a query under the defaults only. The experiment showed that the + query call uses the plan's options. + +Issue #1673 proposes one analyzer pipeline in place of the fixed option +struct. This step sends whatever form the plan has when the step is built. + +Done when a Go plan with EQL's options gives the filter Rust gives, under +one test seed, with no test-only call. + +### 1.2 The tree codec takes any leaf + +`encode_ciphertext` asks for `Leaf: AsRef<[u8]>` +(`packages/recipher-frame/src/transport.rs:200`). A `SealedValue` is a +struct of four fields. So the Go guest first copies the whole tree into one +whose leaves are byte strings (`map_leaves`, +`languages/golang/encrypt/guest/src/ops.rs:702`). The guest also works out +the encoded length a second time (`:743`). + +| Part | Today | After | +|---|---|---| +| Leaf bound | `AsRef<[u8]>` | A trait with two methods: the leaf's length, and writing the leaf. Every `AsRef<[u8]>` type has the trait, so callers compile unchanged | +| `SealedValue` | Copied to bytes in a second tree | Writes its four fields into the output | +| Encoded length | Worked out again in the guest | Exported by the codec | +| Decode | Leaves as byte strings, then converted in a second step | The caller gives a function that reads each leaf | + +A prototype exists. The codec's tests and the cipher module's tests pass +with the prototype, and the bytes are unchanged. + +One part needs design. In the prototype, a leaf that the caller's function +refuses comes back as the codec's single error. The guest reports the leaf's +own error today (the `leaf` class in +`conformance/stack-encrypt/raw-frames-contract.md`). The real version needs +an error with two cases. + +Done when the Go guest has no `map_leaves` and no length function of its +own, and the raw-frame conformance cases pass unchanged. + +### 1.3 A term node, and a passthrough length + +**The term node.** `CipherText<Leaf, P>` +(`packages/vitaminc-aead/src/container.rs:32`) has a new variant for a +term's bytes. In the transport codec a term is a new kind, `0x08`. That is +the next free kind. A `u32` length and the bytes follow the kind. + +The node does not record what kind of term it is. The map key above the +node, such as `eq`, says that. This is the rule today (`IndexSpec::key`, +`packages/stack-encrypt/src/target/index.rs:127`). + +What the node gives every reader: + +- A term stops looking like plaintext. Today a term and a passthrough field + are the same kind of node. Only a passthrough can contain plaintext. +- A reader can tell a term by its kind. Record decrypt does not change in + this plan. It takes the `c` and `passthrough` outputs by the plan's keys + today (`packages/stack-encrypt/src/dynamic/record.rs:381`). +- A reader takes a length and then the bytes. + +A new kind of term needs no change to the codec in any language. The limit +is that nothing in the tree refuses a type that reads the wrong entry. The +stored types are generated from one catalog and compared with Rust's bytes. +That comparison is the check that catches a wrong read. + +**The passthrough length.** A passthrough node is +the frame of its value, written as it is, with no length +(`packages/recipher-frame/src/transport.rs:16`). The frame format has 26 +tags. A reader has to walk that format to find the end of the node. + +Go can use its own value decoder for that once the codec is in +`encrypt/frame`. TypeScript has no frame decoder in the host language, +because values cross through Rust. A `u32` length before the frame lets any +language skip a passthrough node. + +Changes: + +- `vitaminc-aead`: the variant, and what each sink and reader does with it. + Two parts need care: + - A term is not a sealed leaf. Two rules count every node that is not a + passthrough as sealed: `check_shape` + (`packages/vitaminc-aead/src/seal.rs:293`) and `sealed_any` + (`packages/vitaminc-aead/src/walk.rs:146`). Both have to leave out a + term too. Otherwise a container of terms alone passes the rule that + refuses a container with no sealed leaf. + - `walk` (`packages/vitaminc-aead/src/walk.rs:162`) leaves a term node + out. A term is an entry of a map. The sink is not given that entry. + `walk` tells the sink a map's length first, so it counts the entries + that are not terms. A term at the root, or as an element of a sequence, + is refused as malformed. +- `recipher-frame`: the new kind and the length, in both directions. The + encoder still refuses what the decoder would refuse. +- `stack-encrypt`: `shape_record` writes a term node in place of + `bytes_node`. The Rust `Visitor` has a new method for a term's bytes, + described below. +- `languages/golang/encrypt/frame/ciphertext.go`: the same two changes. The + SDK's hand-written mapping reads the new node until step 1.5 replaces + that mapping. +- `languages/typescript/packages/recipher-js/value-napi/src/ciphertext.rs`: + `node_to_js` matches every variant of `CipherText` (`:193` to `:225`), so + it has to handle the new one. The package's CI runs when `vitaminc-aead` + changes. + +**The Rust `Visitor`.** The visitor already has five methods that each take +a typed term: `equality`, `matching`, `ore`, `ope`, and `ore_block` +(`packages/stack-encrypt/src/target/transcode.rs:96`). The typed term +readers call those methods (`:194` to `:215`). Nothing in the tree calls +them, and they stay as they are. + +The new method takes a term's bytes. Only the tree's reader calls it +(`:182`). The new method's default refuses, as the default of every other +method does. + +This plan adds no conversion from a tree's bytes to a typed term. The types +that read a term from a tree are in Go and TypeScript. A Rust type that has +to read one needs that conversion first. + +No stored data changes. The transport codec's own documentation says "This +encoding has no stability guarantee". The storage profile encodes values, +not trees. + +Done when Rust and Go agree on the new bytes in the shared corpora, and +every existing record test passes with terms as term nodes. + +### 1.4 One walk: declarations + +Every target is declared with a `Declaration` +([A declaration](#a-declaration)). A record's plan builds one, and the +derive writes one. Encrypting a record is three steps: one walk of the +source into the declaration's sink, one key request, and one pass. The pass +seals the leaves and keys the terms. + +**The pull requests.** Each one stacks on the one before it. + +1. **One walk for a value.** + - The encrypt sink has no context. + - A staged value is a `Node<Plaintext>`. + - A tree is sealed and opened by closure. + - `AsyncCipher` and the other APIs that the spike removed go here. + - The AES-256-GCM cipher moves into `stack-encrypt` as crate-private + functions. One seals a leaf under a key and an AAD. The other opens + one. The backend is still chosen by the target, so there is no trait. + `vitaminc-aead` loses its `aes` feature and its `aes` module. + - The stored layout of a leaf moves with it. That is `LocalCipherText`, + the writer, the reader, `WIRE_VERSION`, the AAD derivation `for_leaf`, + and the nonce generator. The stored bytes do not change. + - The nonce generator is seeded once for each call, not once for each + leaf. + - The JSON tree code (`packages/stack-encrypt/src/json/derive.rs`) moves to + the new functions. Two tests outside `stack-encrypt` build an + `Aes256Cipher` too: the EQL test `opaque_json_bytes.rs`, and the test + crate of the recipher-js value bridge. Neither calls AES after this + pull request. Both seal and open through Stack Encrypt, with the test + key source of the `test-support` feature. A check of the bytes inside + a leaf moves into the tests of `stack-encrypt`. + - Before this pull request, `cargo deny` and `cargo vet` cover + `stack-encrypt` (#1842). Otherwise aws-lc-rs, aws-lc-sys, and + aes-gcm leave the only graph the two tools check, and the audits + recorded in G2 apply to nothing. + - The pull request changes the public API of `stack-encrypt`. + `eql-bindings` names a `stack-encrypt` version, so that version reaches + crates.io before `eql-bindings` is published with it. +2. **The trait and its adapters.** `Declaration`, `ciphertext()`, + `passthrough()`, and the adapters, in `encrypt/`. Today's combinators + stay where they are. The caller's context is checked before the walk + ([The order of the checks](#the-order-of-the-checks)). +3. **Decrypt.** `Open`, and `decrypt/`. `Open` has an input type of its + own: the parts of a stored value that open. So a stored value with no + term decrypts. `convert_into` and `convert_from` replace the spike's + `map`, `try_map`, and `convert`. +4. **Each index as a declaration:** its operation, and the operators it + answers (`Answers`). The order is equality, order, match, and the JSON + tree. A typed `JsonPlaintext` is handed to the JSON tree directly, as on + `next`. It is not written to text. A map from a language binding is not + turned into a frame first. See open questions 26 and 28. +5. **The targets.** The built-in targets and the 19 targets of + `eql-bindings` return a declaration from `EncryptTarget<S>`. +6. **The derive** writes a struct's record: `record::<P>()`, with a + closure for each field. +7. **The plan** builds a declaration. The dynamic record path encrypts, + decrypts, and queries through it. Step 7 may take two or three pull + requests. +8. **Removals and clean-ups.** + - Today's combinators are deleted. + - `encrypt_tree` and `decrypt_tree` are removed, and `run_decryption` + becomes private. + - The root has its 29 names. + - The smaller clean-ups: the `CipherText` alias, the `E` parameter, + `KnownLogical`, and `UnknownLogicalId`. + - `decrypt_through` and `open_opaque`, merged if they are one function. + - The first decision record of `vitaminc-aead`, and the changelogs. + +**What a plan's declaration needs beyond the spike:** + +| Piece | Today | In a declaration | +|---|---|---| +| Equality terms | `terms(value)` alone, for one scalar (`packages/stack-encrypt/src/sem/mod.rs:664`) | `equality()`. The spike has it | +| Order terms | `order_terms(target, value)` alone (`sem/mod.rs:1935`) | An operation with the sink `Terms::by(Order::new(target))` | +| Match terms | No sink. `MatchTerms` takes text | An operation whose sink keeps a wiped copy of the text, as `match_deferred` does (`sem/mod.rs:1450`) | +| A query term that is not the stored term | The index's `query_operation` | The `Query` type of `Answers`. `between` sends two terms | +| The declared type | `check_field` reads the whole value and converts it before sealing | A sink in front of the others | +| Key descriptors | One descriptor for every key in a tree (`packages/stack-encrypt/src/target/core.rs:105`, and `:161` on open) | A descriptor for each field. The spike has it. The ZeroKMS protocol already takes one for each key (`packages/stack-kms/src/payload.rs:7`) | +| Nulls, and a field with no entry | Handled for each field | A rule of the field's declaration | +| A batch | A sequence of records | A declaration for a sequence, with each row its own root | +| A plan's scopes and bindings | In the context of each field | The context the declaration is handed. The spike passes the plan's, with no values | +| The kinds of error | A refusal names its field and its reason | The walk's errors have to keep both. The spike has one error | + +Two parts stay as they are and join the record's one key request: + +- **The JSON tree's own walk.** It derives selectors and tokens under the + index key (`packages/stack-encrypt/src/json/derive.rs:848`), so it needs + the keyset. It runs in the finishing step of `json_document()`, over the + document that the sink staged. +- **A field that names a stored type**, until step 1.7 removes the + resolver. + +Removed from the dynamic record path: `into_raw_fields`, `lift`, +`FieldShape`, the hand-building in `shape_record`, `compose`, and +`FieldValues`. + +Every one of these pull requests: + +- keeps stored bytes unchanged. The fixture tests, and the Go tests that + open records sealed before the change, pass unchanged; +- runs the full check list, not only the tests. The list is `cargo fmt`, + clippy, doc examples, and rustdoc. The list also has the Go guests with + `go test`, the EQL crates, the fuzz builds, and mutation testing on the + changed lines; +- runs the AES tests on both backends. + +Done when: + +- the record conformance suites pass with their expected files unchanged; +- a record sealed before the change opens after it, and the reverse; +- the tests that count key requests still count one for a batch; +- no field's value is copied into a frame of its own; +- a value with an index is walked once; +- a stored value that keeps only its ciphertext decrypts; +- a declaration lists its contexts without a run, as `contexts()` does + today; +- a plaintext given by value is wiped, also when the call is refused; +- a context that is refused is refused before the plaintext is walked, + unless the context is read from a field of the record; +- every target has one declaration, and nothing uses `Encryption` or + `Decryption`; +- in a record of several fields, a leaf moved to another field's position + does not open; +- a field sealed under one descriptor or lock context does not open under + another. + +The last two are refusals. Without them, a field sealed and opened under the +wrong field's context passes every other item on the list. + +### 1.5 A deserializer and a visitor in Go and TypeScript + +Each language gets one reader of the tree's transport bytes. The reader +calls a visitor and builds no tree of its own. + +The visitor has one method for each of the seven kinds of node. The kinds +are a sealed leaf, a sequence, a map, the two empty markers, a passthrough, +and a term. A type embeds a default that refuses every kind, and writes only +the methods for the shapes it stores. + +A visitor reads a map's entries in order. The reader skips an entry that the +visitor does not read. The reader refuses a repeated key. + +| | Go | TypeScript | +|---|---|---| +| Where | `languages/golang/encrypt/frame`, the public package of the codec | `languages/typescript/packages/recipher-js/src`, in TypeScript | +| Who can use it | Any Go module: the SDK, `encrypt/eql`, and a type that is written outside this repository | The package and the EQL extension | +| Failures | Two errors: malformed bytes, and a shape the type does not store | The same two, as a result value. Nothing throws | +| The way back | #2003 has the function. See the names below | A small encoder, for the tree a decrypt sends | + +**Names.** Each part has one name in every language. Each language writes +the name in its own style. Rust has every part today but the method for a +term node, so Rust's words are used +(`packages/stack-encrypt/src/target/transcode.rs:36` to `:156`, and +`packages/recipher-frame/src/transport.rs:198` and `:261`). The Go names, +the TypeScript names, and the name `term` are proposed. + +| Part | Rust | Go | TypeScript | +|---|---|---|---| +| The interface that a type implements | `Visitor` | `Visitor` | `Visitor` | +| The methods for the six kinds of node that exist today | `sealed`, `sequence`, `map`, `empty_sequence`, `empty_map`, `passthrough` | `Sealed`, `Sequence`, `Map`, `EmptySequence`, `EmptyMap`, `Passthrough` | `sealed`, `sequence`, `map`, `emptySequence`, `emptyMap`, `passthrough` | +| The method for a term node (new in step 1.3) | `term` | `Term` | `term` | +| The elements of a sequence | `SequenceReader` | `SequenceReader` | `SequenceReader` | +| The entries of a map | `MapReader` | `MapReader` | `MapReader` | +| From bytes to a visitor | `decode_ciphertext` | `DecodeCipherText` | `decodeCipherText` | +| From a tree to bytes (the way back) | `encode_ciphertext` | `EncodeCipherText` | `encodeCipherText` | + +The names in the experiment and in #2003 differ from these in three places: + +- The experiment named the two readers `SeqAccess` and `MapAccess`, in Go + and in TypeScript. +- #2003 names Go's two functions `MarshalCipherText` and + `UnmarshalCipherText`. +- The experiment named the TypeScript functions `decode` and `encode`. + +The names of the two errors are not in the table. The naming of errors is +a separate piece of work. + +**Go's reader and visitor are public.** A stored type implements the +visitor, so the visitor is the interface that a new type is written +against. `encrypt/eql` is the first package to use it. Other packages are +likely to use it later. + +- **Why `encrypt/frame`.** The codec for the tree is in that public + package. With the reader beside the codec, one package reads the tree. + The experiment had a package of its own, `encrypt/transcode`. A second + package is not needed. +- **Why not an `internal` package.** Go lets only code inside + `languages/golang` import a package under `languages/golang/internal`. + `encrypt/eql` is inside. A type in another module is not. +- **Why not `gensupport`.** That package is for code that `stashgen` writes. + The package's documentation says that a program never imports it + (`languages/golang/encrypt/gensupport/gensupport.go:3`). +- **No internal type in an exported name.** A type outside the module has to + name everything that the visitor's methods take. `encrypt/frame` imports + the standard library and `encrypt/value` alone. +- **The cost.** The visitor becomes public API of the Go module. A new kind + of node adds a method to the interface. So the interface has one + unexported method that only the default has. Every type then has to + embed the default. A new kind of node breaks no type: the default + refuses it. gRPC's Go code does the same. + +**TypeScript needs the tree first.** Today the package gives TypeScript one +opaque `Ciphertext`, for a single value +(`languages/typescript/packages/recipher-js/crate/src/ciphertext.rs:34`). No +call returns a record's tree. + +So the TypeScript half of this step starts with two native calls: + +- one that returns a record's tree as transport bytes; +- one that takes a tree back, for decrypt. + +PR #1776 adds records to the package in another form, through +`dynamic::Planned`, with each result built in Rust. That PR closes without +merging. TypeScript records are built on the tree from the start. + +Rules for both: + +- **One parser for each language.** Outside tests, Go decodes the tree in + one place (`languages/golang/encrypt/records.go:94`, through a wrapper). + After #2003, the function that call reaches is `UnmarshalCipherText` in + `encrypt/frame`. That function becomes a visitor on the new reader, or it + is removed when the caller moves. +- **Hostile input.** The bytes come from the guest. Both directions are + still treated as input an attacker can reach, as the Rust codec treats + them. The reader refuses every truncation, a repeated key, a tree deeper + than `MAX_DEPTH`, an unknown kind, and bytes left over. +- **No plaintext in an error.** An error names the failure. An error never + contains a value or the kind of a decrypted value. +- **TypeScript runs everywhere the SDK does.** The reader is plain + TypeScript, so the native build and the wasm build share it. The reader + does not use Node's `Buffer`. + +Done when the three codecs pass one shared corpus of trees and refused +inputs, and the Go and TypeScript readers are fuzzed. + +### 1.6 Stored types in each language + +`eql-codegen` already writes Go's EQL types from the catalog +(`languages/golang/encrypt/eql/eql_gen.go`). For each language and each +type, `eql-codegen` now also writes: + +- the outputs the type asks for, with their options; +- the visitor that builds the stored value; +- the function that returns the sealed leaf; +- the query types. In this step a query type is a function of a term's + bytes, because a query still comes back as a `QueryTerm`. Phase 2 makes it + a visitor. + +A small hand-written part in each language has what every type shares: + +- the base64 of `c`, and its prefix. The prefix comes from the EQL catalog + that `eql-codegen` reads. A reader accepts both prefixes (G9); +- the hex of an equality term; +- the list of positions in a match filter. A match term is its positions as + little-endian `u16` values + (`packages/stack-encrypt/src/sem/mod.rs:933`). + +One rule moves to the host type, because the guest no longer has the type: + +- **The stored `i`.** On decrypt, the host type checks the stored `i` + against the plan's label, and refuses a value whose `i` differs. See + [The design](#the-design). + +Empty match text needs no rule in the host type. After G8, every match type +stores it with an empty filter. A plain plan returns the same. + +Rust's own types in `eql-bindings` stay. Rust programs use them, and they +are the reference. A conformance suite compares each language's value with +Rust's, for every type, under the test key source. The suite compares `c` by +opening it. + +The order of work is the scalar text types, the order types, `TextSearch`, +then the JSON search types. The experiment covered two of the scalar text +types. + +**No list of types to ask for.** Today the list of EQL types comes from +the resolver (`packages/stack-encrypt/src/dynamic/target.rs:563`). Go's +`Checker.Targets` asks the guest for the list +(`languages/golang/encrypt/checker.go:73`), and `stashgen` reads it from +there (`languages/golang/stashgen/engine.go:102`). + +After step 1.7, no resolver answers, and nothing needs one. The EQL package +of each language has every concrete type that EQL defines, each with its +visitor. A program names a type by using it. Step 1.8 says how a Go program +does that. + +A type is done when its generated Go and TypeScript types pass the +conformance suite. The step is done when every type whose check passed is +done. + +### 1.7 The resolver removed + +This step starts when step 1.6 is done for every EQL v4 type. + +Removed from `stack-encrypt`: + +- `TargetResolver`, the second form of every dynamic entry point, and + `Verb::Target`. That is about 730 lines of + `packages/stack-encrypt/src/dynamic/target.rs`. +- The `resolver` parameter of `field_operators`, `check_query`, + `query_term`, `verify`, and `target_limit` + (`packages/stack-encrypt/src/dynamic/query.rs:534`, `:815`, `:1093`, + `:1196`, and `:1248`). The branch of `target_limit` for an EQL type's + match options is removed too. +- The record's `eql` output key (`EQL_KEY`, + `packages/stack-encrypt/src/dynamic/record/plan.rs:25`), and the refusal + `NoEqlNode`. +- The `"eql"` form of a query's answer (`query.rs:392`), and the SQL domain + in the answer. Both exist because a resolver returns finished EQL JSON. + +Issue #2033 asks for the `eql` key, the refusal, and the query form to be +renamed. This step removes all three. Under this plan the TypeScript SDK +never reads the `eql` key, because its types ask for plain outputs. + +Two mentions of EQL stay in `stack-encrypt`. This plan does not change them, +and #2033 says to leave both: + +- The JSON query operands. They serialize to EQL's `eql_v4.query_json_*` + forms (`packages/stack-encrypt/src/json/query.rs:403` and `:434`). Open + question 31 asks whether the JSON scheme moves to EQL. That move would + remove this mention too. +- The module `eql_simulator` (`packages/stack-encrypt/src/lib.rs:739`), a + test copy of EQL's read functions. + +Removed elsewhere: + +- The resolver files of `eql-bindings`, about 2,300 lines: `resolver.rs`, + `targets.rs`, and `query.rs` under `src/encryption/`. Two of them are + public modules. See "What this changes elsewhere". +- The Go guest built with the EQL types, and its test build. A Go release + then carries three guests, not five. + +Done when all of these are true: + +- every EQL v4 type has a generated type in Go and TypeScript that passes + the conformance suite; +- the Go PostgreSQL tests pass on one guest; +- `stack-encrypt` builds with no resolver. + +### 1.8 The Go SDK without a generator + +Today a Go program tags a struct and runs `stashgen`. For one test struct +of 12 sealed fields, the generator writes about 360 lines +(`languages/golang/encrypt/internal/testusers/profile_stash.go`). They are +a stored struct, two functions, and a value with the query methods. + +A generator cannot tag a struct that another tool writes. PR #1716 is a +second generator, of 11,213 lines, for a program that uses sqlc. Its +description says: "there is no struct for stashgen to tag". Issue #1307 +asks for the same thing for protobuf messages. + +**The design.** A stored struct is written in Go. Each sealed field has an +EQL type from the EQL package, and that type says how the field is +encrypted: + +```go +type User struct { + ID int64 + Email string + Age int32 +} + +// What the database library reads and writes. sqlc can write it. +type UserRow struct { + ID int64 + Email eql.TextEq + Age eql.IntegerOrd +} + +var rows []UserRow +err := cipher.Encrypt(ctx, users, &rows) // one key request +err = cipher.Decrypt(ctx, rows, &users) +``` + +The SDK reads the two structs' fields while the program runs, with Go's +reflection. `encoding/json` works the same way. + +A value that changes with the caller, such as a tenant, is given with +`cipher.Scope(..)` or `cipher.Bind(..)`, as today +(`languages/golang/encrypt/cipher.go:70`). + +**The stage of each check.** Go cannot compare the fields of two structs +when it compiles. So these mistakes are found when the code runs: + +- a plaintext field of the wrong type for its EQL type; +- a field that one struct has and the other lacks. A plaintext field with + no stored field is refused, so a value is never dropped. + +A check function finds them earlier. A program calls it in a test or at +startup, for each pair of structs. + +**The compiler's checks, as an option.** A stored struct +can have one method that says how it is sealed from its plaintext struct. +The developer writes it, with one line for each field: + +```go +func (r *UserRow) SealFrom(u User, s *eql.Sealer) { + r.ID = u.ID + s.TextEq(&r.Email, u.Email) + s.IntegerOrd(&r.Age, u.Age) +} + +rows, err := encrypt.Encrypt[UserRow](ctx, cipher, users) +``` + +The compiler then refuses a field of the wrong type, and a struct that is +not sealed from the one given. This form is a function, because a Go method +cannot have a type parameter. `encoding/json` has the same pair: reflection +by default, and `json.Marshaler` for a type that writes its own. + +**What was checked.** Three small sketches compiled and ran on Go 1.26.10: +one with reflection, one with the method, and one that lists each column. +None of them encrypts. Each shows the shape of a call and which mistakes +the compiler finds. + +**The trial.** Before the SDK changes, the design is built for `TextEq` and +`TextMatch`, the two types of the experiment. It is run with a program that +uses sqlc, and compared with PR #1716. + +**Not designed yet.** See the open questions: + +- where a stored struct declares its context, and each field's identity; +- how a query names a column, with no generated value to call; +- nulls, a record whose context is one of its fields, a struct sealed as + one value, and a JSON document with declared paths; +- what happens to `stashgen` and to programs that use it today. + +Done when a Go program encrypts, decrypts, and queries with no generated +code, and the trial with sqlc passes. + +## Phase 2: queries + +| Step | What | +|---:|---| +| 2.1 | The dynamic query path returns a `StackCipherText` | +| 2.2 | Query types read it with a visitor, in each language | +| 2.3 | `QueryTerm` and each SDK's second reader are removed | +| 2.4 | The JSON scheme moves to EQL, if the JSON check allows it | + +Phase 2 needs steps 1.3, 1.5, and 1.7. After step 1.7 no resolver builds a +query, so the answer has one form to change. Phase 2 does not need step +1.4. Step 1.4 changes how a query term is derived: from the field's own +declaration. Phase 2 changes the form the answer crosses in. + +### 2.1 The dynamic query path returns a tree + +`dynamic::query_term` +(`packages/stack-encrypt/src/dynamic/query.rs:1093`) returns a tree of +terms. A query has no sealed leaf, so its tree is term nodes, maps, and +sequences. + +| Today's operand | As a tree | +|---|---| +| One term | A map with one entry: the index's key, and a term | +| A range, `lo` and `hi` | The same map, with a sequence of two terms | +| Text, and a list of text (the JSON operators) | Not settled. See the open questions | + +The operator, the fidelity, and the index leave the answer. All three describe +the plan, not one query. An SDK already asks for them in a separate call, +`field_operators`. Go parses that answer in `parseOperators` +(`languages/golang/encrypt/checker.go:295`). The SQL domain and the `eql` +encoding left the answer in step 1.7, with the resolver. + +The form allows a query far larger than today's. A query of 131,072 tokens +was built by hand and read in TypeScript in two forms: + +| Form | Size | Time to read | +|---|---:|---:| +| One node for each token | 1.84 MB | 40 ms | +| One term that contains every token | 1.05 MB | 0.3 ms | + +Both forms pass through the same deserializer. Which form an index uses is a +choice for that index's design, not for this plan. + +### 2.2 Query types read it with a visitor + +A query type is a visitor, as a stored type is. In Rust a query type is +already a target: `TextEqQuery` derives `EncryptTarget` +(`packages/eql/crates/eql-bindings/src/v4/text.rs:457`). Step 1.6 generated +each query type as a function of a term's bytes. `eql-codegen` now writes +each one as a visitor. Two checks that use today's answer stay as calls: +`target_limit` and `verify`. + +### 2.3 The fixed shapes are removed + +Removed: + +- `QueryTerm`; +- `Operand` and its four shapes; +- Go's `parseQueryTerm`; +- the generated code that takes only a term's bytes + (`languages/golang/encrypt/gensupport/field.go:121`). + +**No deprecated `QueryTerm` in Go.** A deprecated form, built from the new +tree, was considered for Go. It would have kept an old generated file +compiling. Step 1.8 has no generated files, so Go's `QueryTerm` is removed +with no deprecated form, as Rust's is. These facts were weighed: + +- A program cannot call `Cipher.QueryTerm` itself. The method takes a plan + type from an `internal` package + (`languages/golang/encrypt/query.go:153`). +- A generated file calls `Term`, `Range`, and `NullTerm` in `gensupport` + (`languages/golang/encrypt/gensupport/field.go:121`, `:131`, and `:143`). + Each returns a term's bytes. +- A generated file names the version of its layout + (`languages/golang/encrypt/gensupport/gensupport.go:35`). A file from + another layout does not compile. + +Removing `QueryTerm` is not a small change. `QueryTerm` and its operand are +public. Outside tests, 12 Rust source files name `QueryTerm` today: seven in +`stack-encrypt`, two in `eql-bindings`, and three in the Go guest. +`packages/eql/crates/eql-codegen/src/targets.rs` names it too, and so do six +files of the Go SDK. Three conformance suites read the operand. + +Done when each SDK has one reader for records and queries, and the query +conformance suites pass on the new form. + +### 2.4 The JSON scheme moves to EQL (possible) + +This step is a possibility. It happens only if the standard declarations of +`stack-encrypt` can declare a JSON document: each node as a term with a +sealed leaf beside it. The JSON check finds that out +([The JSON check](#the-json-check)). + +Today the scheme is in `packages/stack-encrypt/src/json/`: the JSON tree, +the stored document, and the query terms. Each entry of a stored document +has a ciphertext of its own +(`packages/eql/crates/eql-bindings/src/v4/json_tree.rs:125`). Its selectors +and tokens are derived under the index key +(`packages/stack-encrypt/src/json/derive.rs:848`). + +What moves to EQL: + +- the JSON tree and its options; +- the stored document and the JSON query terms, with their EQL forms; +- `eql_simulator`, the test copy of EQL's read functions. + +What the move gives: + +- `stack-encrypt` names no EQL JSON query form. Step 1.7 leaves two + mentions of EQL in `stack-encrypt`, and this step removes both. +- The JSON type is built in Go and TypeScript in the same way as every + other stored type. + +What the move costs: the scheme's leakage design would be in EQL. That +design includes the selectors and the order of entries. The other indexes +stay in `stack-encrypt`, so a review of the indexes reads two places. + +Done when `stack-encrypt` has no `json` module, and the JSON conformance +suites and the PostgreSQL tests pass unchanged. + +## What does not change + +- **Stored bytes.** The sealed leaf, every EQL value, every term's bytes, + and the prefix on `c`. A change to stored bytes during this work is a + defect. +- **Where the security is.** Rust does the sealing, the term derivation, + and the context binding. A host type formats bytes that Rust gave it. +- **The number of key requests.** A call makes one, for any number of rows + and fields. +- **What a stored value authenticates.** A map's membership and a + sequence's order are still not bound. A passthrough field is still not + authenticated. +- **How a Rust target is written.** The derive still writes one expression + of combinators for a record, and the `eql-bindings` types stay. The + combinators are declarations after step 1.4, and their paths change with + the layout. + +## Checks that must move with the code + +| Check | Step | What happens | +|---|---|---| +| `conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json` | 1.3 | Its cases are transport bytes, so they are regenerated | +| The `ciphertext_malformed` section of `conformance/vitaminc-aead/value-conformance.json` | 1.3 | Has new cases for the new kind and the length | +| Go's `FuzzUnmarshalCipherText` and its seeds, which #2003 adds | 1.3, 1.5 | Covers the new reader | +| The record suites' expected files | 1.4 | Must not change | +| The tests that count key requests | 1.4 | Must not change | +| A shared corpus of trees and refused inputs | 1.5 | New. Run by Rust, Go, and TypeScript | +| Refusal tests for one field of a record of several fields | 1.4 | New: a leaf under another field's root, and a wrong descriptor or lock context | +| A stored-type conformance suite against Rust | 1.6 | New. It covers the two refusals that move to the host type | +| A drift check for the generated TypeScript types | 1.6 | New, like `types:check` for Go (`.github/workflows/test-eql.yml:768`) | +| `scripts/__tests__/go-release-artifact.test.mjs` | 1.7 | It expects five guests (`:166`). The number becomes three | +| `scripts/__tests__/stack-exchange-conformance.test.mjs` and `scripts/__tests__/go-binding-test.test.mjs` | 1.7 | Both require the task `wasm:guest:build:eql:deterministic` (`:378` and `:124`) | +| The EQL guest builds in `.github/workflows/tests-golang.yml` | 1.7 | Removed (`:246` and `:249`) | +| The suites that read a query's operand | 2.3 | Move to the tree form | +| The mutation gate on `stack-encrypt` | 1.4 | New sinks and adapters need tests that fail under each mutant | +| The compiler-message snapshots in `packages/stack-encrypt/tests/ui` | 1.4 | Regenerated. A declaration gives other messages than an `Encryption` | +| A compile-fail test for each rule the compiler checks | 1.4 | New: one context for each target, the plaintext's type, and the operator. The spike tried each by hand | +| The heap tests of `stack-encrypt` and EQL | G2, 1.4 | Must pass on both AES backends, with no free excluded | +| `supply-chain/vitaminc-aead` | G2 | The `cargo vet` store and `deny.toml` cover the AES backends | +| The supply-chain checks of `stack-encrypt` (#1842) | 1.4 | New, before the AES cipher moves there. They cover aws-lc-rs, aws-lc-sys, and aes-gcm | +| The tests of the AES cipher, the wasm32 job, and the backend flag `vitaminc_aead_rust_crypto` | 1.4 | Move to `stack-encrypt` with the cipher. The flag is renamed | + +Issue #2004 is the differential fuzzing of the Go codec against the Rust +codec. After step 1.3, that fuzzing covers the new node. + +## What this changes elsewhere + +- **The TypeScript SDK plan** + (`docs/plans/2026-11-22-recipher-typescript-sdk.md`). That plan's EQL + extension becomes TypeScript types with visitors, with no extension inside + the cipher. A query value comes from the query type, not from the `domain` + of a `QueryTerm`. The plan says that a `match` index takes no options. + That is no longer true for a type that fixes them. +- **The Go SDK.** `encrypt/eql` no longer embeds a guest. The release + workflow's list of guests changes in step 1.7, and so does the + description of the guests in `AGENTS.md`. +- **The `eql-bindings` crate.** Step 1.7 removes its public modules + `encryption::query` and `encryption::targets`. `targets` is public on + `main` too. The crate is published at one version with the other four EQL + artefacts. See the open questions. +- **The SDK design principles** (`docs/sdk-design-principles.md`). + Principle 1 says that nothing is rebuilt from parts, and that an SDK + "holds no copy of the engine's rules". The same principle lets an SDK + assemble a wire format in the host language "only when a cross-language + test compares the bytes". This plan uses that for every stored type. The + stored-type conformance suite is the test. + + Two refusals also move from Rust into generated host code: empty match + text (`EmptyTermText`, + `packages/eql/crates/eql-bindings/src/encryption.rs:420`) and the stored + `i`. Both refusals are rules of the EQL types. Each language then has a + copy, so the conformance suite has to cover both. +- **Decision records.** This plan needs a record of its own. That record + changes what four records of `stack-encrypt` describe + (`packages/stack-encrypt/docs/adr`): + - the target model (0003); + - one context for each target, threaded through the declaration tree + (0004). The rule stays. The context becomes an associated type of a + declaration, where it is a type parameter of `Encryption` today; + - how a binding enters (0007, with its amendment for the EQL guest); + - the query term (0009). + + The first decision record of `vitaminc-aead` describes `AsyncCipher` and + the sink that has a context. Both go in step 1.4. +- **The targets of `eql-bindings`, and the derive.** 19 types in + `eql-bindings` implement `EncryptTarget`, and the derive's output names 78 + paths in `target::`. Step 1.4 changes both. +- **Public paths.** The layout moves `sem`, `json`, and `field_reference`, + and takes 68 names off the root. See [Crate layout](#crate-layout). +- **Draft PR #2031.** That PR builds typed records that cross through + serde. This plan did not choose that form. + +## Not in this plan + +- A plan for a nested record. One walk makes it possible. Today a plan + names top-level fields only. +- The developer API of the TypeScript SDK. A sketch exists, and it belongs + to the TypeScript SDK plan. In the sketch: + - a record is an object of fields; + - an EQL type goes by its catalog name; + - a field that is not an EQL type is made with a builder. +- The naming of errors and refusals. +- The Python SDK. + +## Open questions + +1. Context rules: do a record's context rules belong in `stack-encrypt` or + in the cipher's data model? Answered: in `stack-encrypt`, in the + adapters of a declaration (`under`, `under_field`, and `context_from`). + The spike changed no sink trait. +2. Passthrough: does a passthrough node get a length? Answered: yes, a + `u32` length before the frame, as step 1.3 describes. +3. A term outside a record: what does opening a tree do with a term node + when no plan says to skip it? Answered: `walk` leaves it out. A term + opens nothing, as decided for decrypt. A term at the root of a tree, or + as an element of a sequence, is refused as malformed. +4. The stored `i`: does the host type check it on decrypt, or is the check + dropped? Answered: the host type checks it against the plan's label, as + the Go SDK does today. See [The design](#the-design). +5. `eql-codegen`: where does it read each type's outputs, its match + options, and the prefix on `c`? Answered: from the catalog, + `eql-domains`. The outputs are there already. The match options and the + prefix move there from two constants in `eql-bindings` + (`packages/eql/crates/eql-bindings/src/encryption.rs:398` and `:135`). + `eql-bindings` and the generated Go and TypeScript types all read them + from the catalog. +6. The derive: does a static record move to one walk too, after phase 1? + Answered: yes, in step 1.4. The derive writes a declaration, as a plan + builds one. +7. Text in a query: what is the tree form of a JSON operator's answer? + Answered, for a selector and a token: a term node with the raw bytes + in it. A list of tokens is a sequence of term nodes. Today the answer is + base64 text that binds as SQL `text` or `text[]` + (`packages/stack-encrypt/src/dynamic/query.rs:302`). The host type + writes the base64 and decides how the value binds. The element predicate + and the path predicate are whole EQL objects. Their form waits for the + JSON check and step 2.4. +8. Go's visitor: is it in `encrypt/frame`, beside the codec, or in a + package of its own? Answered: in `encrypt/frame`. Does the interface + also make every type embed the default? Answered: yes. The interface + has one unexported method that only the default has. A new kind of node + then does not break a type that is written outside this repository. +9. The crates of the term sinks: when do they move? Answered: + `vitaminc-normalize` moved in G3. `vitaminc-prf` and `vitaminc-ore` + move in G7. +10. Draft PR #2031: does it close? Answered: yes, without merging. Issue + #2029 stays open until step 1.5 lands. The deserializer and the visitor + of that step solve the problem that the issue describes. +11. The readability refactor of the dynamic record path: does it merge + before step 1.4? Answered: yes, as #2042, and step 1.4 stacks on it. +12. The type catalog: where does an SDK read the list of EQL types once no + resolver answers? Answered: it does not read a list. The EQL package of + each language has every concrete type that EQL defines, each with its + visitor. That is the design of this plan. +13. `eql-bindings`: is the removal of its public modules `encryption::query` + and `encryption::targets` a major release of the five EQL artefacts? + Answered: no. No release has the two modules: `eql-bindings` 3.0.6 has + no `encryption` module. The next EQL release waits until this plan is + done, so the modules are deleted before any release has them. +14. PR #1776: does the TypeScript half of step 1.5 build on its record path + or replace it? Answered: it replaces it. #1776 closes without merging, + and step 1.5 builds TypeScript records on the tree from the start. The + issues that #1776 was to close, #1813 and #1803, stay open until then. +15. `QueryTerm` in Go: does Go keep a deprecated `QueryTerm`, built from the + new tree, after step 2.3? Answered: no. A deprecated form was for + generated files. Step 1.8 has none. `QueryTerm` is removed in Go with + no deprecated form. +16. `Cipher`'s methods that take a plan: do they change in step 1.4? + Answered: step 1.8 stops exporting them. Only generated code calls + them, and step 1.8 has none. Six + methods beside `QueryTerm` take a `*record.Plan` from `internal/record`: + `Verify`, `TargetLimit`, `Contexts`, `Seal`, `Open`, and `JSONOpen` + (`languages/golang/encrypt/query.go:305`, + `languages/golang/encrypt/records.go:48`). A program outside the module + cannot name that type, so only generated code calls them. Step 1.4 + rewrites the path behind `Seal` and `Open`. The Go SDK's principle 7 + says that no method that a user touches is called a plan or returns + one. This question came from #2003. +17. `EncryptTarget`: does the record's plan still implement it? Answered: + the third decision stands. The plan builds a declaration from the + combinators, and the cipher runs it. +18. The main calls: how are the keyset's `encrypt` and `decrypt` overloaded + through traits, so that one method serves a scalar, a tree, and a + record? Answered: `EncryptTarget<S>` chooses the declaration for + encrypt, and `DecryptSource<P>` chooses it for decrypt. Each stored type + has an impl for each plaintext type it opens to. +19. Decrypt's type check: what tells the compiler that a target opens to a + given plaintext type? Answered: `DecryptSource<P>`, as today + (`packages/stack-encrypt/src/target/conversion.rs:74`). + `P::decrypt_from(stored, &cipher)` compiles only when the stored type + is `DecryptSource<P>`. Today the trait returns a `Decryption`. In step + 1.4 it returns the decrypt half of the type's declaration. The spike + has no such trait: its decrypt takes any plaintext type. +20. A stored record with no term: does decrypt ignore the missing term? + Answered: yes. Decrypt needs only what opens. Step 1.4 changes `Open` so + that it never reads a term. +21. The order of the checks: does the context have to be checked before the + plaintext is read? Answered: yes, for the caller's context. A context + read from a field of the record is checked after the walk, because the + walk reads it. See [The order of the checks](#the-order-of-the-checks). +22. `contexts()`: how does a declaration report its contexts without a run, + as `Encryption::contexts` does? Answered: it stays, as a requirement of + step 1.4. Each adapter that sets a context reports it, as each + combinator does today + (`packages/stack-encrypt/src/target/operations.rs:148`). The spike does + not have it. +23. The owned mode: how does a declaration wipe a plaintext it is given by + value? Answered: it stays, as a requirement of step 1.4. A plaintext + given by value is wiped once the walk has read it, and also when the + call is refused. Today `SourceMode` does this + (`packages/stack-encrypt/src/target/source.rs:52`). The spike has no + rule for it. +24. Return types: is a long return type acceptable for a declaration written + by hand? Answered: yes, without the position marker. In the spike, a + function that returns a declaration states its query term's type as + `Answers<Eq, Right<Here>, Query: Declaration<Output = EqualityTerm>>`. + `Right<Here>` tells the compiler which side of a `zip` has the index + for `Eq`. Step 1.4 removes it. Each index says, in its type, whether it + has an index for each operator, and `zip` reads that from its two + sides. The return type is then `Answers<Eq, Query = ..>`, as a function + that returns `impl Iterator` states `Item`. A prototype compiled. Each + index has one line for each operator, written out, with no macro. +25. `field(..)` and `entry(..)`: is it enough that a derive writes both + from one name? Answered: no. In the spike the compiler does not check + that the closure and the name mean the same field. A hand-written + declaration could get them wrong. A struct's record is built from + closures, with no names. See [A declaration](#a-declaration). +26. The JSON tree's walk: does it become a sink? Answered: a sink is the + aim, and the JSON check decides. In the spike the sink stages the whole + document, and the tree's own walk runs in the finishing step. A sink + could stage each node's path, kind, and canonical bytes, and leave only + the keyed work to the finishing step. Step 2.4 needs that shape. If the + check finds that a sink does not work, the document is built once as it + is walked. The question comes back at step 2.4. +27. JSON from a walked value: what does the JSON tree do with a scalar + that JSON has no kind for? A date and bytes are two examples. Answered: + it refuses the value. The JSON tree takes JSON kinds only, and the + caller converts anything else first. A document read back is then the + same value that went in. +28. JSON with no copies: how does the declaration read a document without + copying it first? Answered, in two parts. + + A typed `JsonPlaintext` contains a parsed document. It is handed to the + JSON tree directly, as on `next`, and the tree reads it in place. + + Its walk is not used for this. The walk gives the document's JSON text. + That text is the opaque form, as decision record 0013 in + `packages/stack-encrypt/docs/adr` says. The spike used the walk, so it + parsed that text again. + + A Rust struct or a record from a language binding becomes a document + as question 26 says. The spike turned a binding's map into a frame + first. +29. The stored layout of a leaf: is `sealed/` the right module for it in + `stack-encrypt`, or does it sit with the AES functions in `cipher/aes/`? + Answered: `sealed/`, with the other stored types. The nonce generator + is not part of the stored layout, and stays in `cipher/aes/`. +30. The two tests outside `stack-encrypt` that build an `Aes256Cipher`: + what do they seal with once the cipher is crate-private? Answered: + Stack Encrypt. Neither test calls AES. + + The EQL test for opaque JSON opens each leaf itself today, and rebuilds + the leaf's authenticated data by hand to do it + (`packages/eql/tests/encryption/tests/opaque_json_bytes.rs:136`). It + decrypts through Stack Encrypt in place of that. A check of the bytes + inside a leaf belongs in the tests of `stack-encrypt`. + + The test crate of the recipher-js value bridge builds an AES cipher + with a fixed key. It uses Stack Encrypt's cipher with a test key + source. The `test-support` feature of `stack-encrypt` has + `FakeDataKeySource` (`packages/stack-encrypt/Cargo.toml:163`), and the + recipher-js language binding already turns it on for its tests. +31. The JSON scheme: does it belong in EQL, not in `stack-encrypt`? + Answered: it can move at the end of phase 2, as step 2.4, if the + standard declarations of `stack-encrypt` can declare a JSON document. + The JSON check finds that out. +32. Text that cuts no token: which rule do `TextMatch` and `TextSearch` + share? Answered: both store the empty filter, as `TextSearch` does + today. No query that Stack Encrypt builds finds that filter, and a + query of such text is still refused. The other rule is that both refuse + such text. That rule would refuse an empty string in a `TextSearch` + field. Today `=` and `<` can find such a string. G8 changes the Rust + types. +33. A hand-built match query with an empty filter: does + `eql_v4.query_text_match` raise on `"bf": []`, as the search query + domains do? Answered: yes. G8 adds the raise to the generated SQL of + EQL v4. +34. `convert_from` and a term: can a term's empty part be left out of what + `convert_from` returns? Answered: yes. `zip` leaves out a side that + opens nothing, and a term that opens later has a part. A prototype + compiled, and its closure types were inferred. Step 1.4 has to apply + the same rule to `Option`, `Fields`, `under`, and the query lookup. +35. A row that comes back in part: how does decrypt open some fields of a + record and not others? Answered: decrypt opens the fields that are + there, and the output type decides what a missing field means. See + [A row that comes back in part](#a-row-that-comes-back-in-part). +36. A null column and a column that was not selected: how does a stored + record tell them apart? Answered: it does not. The SDK reads the row, + so the SDK knows. +37. An entry that the declaration does not name: does decrypt ignore it? + Answered, in two parts. A term that the declaration has no index for is + always ignored. A field that the declaration does not name is ignored + by default. A declaration can ask for it to be refused. The name of + that adapter is not chosen. + + Today's decrypt ignores both + (`packages/stack-encrypt/src/dynamic/record.rs:901`). A stored field + that the plan does not open is ignored. So is an output of a field that + the plan does not open, such as a term. The spike refuses a field that + the declaration does not name. + + serde is the comparison. A derived `Deserialize` ignores a field that + the type does not name, and `#[serde(deny_unknown_fields)]` on the type + refuses one. So serde is lenient unless the type asks. A declaration + cannot hand an entry that it does not open to the output type. So the + choice has to be made on the declaration, not on the output type. + + A term that the declaration has no index for is a separate case. A + field keeps its old term after its index is removed. If decrypt refused + that term, the old rows could not be read. +38. Encrypt and a field that is not there: does encrypt seal the fields + that a record has, as decrypt opens them? Answered: no. Encrypt keeps + today's rule. A record with no entry for a field is a null for an + `"omitted"` field, and an error for any other field. +39. The name of the null form that stores nothing: what replaces `"sql"`? + Answered: `"omitted"`. +40. The Go SDK's tag: does `null=sql` in a struct tag become + `null=omitted` too? Answered: yes, and `null=sql` stays for a time as a + deprecated spelling. The tag is in programs that use the SDK + (`languages/golang/stashgen/declaration.go:78`). A field takes the tag + whether or not it is stored as an EQL type. +41. The new prefix on `c`: is it rolled out in one release or in two? + Answered: two. A reader that is already released does not open a value + with the new prefix. The first release accepts both prefixes and still + writes the old one. The second release writes the new prefix. A program + can then upgrade every reader before any writer changes. +42. `stashgen`: does the Go SDK keep its code generator once the stored + types are built in Go? Answered: the SDK no longer needs one. See step + 1.8. Parts of this plan were written for generated code, and change + with it: the layout version in step 2.3, and questions 15 and 16. Four + facts led to the answer: + + - `stashgen` runs before the program compiles, so it cannot call a Go + type. It needs each type's name, plaintext, and outputs as data. + `eql-codegen` already writes a table of them + (`languages/golang/encrypt/eql/eql_gen.go:20`), and nothing reads it + today. + - `stashgen` asks the guest for the operators of each field, so it has + no copy of those rules + (`languages/golang/stashgen/engine.go:102`). Nobody has tried that + with a host-built type. + - A type that is written outside the EQL package has no path through + `stashgen`. The generator is a separate program, so it cannot import + the program's own package. + - `Checker.Targets` is a public method that returns the guest's list of + types (`languages/golang/encrypt/checker.go:73`). Step 1.7 leaves the + guest with no list. +43. `stashgen` after step 1.8: is it removed, or kept as an optional tool + that writes the method of step 1.8? What does a program that uses + generated code today have to change? +44. A stored struct's context in Go: where is it declared, and where is + each field's identity? Today both are in struct tags that `stashgen` + reads. +45. A query in Go with no generated code: how does a program name a + column, and get only the operators that the column's type has? One + sketch has a column value for each EQL type, with a method for each + operator. +46. The Go design principles: which other principles change with step + 1.8? Principles 6, 7, 9, and 10 of the Go SDK each describe generated + code (`docs/sdk-design-principles.md`). The file and its decision + record change in a pull request of their own. +47. A struct's record and the adapters for a whole record: how do + `context_from` and a batch work for a record that is built from + closures? Such a record is not itself a sink. The prototype did not + cover either.