From f55d7f43a6f5ec12c6f5436e68a99bbb5c24c090 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 12:49:08 +1100 Subject: [PATCH 01/11] docs(crates): file unreleased changelog entries under their versions The root release-plz line publishes these crates and never writes their changelogs. So each entry under "Unreleased" would publish with no version heading. - stack-encrypt: the 101 entries move into 0.3.0. Each kind of change now has one heading, in the order Breaking, Added, Changed, Fixed. The 0.3.0 section had two Breaking and two Added headings. - stack-kms: the 5 entries move into 0.2.0. - stack-encrypt-jsonpath: the section becomes 0.3.0, the version in its Cargo.toml. The crate is not on crates.io yet. No entry's text changes, and no two entries were the same. --- packages/stack-encrypt-jsonpath/CHANGELOG.md | 2 +- packages/stack-encrypt/CHANGELOG.md | 4217 +++++++++--------- packages/stack-kms/CHANGELOG.md | 40 +- 3 files changed, 2187 insertions(+), 2072 deletions(-) diff --git a/packages/stack-encrypt-jsonpath/CHANGELOG.md b/packages/stack-encrypt-jsonpath/CHANGELOG.md index d418fdb74..dea4617b5 100644 --- a/packages/stack-encrypt-jsonpath/CHANGELOG.md +++ b/packages/stack-encrypt-jsonpath/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.3.0] ### Added diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index ca0482d82..7986d6548 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -5,756 +5,261 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.3.0] - 2026-10-27 -### Added +### Breaking -- **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's - wipeable UUID, built from the uuid crate's `Uuid` with `Uuid::new`. It - seals as one leaf, and an `Option`'s `None` seals as a null as long - as a value. It takes an equality index, whose term never matches the same - sixteen bytes stored as a byte string. It takes no order index: one does - not compile. The type is behind the new `uuid` feature, on by default - beside `jiff` and `rust_decimal`. A data plan declares a UUID field as - `"uuid"` (#1918). +- **An error about input that is not an object names the kind of value + and the row** (#1985). The input is a plan, a field spec, a record to + encrypt, or a stored record. A field spec is the entry in a plan that + describes one field. Before, the engine refused each one with the reason + `not_an_object` and no more detail. Most of those errors named no field + and no row. -- **Read one child of a JSON node, checked against its parent** (#1677). - Your app can now read one level of a document without fetching the - parent's whole subtree. The read takes three steps. - 1. Your app derives the parent's token and key, for example with - `children(path).encrypt_keyed(&keyset)`. Deriving asks ZeroKMS for - nothing. - 2. The database (EQL) runs `eql_v4.json_tree_children(doc, $1)` with the - token. The database returns the parent's direct children as encrypted - entries. - 3. Your app passes each entry to `JsonSubtreeKey::open_child(node)`, and - decrypts the `JsonChild` it gets back. + To upgrade, add `..` to a match that names every field of `Error::Plan`, + `Error::Source`, or `Error::Record`. `Error::Plan` has a new `found` + field. `Error::Source` and `Error::Record` have new `row` and `found` + fields. The existing reason codes keep their names. The two new codes + are `not_a_frame` and `source_failed`. - More detail: + The changes are: + - The error names the kind of value that the engine got, and never + includes the value. The kind is in `Error::found()`, in the payload + field `found`, and in the message. The message is one sentence, such + as `row 2 of the records to encrypt is null, not an object of fields`. + The new `dynamic::Found` lists the kinds, such as `"null"`, `"array"`, + `"string"`, `"uint32"`, `"passthrough"`, and `"sealed"`. The message + says `an encrypted value` for the kind `"sealed"`. + - An error names a kind only when the engine can read the kind without + decrypting anything. That is the kind of a value the caller sent, or + the kind of a node in the unencrypted structure of a stored record. + An example of the second is a row that is a passthrough or an + encrypted value, and not a map. An error about a decrypted value never + names the kind that the value decrypted to. + - An error about a row of a batch names the row by its position, counted + from 0. The position is in `Error::row()`, in the payload field `row`, + and in the message. The message also says whether the record was to + encrypt or to decrypt. An error names the row in any of these cases: + - The row is not an object. + - A value in the row returns an error of its own while the engine + reads it. + - The engine cannot copy a value in the row. The cause is a value + that repeats a map key, does not fit its logical type, is nested too + deep, or is too long. + - An error from comparing a field with the plan names the field and not + the row. Examples are a missing field, a field that the plan does not + name, and a value of another type. + - A source can start a row of a batch and never write it. The engine + refuses that batch with the reason `unframeable`, and the error names + the row. The engine does not move the later rows up one position. + - Bytes given as a plan that are not one transport frame get the new + reason `not_a_frame`. A transport frame is the binary encoding of one + value. The bytes are empty, are cut short, are JSON text, repeat a + key, or continue after the value ends. A frame that is not an object + of field specs keeps the reason `not_an_object`, and the error names + the kind of value in the frame. + - An error about a field spec that is a typed null names the field. + Before, the error named no field. A typed null is a null that records + a type. + - A value that returns an error of its own while the engine reads it + gets the new `Error::SourceFailed`. An example is a JSON document that + is nested too deep. The code is `stack_encrypt::dynamic_source_failed`. + The reason is `source_failed`. Before, the reason was `not_an_object`, + and the error named no field. + - The error names the row that the engine was reading, and the field + whose value the engine was writing. An error between two fields + names no field. An error between two rows names no field and no row. + - The value's error is the cause, and `source()` returns it. The + message leaves the cause out, and `Debug` prints the cause as + `SourceError(..)`, because the text of the caller's error can + include the value. + - The message of an `Error::Source` names the input that the reason is + about. Before, every such message started with `record source does not + fit the plan`. Now the message starts with one of these: + - `the query input does not match the field`, when only the input of a + query can cause the reason. Those reasons are about an operator, a + range, a term, statistics, a null query, or the input of a JSON + operator. + - `the record to encrypt or the query input does not match the plan`, + for a value of another type and for an `undefined` value, when the + error names no row. A record and a query can both cause those + reasons. + - `the record to encrypt does not match the plan`, for every other + reason. + - The message of an `Error::Record` starts with `the record to decrypt + does not match the plan`. Before, that message started with `stored + record does not fit the plan`. + - The message of an `Error::SourceFailed` starts with `a value in the + record to encrypt returned an error while it was read`. The row and + the field follow. For an error that names no field, the message starts + with `the record to encrypt`. - - A `JsonChild` decrypts into a `JsonPlaintext` for the child's value - alone. A `JsonChild` also decrypts into a `JsonChildPlaintext` for the - value with the member's `key()` or the element's `index()`. - - The database returns an object's members in a random order. So use - `JsonChildPlaintext` when your app needs to know which member a value - is. - - The key or index is encrypted with the value, and authenticated. The - key, the index, and the value are wiped on drop. `Debug` hides all - three. - - Decrypting checks the entry's link to its parent, as a subtree read - does. The entry must have a parent tag and sit one level down. The - entry's selector must be the parent's path extended by its key or - index. The entry's self tag must be the one that key or index gives - under the parent's token. - - An entry that fails a check is `Error::JsonWrongEntry`. A child with - children of its own does not decrypt alone (`Error::JsonNotALeaf`). - - Two refusals come before any key is fetched. A key for a path with a - wildcard is `Error::Input`, with reason `JsonPathWildcard`. An entry - with no parent tag is `JsonWrongEntry`. - - For a `JsonDocument` field, the field reference's `children(path)` - returns the key, so the token sent and the key are one value. For a - field of another type, `children(path).encrypt_keyed` returns the - token and the key from one derivation. - - `dynamic::json_open` takes the operation `"children"`, with the - parent's path and one entry or none per group. Each child opens to a - map: `{"key", "json"}` for a member, or `{"index", "json"}` for an - element. `dynamic::check_json_open` checks the request. - - The stored format is unchanged. +- **The `vars` of a `match` query that are not a JSON object get the new + reason `json_vars_not_object`** (#1987). Before, the reason was + `json_input`. The error had no more detail. `json_input` is the reason + for any input that a JSON operator does not take. To upgrade, change + code that compares the reason with `json_input` for this case. + - The error names the field. + - The payload field `found` is the kind of value that the vars are, + such as `"array"`, `"uint64"`, or `"null"`. + - The message for vars that are null is + `the vars of the match are null, not a JSON object`. The field + follows. + - The engine refuses the vars before it reads the predicate. + - Only the dynamic path can get vars that are not an object. A field + reference always builds an object. -- **A guide to building a language integration**, `dynamic::guide` - (`docs/language-integration.md`, in the crate docs under the `dynamic` - feature). It covers the binding versus the language SDK; linking the - engine natively (PyO3, Rustler, napi-rs), with a WebAssembly guest only - for a language that cannot, such as Go; the operations through - `dynamic::Planned`; scopes and bindings; JSON documents; the plan - grammar; control messages versus plaintext; plaintext hygiene and the - tests that prove it; credentials and audit metadata; errors; and - versioning. The Go guest's exports, step loop and status table are - described as the guest path. It traces one `int32` stored as EQL v4 - `IntegerEq` through encrypt, query and decrypt, with the bytes from the - committed fixtures, and ends with a checklist built on - `conformance/stack-encrypt`. The frame format stays in - `recipher-frame`'s documentation and is linked, not restated. -- **A credential with each call** (#1708). A server that decrypts as the end - user who signed in had to build its cipher inside the first request, - because `init` needs a token and a server starting up has no user. It also - had to tell the auth strategy which user each call was for through a - task-local variable. Both are gone. - - Call `.with_credential(credential)` on a call before you await it: - `keyset.decrypt(stored).with_credential(jwt).await?`. Every request the - call makes is then made with that credential, so ZeroKMS serves and - logs it as that caller. The credential is a `kms::SecretToken`. For a - `stack_auth::OidcFederationStrategy` it is a JWT, most often the end - user's. - - Every `Pending` has `.with_credential(..)`. So it works for scalars, - trees, values and records sealed through the conversion traits, terms, - queries and `dynamic`. - - `.with_credential(..)` returns a `WithCredential` call. You can await - it, or call `.audit(..)` on it and await that. So attach the credential - last, to the whole call: `a.zip(b).with_credential(jwt)`, or - `Pending::all(&keyset, calls).with_credential(jwt)`. - `a.with_credential(jwt).zip(b)` does not compile. One call therefore - has one credential. - `.audit(..)` and `.with_credential(..)` go in either order. - - A cipher and a keyset hold no credential. - - A key source is one of two kinds (`KeySource`), and a call can neither - forget a credential nor have one ignored: - - A key source that takes a credential with each call - (`kms::CredentialKeySource`) has no request without one. A call - through its cipher is not a future until `.with_credential(..)`, so - `keyset.decrypt(stored).await` does not compile. A ZeroKMS client - over `OidcFederationStrategy::credential_per_call(crn)` is this - kind. - - A key source with an identity of its own makes every request as that - identity. A call through its cipher is awaited as it is, and has no - `.with_credential(..)`. An access key, a saved login, and an - `OidcFederationStrategy` built with a provider callback are this - kind. - - `init` is the same call for every auth strategy. With an access key or - a saved login it loads the default keyset, as before, so wrong - credentials still fail at startup. With a key source that takes a - credential with each call, `init` has no credential to load the keyset - with. It then makes no request and returns the cipher. So a server - builds its cipher at startup: - `StackCipher::builder().auth_strategy(strategy).key_provider(provider).init().await?`. - `init` has a type parameter that says which kind the key source is. - You never write it: the compiler works it out. - - `default_keyset()` still makes no request and cannot fail. On such a - cipher it returns a handle on a keyset that is not loaded yet. Every - call on the handle works as usual: the first call that is awaited loads - the default keyset, with its own credential, beside its key request. - Callers that arrive together make one load between them. A load that - fails leaves the cipher as it was, and the next call tries again. - - A keyset's index key is still loaded once and kept for every caller, - with the credential of the call that needed it first. Data key requests - are made as each caller; that one load is not. This changes what the - ZeroKMS log shows, not what a caller can reach: a keyset is granted to - a client, and a cipher has one client. - - A call loads the keyset it works under, and no other. With such a key - source, a call on a keyset selected by id or by name does not load the - default keyset. - - The JSON queries, typed and `dynamic`, and the `dynamic` reads work - through a keyset that is not loaded yet too. A query operand is derived - when it is awaited. A read (`json_open`) builds its key requests from a - key derived under the keyset, so it is built when it is awaited. It - still merges with other calls (`zip`, `all`). - - This needs the `stack-kms` and `stack-auth` of this change: - `kms::CredentialKeySource`, `StackKms::generate_keys_with_credential`, - `retrieve_keys_with_credential` and `load_keyset_with_credential`, and - in `stack-auth`, `CredentialAuthStrategy` and - `OidcFederationStrategy::credential_per_call` (a strategy with no - provider callback). - - For tests, `kms::FakeCredentialKeySource` is a key source that takes a - credential with each call and records it: `credentials_seen()` lists - the credential of each request. A test of a request handler built on it - does not compile if the handler forgets its caller's credential. -- **Audit metadata for ZeroKMS key requests** (#1705). ZeroKMS logs every - key request with the identity that made it. An `AuditMetadata` adds - facts about the call to that log, such as its purpose or a request id. - To send it, call `.audit(metadata)` on a call before you await it. A - call without it sends none, and its request is unchanged. - - Build the metadata with `AuditMetadata::new().with(key, value)`. A - value is text, a `bool`, a float, or an integer that fits an `i64`. - A value can also be an `Option` or a `Vec` of these, or another - `AuditMetadata`. There is no conversion from `u64`, because ZeroKMS - cannot record a value above `i64::MAX` exactly. A float that is not - finite is sent as `null`. - - Every `Pending` has `.audit(..)`. So it works for scalars, trees, - targets, records, and `dynamic::record`, and for a batch made with - `zip` or `Pending::all`. - - `.audit(..)` returns an `Audited` call. You can only await an - `Audited` call. So attach the metadata last, to the whole call: - `a.zip(b).audit(m)`, or `Pending::all(&keyset, vec![a, b]).audit(m)`. - Neither `a.audit(m).zip(b)` nor - `Pending::all(&keyset, vec![a.audit(m), b])` compiles. A call - therefore sends one map, with every key request that it makes. - - A call that requests no data key sends no metadata, and still - succeeds. A query term is one such call. So is a call over an empty - list. - - ZeroKMS does not verify the metadata. A decrypt does not need it. - ZeroKMS writes the metadata to its logs. Do not send plaintext, - anything derived from plaintext, or secrets. - - The scalar and tree decrypt methods document this with an example - that runs. - - `AuditMetadata` implements serde's `Deserialize` (#1067). It reads a - map with text keys from any serde format, for a language binding that - has the facts as data. A value follows the same rules as a value given - to `with`. The reader refuses data that is not a map, bytes, an - integer that does not fit an `i64`, a key that is not text, and a key - that appears twice in one map. The reader's message does not show a - key or a value. `serde_json` reads a JSON number above `u64::MAX` as a - float, so that number is sent as a float. -- **`StackCipherBuilder::auth_strategy` and `key_provider`** (#1700). - `StackCipher::builder().auth_strategy(strategy).key_provider(provider).init()` - builds the ZeroKMS client from an auth strategy and a client key provider - that you choose. Before, a caller who wanted another auth strategy had to - build the `StackKms` by hand. `kms(..)` is unchanged. - - `auth_strategy` takes any strategy `StackKmsBuilder::new` takes: an - `OidcFederationStrategy`, an `AccessKeyStrategy`, or an `AuthStrategyFn`. - - `key_provider` is required after `auth_strategy`. The builder then reads - the client key only from that provider. For example, `EnvKeyProvider` - reads `CS_CLIENT_ID` and `CS_CLIENT_KEY`, and `ProfileKeyProvider` reads - the key the CLI saved. - - `init` loads the default keyset's index key, so call `init` where the - strategy can return a token. With an OIDC provider that returns the - current request's JWT, that is while your program handles a request. - - The builder state is `WithAuthStrategy`, behind the `http` - feature. - - Needs stack-auth 0.44.0 and stack-kms 0.2.0. - -- **`predicate!`** (#1459). `predicate!(EncryptedCustomer::PROFILE, "$.age - >= $min && $.name == $name", min = 30, name)` checks a SQL/JSON path - predicate when the program compiles and sends the same text when it - runs: it expands to `predicate(text)` with a `var` for each variable, - so its query, its `scope` and `encrypt`, and its operand are the text - form's. The text is read with the engine's own parser, now in - `stack-encrypt-jsonpath`. Refused at compile time: text that does not - parse; a construct the JSON index cannot answer whatever the variables - hold; a variable used and not given, given and not used, or given twice; - a path the field does not declare (under `ordered` or `paths`), an - ordering of a path declared under `paths`, and a member of an array, in - a filter of more than one condition, that the array does not order; and - a value, variable or literal, of another type than the path's, which - for a number literal means one the path's type does not hold (`1.5`, - `-1` and `99999999999` for a `u32`). A variable's value is moved into - the query. The macro finds a path's accessor by the path's text, through lookups the - derive now generates (hidden, in `field_reference::json::predicate_checks`), - so a `names` override changes nothing. It is a `macro_rules` wrapper - that passes `$crate`, so it works however a program reaches this crate. - The predicate parser moved to `stack-encrypt-jsonpath` with no change to - what it reads, refuses or derives. +- **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a + borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). + `dynamic::frame` re-exports both from vitaminc. A `Frame` is one value's + transport frame, checked and borrowed from bytes the caller keeps. An + `OwnedFrame` is a buffer, wiped when it drops, that holds exactly one + frame: what a record or a target opens into, and a value an async call + holds. What changes for a caller: + - Replace `dynamic::ValueFrame` with `dynamic::frame::OwnedFrame` where a + value is kept, and read bytes a host hands over with + `dynamic::frame::Frame::parse(&bytes)`, which borrows them with no + copy. `ValueFrame::from_bytes` and `ValueFrame::check` are gone: + `Frame::parse` accepts and refuses the same frames, and + `OwnedFrame::from_buffer` keeps a `Buffer` that holds one. + - `OwnedFrame::of` writes any source, `frame()` lends the frame, and + `into_buffer()` hands back the `Buffer`. `kind`, `is_null` and + `elements` are on `Frame` (`owned.frame().kind()`); `elements` lends + each element as a `Frame` with no copy. `risky_ref` and `into_inner` + are gone: read the bytes with `frame().as_bytes()`. + - An `OwnedFrame` has no `==`. Compare `a.frame() == b.frame()`, in + constant time. + - `TargetResolver::encrypt` and `TargetResolver::query` take the + plaintext as `Frame<'_>`; `decrypt` still resolves to an `OwnedFrame`. + An implementation reads `plaintext.kind()` and walks `plaintext` as + before. + - `dynamic::read_json` takes a `Frame<'_>`. `IntoLabel` is implemented + for `Frame<'_>` and `&OwnedFrame`. + - `FieldHandle`'s operator methods take a `dynamic::QueryValue`: an + `OwnedFrame`, a `&OwnedFrame` or a borrowed `Frame`. The trait is + sealed, because a query holds its value until the term is derived, so + only a value whose bytes are wiped is accepted. Write any other value + into a frame first with `OwnedFrame::of`. `DynamicQuery` takes the + value as a third type parameter, `V`, which defaults to `OwnedFrame`. + A borrowed `Frame` is queried with no copy. + - `Planned` is a target over an `OwnedFrame` or a borrowed `Frame`: a + record under a plan encrypts to the stored row, and a query value to + its term, from either. `Planned` is `Zeroize` for those two values + alone: an owned frame is wiped, and a borrowed one is its owner's to + wipe. Before, `Planned` was `Zeroize` for any value that is `Zeroize`, + so a bound such as `Planned: Zeroize` with another `V` no + longer holds. + - `ValueFrame::from_bytes` returned `FromFrameError::Frame`; + `dynamic::FromFrameError` is removed. + - `dynamic::Modeled`, `dynamic::Opening` and `dynamic::Children`, the + sinks behind `ValueFrame`, are removed. `OwnedFrame::sink()` (from + `Decrypt`) is the sink a ciphertext opens into, and it writes the + whole value into one buffer. + - A zeroized `OwnedFrame` holds the plain null. It used to hold no bytes + and walk as an error. + - No stored byte, frame byte or wire name changes. -- **Typed JSON queries from a field reference** (#1459, #1687). A field - whose type stores a JSON document (`JsonDocument`, or EQL's - `JsonTreeDocument`) has one field reference method for each kind of JSON - query, in place of the operator methods: +- **The engine no longer keeps its own list of the value types it + accepts; each index says which kinds it takes** (#1918). What changes: + - **A field can be declared `"uuid"`.** `dynamic::ValueKind::Uuid` is a + new kind, named `"uuid"`: sixteen bytes under vitaminc's UUID logical + type. A `uuid` field is sealed, opened and refused like any other + typed field: it holds a UUID and nothing else, and a `bytes` field + does not hold a UUID. Its null can be sealed (`"null": "sealed"`) as + long as a value. It takes an equality index, whose term is the one + `vitaminc-normalize` gives a UUID and never matches the same sixteen + bytes as a byte string. It takes no order index and no match index: + a plan that asks for one is refused with `index_not_admitted`. A + `match` on `ValueKind` that lists every variant needs a `Uuid` arm. + - **A UUID in an untyped or passthrough field is stored.** It was + refused when the source was read. It is sealed, or carried, in the + `0xF3` envelope it arrived in, and opens to the same bytes. + - **A logical type this build does not know is carried as it is.** An + untyped field seals it and a passthrough carries it, and each opens to + the bytes it was written as. It has no `ValueKind`, so no typed field + holds it and no index takes it, as before. + - `ValueFrame::check` and `ValueFrame::from_bytes` refuse only a frame + that is not one value, or a scalar its logical type does not admit (a + date out of range, a UUID that is not sixteen bytes). Which values a + field takes is its declared kind's and its indexes' rule, checked + when the record is split. + - **`FromFrameError::Value` is removed.** The frame parse refuses a + scalar its logical type does not admit, so `from_bytes` refuses it as + `FromFrameError::Frame`, as `check` already did. A `match` on + `FromFrameError` loses its `Value` arm. + - `admits` takes a kind, not a value. The order indexes refuse bytes and + a UUID in one place. - | Field reference method | Returns, for `JsonDocument` | - | --- | --- | - | `contains(doc)`, `contained_by(doc)`, `at().age().eq(v)` | `JsonQuery` | - | `at().age().lt(v)`, `.lte`, `.gt`, `.gte` | `JsonLeafQuery` | - | `at().age().between(lo, hi)` | `(JsonLeafQuery, JsonLeafQuery)`, low then high | - | `at().age().is_null()` | `JsonQuery` | - | `at().age().selector()` | `JsonSelector` | - | `elements().visits().place().eq(v).and().at().gt(v)` | `JsonElementsQuery` | - | `predicate(text).var(name, v)` | `JsonPredicateQuery` | - | `children(path)` | `JsonSubtreeKey`, which holds the node's one token | + No stored byte or frame byte of a value accepted before changes. - `EncryptedCustomer::PROFILE.at().age().gt(30).encrypt(&keyset)` derives - under the field's column and options, as a scalar field's query does, - and takes a scope with `.scope(..)`. Each query derives the operand the - dynamic interface derives for the same declaration: the field reference - and the data plan read one definition of each input, which no longer - needs the `dynamic` feature. - - **Typed paths.** `#[stash(json(ordered = { "$.age": u32, - "$.visits[*].place": String }, sealed_root = false))]` on the field - names the JSON index's options and the type of the values at each - ordered path. The derive seals the field under them, and the field - queries under them. It parses each path at compile time with the - engine's grammar (`stack-encrypt-jsonpath`): a path that does not - parse, has no `$`, names an array position or is given twice is a - compile error at the path, and a type other than an integer type, - `f64` or `String` (`JsonPathType`) is one at the type. Each path gets - a method under `at()`, returning a `DeclaredPath` of its type, and - each array whose elements have an ordered member gets one under - `elements()`, whose methods are the members (`ElementMember`). A - path, member or array the field does not declare has no method, a - value of another type does not compile (`PathValue`), and `and()` - after a condition gives the same array's members, so a member of - another array cannot be given. A method is named after the path's - keys (`$.visits[*].at` is `visits_at()`); `names = { "key": word }` - names a key the rule cannot. `paths = { "$.name": String, "$.vip": - bool }` declares a path for equality alone: its type is any - `JsonScalarType` (a `JsonPathType` or `bool`), it adds nothing to the - field's options, so no stored or derived byte changes, and its - `DeclaredPath` (kind `EqualityPath`, where an `ordered` path's is - `OrderedPath`) has `eq`, `is_null` and `selector`; an ordering of it - does not compile (`OrderedPathKind`). A path under both keys is a - compile error. An element-scoped condition compares ordering terms, - so `elements()` has ordered members only. The field reference has a fifth type - parameter, the field's paths (`DocumentPaths`); a field that declares - none has `TextPaths`. A field reached through an outer record - (`field`) keeps its paths. - - **Paths as text.** `at_text_path(path)` and `elements_text_path(path)` - take JSONPath text, for a filter built at run time, and check it when - the query is encrypted, before any key is requested, by the dynamic - interface's rules: an ordering at a path the field does not order is - `TermError::JsonPathNotOrdered`. They derive the operand the typed - method derives for the same path and value. A field with no declared - paths has only these. A document type that seals under other options - when its field names none says so with `JsonQueries::default_options`, - which its field queries under. - - **Typed values.** An ordering at a text path takes a number or a - string (`field_reference::json::JsonOrdered`), equality there a scalar - (`JsonScalar`), and containment a document. A boolean ordering, or - equality with an object, does not compile. An element predicate with - no condition has no `encrypt`. A NaN or an infinity, which no JSON - number is, is refused with the new `TermError::JsonNumberNotFinite` - (`stack_encrypt::json_number_not_finite`) before any key is requested, - rather than becoming `null`. There is no `f32` value: serde_json widens - an `f32` when it builds a document, so the query takes the `f64` the - document holds (`f64::from(x)` for one built from `x`). A NaN or an - infinity inside a `serde_json::Value` given to `contains` is already - `null`, and is queried as `null`. - - **Predicate variables.** `predicate(text).var("min", 30)` names one - variable, which the predicate reads as `$min`; `var_null(name)` names - a JSON `null`. A value is a `JsonScalar`. A NaN or an infinity is - refused with `TermError::JsonNumberNotFinite`, and a name given twice - with `Error::Input` and `Reason::JsonDuplicateKey`, each before any - key is requested. The predicate text is checked when the query is - encrypted. - - **Refusals.** A refusal of the input's own shape (an - `elements_text_path` path with no wildcard, a predicate the grammar - does not read) is the new `Error::Input`, below. - - **New public items.** `json::JsonTarget`, which seals a document under - options; `json::JsonQueries`, which converts each operand into the - field type's query type; `json::JsonElementsQuery` and - `json::JsonPredicateQuery`, the typed element and predicate operands; - and `field_reference::json`, the query types: `DeclaredPath`, - `ArrayElements`, `ElementMember`, `DocumentPaths`, `ElementArray`, - `TextPaths`, `JsonPathType` and `PathValue` among them. +- **A timestamp keeps the unit the host wrote it in** (#1846). A + `ValueFrame` no longer rewrites a timestamp in seconds, milliseconds or + microseconds to nanoseconds. A passthrough field now stores exactly the + bytes the host sent, and opens to them. A sealed timestamp is unchanged: + `vitaminc-aead` seals every unit as the same instant in nanoseconds, + so the leaves and terms are the bytes they were. Rows stored before + this change still open. -- **A value passed by value is sealed without a copy** (#1687). Sealing - a value took a copy of it when the target had no owned form of its own. - Both copies were wiped, so nothing leaked, but the copy was not needed. - - A `JsonDocument` field marked `#[stash(json(..))]` moves the document - out of the `JsonPlaintext` into the seal - (`JsonTarget::json_owned_encryption`), as `encrypt_into` already did. - - A derived `plaintext = T` record with exactly one field derived from - the plaintext has its own `owned_encryption`. It moves the value into - the owned form of that field's target. So a record whose one field is a - `StackCipherText` seals the value with no copy. When the record's - context cannot be stored, or its indexes are refused, the value is - wiped. A record with two or more such fields is unchanged. - - Three items for generated and binding code, hidden from the docs: - `Encryption::storing` in `Owned` mode (requires `S: Zeroize`, and - wipes the value when the context cannot be stored), - `Encryption::refused_wiping` (requires `S: Zeroize`), and - `Encryption::over_json_plaintext`, which turns an owned description of - a `serde_json::Value` into one of a `JsonPlaintext` by moving the - document across. No item returns the document to its caller. - - The stored bytes do not change. A target with search terms keeps its - behaviour. +- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, + `ope_term`, and `ore_block_term` are no longer public** (#1760). Each + method built one term on its own, outside the target path and the + query path, and copied its target's code. A query built with one of + them was not tied to the field it searched. Not all query terms are + the same as the stored terms. With `MatchOptions::short_words` on, the + `match_terms` filter of "Mike Ng" misses "Mike Nguyen". -- **`Error::Input`: a refusal of the caller's input** (#1459). A field - field reference's JSON query whose input has the wrong shape, and a data plan run - through `dynamic::Planned` whose source does not fit it, now fail with - `Error::Input`, which holds the dynamic interface's error. Its message, - code (`stack_encrypt::dynamic_source`, `stack_encrypt::dynamic_predicate` - and the rest) and payload (`reason`, and `field`, `construct` and `at` - where it has them) are that error's, so a refusal reports the same way - on both paths. They used to be `Error::Other`, whose code - (`stack_encrypt::other`) a caller could not tell from an engine fault. - The error type is now public without the `dynamic` feature too, as - `stack_encrypt::refusal::Error` and `refusal::Reason` (the same types as - `dynamic::Error` and `dynamic::Reason`). This module's own bug - (`Internal`) and a target resolver's own failure stay `Error::Other`. -- **Two more records derive** (#1661). The owned derives did not accept - these shapes, and the removed derives did: - - A `plaintext = T` record can have a `struct = ..` record as a field. - The caller's context extends each of the inner record's fields. - - A record with `context_type = NonEmpty` can have a ciphertext or a - term as a field. -- **The JSON targets implement the owned traits** (#1660). The plaintext - is `json::JsonPlaintext`, which holds a `serde_json::Value` and wipes it - when it is dropped. - - `JsonDocument` implements `EncryptTarget` and - `DecryptSource`. So - `profile.encrypt_into_with_context(&keyset, column)` seals a document - under the default options, and - `JsonPlaintext::decrypt_from_with_context(document, &cipher, column)` - opens it. - - `JsonExtracted`, the entry `->` returns, implements - `DecryptSource`. - - `JsonSubtree`, the rows of a read, implements `DecryptSource` for - `JsonPlaintext`, `Option` and `Vec`. - - The context is required in each case. The stored bytes do not - change. + A query must be built in the same domain as the stored term it + searches. A field reference does this: it builds the query under the + field's own context and options. A term does not have to share its + ciphertext's context. A type that needs that ties the two together, as + an EQL type does with its one context field. -- **A field type that stores its context can be a record field** (#1658). - A derived `struct = ..` record gives each field a context of its own: - the record's scope, then the field's name. A type that stores its - context in the row (`#[stash(context_field)]`), such as an EQL type that - stores a table and a column, stores that own context. The stored type - implements the new trait `target::ContextFromField`. - - `ContextFromField::from_field` builds the stored context from the - field's own context, or returns `None` when the type cannot store it. - - The scopes and the bindings that the record lists, and the names of a - record that holds this one, come after the own context, as they do - for a field of any other type. The search terms derive under the own - context and the scopes. The data key and the AAD derive under the - bindings too. The field does not store them, so the reader supplies - them again. - - On decrypt, the stored context must equal the field's own, as a - standalone decrypt with an expected context checks it. - - An own context that the type cannot store is refused before any key - is requested, on encrypt and on decrypt, with the new - `PlanError::ContextNotStorable` - (`stack_encrypt::plan_context_not_storable`), which names that - context (`members/email`). - - The encrypt input of a `context_field` record is the hidden type - `target::StoredContext`, in place of - `RequiredContext>`. A caller passes a `NonEmpty`. - Generic code names the input as - `ContextInput: AcceptsContext>`. + To upgrade, build each term one of two ways: + - **To store a value**, encrypt it into a derived record with a field + of the term type, or run `target::indexed` over it. Use + `EqualityTerm` for `equality_term`, `MatchTerms` for + `match_terms`, `OreTerm` for `ore_term`, `OpeTerm` for + `ope_term`, and `OreBlockTerm` for `ore_block_term`. Encrypting + the value into the bare term type gives the same term, with no + ciphertext beside it. `OreTerm::inner()` and `OpeTerm::inner()` + return the ciphertext the old methods returned. A target takes text + as a `String`, not a `&str`. + - **To query**, use the field reference's operator method, such as + `EncryptedUser::EMAIL.eq(&email)` or + `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its + own, such as `target::matching_query`, also works. A bare + `MatchTerms` with `short_words` on is a stored filter, not a + query. -- **`json::JsonPlaintext`, a JSON document as one ciphertext** (#1636). - `JsonPlaintext` holds a `serde_json::Value` and wipes it when it is - dropped. Build one with `JsonPlaintext::from(value)` or - `JsonPlaintext::parse(text)`, which applies the strict checks of - `json::parse_text`, and read it with `value()`. It is a single value to - the cipher, so `keyset.encrypt(document)` returns one `Ciphertext`, and - `keyset.decrypt::(ct)` opens it. A target with a - ciphertext field takes it as a plaintext too. - - The stored plaintext is the document's JSON text, sealed as one text - leaf. It is the text `serde_json` writes, with no whitespace. Key - order, whitespace and the spelling of a number are not kept. - - A document is sealed only if it will open. Its depth is checked and - its text is parsed by the strict rules before it is sealed, so a - `Value` nested deeper than 127 levels is refused as `Error::Aead` and - no key is requested. The depth check does not recurse past the limit, - so a document of any depth is refused and does not overflow the stack. - - On decrypt the leaf is authenticated first, then the text is parsed by - the same strict rules. A leaf that is not text, or text that is not a - document, is `Error::OpenedType`. The ciphertext is authentic in that - case: it was sealed as something else. - - A target that derives an equality term from a single value derives - the term of the document's JSON text. Equal documents have one term - while `serde_json` keeps members in key order, its default. - - `dynamic::JsonPlaintext` is now this type, re-exported, so - `dynamic::read_json` returns it. It gains `Clone`, `Zeroize`, a - redacted `Debug`, `From` and `parse`. - - ADR-0013 records the decision. -- **Field references** (#1486, #1590, #1596, #1600). `#[derive(EncryptTarget)]` on - a `struct = ..` record emits one `FieldReference` per derived field. It is an - associated constant named after the field in upper case: - `EncryptedUser::EMAIL`. A field reference is `FieldReference`. `W` is where - the field sits: `field_reference::Root` for a field of the record `R`, or - `field_reference::Nested` for one reached through a record field. `T` is the - field's target type. `C` is the type of the scopes a query takes: - `NoScope`, one `Scope`, or `target::Scopes` for a field of a nested - record. - `P` is the type a query takes: `field_reference::TakesAny`, or `field_reference::Takes` - for a field marked `#[stash(query = V)]`. - - Its methods are one per operator the field's indexes answer, checked - at compile time through `Answers`: `eq`, `lt`, `lte`, `gt`, `gte`, - `between`, and `matches`. A field of several indexes, - `Encrypted<(EqualityTerm, MatchTerms)>`, answers each operator through - the one index that answers it. Each term states its answer with - `op::OperatorAnswer`. An operator no index answers, or two answer, has - no method. An `Option<..>` field has the methods a present value has. - - `EncryptedAccount::ADDRESS.field(EncryptedAddress::STREET)` is the - inner field's reference under the outer field's context. `field` accepts - only a field reference of the inner record. - - A nullable record field, `Option`, has the same - `field` (`field_reference::Holds`). A row whose field is `None` stores nothing - to match. - - An inner record may list a scope of its own, such as - `scope(field = "tenant")`. The query then takes one scope for each - record that lists one, outermost first. The new `Scope::scope` - chains them: `.scope(Scope::new(outer).scope(inner))` - (`field_reference::JoinScope`). The chain returns the new `target::Scopes`, - and any number of records can list a scope. Where one record lists a - scope, `scope` takes that scope alone. - - `#[stash(query = String)]` states the type a field's queries take. The - derive checks it against the plaintext struct's field. - - A record that lists a scope, `scope(tenant: u64)` or a stored - `scope(field = "tenant")` over a `u64`, gives a query with no `encrypt` - until `.scope(..)` is given once, with a `Scope`. A record with no - scope gives a query that is ready at once. The query has no `bind` - method, and ends with `.encrypt(&keyset)`. The output is the index's - query term. - - A query from a field reference derives under the declaration the derive wrote, - so it is the stored term. No plan is written by hand beside the - record. A method takes its value by value, and a string literal as - it is (`QueryInput`). The query's value is wiped when it is derived, - refused, or dropped. `assert_context!` takes a field reference, and - `FieldReference::contexts()` is the record's contexts narrowed to the field. - A tuple field has no field reference. -- **Tuples of terms answer a query too** (#1596). The field reference of a field - typed `Encrypted<(EqualityTerm, MatchTerms)>` answers `eq` and - `matches`. The query uses the one term that answers the operator. `OreBlockTerm` implements `LabelledTarget`, so a block ORE field - is queried under its label. -- **`dynamic::Planned`, a value under a plan that is data** (#1486). A - record under a `Plan`, or a query value under a `QueryPlan`, each a - `ValueFrame`, is a target in the owned API's sense. `StackCipherText` - implements `EncryptTarget>`. `QueryTerm` - implements `EncryptTarget>`. - `Planned` implements `DecryptSource`. - So `encrypt_into`, `decrypt_from`, and their `_with_context` forms run - them. The caller's scope and bindings are the one context argument, - after the plan's own. A query takes scopes alone, and refuses a binding - before any key is requested, as `PlanError::BindInQuery`. A refused - term keeps its kind (`Error::Term`); a refusal of the caller's input is - `Error::Input`. `Planned::contexts()` shows every field's context with - a placeholder for the caller's scope and one for the caller's binding, - before any value is encrypted. -- **Query plans and the dynamic field handle** (#1486). `Plan::query(field, - op)` and `Plan::query_with(.., &resolver)` narrow a record plan to one - field and one operator. They are refused where they are made when none - of the field's indexes answers the operator (`operator_not_answered`), - or when the plan has no such field. `Plan::field(name)` and - `Plan::field_with(name, &resolver)` are the handle a program whose plan - is data queries through. It has one method per scalar operator and - `op(..)` for any, each checked against the plan where it is called, then - `.scope(..)` and `.encrypt(&keyset)`. Neither has a `bind` method. -- `ValueFrame` implements `Zeroize`. `dynamic::query_term` takes any - `K: 'static`, as `record::encrypt_with` does. The key source's bounds - apply when the pending is awaited, not when the term is described. + ```rust + // Before + let term = keyset.equality_term("alice@example.com", nonempty!("users/email")).await?; -### Breaking + // After: the term to store + let term: EqualityTerm = String::from("alice@example.com") + .encrypt_into_with_context(&keyset, nonempty!("users/email")) + .await?; + // After: the query + let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; + ``` -- **An error about input that is not an object names the kind of value - and the row** (#1985). The input is a plan, a field spec, a record to - encrypt, or a stored record. A field spec is the entry in a plan that - describes one field. Before, the engine refused each one with the reason - `not_an_object` and no more detail. Most of those errors named no field - and no row. + `OreTerm`, `OpeTerm`, and `OreBlockTerm` need `T: Zeroize`. + The old `ore_term`, `ope_term`, and `ore_block_term` also took three + types that are not `Zeroize`: jiff's `civil::Date` and `Timestamp`, + and rust_decimal's `Decimal`. For these, convert the value to + `value::Date`, `value::Timestamp`, or `value::Decimal` first. Or run + the borrowed operation, as below, to read the value in place: - To upgrade, add `..` to a match that names every field of `Error::Plan`, - `Error::Source`, or `Error::Record`. `Error::Plan` has a new `found` - field. `Error::Source` and `Error::Record` have new `row` and `found` - fields. The existing reason codes keep their names. The two new codes - are `not_a_frame` and `source_failed`. - - The changes are: - - The error names the kind of value that the engine got, and never - includes the value. The kind is in `Error::found()`, in the payload - field `found`, and in the message. The message is one sentence, such - as `row 2 of the records to encrypt is null, not an object of fields`. - The new `dynamic::Found` lists the kinds, such as `"null"`, `"array"`, - `"string"`, `"uint32"`, `"passthrough"`, and `"sealed"`. The message - says `an encrypted value` for the kind `"sealed"`. - - An error names a kind only when the engine can read the kind without - decrypting anything. That is the kind of a value the caller sent, or - the kind of a node in the unencrypted structure of a stored record. - An example of the second is a row that is a passthrough or an - encrypted value, and not a map. An error about a decrypted value never - names the kind that the value decrypted to. - - An error about a row of a batch names the row by its position, counted - from 0. The position is in `Error::row()`, in the payload field `row`, - and in the message. The message also says whether the record was to - encrypt or to decrypt. An error names the row in any of these cases: - - The row is not an object. - - A value in the row returns an error of its own while the engine - reads it. - - The engine cannot copy a value in the row. The cause is a value - that repeats a map key, does not fit its logical type, is nested too - deep, or is too long. - - An error from comparing a field with the plan names the field and not - the row. Examples are a missing field, a field that the plan does not - name, and a value of another type. - - A source can start a row of a batch and never write it. The engine - refuses that batch with the reason `unframeable`, and the error names - the row. The engine does not move the later rows up one position. - - Bytes given as a plan that are not one transport frame get the new - reason `not_a_frame`. A transport frame is the binary encoding of one - value. The bytes are empty, are cut short, are JSON text, repeat a - key, or continue after the value ends. A frame that is not an object - of field specs keeps the reason `not_an_object`, and the error names - the kind of value in the frame. - - An error about a field spec that is a typed null names the field. - Before, the error named no field. A typed null is a null that records - a type. - - A value that returns an error of its own while the engine reads it - gets the new `Error::SourceFailed`. An example is a JSON document that - is nested too deep. The code is `stack_encrypt::dynamic_source_failed`. - The reason is `source_failed`. Before, the reason was `not_an_object`, - and the error named no field. - - The error names the row that the engine was reading, and the field - whose value the engine was writing. An error between two fields - names no field. An error between two rows names no field and no row. - - The value's error is the cause, and `source()` returns it. The - message leaves the cause out, and `Debug` prints the cause as - `SourceError(..)`, because the text of the caller's error can - include the value. - - The message of an `Error::Source` names the input that the reason is - about. Before, every such message started with `record source does not - fit the plan`. Now the message starts with one of these: - - `the query input does not match the field`, when only the input of a - query can cause the reason. Those reasons are about an operator, a - range, a term, statistics, a null query, or the input of a JSON - operator. - - `the record to encrypt or the query input does not match the plan`, - for a value of another type and for an `undefined` value, when the - error names no row. A record and a query can both cause those - reasons. - - `the record to encrypt does not match the plan`, for every other - reason. - - The message of an `Error::Record` starts with `the record to decrypt - does not match the plan`. Before, that message started with `stored - record does not fit the plan`. - - The message of an `Error::SourceFailed` starts with `a value in the - record to encrypt returned an error while it was read`. The row and - the field follow. For an error that names no field, the message starts - with `the record to encrypt`. - -- **The `vars` of a `match` query that are not a JSON object get the new - reason `json_vars_not_object`** (#1987). Before, the reason was - `json_input`. The error had no more detail. `json_input` is the reason - for any input that a JSON operator does not take. To upgrade, change - code that compares the reason with `json_input` for this case. - - The error names the field. - - The payload field `found` is the kind of value that the vars are, - such as `"array"`, `"uint64"`, or `"null"`. - - The message for vars that are null is - `the vars of the match are null, not a JSON object`. The field - follows. - - The engine refuses the vars before it reads the predicate. - - Only the dynamic path can get vars that are not an object. A field - reference always builds an object. - -- **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a - borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). - `dynamic::frame` re-exports both from vitaminc. A `Frame` is one value's - transport frame, checked and borrowed from bytes the caller keeps. An - `OwnedFrame` is a buffer, wiped when it drops, that holds exactly one - frame: what a record or a target opens into, and a value an async call - holds. What changes for a caller: - - Replace `dynamic::ValueFrame` with `dynamic::frame::OwnedFrame` where a - value is kept, and read bytes a host hands over with - `dynamic::frame::Frame::parse(&bytes)`, which borrows them with no - copy. `ValueFrame::from_bytes` and `ValueFrame::check` are gone: - `Frame::parse` accepts and refuses the same frames, and - `OwnedFrame::from_buffer` keeps a `Buffer` that holds one. - - `OwnedFrame::of` writes any source, `frame()` lends the frame, and - `into_buffer()` hands back the `Buffer`. `kind`, `is_null` and - `elements` are on `Frame` (`owned.frame().kind()`); `elements` lends - each element as a `Frame` with no copy. `risky_ref` and `into_inner` - are gone: read the bytes with `frame().as_bytes()`. - - An `OwnedFrame` has no `==`. Compare `a.frame() == b.frame()`, in - constant time. - - `TargetResolver::encrypt` and `TargetResolver::query` take the - plaintext as `Frame<'_>`; `decrypt` still resolves to an `OwnedFrame`. - An implementation reads `plaintext.kind()` and walks `plaintext` as - before. - - `dynamic::read_json` takes a `Frame<'_>`. `IntoLabel` is implemented - for `Frame<'_>` and `&OwnedFrame`. - - `FieldHandle`'s operator methods take a `dynamic::QueryValue`: an - `OwnedFrame`, a `&OwnedFrame` or a borrowed `Frame`. The trait is - sealed, because a query holds its value until the term is derived, so - only a value whose bytes are wiped is accepted. Write any other value - into a frame first with `OwnedFrame::of`. `DynamicQuery` takes the - value as a third type parameter, `V`, which defaults to `OwnedFrame`. - A borrowed `Frame` is queried with no copy. - - `Planned` is a target over an `OwnedFrame` or a borrowed `Frame`: a - record under a plan encrypts to the stored row, and a query value to - its term, from either. `Planned` is `Zeroize` for those two values - alone: an owned frame is wiped, and a borrowed one is its owner's to - wipe. Before, `Planned` was `Zeroize` for any value that is `Zeroize`, - so a bound such as `Planned: Zeroize` with another `V` no - longer holds. - - `ValueFrame::from_bytes` returned `FromFrameError::Frame`; - `dynamic::FromFrameError` is removed. - - `dynamic::Modeled`, `dynamic::Opening` and `dynamic::Children`, the - sinks behind `ValueFrame`, are removed. `OwnedFrame::sink()` (from - `Decrypt`) is the sink a ciphertext opens into, and it writes the - whole value into one buffer. - - A zeroized `OwnedFrame` holds the plain null. It used to hold no bytes - and walk as an error. - - No stored byte, frame byte or wire name changes. - -- **The engine no longer keeps its own list of the value types it - accepts; each index says which kinds it takes** (#1918). What changes: - - **A field can be declared `"uuid"`.** `dynamic::ValueKind::Uuid` is a - new kind, named `"uuid"`: sixteen bytes under vitaminc's UUID logical - type. A `uuid` field is sealed, opened and refused like any other - typed field: it holds a UUID and nothing else, and a `bytes` field - does not hold a UUID. Its null can be sealed (`"null": "sealed"`) as - long as a value. It takes an equality index, whose term is the one - `vitaminc-normalize` gives a UUID and never matches the same sixteen - bytes as a byte string. It takes no order index and no match index: - a plan that asks for one is refused with `index_not_admitted`. A - `match` on `ValueKind` that lists every variant needs a `Uuid` arm. - - **A UUID in an untyped or passthrough field is stored.** It was - refused when the source was read. It is sealed, or carried, in the - `0xF3` envelope it arrived in, and opens to the same bytes. - - **A logical type this build does not know is carried as it is.** An - untyped field seals it and a passthrough carries it, and each opens to - the bytes it was written as. It has no `ValueKind`, so no typed field - holds it and no index takes it, as before. - - `ValueFrame::check` and `ValueFrame::from_bytes` refuse only a frame - that is not one value, or a scalar its logical type does not admit (a - date out of range, a UUID that is not sixteen bytes). Which values a - field takes is its declared kind's and its indexes' rule, checked - when the record is split. - - **`FromFrameError::Value` is removed.** The frame parse refuses a - scalar its logical type does not admit, so `from_bytes` refuses it as - `FromFrameError::Frame`, as `check` already did. A `match` on - `FromFrameError` loses its `Value` arm. - - `admits` takes a kind, not a value. The order indexes refuse bytes and - a UUID in one place. - - No stored byte or frame byte of a value accepted before changes. - -- **A timestamp keeps the unit the host wrote it in** (#1846). A - `ValueFrame` no longer rewrites a timestamp in seconds, milliseconds or - microseconds to nanoseconds. A passthrough field now stores exactly the - bytes the host sent, and opens to them. A sealed timestamp is unchanged: - `vitaminc-aead` seals every unit as the same instant in nanoseconds, - so the leaves and terms are the bytes they were. Rows stored before - this change still open. - -- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, - `ope_term`, and `ore_block_term` are no longer public** (#1760). Each - method built one term on its own, outside the target path and the - query path, and copied its target's code. A query built with one of - them was not tied to the field it searched. Not all query terms are - the same as the stored terms. With `MatchOptions::short_words` on, the - `match_terms` filter of "Mike Ng" misses "Mike Nguyen". - - A query must be built in the same domain as the stored term it - searches. A field reference does this: it builds the query under the - field's own context and options. A term does not have to share its - ciphertext's context. A type that needs that ties the two together, as - an EQL type does with its one context field. - - To upgrade, build each term one of two ways: - - **To store a value**, encrypt it into a derived record with a field - of the term type, or run `target::indexed` over it. Use - `EqualityTerm` for `equality_term`, `MatchTerms` for - `match_terms`, `OreTerm` for `ore_term`, `OpeTerm` for - `ope_term`, and `OreBlockTerm` for `ore_block_term`. Encrypting - the value into the bare term type gives the same term, with no - ciphertext beside it. `OreTerm::inner()` and `OpeTerm::inner()` - return the ciphertext the old methods returned. A target takes text - as a `String`, not a `&str`. - - **To query**, use the field reference's operator method, such as - `EncryptedUser::EMAIL.eq(&email)` or - `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its - own, such as `target::matching_query`, also works. A bare - `MatchTerms` with `short_words` on is a stored filter, not a - query. - - ```rust - // Before - let term = keyset.equality_term("alice@example.com", nonempty!("users/email")).await?; - - // After: the term to store - let term: EqualityTerm = String::from("alice@example.com") - .encrypt_into_with_context(&keyset, nonempty!("users/email")) - .await?; - // After: the query - let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; - ``` - - `OreTerm`, `OpeTerm`, and `OreBlockTerm` need `T: Zeroize`. - The old `ore_term`, `ope_term`, and `ore_block_term` also took three - types that are not `Zeroize`: jiff's `civil::Date` and `Timestamp`, - and rust_decimal's `Decimal`. For these, convert the value to - `value::Date`, `value::Timestamp`, or `value::Decimal` first. Or run - the borrowed operation, as below, to read the value in place: - - ```rust - let term: OpeTerm = value::Date::new(dob) - .encrypt_into_with_context(&keyset, nonempty!("users/dob")) - .await?; - // Or, with the jiff date as it is - let context = CallerContext::from(nonempty!("users/dob")); - let term: OpeTerm = keyset - .run(target::ope::<_, _, Borrowed>(), &dob, context) - .await?; - ``` + ```rust + let term: OpeTerm = value::Date::new(dob) + .encrypt_into_with_context(&keyset, nonempty!("users/dob")) + .await?; + // Or, with the jiff date as it is + let context = CallerContext::from(nonempty!("users/dob")); + let term: OpeTerm = keyset + .run(target::ope::<_, _, Borrowed>(), &dob, context) + .await?; + ``` `target::ore` gives the order-revealing encryption (ORE) term the same way. The two routes give the same bytes. `target::ore_block` gives the @@ -919,6 +424,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 term's normalized form or order encoding, wiped on drop. A borrowed JSON document is the one plaintext that is copied. That copy is made once, and wiped. + - **An operation in `Owned` mode wipes the value it is handed** (#1734). `ciphertext` dropped a value whose context was refused without wiping it. A match term dropped every value it was handed without wiping it. @@ -940,6 +446,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 reads an owned value, `zip` holds the value in a guard. If a reader panics, the value is wiped as the stack unwinds. A match term guards the value it reads in the same way. + - **An order index is bounded by vitaminc-ore's `Orderable`** (#1734). `sem::Orderable` and `op::Ordered` are removed. `stack_encrypt::Orderable` re-exports vitaminc-ore's trait, and its table is vitaminc-ore's. @@ -965,6 +472,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The JSON index derives a string leaf's OPE term from the document in place, and a data plan derives a text field's order term from the frame in place. Each copied the text before. + - **`value::Date`, `value::Timestamp`, and `value::Decimal` are vitaminc's types** (#1734). Stack Encrypt's own copies are removed. The stored format is unchanged. @@ -983,6 +491,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The `jiff` and `rust_decimal` features are on by default, and the `dynamic` feature turns both on. With one off, its types do not exist. A build with `default-features = false` must name them. + - **The tree entry points return a `Pending`** (#1705), so they can take audit metadata like every other call. `KeysetCipher::encrypt_tree`, `KeysetCipher::decrypt_tree`, and `StackCipher::decrypt` were @@ -1044,6 +553,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `Error::Input`, matched as `Error::Input(refusal)` with `refusal.as_ref()` the `dynamic::Error::Term`, and its code is `stack_encrypt::dynamic_term` rather than `stack_encrypt::other`. + - **The structural API is removed** (#1661, #1662). Stack Encrypt had two ways to encrypt a record and two ways to query one. The owned API stays: `EncryptTarget`, `DecryptSource`, `EncryptInto`, `DecryptFrom`, field @@ -1108,6 +618,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 target that calls `open` for its own plaintext type is unaffected. A caller that opens a type that is not `Zeroize` wraps it in one that is, or implements `Zeroize` for it. + - **The JSON index answers no typed operator through `Supports`** (#1459). `Json`'s `Supports` impls for `op::Contains`, `op::ContainedBy` and `op::AtPath`, `JsonDocument`'s `Answers` and `LabelledTarget` impls, the @@ -1259,6 +770,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `op::Matches.case_sensitive()`; a `MatchConfig` needs no `MatchCase`. - `dynamic::term` prepares its probe as `query_term` does, and the stored-term derivation no longer carries a query flag. + - **A field declares at most one index per operator** (#1233). `(Ore, Ope)` and `(Ore, OreBlock)` are refused when the plan is built, as `PlanError::IndexOverlap` on the typed path and `overlapping_outputs` @@ -1325,12 +837,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 bound. The change lets `OpaqueBlob` implement `OpaqueDecode`: a blob opens as a bytes leaf and is decoded afterwards, so it cannot implement `Decrypt`. + - **The record attribute `context = ".."` is now `scope = ".."`**. The value is the record's name, the first scope of each field's context, and the stored data does not change. Write `#[stash(struct = User, scope = "users")]`. The old spelling is a compile error that names the new one. The Go `context=` tag is not renamed yet. + - Repeated plan-chain `.extend(..)` calls now append parts in order, matching Go's `Cipher.Extend`, instead of replacing earlier extensions. `.extend(())` adds nothing, and grouped `NonEmpty` parts retain their grouping. @@ -1339,6 +853,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 different terms and silently miss those old rows: they return no error. Keep the final extension alone for both reads and queries of old data, or re-encrypt and re-index it under the appended context. This does not migrate stored data. + - **stack-encrypt requires the vitaminc 0.9 crates (vitaminc-protected 0.9.1), clww-ore 0.7 and ore-rs 0.11.** If your crate names a vitaminc type that stack-encrypt takes or returns, move it to vitaminc 0.9 too. No sealed bytes, terms, or stored @@ -1378,642 +893,1454 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 it needs a `_` arm. To migrate code that names `recipher`, see the stack-kms CHANGELOG. -### Added +- **`KeysetCipher::encrypt` and `decrypt` are the owned scalar API.** + `keyset.encrypt(value)` consumes an `OpaqueEncode` value (`bool`, the fixed-width + integers except `u8`, `f32`, `f64`, `String`), wipes it, and returns one + opaque `Ciphertext`; `keyset.decrypt::(ciphertext)` opens it to an `OpaqueDecode` type. + `encrypt_with_context` and `decrypt_with_context` bind a context. The + previous structural forms, which take any `Encrypt` value and a context and + return a `StackCipherText`, are renamed `encrypt_tree` and `decrypt_tree`. + `Ciphertext`'s bytes are the unchanged `SealedValue` v1 envelope, so + stored values open through either API. + Nullable `Option` values remain on `encrypt_tree` / `decrypt_tree` in this + slice, including Vitamin C's padded-null encoding for fixed-width types. -- **A declaration and a call show the context they use, before any key is - requested** (#1568). `Encryption::contexts()` lists the context of each - field that is sealed or indexed, with a typed placeholder for each part - the caller supplies, such as `{context: u64}`. The derives emit - `contexts()` on every record, and `Plan::contexts()` shows a plan's. A - data plan's field that names an EQL type is shown under its label alone, - in plan order, since an EQL value takes no part from the caller. - `Pending::context()` lists the exact contexts a prepared call will use, - with the caller's values filled in. Both views show each part's type: - `7u64`, `7i64`, the text `7`, and the bytes `0x37` are four different - contexts. The views are built by the same combinators that build the key - descriptor and the AAD, so what a developer sees is what the engine uses. - The dynamic interface has the same view, `dynamic::record::Plan::contexts`. -- **The `testing` feature adds `assert_context!`**, which pins the context - of a declaration or a call in a test. It names the first part that - differs. `assert_contexts!` pins each context a call uses, in order. - `stack_encrypt::testing` also has `required`, `optional`, `extension`, - `from_plaintext`, and `list`, which state the caller's parts and a - one-part list. -- **A context can be passed by reference.** `CallerContext`, `AeadContext`, - and `DeclaredContext` convert from `&NonEmpty`, so - `value.encrypt_into_with_context(&keyset, &column)` compiles for a target - that takes a `CallerContext`, and the column is still usable afterwards. -- **A target can take its context from a field of the plaintext: - `Encryption::context_from`** (#1586). Some values arrive together with the - context they are stored under. For example, a value decrypted from an older - format comes with its column. Such a value now encrypts with no context - argument. - - A type that wraps the target names the field once, in its - `EncryptTarget` declaration. The type declares `NoCallerContext`. - - The target must store its context in the row, so its context input must - be a typed `NonEmpty`. Records with a `context_field`, and EQL types, - qualify. Opening a value never needs its plaintext. - - The field is picked by reference, so a context cannot be computed from - the sealed value. - - An empty context fails the encryption. No key is requested. - - The picked field is sent to ZeroKMS and stored in the clear. The field - must not be secret. -- **Optional values through the owned API: `Option`** (#1585). An - `Option` encrypts into an `Option` for any owned target `T`, and - decrypts back. - - `None` stays `None`. Nothing is stored. No key is requested. The column - is a database NULL. - - `Some` is the target alone, under the same context. - - The context input is the target's, so a call is the same whatever the - data. +- **The root `EncryptInto` and `DecryptFrom` are new owned conversion + traits** over `EncryptTarget` / `DecryptSource`. The borrowed traits they + replace, and that `#[derive(EncryptFrom, DecryptInto)]` types use, are + `stack_encrypt::target::legacy::{EncryptInto, DecryptFrom}`; import one + pair or the other, not both. - A database NULL is not a sealed null. A sealed null is a stored value that - means "null". An EQL type encrypted from an `Option` writes one. -- **Owned records: `#[derive(EncryptTarget, DecryptSource)]`** (#1483). A - struct now encrypts field by field into a record type that declares its - own layout. The crate docs' "Records" section and the derive crate's - "Owned records" section show each form. The `tests/ui` cases pin the - forms that are refused, with the error at the field. - - With `#[stash(struct = User, scope = "users")]`, each field's target - is given the context `("users", "")`: the record's name, then the - field's name. `#[stash(from = ..)]` - names another source field, and `identity = ".."` sets the second part - of the context, as on the structural derive. - - A `#[stash(passthrough)]` field is moved from the plaintext into the - record, in the clear. It is never copied. A passthrough field is **not - encrypted and not authenticated**. Use it only for values that are not - secret, and treat the value read back as untrusted input. - - `user.encrypt_into(&keyset)` consumes the plaintext, wipes every field - it seals, and moves the passthrough fields. `User::decrypt_from(record, - &cipher)` decrypts each field under its context, and moves the - passthrough fields back. - - A `struct` record takes no context from the caller. Its input is - `DeclaredScopes`, so `encrypt_into_with_context` does not compile for - it. A caller's scope or row binding will be declared on the record, with - attributes that are not built yet. - - Records nest. The outer field's context extends the contexts of the - inner record's fields. - - A `#[stash(plaintext = String)]` record can be searched, for example a - `Ciphertext` beside an `EqualityTerm`. It can be a field of a `struct` - record. - - A `context_field` record stores its context, and decrypts under an - `ExpectedContext`. - - A `Vec` encrypts into a `Vec` with one batched key - request. - - The plaintext type must implement `Zeroize`. A `struct` record must name - every field of its plaintext, as a sealed field or a passthrough field. - A field it leaves out is a compile error, so no field is dropped without - being wiped. For the same reason, the plaintext type cannot implement - `Drop`, so it cannot derive `ZeroizeOnDrop`. - - The decrypt derive also implements `DecryptSource>` for - each plaintext type the record names. `Protected::::decrypt_from( - record, &cipher)` returns the plaintext inside a `Protected`, which - wipes it when it is dropped. A `Vec` of records decrypts into a - `Vec>`. `User::decrypt_from` still returns a bare - `User`, which the caller must wipe. - - If a later field is refused during decryption, the fields already - decrypted are wiped. - - `#[derive(DecryptSource)]` also implements `DecryptField`, so a - record can be a field of another record. -- **A `Ciphertext` decrypts into a `Protected`.** `OpaqueDecode` now covers - every `Decrypt + Zeroize` type, not only the `FromScalar` ones. So - `keyset.decrypt::>(ct)` and - `Protected::::decrypt_from_with_context(ct, &keyset, ctx)` work, and - the `Protected` wipes the plaintext when it is dropped. A target that is - not a scalar, such as `Vec`, now compiles too. Opening refuses it - with `Error::OpenedType`. -- **`Decryption::zip_wiping`**, a `zip` for recovered plaintext. The right - side can fail after its key arrives, or panic in its conversion. The - plaintext that the left side recovered is then wiped, not dropped as it - is. The owned record derive decrypts its fields through this method. -- **`EncryptTarget::owned_encryption` and `EncryptTarget::indexes`.** - - `owned_encryption` describes the encryption over the plaintext by - value, in `Owned` source mode. By default, it guards the value with - `Protected`, runs `encryption` over a borrow of it, and wipes it before - the pending request is returned. `EncryptInto` and the owned column run - this method. - - A record overrides `owned_encryption`. It divides the struct between its - fields with the new `Encryption::split`. `split` runs two descriptions - over two parts of one value, under one context. `split` also takes a - `wipe` function for the part that waits while the first description - runs. If that description panics, `wipe` wipes the waiting part. - - `Encryption::project_owned` is also new, for generated code. The method is - hidden from the docs. It drops the other fields of the struct without - wiping them. The derive calls it only when the plaintext has one field. - - `EncryptInto` guards the plaintext until the declaration and its context - have been built. So a declaration that panics while it is being built - wipes the plaintext. - - `indexes` returns the indexes that a plan field typed with the target - supports. The terms, `Encrypted`, and `plaintext` records report - their indexes. -- **The core leaves implement the owned declarations.** - - `StackCipherText` takes a `RequiredContext`, to encrypt - and to decrypt. The owned form seals the value without a copy. When the - context is refused, the value is wiped. - - `Encrypted` takes a `RequiredContext` to encrypt, - and a `RequiredContext` to decrypt. The owned form wipes - the ciphertext's copy of the value when the context is refused. - - `EqualityTerm`, `MatchTerms`, `OreTerm`, `OpeTerm`, and `OreBlockTerm` - implement `EncryptTarget` alone. - - `Ciphertext` implements `Decryptable` and `DecryptField`, so it can be a - record field. -- **`DeclaredScopes`** is the input of a `struct` record, whose fields have - their own contexts. The caller passes no context. A record that contains - the record, or a plan, passes the field's context, which extends each of - the inner record's contexts. -- **`ExpectedContext` is a `ContextInput`.** If the caller leaves the - context out, the record decrypts under the context it stores, unchecked. - If the caller passes a `NonEmpty`, the stored context must equal it. - - `DeclaredScopes` and `ExpectedContext` convert from the structural - contexts, `DeclaredContext` and `CallerContext`. So do the - `RequiredContext` wrappers of the core contexts. This is how a record - field is given its context. -- **Owned collections: `EncryptInto` encrypts a `Vec` into a `Vec`, - and `DecryptFrom` decrypts it back** (#1482). `Vec` implements - `EncryptTarget>` and `DecryptSource>` for any owned element - target. For example, `vec![29i32, 34].encrypt_into::, _>(&keyset)` - needs no caller context, and `Vec::::decrypt_from(ciphertexts, &keyset)` - decrypts the result. - - A collection uses its element target's `ContextInput`. A collection of a - `RequiredContext` target must be given a context, and a collection of a - `NoCallerContext` target cannot be given one. `Default` does not change - either rule. - - Each element is encrypted under its own data key and authenticated on - its own. An element's position and the number of elements are not - authenticated. That suits the common case of storing each element in its - own database row. A query can return rows in any order, or only some of - them. - - A collection makes one logical batch of key requests, in element order. - That is one `generate_keys` call to encrypt it, and one `retrieve_keys` - call for each keyset to decrypt it. An empty collection makes no call. The key - source can still split a logical batch into several requests to its - provider. - - Each element is wiped by its own declaration before the pending request - is returned, even when the context is refused. If a declaration panics, - the elements not yet handed over are wiped too. The elements do not need - to implement `Clone`. - - If an element fails after earlier elements were decrypted, the earlier - plaintexts are wiped before the error is returned. If an element's - conversion panics, they are wiped before the panic unwinds. - - A `Vec` is not a collection of bytes. A `Vec` is one byte - string, as the next entry describes. - - `keyset.encrypt` still takes a single value, and `encrypt_tree` is still - the structural path. -- **Byte strings encrypt as one value: `Vec` and `[u8; N]` encrypt into - one `Ciphertext`, and a `Vec>` encrypts into a `Vec`.** So - `keyset.encrypt(vec![1u8, 2, 3])` and - `Vec::::decrypt_from(ciphertext, &keyset)` now compile. The structural - API and the Go SDK already encrypted byte strings this way. - - `OpaqueEncode` is now implemented for every owned `Zeroize` type whose - borrow is a Vitamin C `plaintext::Scalar`. A `Scalar` is a type that - Vitamin C encrypts as a single value. `OpaqueDecode` is implemented for - every `Zeroize` type that implements `FromScalar`. - - Before this change, both traits were implemented for a list of types - kept by hand. That list did not include the byte strings that Vitamin C - treats as single values. - - Your own type becomes an `OpaqueEncode` type if its borrow implements - `Scalar` and the type implements `Zeroize`. - - `u8` alone, and a `Vec` of any type other than `u8`, still do not encrypt - into one `Ciphertext`. -- **`ValueFrame` implements `PartialEq`, comparing frames in constant time.** - Two frames are equal when their bytes are. So `34u32` and `34u64` are not - equal. Two maps with their keys in a different order are not equal either. Frames - of different lengths are unequal at once. The frame is now held in an - `Equatable>>`. Until vitaminc-protected implements - `ConstantTimeEq` for `Vec` (cipherstash/vitaminc#602), the bytes are - compared through `TimingSafeEq`. -- **`OpaqueBlob` encrypts a whole value as one `Ciphertext`** (#1484). - Use it to store a struct, map, or `Vec` as one ciphertext under one data - key. Encrypt with `keyset.encrypt(OpaqueBlob::new(value))`, for any - `Serialize + Zeroize` value. Decrypt with - `keyset.decrypt::>(ct)`, for any - `DeserializeOwned + Default + Zeroize` type, then call `into_inner()`. - - The value is encoded with version 1 of Vitamin C's storage profile - (`recipher_frame::storage`). The encoded bytes start with a `VCS` - header and a version byte, inside the plaintext. The profile has a - frozen specification and a golden corpus of test vectors. - - The encoded bytes are sealed as one bytes leaf of the `SealedValue` v1 - envelope. The envelope does not change. Encrypting a blob makes the same key - request as encrypting a scalar. - - The format is the Go SDK's opaque-struct format - (`vcffi.MarshalStorage`). A Go-written opaque column opens in Rust, and - a Rust-written one opens in Go, when the field types correspond. The - `blob` module docs give the rules. Both test suites pin the same bytes. - - A `Vec>` encrypts into a `Vec`, one ciphertext - per element, with every key requested together. An - `OpaqueBlob>` is one ciphertext. - - There is still no `Serialize` fallback. A struct passed to `encrypt` - without the wrapper does not compile. An `OpaqueBlob` of a type that - does not implement `Zeroize` does not compile either. - - `OpaqueBlob::encode` and `OpaqueBlob::decode` give access to the - encoding. `blob::HEADER` and `blob::VERSION` are the header bytes. - - The `blob` module docs cover the supported types and schema changes. - The docs also say what the ciphertext's length reveals: the encoded - length plus a constant, because nothing is padded. Architecture - decision record ADR-0011 records the decision. -- **A decrypted `OpaqueBlob` is wiped when it is dropped.** The blob - stores its value in a `Zeroizing`. `into_inner` returns that - `Zeroizing`, so the value is still wiped on drop after it leaves the - blob. `Zeroizing` derefs to `T`. A decrypted scalar is still an ordinary owned value, and nothing - wipes it on drop. -- **A blob refused part-way through reading wipes the fields it read** - (#1676). A valid blob of another shape can be refused after some of its - fields are read, for example when a later field is missing or has another - type. Those fields used to be dropped unwiped, because serde holds them - until the whole `T` is built. Decrypting now reads the blob in place - into a `T::default()` held in a `Zeroizing`, through serde's - `Deserialize::deserialize_in_place`, and a refusal wipes that value. This - covers the fields of most derived structs, the fields of a struct nested - in one, and the elements of a `Vec` stored before the refusal. - - Decrypting an `OpaqueBlob` now needs `T: Default`. Add - `#[derive(Default)]` to the type. - - stack-encrypt turns on serde_derive's `deserialize_in_place` feature. - Cargo shares a crate's features across a build, so every - `#[derive(Deserialize)]` in a build with stack-encrypt also writes - `deserialize_in_place`. `deserialize` does not change. - - A field serde skips when reading (`#[serde(skip)]` or - `#[serde(skip_deserializing)]`) keeps the value `T::default()` gives - it. A `#[serde(default = "...")]` on that field or on its struct is not - used, so make `T::default()` give the value the field should have. - - serde still builds some values whole, and a refusal inside one of them - still drops what it built unwiped (#1754): an element of a sequence, a - map, an `Option`, a `Box`, an enum, a field read with - `deserialize_with`, and a struct the derive writes no in-place read - for. That is a struct marked `#[serde(transparent)]`, `from` or - `try_from`, one with a `#[serde(flatten)]` field, and one whose every - field uses `deserialize_with`; when `T` is such a struct, a refusal - wipes nothing `T` read. A part that wipes itself on drop, such as a - `Zeroizing`, closes that gap for that part. - - serde reserves room for at most 1 MiB of a sequence's elements before - reading them. A longer sequence regrows its buffer as it is read and - frees each old buffer unwiped, as it did before this change. -- **Encrypting an `OpaqueBlob` wipes the value in every case.** The value is - wiped before `encrypt` returns the pending request, both on success and - when the value cannot be encoded. A failed encoding requests no key. A - context that is too long for a key request is refused before the value - is encoded, as it is for a scalar. The encoded bytes are held in a `Buffer` - that wipes itself. On decrypt, the opened bytes are held in a `Protected` - buffer while they are read. -- **`Error::Blob(BlobError)` reports why a blob was refused.** It has one - variant and one error code for each kind of refusal: - - `blob_unwritable`: the value cannot be encoded. This error happens - before any key is requested. - - `blob_not_a_blob`: the decrypted bytes are not a storage blob. - - `blob_unsupported_version`: the blob is a later version of the storage - profile. Upgrade stack-encrypt to read it. - - `blob_malformed`: the blob breaks a rule of its version. - - `blob_mismatch`: the blob is valid. It is not a value of the type you - asked for. +- **`OpSpec`, `Operand` and the query term's wire form grow for documents** + (#1350). `OpSpec` gains twelve operators and `Operand` gains `Text` and + `TextList`; a binding that matches on either adds the arms. The query + term an `se_query_term`-style export writes has a sixth key, + `encoding` (`bytes`, `eql`, `text`, `text_array`), and an operator entry + a fifth, `input` (`value`, `pair`, `json`, `path_json`, `path_pair`, + `path`, `path_bound`); a reader that checks every key reads the new + ones. `TargetDescriptor` has a `leaf_query_sql_domain`, set with + `with_leaf_query_sql_domain`. + +- **`TargetResolver::encrypt` takes the field's target options** (#1349): + `encrypt(name, options: Option<&TargetOptions>, keyset, label, + plaintext)`. A resolver implemented outside this crate adds the + parameter; one that resolves no document type ignores it. + +- **`dynamic::ValueKind` gains `Json`, and `ValueKind::ALL` holds 21 + kinds** (#1349). The enum is not `#[non_exhaustive]`, so an exhaustive + `match` on it, or a `[ValueKind; 20]` binding of `ALL`, stops compiling. + +- **`IndexSpec` has a sixth variant, `Json(JsonOptions)`** (the JSON index + above), so a `match` over it needs an arm for it. + +- **The order terms' `from_bytes` takes the buffer.** `OreTerm`, `OpeTerm` + and `OreBlockTerm::from_bytes` take a `Vec` and keep it, copying + nothing; each also implements `TryFrom>`. `TryFrom<&[u8]>` + remains, and copies once. `OpeTerm` now refuses a term whose leading + carry byte is not 0 or 1, which clww-ore's comparator already refuses + (`TermBytesError::MalformedCllwCiphertext`). + +- **stack-encrypt requires stack-kms 0.2 and stack-auth 0.44.** It + re-exports `stack_kms::{diagnostic, ErrorPayload}` and stack-kms as + `stack_encrypt::kms`, so a crate that names a stack-kms or stack-auth type + stack-encrypt takes or returns moves to those versions with it. + +- **stack-encrypt requires the vitaminc 0.8 crates, clww-ore 0.6 and + ore-rs 0.10.** A crate that names a vitaminc type stack-encrypt takes or + returns moves to 0.8 with it. What changes for a caller: + - **Every order term changes.** cllw-ore is now `clww-ore`. Its + keystream was fixed, and its schemes' names (`clww-ore`, `clww-ope`), + which every term's salt binds, changed, so ORE and OPE terms written + before do not compare with new ones. Block ORE goes through ore-rs's + single `BlockOre` scheme, which keys its 6-bit and chained engines + under a new label, so its terms change too. The wire formats, the key + domains of this crate and every sealed ciphertext and equality term are + unchanged: a stored row still opens, and its order terms are re-derived. + `tests/fixtures/stored_rows_v1.json`'s order terms were re-frozen. + - `sem::OreCllw8VariableV1` and `sem::OpeCllw8VariableV1` are renamed + `OreClww8VariableV1` and `OpeClww8VariableV1`, as clww-ore names them. + - **A sealed `None` of a fixed-width type is as long as a `Some`.** + vitaminc 0.8 seals it as a typed null, padded to the type's leaf length, + so absent values no longer show in the length of their ciphertexts. A + reader on vitaminc 0.7 or older refuses a typed null, so upgrade + readers before writers; every null written before still opens. The + `dynamic` feature's sinks carry a typed null through the value model, + and the frame a binding receives holds the plain null. + - **A null has an equality term** (vitaminc-normalize 0.8, #1298), the + one term every null of a context shares, on the typed path + (`EqualityTerm` of a `None`) and the dynamic one (`IndexSpec::Equality` + now defines a null). No other index has a term for a null. + - **Block ORE's text ceiling is unchanged, but counted the new way.** + `vitaminc-ore` puts the marker byte in front of text itself now, and + ore-rs's 1024-byte ceiling counts it, so the fold is still at most 1023 + bytes. + +- **`IndexSpec` has a fifth variant, `OreBlock`** (the block ORE index + above). The enum is exhaustive on purpose, since a binding has to be + taught each index, so a `match` over it needs an arm for `OreBlock`. The + dynamic path answers an ordering through ORE, else block ORE, else OPE, + whichever the field declares. + +- **A target's query is handed the index that answers its operator** + (`dynamic` feature). `TargetResolver::query` and `record::query` take an + `&IndexSpec` after the type's name and the field respectively; + `query_term` passes the index `OpSpec::answered_by` picks over the type's + indexes. A type whose query carries every term may ignore it. One whose + terms are optional derives that index's term alone, so EQL v4's + `TextSearch` answers `=` and `<` on text too short to make a match term, + and makes one only for `matches`. A resolver adds the parameter; a caller + of `record::query` passes the index it queries through. + +- **A ciphertext that opens as the wrong type is `Error::OpenedType`, not + `Error::Aead`** (#1118). A typed decrypt of a leaf that authenticates but + holds another type (an integer opened as `String`, a value too wide for + the target) was reported as `Aead`, the error for a wrong key or a + tampered ciphertext, and the Go guest reported it as `STATUS_AUTH`. The new + variant names only the type the target reads (`expected`). The Go guest + maps it to `STATUS_ENCODING`, as it does a typed record field that opens to + another kind. A wrong key, a wrong context and a tampered ciphertext are + still `Aead`. A container whose shape the target refuses (a map missing a + field) is `OpenedType` too: a container's membership and order are not + authenticated, by design, since stored values map to rows and columns a + database returns in any order and a query selects in part. + +- **An 8- or 16-bit integer in a dynamic value keeps its width** (`dynamic` + feature; #1144). The value model used to widen it to 32 bits before it + was sealed; now it is sealed as itself, so a field declared `int16` seals + an int16 leaf. A record sealed before under a 32-bit `type` does not open + under a plan that declares the narrower kind (`Plan(FieldType)`): the + typed decrypt checks the leaf's kind against the plan's. The seal side + breaks the same way: a host that sends an 8- or 16-bit leaf for a field + whose plan declares a 32-bit `type` is refused (`Reason::FieldType`, naming + the field), where the leaf used to be widened. Send the declared width, or + declare the narrower kind. The Go SDK converts to the declared width itself, + so Go code generated before this change still seals. + +- **A dynamic plaintext is a frame, not a value tree** (`dynamic` feature; + #1232, vitaminc ADR 0001). vitaminc 0.6 has no shared value type: a value + describes itself once, and sinks consume it. `dynamic::ValueFrame` is now + the engine's plaintext for a value whose type is known only at run time: + one value as its transport frame, in the engine's value model (an 8- or + 16-bit integer read as the 32-bit integer of its sign, as before; a + 128-bit integer or a date refused, as before), in a `Protected` buffer + wiped when it drops. It walks its own bytes into any sink (`Encrypt`) and + is a decrypt target that writes what it opens straight into a frame + (`Decrypt`). The plaintext paths walk frames: + - `record::encrypt`, `encrypt_with` and `check_source` take the source as + any `Encrypt` (a `ValueFrame`, a `vitaminc_aead::Frame`, or a Rust value + a test spells), walk it once and write each field's value into a + `ValueFrame` of its own, which is all the engine keeps of it. A value + refused while the source is split names its field, with the reasons it + had (`RepeatedKey`, `Unframeable`, `FieldType`; a value the value model + does not hold is `FieldType` inside a passthrough subtree too). + - Two refusals changed. The split is one walk of the source that stops + at its first fault, so of several faults in one row, those the split + finds (a repeated key, a value outside the model) are reported in + source order rather than plan order: the walk does not copy the rest of + a source it has already refused. And a passthrough value in a field + that seals a ciphertext and derives a term is now `Source { reason: + Passthrough }` whatever order the field lists its outputs in. It was + `Term` when a term output came before `c` in the plan and `Source` + otherwise, so the answer depended on how the outputs were spelled. + - `record::decrypt` and `decrypt_with` resolve to one `ValueFrame` (the + record, or the batch) instead of an `FfiValue`: each field opens into a + frame, which is walked into its entry of the record's frame and wiped. + - `read`, `query_term`, `check_query` and `verify` take their input as any + `Encrypt`, and `read` returns a `ValueFrame`; `verify` takes the page of + values as any iterator of sources (`ValueFrame::elements` splits a list + a binding handed over). + - `ValueFrame::check` checks frame bytes as `ValueFrame::from_bytes` does + and hands them back as a `Frame` to walk in place, with no copy: the Go + guest encrypts and checks a record source, and reads a query's input, + that way, so the only copies of a source's plaintext are the per-field + frames the split writes. + - `IndexSpec` is an `Index` of `ValueFrame` (it was of `FfiValue`), so a + Rust chain over dynamic fields names `ValueFrame` fields. + - `TargetResolver::encrypt` and `query` take a `ValueFrame`, and + `decrypt` resolves to one. + + `FfiValue` is gone (see the entry after next). + Ciphertexts, terms and the cross-language fixtures are byte for byte what + they were. The Go guest decodes plaintext as `ValueFrame`s and returns an + opened record's frame as it is. Copies of an opened string that remain in + the guest's memory after a decrypt were traced to the plaintext output of + AES-256-GCM's keystream XOR, left in the unwiped stack temporaries of the + RustCrypto crates behind vitaminc-encrypt's wasm32 backend (their number varies + with the leaf's length), not to this crate, and + `TestPlaintextDoesNotRemainInGuestMemoryAfterDecrypt` stays skipped with + that reason (cipherstash/vitaminc#370). The heap is guarded separately: + `tests/heap_hygiene.rs` runs the record encrypt (from a `ValueFrame` and + from a raw frame), the record decrypt (with a nested field), `query_term` + and `verify` under an allocator that fails the test on any freed block + still holding plaintext. + +- **Order terms encrypt through cllw-ore's vitaminc schemes, and text is + ordered.** An ORE or OPE term is now cllw-ore 0.5.2-rc.1's + `vitaminc::Ore`/`vitaminc::Ope` encryption of the value's `vitaminc-ore` + order encoding: the engine passes the value through and names its type's + target (`sem::Orderable`: integers at their own width, `f32`/`f64` as + `F64`, text as `Text`, bytes as `Bytes`), and cllw-ore does the encoding. + Text is ordered by the system ADR-0002's fold (Unicode 16 NFC with case + and accents folded), so `Café`, `cafe`, `CAFÉ` and `cafe` with a + combining accent are one term and tie, `alice` orders before `Zoe`, and + `é` orders with `e`, not after `z`. Every order term changes bytes: the + key labels move to `/v2`, the column salt binds the scheme and the + target, and text and bytes go in behind cllw-ore's marker byte. An order + term written by 0.1.0 or 0.2.0 (or by the Go module's v0.1.0-alpha.1) + does not compare with one this release derives, and nothing refuses it: + a `<`, `BETWEEN` or `ORDER BY` over a column holding the old terms + silently misses or misplaces rows. Re-derive a column's ORE and OPE terms + (encrypt its rows again) before querying it with this release. Every source type's term is one ciphertext type, + `OreCllw8VariableV1` or `OpeCllw8VariableV1`; `OreTerm` and + `OpeTerm` keep `T` to name the source, and `new`, `inner` and + `into_inner`, `KeysetCipher::ore_term` and `ope_term` take or return those + types. `sem::CllwOreEncrypt` and `sem::CllwOpeEncrypt` are no longer + re-exported, and the term bounds are `sem::Orderable`: a sealed trait + with one item, `const TARGET: OrderTarget`, the `vitaminc-ore` target a + type's values are encoded as. The value goes to the scheme as the + `vitaminc-aead` `Encrypt` source it is, by reference, and the engine + holds the one copy in a `Zeroizing` and wipes it; so an order term's + source is an owned `String` or `Vec`, and `&'static str`, + `&'static [u8]`, `Zeroizing` and `Zeroizing>` are no + longer sources. Text holding a code point Unicode 16 does not assign has + no order term (`TermError::Normalize`), on write and on query. The + ordering operators are answered on text, on the typed path + (`op::Ordered` for `String`) and on the data-plan path, so a binding + generates them too. + +- **A `u8` and an `i8` have no order term, as a `bool` has none.** An order + term over 256 values ranks every row among 256, which a few known rows + resolve to the values, the leak the crate already refuses for a boolean's + two. `u8` and `i8` leave `op::Ordered` and `sem::Orderable`, so + `OreTerm`, `OpeTerm` and an `Ore` or `Ope` index on either do not + compile; `dynamic::admits` refuses ORE and OPE on `int8` and `uint8` + (`Reason::IndexNotAdmitted`, as for a boolean), and a data plan naming + one is refused when it is built. Both keep their equality term. The + refusal is a compile error now, so `TermError::NoOrderTerm` (code + `stack_encrypt::no_order_term`), which `bool` raised at run time, is + gone. The `value_kinds.json` fixture's `i8` and `u8` fields carry + equality alone, and the frozen `stored_rows_v1.json` loses its four + 8-bit order terms under the order-term exception; every other stored + byte is as it was. + +- **Floats are ordered.** An `f32` or `f64` is encoded at the `F64` + target, whose encoding folds `-0.0` into `0.0` and every NaN into one + value above `+Infinity`: Postgres's `float8` order. So the ordering + operators are answered over `f32` and `f64` (`op::Ordered`) and over a + data plan's `float32` and `float64` fields, which they were not. An `f32` + is ordered as the `f64` it widens to: vitaminc widens it exactly, so an + `f32` and its `f64` are one term. Float order terms change bytes with + every other order term (above). + +- **A binding's control data is read from its frame with serde, not + decoded into an `FfiValue`** (`dynamic` feature). Each message is a typed + value read straight from the frame bytes by `vitaminc_aead_frame::serde`, + so no tree is built and every message refuses an unknown key, a repeated + key or a wrong type the same way: + - `dynamic::context` takes the context's frame bytes. An integer is read + at the width the frame carries, and only `i32`, `i64`, `u32` and `u64` + are contexts: an 8- or 16-bit integer, which was widened to 32 bits + before, and a 128-bit one are `Reason::ContextKind`, as are bytes that + are not one frame. + - `record::plan` and `record::plan_with` take the plan's frame bytes. + `IndexSpec::from_frame` replaces `IndexSpec::from_value`, and + `Output::from_value` is gone. Each `Reason` a plan was refused with is + unchanged, with two exceptions: a key, a field or a match option given + twice is refused by the frame before the plan is read, as + `Reason::NotAnObject` naming no field (it was `RepeatedKey` or + `DuplicateField`), and so are bytes that are not one frame. An index's + payload may be missing or null alike: `{"match": null}` is a bare + `"match"`, and `{"eq": null}` a bare `"eq"`. + - `Stats::from_frame` replaces `Stats::from_value`. + - The engine's answers are `Serialize`, written to a frame by serde, + byte for byte what the `FfiValue` encoders wrote (pinned in the tests): + `QueryTerm`, `TargetDescriptor` and `IndexSpec` replace their + `to_value`, `OperatorEntry::new` replaces `operator_to_value`, and + `Limit::rows` replaces `limit_to_value` (`None` writes null). + +- **`dynamic::FfiValue` is removed** (`dynamic` feature, #1252). Nothing + takes a value tree any more: a plaintext is a `ValueFrame`, and control + data is read from its frame by serde (above). Gone with it are + `Utf8String`, the tree's sink types (`ValueSink`, `ValueSeq`, `ValueMap`, + `Put`, `Root`, `Element`, `Entry`), `ValueKind::holds` and + `FfiValue::kind`. `ValueKind` and `ParseValueKindError` are unchanged and + still exported from `dynamic`, as is `FromFrameError`, now the error of + `ValueFrame::from_bytes` and `ValueFrame::check` alone. A value a test or + a caller spelled as an `FfiValue` is a Rust value instead + (`ValueFrame::of(34u32)`, `ValueFrame::of(&map)`), or the frame bytes a + binding sends. Stored records, terms and the frozen fixtures are byte for + byte what they were. + +- **A match value with no tokens is stored as the empty filter, so + `KeysetCipher::match_terms` is no longer a query.** In 0.2.0 the same call + served write time and query time, and refused text that cuts no token + under the match index's tokenizer (empty or separator-only text, or text + shorter than the n-gram length) with `TermError::EmptyTermText`. Now it + derives the stored filter only, and returns the empty filter (`bf: []`) + for such text with no error. **Do not send the output of `match_terms` as + a query:** EQL treats an empty filter as contained by every stored filter, + and its query domains do not refuse one, so that query returns every row + with no error anywhere. A query comes from `cipher.query(op::Matches, ..)`, + which still refuses such text with `TermError::EmptyTermText`, when the + query is awaited, before a term exists and before any keyset is loaded + (`op::Supports::check` now takes the query's value); `dynamic::term` + refuses it for a match kind the same way. The stored side is the change a + caller sees: one two-letter name no longer fails a whole row, the value + seals and opens as any other, and the `dynamic` record path stores it the + same way. Storing the empty filter tells a reader of the database that the + value is empty, separator-only or shorter than the n-gram length + (ADR-0009). + +- **stack-encrypt requires the vitaminc 0.6 crates.** They are the first + release of vitaminc ADR 0001, which the entries below build on. A crate + that names a vitaminc type stack-encrypt takes or returns (`Encrypt`, + `Decrypt`, `Protected`) moves to 0.6 with it. + +- **Equality terms derive through `vitaminc-normalize`, so `TextEq` compares + text in Unicode 16 NFC.** An equality term is the PRF over the value's + normalized bytes under vitaminc's domain for its kind: `café` written with + a precomposed `é` and with `e` and a combining accent is one term, every + integer width of one number is one term (`34u32` and `34i64` match), both + float widths of one number are one term, and a date, timestamp, decimal + or uuid derives in a domain of its own. `KeysetCipher::equality_term`, + `target::equality`, the `Equality` index and `op::Eq` take an `Encrypt` + that is one scalar where they took a `PrfValue`. A boolean, a null or a + container has no equality term (`TermError::NoEqualityTerm`); a `bool` + satisfies the new bound, so equality on one now fails when the term is + derived where it used to fail to compile. Text holding a code point + unassigned in Unicode 16 (an emoji newer than it, say) is refused + (`TermError::Normalize`), when it is written to an equality or match + column as well as when it is queried: the whole record's encrypt fails. + Match text is tokenized in the same normal form, and refused the same + way. Every equality and match term changes + bytes (the domains move to `/v2`); ORE and OPE terms do not. No stored + term existed to keep; the record fixture is regenerated. Text order + terms are encoded in the same normal form, folded further (see "Order + terms encrypt through cllw-ore's vitaminc schemes" above), so equality + and ordering agree on two forms of `café`. + +- **`dynamic::Value` and `dynamic::Scalar` are gone.** A field lowered from + data holds an `FfiValue`, which is now `Clone` (a deep copy into fresh + `Protected` payloads, as `Value`'s was) and reads as a context label. + `dynamic::term` takes any `Encrypt` (an `&FfiValue`, a transport frame + walked in place, a Rust value) and derives at the one scalar it holds; + `IndexSpec::defines(value)` replaces `IndexSpec::supports(&scalar)`, and + `IndexSpec` is an `Index`. + +- **A boolean has no order term**, on the typed path and through a plan or + `dynamic::term`: with two values, an ORE or OPE term would tell anyone + holding the column which rows are `true`. An ORE or OPE term of a `bool` + (`KeysetCipher::ore_term`, the `Ore` and `Ope` indexes) is refused with + the new `TermError::NoOrderTerm`, before any key is minted, where cllw-ore + used to order one. `dynamic::admits` now refuses ORE and OPE on `bool`, and + admits equality on `float32` and `float64`, which vitaminc gives an + equality domain. A 128-bit integer has an equality term and no order + term. + +- **Values describe themselves with vitaminc's new `Encrypt` and read back + with `Decrypt` (vitaminc ADR 0001).** `KeysetCipher::encrypt`, + `StackCipher::decrypt` and every target take the new `Encrypt`, a source + that describes its value to a sink, where they took the old + visitor-driven `Encrypt`, and `Decrypt` where they took + `Decrypt<'static>`; derive both with `vitaminc_aead::{Encrypt, Decrypt}` + (`stack_encrypt::{Encrypt, Decrypt}` re-exports them). The name is the + same and the trait is not: a hand-written impl of the old one does not + compile against the new one. `Decipher`, `Element` and `Cipher` are no + longer re-exported, and `StackDecipher` and `BoxedPassthrough` are gone. + A pending tree is planned rather than driven: + `PendingStackCipherText::plan(value, aad)`, then `seal` or + `into_pending` as before. The key fetch is unchanged: one batched + `generate_keys` per assembly to seal, one `retrieve_keys` per keyset to + open. + +- **Every leaf records its type, so a Rust field and a data-plan field + share leaves.** A Rust `u32` and a data plan's `uint32` field seal the + same leaf under the same context, and each opens the other's; a reader of + another kind (text for an integer, an integer for bytes) is refused rather + than handed changed plaintext, as a bare `String` reader used to read a + binding's leaf as `"\nalice"` (#1118). An integer reader accepts an integer + leaf of any width whose value fits, and an `f64` reader an `f32` leaf, + which change no value. + Leaves are vitaminc's wire version 2, so a ciphertext sealed by an + earlier build does not open. + +- **An absent value is a sealed null leaf**, a `Single` like any other + value: the absent marker (`CipherText::None`) and + `transcode::Visitor::absent` are gone. + +- **A passthrough travels as its frame.** `StackCipherText` is vitaminc's + `Node`: a passthrough subtree is a `PassthroughFrame`, the + transport frame of its value, in place of a boxed value, and + `transcode::Visitor::passthrough` takes one. + A dynamic passthrough value the frame cannot carry is refused when the + source is read, before any key is requested, as `Error::Source` naming + the field: a repeated key as `Reason::RepeatedKey`, and a value nested + deeper, or holding text, bytes or a key longer, than a frame carries as + the new `Reason::Unframeable` (`"unframeable"`). + +- **`dynamic::FfiValue` and `dynamic::ValueKind` are this crate's own**, + with the same variants and kind names, since vitaminc no longer has a + value tree. A value crosses a binding's boundary as a transport frame + (`FfiValue::to_frame`, `FfiValue::from_frame`), and is read through its + `Decrypt` sink: an 8- or 16-bit integer in a frame reads as the 32-bit + variant of its sign, and a scalar no variant holds is refused. + +- **`StackCipher::query_index` is gone**, with `QueryIndexBuilder` and + `QueryIndex`. Every query names an operator now that the orderings have + arrived: + - `query_index(Ore, &v)` over an integer is `query(op::Lt, &v)` (or any + ordering; the term is the same `OreTerm`). + - `query_index(Match, text)` is `query(op::Matches, text)`, which is not + the same call. It returns a `MatchQuery`, not the stored `MatchTerms`; + it refuses text that cuts no token (`TermError::EmptyTermText`); and it + compiles only for a configuration that implements `op::MatchCase`. A + configuration without one needs that one-line impl to be queried. + - `query_index(Ore, text)` and `query_index(Ope, text)` are + `query(op::Lt, text)` and `query(op::Lt, text).via(Ope)` (or any + ordering), whose term is the text's folded order term (see "Order terms + encrypt through cllw-ore's vitaminc schemes" above). + +- **`op::Supports`, `op::Answers` and `op::DefaultIndex` are keyed by the + query's input**, `Supports` with `In: Input`, in + place of the plaintext; for every operator but `Between` the input is + the plaintext, so `Supports` reads as before. `Supports::check` + takes the input and returns `Error`, and `Supports::query` takes the + input's terms (`In::Terms`: one term, or a pair for a + range). `plan::Resolves::resolve` takes the index and the call's context + and returns the index and the label. + +- **The query chain starts with the operator.** `cipher.query(op, v)` + replaces `cipher.query(v)`: `cipher.query(op::Eq, v).on(&plan)` replaces + `cipher.query(v).using(&plan).equality()`, and `on` replaces `using` for + queries only (a write still runs `using` a plan). An index's own term, for + an index no operator answers yet (`Ore`, `Ope`), is + `cipher.query_index(Ore, v).on(&plan)`, which goes when the ordering + operators arrive. `QueryUsing` is gone; the chain's types are `QueryBuilder`, `QueryVia`, + `QueryIndexBuilder`, `QueryIndex` and `QueryOp`, and the plan shapes + implement `plan::Chooses` and `plan::Resolves`. + +- **`Match::default()` is `Match`.** The match index under the default + configuration is the value `Match`, and `Default` is now implemented for + every `Match`, so `Match::default()` no longer infers the configuration. + +- **Update pattern matches for `dynamic::Error`.** `Context`, `Plan`, + `Source`, and `Record` now carry + `{ field: Option, reason: Reason }`; `Term` also gains + `field: Option`. For example, replace `Error::Plan` with + `Error::Plan { .. }`. Messages include the reason and the field when + known. Extra input fields are reported as `UnknownField` after the + plan's declared fields are checked, replacing the earlier field-count + check. + +- **Key-management errors pass through directly.** `Error::Kms` now uses + the underlying `stack_kms::Error` message, code, and help. The + `ZeroKMS data-key operation failed:` prefix is removed, and `source()` + returns the underlying error's own cause. ZeroKMS is CipherStash's + key-management service. + +- **Error messages omit potentially sensitive values.** + `Error::ContextMismatch` reports the stored context's length and number + of parts instead of its contents. `sem::TermError::Prf` omits the + underlying pseudorandom-function implementation's message, and + `sem::TermBytesError::MatchPositionOutOfRange` omits the position read + from search-index bytes, and `LabelError::Reserved` names the segment + but not the reserved character, since a `context_field` label is record + data. These details remain available on the Rust + error values for callers in the same process, including the `stored` + field on `ContextMismatch`. A one-value plan's + `PlanError::DuplicateIndex`, `IndexNotDeclared` and `IndexOptions` name + `the value` where they used to quote the plan's or the call's context; + the caller already holds that context. + +- **A data plan field with a term output must declare its `"type"`.** A + plan whose indexed field (`"eq"`, `"match"`, `"ore"`, `"ope"`) has no + `"type"` is refused when it is built (`Error::UntypedIndex`, naming the + field), by `record::plan`, + `record::plan_with`, `Plan::new` / `Plan::new_with` and + `Plan::with_context_field` alike: the field's + terms derive from the one declared kind, with every value checked against + it, never from whatever tag each value arrived with. The type stays + optional on a field whose only output is `"c"` or `"passthrough"`, and on + a target field, whose kind is the EQL type's own. The Go SDK already + fills `"type"` on every field from the Go type, and `record.Plan.Validate` + refuses an indexed `Untyped` field naming it, so generated code is + unaffected; a plan written by hand without types must add them. Declaring + a type changes no stored byte, so a row stored as the declared kind opens + as before. A row stored as another kind fails to open with + `PlanError::FieldType`, and fails any batch that holds it; its terms do + not match a query of the declared kind either. Re-encrypt such rows as + the declared kind: they are still readable, because a plan that gives the + field only `"c"` and no `"type"` remains valid and opens a row of any + kind, whatever indexes it was sealed with. Open the rows under that plan, + convert each value to the declared kind, and encrypt it again under the + typed plan. + +- **A target description carries a source mode.** `Encryption` gains a + last type parameter, `M: SourceMode = Borrowed`, saying how it is handed + its plaintext. Code that names `Encryption<'s, S, T, K, Ctx>` still + compiles and means the borrowed mode it always ran in. + +- `ciphertext`, `equality`, `matching`, `ore` and `ope` gain a source-mode + type parameter, `M`. A turbofish must name it: `ciphertext::()`, + and in `matching` it comes before `O` (`matching::()`). A call + whose result type does not fix the mode must name it; `Borrowed` is the + old behaviour. In return `ciphertext`, `equality`, `ore` and `ope` no + longer ask `S: Clone` themselves: only borrowed mode does. + +- `sem::MatchTerm` is renamed `MatchTerms`: a match index produces a set of + terms, not one. `MatchTerm` remains as a deprecated alias. + +- `TermBytesError::OddMatchTermLength` is renamed `OddMatchTermsLength`. An + enum variant cannot be aliased, so a `match` that names it must change. + +- `dynamic::TermKind` is gone; `target::IndexSpec` is the one data form of + an index. `Output::Term`, `Error::Term`'s `kind`, `Scalar::of` and + `dynamic::term` take an `IndexSpec` (the last two by reference), and + `Output` is no longer `Copy`. A plan's wire form is unchanged: a bare + `"match"` still means the default options. + +- **`dynamic::record` is a lowering into the plan builder, not a second + executor** (ADR-0007). `record::encrypt` and `record::decrypt` are no + longer `async`: each checks and converts its input with no cipher + (`Error::Source`, `Error::Term`, `Error::Record`, as before) and returns + the plan's `Pending`, whose failure is the crate's `Error`; a typed field + that opens to another kind is now `Error::Plan(PlanError::FieldType)` on + the await rather than `dynamic::Error::Record`. `dynamic::term` asks + `K: 'static`. The stored record shape (`"c"` and the term keys per field) + is unchanged, with one addition below. + +- **A data plan field's `"context"` must be the field's label** — a list of + at least two plain segments (`["users", "age"]`), optionally extended by + scalar parts nested to the left (`[["users", "age"], 7]`) — and every + field of one plan must share the label's prefix and the extension, which + become the plan's one context and its `.extend(..)`. A bare text part + (`"users/age"`), an integer, bytes or a one-segment label is refused + (`Error::Plan`): a fields plan cannot seal a field outside the record + context, and the derive lost that in the same release. Two sealed or + indexed fields under one label are refused for the same reason the + builder refuses them (`PlanError::SharedIdentity`). A record a Go program + wrote with a `label=` tag is unaffected; one written with a `context=` + tag is not readable through a plan. + +- **Every data plan field seals the tagged `FfiValue` leaf, whatever its + `"type"`**, as every field did before; the type admits indexes and checks + kinds and changes no bytes, so a row written without a type opens under a + plan that declares the kind it was sealed as, and a binding that starts + sending `"type"` re-encrypts nothing stored as that kind. A Rust `u32` or `String` field under the same label + derives the same terms as the data field but a different leaf, and the + two leaves cannot be told apart by inspection (a bare string that begins + with U+000A is a valid tagged string), so the lowering does not choose an + encoding from the type and a Rust record whose rows a binding must open + declares `dynamic::Value` fields, which are the same declaration as a data + plan's. One leaf encoding for both authors, or the encoding bound into + the leaf's context so the wrong reader fails closed, is a change to the + Rust chain's bytes, tracked in #1118. + +- `dynamic::Output` gains `Passthrough` (the wire key `"passthrough"`). The + enum is exhaustive on purpose, so a match over it must name the variant. + +- `target::DeclaredContext` holds several extension parts: `with(part)` + appends one, and `under` nests them to the left as `NonEmpty::with` does. + One part behaves exactly as before. + +- **`stack-encrypt-derive`: a field-level `#[stash(context = "..")]` is + removed on every derive form** (0.2.0 accepted it). On a `plaintext = T` + record, remove it: all outputs of the record share the caller's context. On + a field of a `struct = ..` derive, write `#[stash(identity = "..")]`, which + keys the field under `("", "")` (`users/nickname`), not + under the bare literal (`nickname`). Either way the field moves to a + different context from the one 0.2.0 used: data written by 0.2.0 does not + decrypt under it (ZeroKMS refuses the key, `Error::Kms`) and its equality, + match and order terms do not match new query terms, so re-encrypt that + data. Before the literal went, a non-plain literal such as + `"readings/unit"` was already refused, for the same reason. + +- **`stack-encrypt-derive`: `#[stash(nested)]` is removed** (0.2.0 accepted + it). Remove it: a record-typed field of a `struct = ..` derive is an + ordinary field, keyed under `("", "")`, and its inner + fields sit under that (`("user/age", "accounts/user")` where `nested` gave + `user/age`). That is a different context from the one 0.2.0 used: data + written by 0.2.0 does not decrypt under it and its terms do not match, so + re-encrypt that data. + +- **`stack-encrypt-derive`: a plaintext field of a `struct = ..` derive has + one output.** 0.2.0 accepted several fields `from` one plaintext field + (`email: StackCipherText` beside `#[stash(from = email)] email_hm: + EqualityTerm`). Write one field of type `Encrypted` instead + (`email: Encrypted`). Its ciphertext and terms are derived + under the same context as before (an equality term is the same bytes), so + stored data still opens and its terms still match; what changes is the + record's shape, one field where it held two. + +- **The plan API listed under Added changes shape before its first + release** (none of this is in 0.2.0; it matters only to code built + against the unreleased tree). `Plan::fields()` now starts a fields plan, + so a built plan's field iterator is `Plan::field_plans()`. A one-value + plan is `ValuePlan>` (from `with`) or + `ValuePlan>` (from `encrypt_into`), in place of + `ValuePlan`. `Plan::label` and `ValuePlan::label` return + `Option<&Label>` (`None` for a plan whose context comes from the call or + a context field), as `FieldPlan::label` does. `Runs::pending`, + `Opens::decryption`, `Plan::encryption`, `Plan::decryption` and + `ValuePlan::encryption` take the context the call names (an + `Option