diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 27b3cb59a1..107f70367d 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -7,8 +7,9 @@ # code is not asserted on — in a crypto crate, the comparisons, length checks # and context bindings a test can execute without ever checking. # -# CI runs this `--in-diff` as a per-PR gate (.github/workflows/mutants.yml): -# only the lines a PR changes are mutated, so the gate trips when a PR adds +# CI runs this `--in-diff` as a per-PR gate (.github/workflows/mutants.yml). +# For now the gate runs only on a pull request into main (#2017). +# Only the lines a PR changes are mutated, so the gate trips when a PR adds # logic its tests do not exercise. A full per-crate sweep is # `mise run mutants:` (stack-auth ~15 min, stack-encrypt ~60 min on a # laptop with four jobs); `mise run mutants` runs every crate that has one. @@ -33,7 +34,18 @@ additional_cargo_test_args = ["-E", "not binary(ui) & not test(stress_tests)"] # points at compile time, not in the instrumented test binary, so every # mutant there survives spuriously. Its behaviour is pinned by stack-encrypt's # `tests/derive.rs` and the trybuild UI suite instead. -exclude_globs = ["packages/stack-encrypt-derive/**"] +# +# vitaminc-aead-derive is mutated: only its `#[proc_macro_derive]` shims in +# lib.rs run at compile time, and the expansion they delegate to is in +# modules its unit tests call directly. +# +# recipher-frame's Kani harnesses build only under `cfg(kani)`, so no +# test binary contains them. kani.yml checks them. +exclude_globs = [ + "packages/stack-encrypt-derive/**", + "packages/vitaminc-aead-derive/src/lib.rs", + "packages/recipher-frame/src/storage/proofs.rs", +] # Mutants no test binary can kill, by name. Every other survivor is a test to # write, not a line to add here. Two kinds qualify: @@ -47,12 +59,28 @@ exclude_globs = ["packages/stack-encrypt-derive/**"] # # The regexes match the name `--list` prints, `path:line:col: replace …`. # Anchor on the replacement text, so an entry cannot swallow a reachable -# sibling with the same function name. The wasm32 `TokenStoreFn`, -# `AutoStrategy::detect_inner` and `Pending::into_future` entries also anchor -# on the line because their names are identical to the native impl's. -# If those lines move, a full sweep reports them again and the line numbers -# here need moving with them. +# sibling with the same function name. The wasm32 `TokenStoreFn` entry also +# matches on the line number, because its name is identical to the native +# impl's. If those lines move, a full sweep reports them again. Then change +# the line numbers here. +# +# The wasm32 `AutoStrategy::detect_inner` entry matches any line. The native +# function of the same name has one mutant, with the same replacement. That +# mutant does not compile, because `AutoStrategy` has no `Default`. So the +# entry excludes no mutant that a test could catch. +# +# The four wasm32 `into_future` entries in `pending.rs` match any line for the +# same reason. The future that a native `into_future` returns has no +# `Default`, so the native mutant does not compile. So do the wasm32 +# `fulfil_column` and `fulfil_pair` entries: the native functions of those +# names return a `FulfilBox`, a boxed closure, and no replacement the entries +# match builds one. exclude_re = [ + # stack-encrypt — equivalent. `predicate!`'s finders return the type of a + # path's values as a `PhantomData`, a zero-sized type with one value, so + # `PhantomData::from(Default::default())` is the same value. (Nothing calls + # them at run time either: the macro's checks are type-checked, never run.) + 'stack-encrypt/src/field_reference/json/predicate_checks\.rs:\d+:\d+: replace .* -> PhantomData<[^>]*> with PhantomData::from\(Default::default\(\)\)$', # stack-auth — unreachable under the native test build. 'stack-auth/src/transport\.rs:\d+:\d+: replace ::fmt ', 'stack-auth/src/transport\.rs:\d+:\d+: replace ::send_dyn -> std::pin::Pin>\+\x27a>> ', @@ -62,7 +90,7 @@ exclude_re = [ # Under `http` the body is `false`; the no-`http` arm is pinned by # `a_builder_without_a_transport_is_refused_when_there_is_no_bundled_one`. 'stack-auth/src/error\.rs:\d+:\d+: replace RequestError::is_no_transport -> bool with false$', - 'stack-auth/src/auto_strategy\.rs:150:9: replace AutoStrategy::detect_inner -> Result with Ok\(Default::default\(\)\)$', + 'stack-auth/src/auto_strategy\.rs:\d+:\d+: replace AutoStrategy::detect_inner -> Result with Ok\(Default::default\(\)\)$', 'stack-auth/src/token_store\.rs:(273|281):9: replace >::(load|save)', # stack-auth — equivalent. 'stack-auth/src/(access_key|oidc)_refresher\.rs:\d+:\d+: replace )?>::try_credential -> Option with Some\(Default::default\(\)\)$', @@ -70,16 +98,94 @@ exclude_re = [ # stack-encrypt — unreachable under the native test build (the wasm32 # variant; the native one returns a `FallbackKeyProvider`). 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace client_key_provider -> EnvKeyProvider with Default::default\(\)$', - 'stack-encrypt/src/target/pending\.rs:443:9: replace >::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>>::into_future -> Self::IntoFuture with Default::default\(\)$', + # A wasm guest's column and pair, which stop part way so the guest can + # yield to the host. Natively a column and a pair run to their end, so + # `fulfil_column_from`, `fulfil_column_item` and `fulfil_pair_right` exist + # only in wasm32. The chunking is pinned from Go instead: + # `TestABigBatchYieldsAndRoundTrips` counts the yields of a 200-row batch + # through the real guest, exactly, both ways. + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace (fulfil_column|fulfil_pair) -> FulfilBox<.*> with FulfilBox::', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace (fulfil_column_from|fulfil_column_item|fulfil_pair_right) ', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace .* in (fulfil_column_from|fulfil_column_item|fulfil_pair_right)$', # stack-encrypt — equivalent. - 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace StackCipher::builder -> StackCipherBuilder with Default::default\(\)$', + # An operator and an index are unit structs, whose `Default` is the value + # `clone` and `case_sensitive` already return. + 'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace >::clone -> Self with Default::default\(\)$', + 'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace Matches::case_sensitive -> Matches with Default::default\(\)$', + 'stack-encrypt/src/target/index\.rs:\d+:\d+: replace >::clone -> Self with Default::default\(\)$', + 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace StackCipher::builder -> StackCipherBuilder with Default::default\(\)$', 'stack-encrypt/src/sem/mod\.rs:\d+:\d+: replace ::options -> MatchOptions with Default::default\(\)$', + # `Orderable`'s default `check_query` refuses nothing: its body is + # `Ok(())`, so the replacement is the body. Text overrides it with + # `query::order_text`, pinned by `an_ordering_refuses_only_text_it_cannot_encode`. + 'stack-encrypt/src/sem/mod\.rs:\d+:\d+: replace sealed::Sealed::check_query -> Result<\(\), super::TermError> with Ok\(\(\)\)$', + # A JSON document type's default options are the defaults: the trait's + # body is `JsonOptions::default()`. A type that overrides them is pinned + # by `a_field_that_names_no_options_queries_under_its_types_own`, and + # `Option` forwarding by `a_nullable_field_queries_under_its_types_own_options`. + 'stack-encrypt/src/json/target\.rs:\d+:\d+: replace JsonQueries::default_options -> JsonOptions with Default::default\(\)$', # Both unit-context conversions explicitly return Self::default(). 'stack-encrypt/src/target/context\.rs:\d+:\d+: replace for (DeclaredContext|ExpectedContext)>::from -> Self with Default::default\(\)$', + # A caller shape with no placeholder IS `CallerShape::default()`: + # `CallerShape::none` returns it, and a context that supplies no part + # (`NoCallerContext`, `DeclaredScopes`) supplies `none()`. Each is + # pinned by `a_caller_shape_holds_its_placeholders` and the derive + # tests' `contexts()` views, which show no placeholder for them. + 'stack-encrypt/src/contexts\.rs:\d+:\d+: replace CallerShape::none -> Self with Default::default\(\)$', + # A record with no stored part IS `StoredParts::default()`: `none` returns it. + 'stack-encrypt/src/target/context\.rs:\d+:\d+: replace StoredParts::none -> Self with Default::default\(\)$', + 'stack-encrypt/src/contexts\.rs:\d+:\d+: replace ::supplies -> CallerShape with Default::default\(\)$', + # Omitting an expectation is expecting nothing: `ExpectedContext::omitted` + # returns Self::default(). That an omitted expectation opens under the + # stored context without checking it is pinned by + # `a_stored_context_opens_as_stored_and_checks_an_expectation`. + 'stack-encrypt/src/target/input\.rs:\d+:\d+: replace >::omitted -> Self with Default::default\(\)$', + # Omitting a struct record's caller context declares no extra scope: + # `DeclaredScopes::omitted` returns Self::default(). + 'stack-encrypt/src/target/input\.rs:\d+:\d+: replace ::omitted -> Self with Default::default\(\)$', + # A caller-free declaration adds nothing to the declared context: the + # conversion returns Self::default(). + 'stack-encrypt/src/target/input\.rs:\d+:\d+: replace for super::DeclaredContext>::from -> Self with Default::default\(\)$', # The resolver of a build without EQL types holds none: its `targets` IS # the empty list (`dynamic::target::NoTargets`), which a test asserts on # and `resolve` turns into `TargetError::NoTargets`; `vec![]` is the body. 'stack-encrypt/src/dynamic/target\.rs:\d+:\d+: replace ::targets -> Vec with vec!\[\]$', + # A serde visitor's `expecting` writes only the "expected ..." part of + # the message of a serde error. No caller of these three visitors reads + # that message: + # - A context is refused with the fixed `Reason` `ContextKind`. + # - Statistics are refused with the fixed `Reason` `NotStats`. + # - The root of a plan is refused with `NotAFrame`, or with `NotAnObject` + # and the kind of value in the frame. + # - The reasons for one field of a plan are read from the path of the + # error. + # So a mutant that writes nothing refuses the same input with the same + # error. + 'stack-encrypt/src/dynamic/(context|query|record)\.rs:\d+:\d+: replace for ContextVisitor|serde::Deserialize<\x27de> for Confidence>::deserialize:: for V|Deserialize<\x27de> for PlanWire>::deserialize:: for V)>::expecting -> fmt::Result with Ok\(Default::default\(\)\)$', + # The JSON index. `unhex` joins a high nibble shifted into the top four + # bits with a low nibble below 16: the bits never overlap, so `^` is `|`. + 'stack-encrypt/src/json/mod\.rs:\d+:\d+: replace \| with \^ in unhex$', + # `JsonPath::root` is `Self::default()`. + 'stack-encrypt-jsonpath/src/path\.rs:\d+:\d+: replace JsonPath::root -> Self with Default::default\(\)$', + # A document always has a root, so its terms are never empty: `false` is + # the value `is_empty` returns. The `true` replacement is still caught. + 'stack-encrypt/src/json/derive\.rs:\d+:\d+: replace JsonTerms::is_empty -> bool with false$', + # A JSON operator's input: the `JsonText` visitor's `expecting` writes a + # message `read_frame` discards for its fixed `Reason::JsonInput`. + 'stack-encrypt/src/dynamic/json_query\.rs:\d+:\d+: replace for JsonText>::deserialize:: for V>::expecting -> std::fmt::Result with Ok\(Default::default\(\)\)$', + # vitaminc-aead — unreachable. `Nothing` is an uninhabited enum, so no value + # exists to call `scalar`, `typed_null` or `passthrough` on, and replacing + # those bodies with `Ok(())` cannot be observed. Its `seq` and `map` + # mutants are unviable for the same reason. + 'vitaminc-aead/src/typed\.rs:\d+:\d+: replace ::(scalar|typed_null|passthrough) -> Result<\(\), DecodeError> with Ok\(\(\)\)$', + # vitaminc-aead — equivalent. `max` picks the larger of two depths, and + # when they are equal `a > b` and `a >= b` return the same number. Its + # other mutants stay gated. + 'vitaminc-aead/src/plaintext/depth\.rs:\d+:\d+: replace > with >= in max$', ] # Headroom over the measured baseline before a slow-but-correct mutant is diff --git a/.changeset/auth-aws-lc-rs-1-18-1.md b/.changeset/auth-aws-lc-rs-1-18-1.md new file mode 100644 index 0000000000..47458972a9 --- /dev/null +++ b/.changeset/auth-aws-lc-rs-1-18-1.md @@ -0,0 +1,8 @@ +--- +"@cipherstash/auth": patch +--- + +The native binaries now use aws-lc-rs 1.18.1 and aws-lc-sys 0.45.0. These +versions fix the GitHub security advisory GHSA-xv35-xp83-5wrf. The advisory +affects aws-lc-rs 1.18.0 and aws-lc-sys before 0.45.0. The package does not +call the affected code. The package's API is unchanged. diff --git a/.changeset/auth-background-refresh.md b/.changeset/auth-background-refresh.md new file mode 100644 index 0000000000..2adbc0ae3c --- /dev/null +++ b/.changeset/auth-background-refresh.md @@ -0,0 +1,29 @@ +--- +'@cipherstash/auth': patch +--- + +Access-key and device-session tokens are now refreshed before they expire, +in the background. In Node, such a strategy refreshes its token on a task of +its own. The refresh is due between 90 seconds and two minutes before the +token expires. So +`getToken` returns the current token at once while it has more than 30 +seconds left. Before, the first call in the last 90 seconds started the +refresh and waited for it. + +A call whose token has less than 30 seconds left still refreshes it, or +waits for the refresh already running. It does not get back a token that may +expire before it is used. The refresh runs only while the strategy is in use, +so an idle process stops asking the token service. + +`OidcFederationStrategy` has no background task: each user's token is still +refreshed by that user's calls, in the last 90 seconds before it expires. The +30-second rule above does not apply to it. + +After a refresh fails, the next attempt waits about a second, doubling up to +30 seconds. Meanwhile a call whose token still works gets it. A call whose +token has expired fails at once with that refresh's error, rather than every +call asking the token service again. This backoff also applies to the WASM +build. That build has no background task, and still refreshes in the last 90 +seconds. + +The JavaScript API is unchanged. diff --git a/.changeset/auth-credential-per-call.md b/.changeset/auth-credential-per-call.md new file mode 100644 index 0000000000..55eb529ca7 --- /dev/null +++ b/.changeset/auth-credential-per-call.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/auth': patch +--- + +Rebuild on a `stack-auth` whose Rust API can issue the token for a credential passed with the call. The JavaScript API is unchanged: `getToken` and `getTokenForJwt` behave as before, and share one token cache. In Rust, `CredentialAuthStrategy` is the trait for a credential passed with the call, and an `OidcFederationStrategy` can be built with no provider callback (`OidcFederationStrategy::credential_per_call`). Such a strategy has no `get_token`, so a call that brings no credential does not compile. A Rust strategy built with a provider callback takes no JWT from its caller. The Node and wasm bindings therefore build the Rust strategy with `credential_per_call`, keep the `getJwt` callback themselves, and pass a JWT with each call. diff --git a/.changeset/auth-oidc-detected-workspace.md b/.changeset/auth-oidc-detected-workspace.md new file mode 100644 index 0000000000..74994ec384 --- /dev/null +++ b/.changeset/auth-oidc-detected-workspace.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/auth": patch +--- + +No change to the npm package's API or behaviour. This release is built from a newer copy of the Rust crate behind the package. The newer crate adds two constructors for Rust callers, `OidcFederationStrategy::with_detected_workspace` and `OidcFederationStrategy::builder_with_detected_workspace`. Both read the workspace from `CS_WORKSPACE_CRN` or from the CLI's saved session. diff --git a/.changeset/auth-profile-workspace-crn.md b/.changeset/auth-profile-workspace-crn.md new file mode 100644 index 0000000000..c0a5e85316 --- /dev/null +++ b/.changeset/auth-profile-workspace-crn.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/auth": patch +--- + +No change to the npm package's API. This release is built from a newer copy of the Rust crate behind the package. In that crate, `OidcFederationStrategy::with_detected_workspace` no longer reports an `auth.json` it cannot read as "not logged in", and reports a saved session whose region it does not know as `AuthError::Region` instead of a server error. `Token::workspace_crn` reports the unknown region the same way. The new `profile_workspace_crn` function returns the workspace CRN of the CLI's saved session in a given profile directory. diff --git a/.changeset/chacha20-0-10-2.md b/.changeset/chacha20-0-10-2.md new file mode 100644 index 0000000000..266d137e44 --- /dev/null +++ b/.changeset/chacha20-0-10-2.md @@ -0,0 +1,6 @@ +--- +'@cipherstash/protect-ffi': patch +'@cipherstash/auth': patch +--- + +Build the native binaries against `chacha20` 0.10.2. Versions 0.10.0 and 0.10.1 were yanked: on an x86 CPU without AVX2, their SSE2 fallback for the random number generator used an SSE4.1 instruction it had not checked the CPU for. A CPU without SSE4.1 (one from before 2008, or a virtual machine using QEMU's default `qemu64` CPU model) would crash with an illegal-instruction error. Every other CPU produced correct random numbers, so randomness was never weakened. No API change. diff --git a/.changeset/eql-3-1-0-migration.md b/.changeset/eql-3-1-0-migration.md index 39e2388a04..3b82adc2df 100644 --- a/.changeset/eql-3-1-0-migration.md +++ b/.changeset/eql-3-1-0-migration.md @@ -10,7 +10,7 @@ constant number of operations whatever two values share, closing a timing leak. Ordering results are unchanged for well-formed values, but a block-ORE text value with a malformed or mismatched-width term now raises on every comparison against it. Check your `_ore` text columns before migrating; see -[U-001](../../../../packages/eql/docs/upgrading/v3.1.md#u-001-block-ore-text-comparisons-check-every-term). +[U-004](../../../../packages/eql/docs/upgrading/v3.1.md#u-004-block-ore-text-comparisons-check-every-term). No domain, wire format or index term changes. Two artefacts carry the new bundle: diff --git a/.changeset/eql-bindings-optional-storage-only.md b/.changeset/eql-bindings-optional-storage-only.md new file mode 100644 index 0000000000..77555112ef --- /dev/null +++ b/.changeset/eql-bindings-optional-storage-only.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": patch +--- + +`eql-bindings` (the Rust crate released with this package): an EQL v4 type whose terms a null has, a storage-only type (`Date`, `Integer`, `Text`, ...) or one whose only term is equality's (`DateEq`, `IntegerEq`, `TextEq`, ...), now also implements `EncryptTarget` and `DecryptSource` for an `Option` of its plaintext, and its query twin `EncryptTarget` for one. For a type of fixed width a `None` seals as a typed null as long as a value (vitaminc 0.8), so an optional column does not show which rows are absent. For text it seals as a null that is not padded, since text's ciphertext is as long as the text, so its length may show that the value is absent. Either way it opens as `None`; its `hm` is the one term every null shares, and the query of a `None` finds the stored nulls with `=`. A value seals exactly as before. The by-name dispatch (`encryption::targets`) reads, opens and queries these types through the `Option`; a type with an order or match term still refuses a null. eql-bindings' own `Date`, `Timestamp` and `Decimal` plaintexts declare their fixed width to vitaminc, so their `None` is padded too. The SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-bindings-order-queries.md b/.changeset/eql-bindings-order-queries.md new file mode 100644 index 0000000000..8d58b0941b --- /dev/null +++ b/.changeset/eql-bindings-order-queries.md @@ -0,0 +1,9 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: the field reference of an ordered EQL v4 type answers order queries. `EncryptedMember::AGE.gt(30).encrypt(&keyset)` gives the type's query twin (`IntegerOrdQuery`, `DateOrdOreQuery`, …) for `lt`, `lte`, `gt` and `gte` on every `…Ord`, `…OrdOpe` and `…OrdOre` type. `TextOrd`, `TextOrdOpe` and `TextOrdOre` answer `eq` too, and `TextSearch` and `TextSearchOre` answer `eq`, the orderings and `matches`. Each query is the one a data plan derives for a field that names the type. + +A `TextOrd*` query carries its `hm` and its order term whatever the operator, and is refused, before any key is requested, for text either index refuses. `between` is not answered from a field reference. + +The stored format, the SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-bindings-plaintext-by-reference.md b/.changeset/eql-bindings-plaintext-by-reference.md new file mode 100644 index 0000000000..674b2634ce --- /dev/null +++ b/.changeset/eql-bindings-plaintext-by-reference.md @@ -0,0 +1,10 @@ +--- +'@cipherstash/eql': minor +--- + +**eql-bindings reads every plaintext in place** (`stack-encrypt` feature). The EQL v4 types seal and index a plaintext without copying it, so a plaintext no longer needs `Clone`. + +- The `Ciphertext` and `Hmac256` targets, and the query twins, are bounded by `Encrypt + EncryptRef`, where they were bounded by `Encrypt + Clone`. A plaintext with only a by-value `Encrypt` impl adds `impl Encrypt for &T`. +- A query twin's plaintext is `Zeroize`, because a query hands its value to the index by value and wipes it. +- `v4::plaintext::Date`, `Timestamp`, and `Decimal` are Vitamin C's types, built from jiff's and rust_decimal's values. They are not `Clone`. +- The crate's `jiff` and `rust_decimal` features now only turn on `stack-encrypt`. That feature turns on both. diff --git a/.changeset/eql-bindings-shared-resolver.md b/.changeset/eql-bindings-shared-resolver.md new file mode 100644 index 0000000000..2cb41458b8 --- /dev/null +++ b/.changeset/eql-bindings-shared-resolver.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": minor +--- + +`eql-bindings` (the Rust crate released with this package) now ships a resolver for Stack Encrypt's dynamic interface: `eql_bindings::encryption::EqlTargets`, behind the `targets` feature. The dynamic interface runs a plan that arrives as data, and a field of that plan can name an EQL type, such as `"TextEq"`. A program gives Stack Encrypt the EQL types through its `TargetResolver` trait. Until now each program wrote its own resolver over `encryption::targets`. `EqlTargets` holds every type in `targets::targets()` and runs a named type's `encrypt_with`, `decrypt` and `query`. Two conversions come with it: `From<&Target>` for Stack Encrypt's `TargetDescriptor`, and `From` for Stack Encrypt's `TargetError`. Stored bytes and query operands do not change. The SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-domains-refuse-null-version.md b/.changeset/eql-domains-refuse-null-version.md new file mode 100644 index 0000000000..3f9bcabaf0 --- /dev/null +++ b/.changeset/eql-domains-refuse-null-version.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': patch +--- + +The stored and query-operand domains (`eql_v3_*`, `eql_v4_*`, `eql_v3.query_*`, `eql_v4.query_*`) now refuse a payload whose `v` is JSON `null`. The CHECK compared `v` with the bundle's version, and a comparison with `null` is NULL, which a CHECK lets through, so such a payload fitted both a v3 and a v4 domain. The range domains already refused it. A NULL value still fits every domain. diff --git a/.changeset/eql-encrypted-json-operations.md b/.changeset/eql-encrypted-json-operations.md new file mode 100644 index 0000000000..bf9576dbbd --- /dev/null +++ b/.changeset/eql-encrypted-json-operations.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": minor +--- + +**`JsonSearch` answers its JSON operators by name.** `eql-bindings`' target table row now tells Stack Encrypt the domain an ordering at a path binds as (`Target::leaf_query_sql_domain`, `eql_v4.query_json_leaf`), so a data plan's `lt_at`, `lte_at`, `gt_at`, `gte_at` and `between_at` bind their operand as that domain, beside `contains`, `contained_by` and `eq_at`, which bind the needle as `eql_v4.query_json`. No SQL changes. diff --git a/.changeset/eql-encrypted-json-target.md b/.changeset/eql-encrypted-json-target.md new file mode 100644 index 0000000000..d27a5adca6 --- /dev/null +++ b/.changeset/eql-encrypted-json-target.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": minor +--- + +**The `json_tree` family is in the EQL catalog as EQL v4's searchable JSON document, and a data plan can produce `public.eql_v4_json_search` by name: the target `JsonSearch`.** A language SDK names it in a plan field with the `json` type, gives it the JSON index's options (`{"name": "JsonSearch", "options": {"sealed_root": true, "ordered": ["$.age"]}}`, or the bare name for the defaults), and hands each document over as UTF-8 JSON text; the `eql-bindings` crate's by-name dispatch (`encryption::targets::encrypt_with`, `decrypt`) seals it through the same JSON index layout typed Rust uses and opens it back to its text. The text is parsed by Stack Encrypt's rules, before any key is requested: an object that names a member twice, an integer literal outside the 64-bit range, and text that is not JSON are refused (`TargetError::Json`, with a code and never a byte of the text). The catalog lists the family once (`eql_domains::DOCUMENT_FAMILIES`), so the target table, `v4::all()` / `v4::all_query()` and the Go types (`eql.JSONSearch`, `JSONSearchQuery`, `JSONSearchLeafQuery`, `JSONEntry`) are generated from it. The types take the names EQL v3 gives its searchable JSON document: `Json` (`public.eql_v4_json`) stays the storage-only type, `JsonSearch` is the searchable document, queried with `JsonSearchQuery` (`eql_v4.query_json`) and `JsonSearchLeafQuery` (`eql_v4.query_json_leaf`), and `JsonEntry` (`public.eql_v4_json_entry`) is one node as `->` and the reads return it. The JSON tree SQL domains are renamed to match: `public.eql_v4_json_tree` is now `public.eql_v4_json_search`, `public.eql_v4_json_tree_entry` is `public.eql_v4_json_entry`, `eql_v4.query_json_tree` is `eql_v4.query_json` and `eql_v4.query_json_tree_leaf` is `eql_v4.query_json_leaf`; the `eql_v4.json_tree_*` functions keep their names. The v4 bundle no longer carries the SteVec domains: in v4, `json_tree` implements `json_search`. The SteVec SQL (`src/v3/json/`) and the generated `json_entry_` cross operators are confined to EQL v3 with `-- ONLY EQL VERSION: 3`, and the v4 target table drops its unproducible `SteVecDocument` row. The v3 bundle gains only those directive comment lines. diff --git a/.changeset/eql-identifier-borrowed-context.md b/.changeset/eql-identifier-borrowed-context.md new file mode 100644 index 0000000000..d879c6bc4c --- /dev/null +++ b/.changeset/eql-identifier-borrowed-context.md @@ -0,0 +1,7 @@ +--- +"@cipherstash/eql": patch +--- + +`eql-bindings` (the Rust crate released with this package): a borrowed `&Identifier` is now a Stack Encrypt context, the same context as the `Identifier`. A program can hold one identifier and pass `&column` to the cipher-directed API, or build a `NonEmpty<&Identifier>` for a term, without a clone. The stored EQL (Encrypt Query Language) types still take their `NonEmpty` by value. + +The EQL types also gain `contexts()`, from Stack Encrypt. The method shows the context each stored field is sealed and indexed under, before any key is requested. The SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-json-field-reference-queries.md b/.changeset/eql-json-field-reference-queries.md new file mode 100644 index 0000000000..2d1e36db80 --- /dev/null +++ b/.changeset/eql-json-field-reference-queries.md @@ -0,0 +1,17 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: a `JsonTreeDocument` field of a derived Stack Encrypt record is queried from its field reference, and each query returns the EQL query type a parameter binds as. + +- `EncryptedCustomer::PROFILE.contains(doc)` gives a `JsonTreeQuery` for `@>`, and `contained_by(doc)` one for `<@`. +- `#[stash(json(ordered = { "$.age": u32, "$.visits[*].place": String }))]` on the field names the paths the documents order and the type of the values at each. The field is sealed under those options and queried under them. `paths = { "$.name": String }` beside it declares a path compared with equality alone, which adds no ordering term. Stack Encrypt's derive checks every path when it compiles the record. +- Each declared path has a typed method: `at().age().gt(v)` and the other comparisons give a `JsonTreeLeafQuery`, `at().age().between(lo, hi)` two of them, and `at().age().selector()` the `JsonTreeSelector` that `->` takes. A path, a member or a value type the field does not declare does not compile, and neither does an ordering of a `paths` path. +- `elements().visits().place().eq(v).and()..` gives a `JsonTreeElementsQuery`, `predicate(text).var(name, v)` a `JsonTreePredicateQuery`, and `children(path)` a `JsonTreeToken`. +- A path built at run time is text: `at_text_path(path)` and `elements_text_path(path)` check it when the query is encrypted. + +Each query is the operand a data plan naming `JsonSearch` derives for the same column and options, which is what the Go SDK sends. + +A value passed by value is now sealed without a copy when its type seals it and derives no search term: a `JsonTreeDocument`, a data plan field that names `JsonSearch`, and the storage-only v4 types (`Integer`, `Text`, `Json` and the rest). The copy was wiped before, so nothing leaked; it was not needed. + +The stored format, the SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-json-tree-cascade-and-random-order.md b/.changeset/eql-json-tree-cascade-and-random-order.md new file mode 100644 index 0000000000..c4894f2a1c --- /dev/null +++ b/.changeset/eql-json-tree-cascade-and-random-order.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": patch +--- + +EQL v4 `json_tree` (unreleased): a stored document's entries are now in a random order, root first, an object's members get a random permutation as their ordinals (the `o` the server probes a node's children at, which was a keyed rank), and its containment projection `q` is shuffled the same way, so the stored order no longer shows each row's tree, the size of every subtree or the byte order of sibling key names (#1357). A containment or equality needle is sent in a random order of its own too, so a query no longer shows sibling key order either. Every entry's ciphertext now also commits to its children's AEAD tags, so the client checks a subtree read's rows by the chain rather than by their positions, and a row swapped, dropped, added, reordered or moved beneath the node read is refused by the cipher. Nothing stored changes shape; `json_tree_children` returns a node's children in ordinal order (an array's elements by position), where it returned them by stored slot, and no other SQL function changes (three doc comments stop promising document order); documents sealed by the earlier build of this unreleased family no longer open. `->`, `->>` and an ordering on `eql_v4.ord_term(col -> sel)` at a wildcard path now return an unspecified element of the row (the same one every time), not element 0; read every element with `json_tree_path_query`. `->` on an object or array with members no longer opens on the client (the entry's ciphertext commits to its children, which `->` does not return): Stack Encrypt reports `JsonNotALeaf`, which is also what an altered entry looks like through `->`; read a container with a subtree read. `docs/reference/json-tree-leakage.md` says what the stored row still shows and what a read now proves. diff --git a/.changeset/eql-json-tree-derivable-tokens.md b/.changeset/eql-json-tree-derivable-tokens.md new file mode 100644 index 0000000000..f6501623ef --- /dev/null +++ b/.changeset/eql-json-tree-derivable-tokens.md @@ -0,0 +1,9 @@ +--- +"@cipherstash/eql": minor +--- + +EQL v4 `json_tree` (unreleased): a subtree read sends the token of exactly the node it reads, and returns that node. Every token is now derivable from its node's path alone: an object member's is `H("t" ‖ t(parent) ‖ s)`, with no ordinal, and an array element's keeps its index. Every stored entry gains a self tag `x`, the first eight bytes of `H("x" ‖ iv ‖ t)`, by which the server finds the node a token names; the entry validator requires it, so a document written by the earlier build of this unreleased family is refused. A read of `$.profile.address.city` used to send `$.profile`'s token, a capability over that whole field in every row, and walk to the leaf through gates; it now sends the leaf's token and nothing that covers any node above it. + +**SQL signature changes.** `eql_v4.json_tree_subtree(doc, tokens text[], budget integer DEFAULT 64)` replaces `json_tree_subtree(doc, token, budget)` and `json_tree_subtree_at(doc, token, gates, budget)`, which is removed: for each token in order it returns the entry whose `x` matches at `d = 0`, then its descendants with `d` their depth below it, so `{}`, `[]`, a scalar and a missing node are four answers, as `jsonb` gives them (#1356). The budget counts rows across all the tokens. `json_tree_children(doc, token)` and `json_tree_child_count(doc, token)` lose their `gates` argument and take the token of any node; `json_tree_child_count` of a token that names no node is NULL, as `jsonb_array_length` of a missing path is (it was 0), and so is the sealed root's, whose top-level fields chain from nothing. `eql_v4_internal.json_tree_child_token` is replaced by `json_tree_member_token`, `json_tree_element_token`, `json_tree_self_tag`, `json_tree_hit_token` and `json_tree_index`, which maps every entry's `x`, and every chained entry's `p`, to its position in `sv`; `json_tree_by_parent` is removed. The chain primitives carry the `eql-inline-critical` marker, so the post-install step leaves their `search_path` unpinned and the planner inlines them: pinned, every probe of a walk was a full SQL-function call, which was most of a read's cost. + +A wildcard (`$.items[*].price`) is expanded by the client into one token per position below a bound, 64 by default, plus a probe at the bound; a row where the probe finds an element fails the read with the bound rather than return part of the list, walked or fallen back to the sealed root. A read of `$` is legal under the sealed root and returns the root entry, which opens to the whole document. Stored documents grow by about a tenth in characters (+9.8% on a nested document, +9.4% on a flat one). `JsonHeader::FORMAT_VERSION` and the document's `v` are unchanged. In `eql-bindings`, `JsonTreeEntry` gains `x` and `JsonTreeSubtree` opens to `Option`; in Stack Encrypt, `JsonSubtreeKey` carries the token list (`tokens()`, `probes()`, `bound()`), `KeysetCipher::json_subtree_key_with_bound` sets the bound, `Error::JsonWildcardTruncated` and `TermError::JsonWildcardTooWide` are new, and `TermError::JsonSealedRoot` is removed. What the database learns is in `docs/reference/json-tree-leakage.md`; the design and the decisions behind it are in `docs/plans/2026-10-17-json-tree-index.md`, "Design change (2026-10-24)". diff --git a/.changeset/eql-json-tree-domain.md b/.changeset/eql-json-tree-domain.md new file mode 100644 index 0000000000..5089199504 --- /dev/null +++ b/.changeset/eql-json-tree-domain.md @@ -0,0 +1,7 @@ +--- +"@cipherstash/eql": minor +--- + +**EQL v4 gains the `json_tree` domain family: `public.eql_v4_json_search`, an encrypted JSON document stored as one entry per node, with `@>` and `<@` that agree with PostgreSQL's own `jsonb @>` across array elements.** The family is new beside `public.eql_v4_json` and is not a port of the v3 SteVec surface: it is what Stack Encrypt's JSON index writes. A document's entries each carry a path selector `s` and a value selector `vs` (containment is a set comparison over the pair), the node's own ciphertext `c` (its label, kind and scalar value; a document's ciphertext is linear in its size, where a SteVec document repeats every subtree at every level), and a token chain (`p`, `w`, `o`) that lets core PostgreSQL walk the subtree under a node from one client-derived token: `eql_v4.json_tree_subtree(doc, token)`, `json_tree_subtree_at(doc, token, selector)`, `json_tree_children` and `json_tree_child_count`. By default the root is sealed, so no query can hand the server a token for the whole column. Containment projects a stored document into an element-nested shape from its group tags (`n`, `g`), `eql_v4.json_tree_query(doc)`, and compares it with the needle (`eql_v4.query_json`) by native `jsonb @>`, so each needle array element must fit inside one stored element, which closes the cross-element false positives of selector-set containment (#1231) for this family; a GIN index on `(eql_v4.json_tree_query(col)::jsonb) jsonb_path_ops` serves it. `->` by selector returns an entry that opens on its own (`public.eql_v4_json_entry`, with the header and ordinal grafted), and `eql_v4.query_json_leaf` orders an extracted number or string leaf with `<`, `<=`, `>`, `>=`. Every other native jsonb operator on the column is blocked, as on the other EQL domains. EQL v4 only (`-- ONLY EQL VERSION: 4`); the v3 bundle's SQL is unchanged. The `eql-bindings` crate carries the hand-written `v4::json_tree` types with Stack Encrypt's `EncryptTarget` for the document and `DecryptSource` for the document and the entry. + +Why. Stack Encrypt had no JSON index: the operators (`Contains`, `ContainedBy`, `AtPath`) were declared and answered by nothing, and the v4 JSON wire format was unconstrained by anything shipped. This is Phase 1 and 2 of the `json_tree` index's phased plan (#1249), implemented against `docs/plans/2026-10-17-json-tree-index.md`, whose "Implementation notes" section records where the code deviates from the design. diff --git a/.changeset/eql-json-tree-element-match.md b/.changeset/eql-json-tree-element-match.md new file mode 100644 index 0000000000..3d41291e79 --- /dev/null +++ b/.changeset/eql-json-tree-element-match.md @@ -0,0 +1,9 @@ +--- +"@cipherstash/eql": minor +--- + +EQL v4 `json_tree`: a predicate on one array element, `eql_v4.json_tree_element_match(col, $1::eql_v4.query_json_elements)` (#1440). + +`exists($.contacts[*] ? (@.relationship == "Sibling" && @.calls > 5))` asks for one contact that is both. On a `public.eql_v4_json_search` column the nearest query, `@>` for the relationship and an ordering over `eql_v4.json_tree_path_query` for the calls, can be answered by two different contacts, so it returned more rows than the plaintext query. The new function answers the element-scoped question with one operand, the new domain `eql_v4.query_json_elements`, which Stack Encrypt's `element_match` query operator derives: for each field of the element, the tokens of a subtree read of its path and its bounds. Every field must be at a path the column orders, and equality is the ordering term's, so text compares case- and accent-folded and integers past 2^53 can tie. A row whose array is longer than the bound the operand was derived to raises `invalid_parameter_value` rather than answer over part of the array. + +`eql_v4.json_tree_subtree_indexed(col, tokens, budget)` is the subtree read with `k`, the place in `tokens` of the token whose node each row sits in, which pairs the fields of one element. `eql_v4.json_tree_subtree` now returns its rows without `k`, and is otherwise unchanged. diff --git a/.changeset/eql-json-tree-extracted-entry-check.md b/.changeset/eql-json-tree-extracted-entry-check.md new file mode 100644 index 0000000000..04662ee6cc --- /dev/null +++ b/.changeset/eql-json-tree-extracted-entry-check.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": patch +--- + +EQL v4 `json_tree` (unreleased): the client now checks that what `->` and the subtree walks return is what it asked for. Every entry of a stored document is sealed under its own path selector and position, so any entry of the row opened, and a database could answer `doc -> s($.salary)` with the row's `$.bonus`, or with the sealed root (the whole document), or splice other entries into a walk. In the `eql-bindings` crate an entry `->` returned now opens through the selector that asked for it, `JsonTreeExtracted::from_selector(&selector, entry)`, which refuses an entry carrying any other selector; `JsonTreeEntry` no longer opens on its own. A walk's rows, opened through `JsonTreeSubtree::from_key(&key, rows)` as before, are each checked against the key's path: the node a gated walk reaches must carry the path's selector and position, every other row the selector of its parent's path and its own label, and the rows must follow each other in the document with no gap. A refusal is `stack_encrypt::Error::JsonWrongEntry`. Not checked, by design: which row of the column an entry comes from (ADR 0010). The SQL is unchanged. diff --git a/.changeset/eql-json-tree-match.md b/.changeset/eql-json-tree-match.md new file mode 100644 index 0000000000..5e9eb11d9a --- /dev/null +++ b/.changeset/eql-json-tree-match.md @@ -0,0 +1,9 @@ +--- +"@cipherstash/eql": minor +--- + +EQL v4 `json_tree`: a whole filter as one parameter, `eql_v4.json_tree_match(col, $1::eql_v4.query_json_predicate)` and `col @@ $1::eql_v4.query_json_predicate` (#1441). + +An application that compiles a filter language into SQL targets `jsonb_path_match(col, $1, $2)` on a plaintext column: one predicate, one set of values. On a `public.eql_v4_json_search` column each question is its own operator, so the same filter had to be assembled by hand, one operand per leaf. The new domain `eql_v4.query_json_predicate` is a boolean tree (`and`, `or`, `not`) whose leaves are the operands those operators already take (a `contains` needle, an `exists` selector, `cmp` ordering bounds and an `elements` predicate), each checked by its own domain's rule, and `eql_v4.json_tree_match` evaluates it with SQL's three-valued logic, the answer the hand-written WHERE gives. Stack Encrypt's `match` query operator compiles a jsonpath predicate in the subset the terms can answer into the tree. The tree is evaluated inside a function, so it filters a scan and engages no index; the operators written out per leaf are the fast path. The operand must carry its type: an untyped operand on the right of `@@` is refused as ambiguous, and `@@` with a `jsonpath` is still blocked. + +`eql_v4.json_tree_element_match` now reads an opened document through `eql_v4_internal.json_tree_element_match_opened`, which `json_tree_match` shares; its answers are unchanged. diff --git a/.changeset/eql-json-tree-open-one-child.md b/.changeset/eql-json-tree-open-one-child.md new file mode 100644 index 0000000000..90ecf96fd1 --- /dev/null +++ b/.changeset/eql-json-tree-open-one-child.md @@ -0,0 +1,12 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package, can now decrypt one child of a JSON node on its own. A read of one child no longer needs the parent's whole subtree. + +- Your app pairs each entry that `eql_v4.json_tree_children` returned with the parent's `JsonSubtreeKey`, through `JsonTreeChild::from_key(&key, entry)`. +- Decrypting checks that the entry is a child of that parent. +- Your app decrypts into a `JsonPlaintext` for the child's value. Decrypt into a `JsonChildPlaintext` for its key or index too. +- A child with members of its own does not decrypt alone. Read it through `JsonTreeSubtree`. + +The EQL v4 JSON tree reference describes the child read. The stored format and the SQL bundle do not change. diff --git a/.changeset/eql-json-tree-ordinal-chain.md b/.changeset/eql-json-tree-ordinal-chain.md new file mode 100644 index 0000000000..11964b9522 --- /dev/null +++ b/.changeset/eql-json-tree-ordinal-chain.md @@ -0,0 +1,13 @@ +--- +"@cipherstash/eql": minor +--- + +EQL v4 `json_tree` (unreleased): the token chain is derived by ordinal and the walk probes to the first miss. + +A stored entry now carries four fields, `s`, `c`, `p` and `op`. The value selector `vs` lives only in the document's projection `q`, which the engine now reads back as the projection instead of rebuilding it from the entries; the group tags `n` and `g` are gone with it, since nothing read them once `q` was stored. The wrapped token `w` and the ordinal `o` are gone too: a child's token is `H("t" ‖ t(parent) ‖ s ‖ LE32(o))`, `s` being the child's own selector, which the server derives as it walks, and the ordinals under a node are dense from zero, so the walk probes them in turn and stops at the first miss. A subtree of `N` nodes costs about `2N` probes (a SHA-256 and a lookup each) and `N` token hashes whatever the document's width, where it cost a probe for every ordinal up to the document's widest node at every node visited. The entry validator accepts the four fields only, so a document written by the earlier build of this unreleased family is refused. + +The client can derive a token only for a chain head and the array positions that directly follow it, since an object member's ordinal is a rank among its siblings' keys. `JsonSubtreeKey::gates()` gives the rest of a path as one gate per step, a selector, or `#n:` for an array position with the array elements' selector, and `eql_v4.json_tree_subtree_at(doc, token, gates text[], budget DEFAULT 64)` walks them, replacing the earlier `json_tree_subtree_at(doc, token, selector, budget)`. `json_tree_children` and `json_tree_child_count` take the same `gates`, optional and empty by default. A gated walk returns the node the gates reach with `d = 0` and its descendants beneath it, so a wildcard reaches several nodes and opens as a list; `json_tree_subtree(doc, token, budget)` is now `json_tree_subtree_at` with no gates and still returns the descendants of the token's node from `d = 1`. Past the budget a walk still returns the sealed root alone, with `j = 0` and `d = 0`. `eql_v4_internal.json_tree_unwrap`, `json_tree_xor16` and `json_tree_fanout` are removed; `eql_v4_internal.json_tree_child_token(token, s, o)` is added. Binding the child's selector into its token, and the element selector into a position gate, is what makes a position name an array element only: an ordinal alone is an element's position or an object member's rank, so in a row whose node at the path is an object, `$.a[0]` would otherwise reach the member that ranks first, where `jsonb` has no node. + +**Byte encodings.** Every field the SQL compares, derives or decodes is padded standard base64, as PostgreSQL's `encode(x, 'base64')` writes it: the selectors `s`, the `s` and `vs` pairs of `q`, the parent tag `p`, the ordering term `op`, and the tokens and gates `json_tree_subtree_at`, `json_tree_children` and `->` take, where they were hex; the header `h` was base64 already. The ciphertext `c`, which no SQL function decodes, is RFC 1924 base85. The parent tag `p` is the first eight bytes of its hash, since it is a lookup key within one document and nothing authenticates through it. `eql_v4_internal.json_tree_ope_cllw` is added for `eql_v4.ord_term`, because the `ope_cllw(jsonb)` the scalar types share reads hex. A document written by the earlier build of this unreleased family is refused by the engine. In `eql-bindings` each json_tree wire type names its encoding, holding an `encoding::Base64Text` or, for `c`, an `encoding::Base85Text`; the wire form is the same string. The encoding type guarantees its text is in that encoding: a value is made only by `encode`, from bytes, or by deserializing, which decodes the text and refuses text that is not in the encoding, so a payload with a field in the wrong encoding fails to deserialize. Re-encoding 1,000 stored rows of each benchmark corpus: a nested document measures 22% smaller on disk (`pg_column_size` 40,808 to 31,894 bytes) and a flat one 12% (1,596 to 1,398). + +Measured on 10,000 and 100,000 rows of a nested corpus (about 213 entries a document), query-only medians: subtree walks 30 to 55% faster (a 122-entry subtree walked out, 23 ms to 11 ms), `json_tree_children` and `json_tree_child_count` 6 to 9%, a stored nested document 25% smaller (heap 810 MB to 621 MB at 10,000 rows), containment and field queries unchanged within the run's noise. diff --git a/.changeset/eql-json-tree-owned-reads.md b/.changeset/eql-json-tree-owned-reads.md new file mode 100644 index 0000000000..f1fe20f5bd --- /dev/null +++ b/.changeset/eql-json-tree-owned-reads.md @@ -0,0 +1,12 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: the parts of a `JsonSearch` document now decrypt through the owned API. + +- `JsonTreeExtracted`, the entry `->` returns, implements `DecryptSource`. +- `JsonTreeSubtree`, the rows of a subtree read, implements `DecryptSource` for `JsonPlaintext`, `Option` and `Vec`. +- The decrypted value is a `JsonPlaintext`, which is wiped when it is dropped. +- The context is required. Pass the document's column. For a document that is a field of a record with scopes or bindings, pass the column, then those scopes and bindings. + +The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/.changeset/eql-json-tree-planner-and-leakage.md b/.changeset/eql-json-tree-planner-and-leakage.md new file mode 100644 index 0000000000..7479de1cc1 --- /dev/null +++ b/.changeset/eql-json-tree-planner-and-leakage.md @@ -0,0 +1,5 @@ +--- +"@cipherstash/eql": patch +--- + +EQL v4 `json_tree` (unreleased): the reference docs gain "What an encrypted JSON tree reveals" (`docs/reference/json-tree-leakage.md`), one page on what a stored row shows the database at rest (including the row's shape, which the stored depth-first entry order gives away), what each query type hands it, what is and is not authenticated, and the side-by-side with v3 `ste_vec`. The encryption test suite now holds the planner to the GIN and btree indexes with every setting at its default, on inline and TOASTed documents, for one-shot and prepared statements, and CI runs that suite on every supported PostgreSQL version. diff --git a/.changeset/eql-json-tree-walk-and-projection.md b/.changeset/eql-json-tree-walk-and-projection.md new file mode 100644 index 0000000000..e9dcc6e2be --- /dev/null +++ b/.changeset/eql-json-tree-walk-and-projection.md @@ -0,0 +1,15 @@ +--- +"@cipherstash/eql": minor +--- + +**The `json_tree` family's read path no longer pays for the document's size per query.** Three changes to the EQL v4 `json_tree` SQL, each measured (cipherstash/benches, `report/JSON_TREE_COMPARISON.md` at 57abcf9) on a 10,000-row corpus of nested documents (about 220 nodes each) where the shipped surface was one to four orders of magnitude behind native `jsonb`: + +- **A stored document carries its own containment projection, `q`.** The client writes the document's `{s, vs}` pairs nested by array element beside `sv`, and `eql_v4.json_tree_query(doc)` now reads that field instead of rebuilding the projection from the group tags on every call. The GIN index recheck, which runs the projection once per candidate row, was the whole cost of `@>` on a nested document: 75 ms for ten rows, 16 s for a two-thousand-row result set, 44 s to build the index on 10,000 rows. With the projection stored the same queries measure in the low milliseconds and the index builds in seconds. `json_tree_query` returns `jsonb` rather than the needle domain, since the domain's CHECK would run per recheck; the document's own CHECK validates `q` when the row is written. It is a plpgsql function costed at 1000 rather than an inlinable SQL one: inlined to `value -> 'q'` the planner costs the filter as one operator, and a column of large documents is TOASTed out of the heap, so a sequential scan over it looked nearly free and was chosen over the GIN index while in fact decompressing every row (1.5 s for a one-row match on 10,000 rows; 0.5 to 0.7 ms through the index). The index expression is `(eql_v4.json_tree_query(col)) jsonb_path_ops`; the `::jsonb` cast earlier guidance wrote is harmless and no longer needed. **Wire change:** `q` is required in `public.eql_v4_json_search`, and a document written by the earlier build of this unreleased family is refused by the domain CHECK. +- **The token-chain walk reads the document once.** `json_tree_subtree`, `json_tree_subtree_at`, `json_tree_children` and `json_tree_child_count` computed each parent tag inside a scan of `sv`, once per (node, ordinal, entry); a 244-entry subtree took ten seconds. The walk now builds one map of the document's entries keyed by parent tag and looks each computed tag up in it, so a level costs its fan-out in SHA-256 evaluations and the document is never scanned per node. The same subtree walks out in 23 ms; `children` and `child_count` in 1.6 ms. The walk is also bounded by the document's size, so a stored document whose unauthenticated chain fields claim a huge ordinal, or loop back to an ancestor, can no longer keep a query running until `statement_timeout`. +- **A walk has a budget, and past it returns the sealed root.** `json_tree_subtree(doc, token, budget DEFAULT 64)` and `json_tree_subtree_at(doc, token, selector, budget DEFAULT 64)` stop once the subtree exceeds `budget` entries and return the root entry alone, with `d = 0`, when the document's root is sealed: the root's ciphertext is the whole document at about the plaintext's size, where the walk returns some four hundred characters per entry and pays the fan-out in hashes per node, so past a dozen or so entries the whole document is cheaper on both sides. The client opens the root and takes the walked path over it, and gets what the walked rows open to. The rows are opened through the key that keyed the walk, which carries the path it was derived from and knows from its gates which walk the rows came from: `key.open(rows)` in `stack-encrypt`, `JsonTreeSubtree::from_key(&key, rows)` in `eql-bindings`. Rows cannot be opened without it, so a document that grows past the budget does not break a caller. A budget of `0` never falls back; a token that names no node still yields no row; a document whose root is not sealed is always walked out. + +Also: `eql_v4.json_tree_path_query_first`, the function `->` and the ordering comparisons extract through, is costed at 1000 so a prepared statement's generic plan keeps the functional btree on `eql_v4.ord_term(col -> sel)` instead of filtering a sequential scan (16.9 ms down to 0.11 ms after the fifth execution). `eql_v4_internal.json_tree_group`, the server-side projection builder, is removed. + +The `eql-bindings` crate's `JsonTreeDocument` gains the `q` field and `JsonTreeSubtree` becomes a struct of the rows and the key that keyed the walk; `stack-encrypt`'s `JsonDocument` writes `q` on the wire and ignores it on the way in, `JsonPath::select` evaluates a path over a value, and `JsonSubtreeKey::path` and `open`, `JsonSubtree::path` and `is_sealed_root` carry the fallback. EQL v4 only; the v3 bundle is unchanged. + +**The leaf ordering term `op` is opt-in per path.** A stored leaf carried the order-preserving term on every number and string, about 80 bytes each and the largest field of a nested document, whether or not anything ordered by it. Now the JSON index's options name the paths that order (`{"json": {"ordered": ["$.age", "$.orders[*].total"]}}` on the data plan; `JsonOptions::ordering([...])` in Rust), a wildcard covering every element of an array, and no path is ordered by default. A position in an ordered path (`$.scores[2]`), or in the path an ordering asks at, is refused: the comparison extracts by selector, which reads a position as the wildcard and reaches the first element, never the one named. An ordering query at a path the index does not order is refused before any key loads rather than silently matching no row. The SQL is unchanged: `eql_v4.ord_term` was already NULL for a leaf without a term. `eql-bindings` gains `v4::JsonTree`, which describes the `json_tree` encryption under options: `JsonTree::new(options).encryption()`. diff --git a/.changeset/eql-lints-own-domains.md b/.changeset/eql-lints-own-domains.md new file mode 100644 index 0000000000..e8ed05994a --- /dev/null +++ b/.changeset/eql-lints-own-domains.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': patch +--- + +`eql_v3.lints()` now judges only EQL's own `public.eql_v3_*` domains. It used to take every `jsonb` domain in `public`, so a database with another set of encrypted domains installed beside EQL v3 got thousands of false `inlinability_*` errors from the self-check. diff --git a/.changeset/eql-ore-block-256-constant-op-count.md b/.changeset/eql-ore-block-256-constant-op-count.md index ef0ac0a27c..91541933f2 100644 --- a/.changeset/eql-ore-block-256-constant-op-count.md +++ b/.changeset/eql-ore-block-256-constant-op-count.md @@ -16,6 +16,6 @@ terms now run the hash too; text comparisons now take about 18 µs whatever the operands. Multi-term (text) values now check every paired term, so a malformed or mismatched-width term after the first difference, or one paired with a NULL element, raises instead of being skipped; see -[U-001](../../docs/upgrading/v3.1.md#u-001-block-ore-text-comparisons-check-every-term) +[U-004](../../docs/upgrading/v3.1.md#u-004-block-ore-text-comparisons-check-every-term) for how to find such rows before upgrading. A timing harness is in `packages/eql/tests/timing/ore_block_256/`. diff --git a/.changeset/eql-plan-field-targets.md b/.changeset/eql-plan-field-targets.md index e1fd16c148..16c52e75f9 100644 --- a/.changeset/eql-plan-field-targets.md +++ b/.changeset/eql-plan-field-targets.md @@ -2,4 +2,4 @@ '@cipherstash/eql': minor --- -**The `eql-bindings` crate resolves an EQL type named as a string to its own Stack Encrypt plan** (`stack-encrypt` feature). `eql_bindings::encryption::targets` carries a catalog-generated table of every EQL type a data plan may name as a field target — its name across languages, family and suffix, the plaintext `ValueKind` it takes, the indexes it carries, its query twin, and whether the engine can produce it today with the reason when not — and `encrypt` / `decrypt` / `query` entry points that dispatch on the name and run the type's derived `EncryptFrom` / `DecryptInto`, resolving to the EQL value's JSON bytes through the engine's `Pending` so a guest batches it with the rest of a plan. This is the EQL half of EQL types as plan field targets (cipherstash/stack#1062): a Go data plan names `TextEq` and the guest returns the finished EQL value instead of assembling one. `TextEq` is the only producible type; every other name is refused with the plan's reason. The SQL surface and the TypeScript package are unchanged. +**The `eql-bindings` crate resolves an EQL type named as a string to its own Stack Encrypt plan** (`targets` feature, which turns on `stack-encrypt`). `eql_bindings::encryption::targets` carries a catalog-generated table of every EQL type a data plan may name as a field target — its name across languages, family and suffix, the plaintext `ValueKind` it takes, the indexes it carries, its query twin, and whether the engine can produce it today with the reason when not — and `encrypt` / `decrypt` / `query` entry points that dispatch on the name and run the type's derived `EncryptTarget` / `DecryptSource`, resolving to the EQL value's JSON bytes through the engine's `Pending` so a guest batches it with the rest of a plan. This is the EQL half of EQL types as plan field targets (cipherstash/stack#1062): a Go data plan names `TextEq` and the guest returns the finished EQL value instead of assembling one. Every target is an `eql_v4_*` domain. Every type in the table is producible today. A name the table marks as not producible is refused with its reason. The SQL surface and the TypeScript package are unchanged. diff --git a/.changeset/eql-remove-structural-traits.md b/.changeset/eql-remove-structural-traits.md new file mode 100644 index 0000000000..ec53add9c4 --- /dev/null +++ b/.changeset/eql-remove-structural-traits.md @@ -0,0 +1,12 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: the EQL v4 types no longer implement Stack Encrypt's older traits `EncryptFrom` and `DecryptInto`. Stack Encrypt removed them, with `encrypt_as`, `decrypt_as`, the plan builder and the query chain. + +- Every type keeps `EncryptTarget` and `DecryptSource`. Write with `value.encrypt_into_with_context(&keyset, column)` and read with `P::decrypt_from_with_context(stored, &keyset, column)`. +- A typed query is a field reference of a derived record, such as `EncryptedMember::EMAIL.eq("bob").encrypt(&keyset)`. +- A JSON document is a `JsonPlaintext`, not a `serde_json::Value`. A typed JSON query is a document field's reference query, such as `EncryptedCustomer::PROFILE.at().age().gt(30).encrypt(&keyset)`. +- `JsonTree` no longer implements `stack_encrypt::target::Layout`. `encryption()`, `index()` and `specs()` are its own methods. + +The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/.changeset/eql-target-match-options.md b/.changeset/eql-target-match-options.md new file mode 100644 index 0000000000..49368aa914 --- /dev/null +++ b/.changeset/eql-target-match-options.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**`eql-bindings` says which match options an EQL type's filter is built under** (`targets` feature). `Target::match_options()` returns `EqlMatch`'s options for a type with a match index (`TextMatch`) and `None` otherwise, so Stack Encrypt can answer `matches` through the type's query twin: it cuts the query's tokens for `verify` exactly as the stored filter was cut. The SQL surface and the TypeScript package are unchanged. diff --git a/.changeset/eql-text-equality-transcoding.md b/.changeset/eql-text-equality-transcoding.md index 969aa9653b..e3aae722e2 100644 --- a/.changeset/eql-text-equality-transcoding.md +++ b/.changeset/eql-text-equality-transcoding.md @@ -2,4 +2,4 @@ '@cipherstash/eql': minor --- -**Rust `TextEq` and `TextEqQuery` support Stack Encrypt's target-directed API behind the `stack-encrypt` feature.** The stored table and column identifier supplies the encryption context; native ciphertext and equality terms are transcoded into EQL payloads while Vitamin C owns plaintext encoding. This is a new producer profile with exact string equality, independent of existing cipherstash-client ciphertext and terms. Query operands carry no recoverable ciphertext. +**Rust `eql_bindings::v4::text::{TextEq, TextEqQuery}` support Stack Encrypt's target-directed API behind the `stack-encrypt` feature.** Stack Encrypt writes EQL v4 only, so the `eql_v3` types carry no Stack Encrypt traits. The stored table and column identifier supplies the encryption context; native ciphertext and equality terms are transcoded into EQL payloads while Vitamin C owns plaintext encoding. This is a new producer profile whose string equality compares text in Unicode 16 NFC without folding case, independent of existing cipherstash-client ciphertext and terms. Text holding a code point unassigned in Unicode 16 is refused, when it is stored as well as when it is queried. Query operands carry no recoverable ciphertext. diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md new file mode 100644 index 0000000000..f584e3cf50 --- /dev/null +++ b/.changeset/eql-types-as-record-fields.md @@ -0,0 +1,14 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: an EQL v4 type can now be a field of a Stack Encrypt record. + +- A `#[derive(EncryptTarget, DecryptSource)]` record with `struct = ..` can have fields such as `email: TextEq` or `profile: JsonTreeDocument`. The field's column is the record's scope and the field's name, so `scope = "members"` and the field `email` store `{"t": "members", "c": "email"}` in `i`. +- With no scope and no binding, a field writes the same terms as the type written on its own under that column, and as a data plan that names the type. A data plan is how the Go module writes the type. +- A record can list a scope or a binding, such as `scope(tenant: u64)` or `bind(row: u128)`. The terms of an EQL field then derive under the column and the scope. The ciphertext is sealed under the column, the scope and the binding. A field of any other type works the same way. `i` stores the column alone, so the reader supplies the scope and the binding again. The same is true of an EQL field of a record nested in another. +- A query from a field reference takes the record's scope with `.scope(..)`. It gives the term of the values stored under that scope. +- A data plan that names an EQL type takes a scope and a binding in the same way. So a Go struct with an `encrypt_into` field now seals through `cipher.Scope(..).Bind(..)`, where it was refused. +- `JsonTreeDocument` now implements `EncryptTarget` and `DecryptSource` for `JsonPlaintext`. It encrypts under the default options, with the column as its context. + +The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/.changeset/eql-v4-bindings.md b/.changeset/eql-v4-bindings.md new file mode 100644 index 0000000000..f3c979fec1 --- /dev/null +++ b/.changeset/eql-v4-bindings.md @@ -0,0 +1,9 @@ +--- +'@cipherstash/eql': minor +--- + +**The `eql-bindings` crate has an `eql_bindings::v4` module, with the `stack-encrypt` feature: payload types for the EQL v4 domains.** EQL v4 is the v3 SQL installed under a second name (ADR-0002), for values written by Stack Encrypt, so the module exists only with that feature and its types derive Stack Encrypt's traits without a further gate. The module is generated from the same catalog as `v3`, with `eql_v4_*` domain names and `"v": 4`. `SchemaVersion` is now generic over the version it admits: `v3::SchemaVersion` is `SchemaVersion<3>` and `v4::SchemaVersion` is `SchemaVersion<4>`, each refusing the other's payloads, and plain `SchemaVersion` still means v3. Only v4 types derive Stack Encrypt's `EncryptTarget` and `DecryptSource`, and the Stack Encrypt target table (now `eql_bindings::v4::targets`) names v4 domains. Besides `TextEq`, Stack Encrypt now produces the storage-only types `Text`, `Integer`, `Bigint`, `Boolean`, `Real` and `Double`, and `TextMatch` (3-grams, `k = 6`, a 2048-bit filter, pinned as `eql_bindings::encryption::EqlMatch`; text shorter than three characters is refused, stored or queried, and only `stored @@ query` matches until #1171 is fixed), from the Rust primitives `i32`, `i64`, `bool`, `f32` and `f64`; the Go SDK's `encrypt/eql` table marks them producible. Stack Encrypt also produces the number equality types `IntegerEq`, `BigintEq`, `RealEq` and `DoubleEq`, whose `=` compares as PostgreSQL compares the plain types: an integer has one term whatever its width, and for floats `-0.0 = 0.0` and `NaN = NaN` (ADR-0002's semantic baseline). Every type it cannot produce yet names the issue that tracks its blocker. A Rust caller queries those types through a field reference of a derived record: `EncryptedMember::EMAIL.eq(v).encrypt(&keyset)` on a field typed `TextEq` or a number equality type returns the type's query twin, and `.matches(text)` on a field typed `TextMatch` returns a `MatchTwin` with `verify` and `target_limit`, the same bytes and answers as the data path the Go SDK uses (`eql_bindings::encryption::query`; an operator a type does not answer does not compile). The by-name target entry points (`eql_bindings::encryption::targets::encrypt`, `decrypt` and `query`) take the plaintext as a borrowed `dynamic::frame::Frame`, one value as its transport frame, rather than a value tree, and `decrypt` opens into `dynamic::frame::OwnedFrame`, vitaminc's owned frame (Stack Encrypt re-exports both). They, and the generated `v4::targets` table, need the new `targets` feature, which turns on `stack-encrypt` and Stack Encrypt's `dynamic` feature. `stack-encrypt` alone no longer builds Stack Encrypt's `dynamic` layer, so a Rust program using the typed v4 types through `encrypt_into` doesn't compile it. + +**The EQL v4 SQL bundle has range query domains and `eql_v4.between`, so a `BETWEEN` query is one operand.** The v4 bundle (`cipherstash-encrypt-v4.sql`) is built from this source and reaches users as the `eql-v4-install.sql` attached to each Go release; neither the npm package nor the crate ships it, and the v3 SQL they ship does not change. Every ordered family has one range query domain per order term, beside its single-bound ones: `eql_v4.query_integer_range_ore` beside `eql_v4.query_integer_ord_ore`, `eql_v4.query_integer_range_ope` beside `eql_v4.query_integer_ord_ope`, and the same for `smallint`, `bigint`, `date`, `timestamp`, `numeric`, `text`, `real` and `double`. A range is `{"v": 4, "i": …, "lo": , "hi": }`: each bound is the single-bound domain's `ob` (ORE) or `op` (OPE) value, in a `{v, i, lo, hi}` envelope. Stack Encrypt does not build that envelope yet; it will need to when the ordered types become producible. `eql_v4.between(column, range)` is true when the column's order term lies between the bounds, both included, and has an overload for every ordered column domain with the range of the term it stores (`_ord_ore` and `_search_ore` take the ORE range; `_ord`, `_ord_ope` and `_search` the OPE one). It is an inlinable SQL function, so a btree on the column's order term (`eql_v4.ord_term_ore(col)` or `eql_v4.ord_term(col)`) serves it as one index range scan. Write it schema-qualified (`BETWEEN` is an SQL keyword, so a bare `between(...)` does not parse), and cast the range to its exact domain (`$1::eql_v4.query_integer_range_ore`): an uncast `$1`, a `jsonb` parameter, or a range of another term or family fails with SQLSTATE 42725 ("function … is not unique"), unlike the single-bound operators, which resolve an untyped `$1`. An ORE range scan needs the `ore_block_256` btree operator class, which the installer creates only as a superuser; on an install without it (Supabase and other non-superuser roles), the ORE range domains are disabled like the single-bound ORE domains, and a value cast to one raises `feature_not_supported` naming the family's OPE range. In the crate, `eql_bindings::v4` (`stack-encrypt` feature) has a type for each range domain (`IntegerRangeOreQuery`, `TextRangeOpeQuery`, …, listed by `v4::all_range_query()`). EQL v3 has no range domains: its SQL and types are unchanged (ADR-0009, decision 7). + +Nothing a released version shipped has changed. The v3 types, the v3 SQL and the TypeScript package are as they were; the `stack-encrypt` derives on the v3 text types and the `v3::targets` module were added after the last release and are moved to v4 here, not removed from a release. diff --git a/.changeset/eql-v4-block-ore-types.md b/.changeset/eql-v4-block-ore-types.md new file mode 100644 index 0000000000..4f556dda5e --- /dev/null +++ b/.changeset/eql-v4-block-ore-types.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**EQL v4 compares ore-rs's 6-bit block ORE, and Stack Encrypt produces the block ORE types `IntegerOrdOre`, `SmallintOrdOre`, `BigintOrdOre`, `RealOrdOre`, `DoubleOrdOre`, `TextOrdOre` and `TextSearchOre`.** A v4 `ob` term is one ore-rs ciphertext: the fixed-width scheme for numbers, the chained scheme for text (padded to a power-of-two length bucket of at least 16 bytes). The v4 bundle names its block ORE objects `ore_block_v2` (`eql_v4_internal.ore_block_v2_term`, `compare_ore_block_v2_term`) and compares them with a new comparator that checks each term's shape, raises on malformed or mismatched terms, and runs a constant operation count for terms of one shape. This change leaves the EQL v3 bundle as it was: its `ob` is still cipherstash-client's 8-bit block ORE under `ore_block_256`. See [U-002](../../docs/upgrading/v3.1.md#u-002-the-block-ore-term-is-ore-rss-6-bit-scheme): the comparator refuses the 8-bit terms the previous `eql_v4` bundle compared, so rows or operands holding them must be written again through Stack Encrypt. diff --git a/.changeset/eql-v4-date-timestamp-numeric.md b/.changeset/eql-v4-date-timestamp-numeric.md new file mode 100644 index 0000000000..c7899b0953 --- /dev/null +++ b/.changeset/eql-v4-date-timestamp-numeric.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**Stack Encrypt produces the EQL v4 date, timestamp and numeric types `Date`, `DateEq`, `Timestamp`, `TimestampEq`, `Numeric` and `NumericEq`** (`eql-bindings`, `stack-encrypt` feature). Their Rust plaintexts are Vitamin C's `Date`, `Timestamp` and `Decimal`, which `stack_encrypt::value` re-exports, re-exported again as `v4::plaintext::Date`, `Timestamp` and `Decimal`. A `Date` is built from a jiff `civil::Date`, a `Timestamp` from a jiff `Timestamp`, and a `Decimal` from a rust_decimal `Decimal`, and each is read back as that type. None is `Clone`, and each is wiped when it is dropped. The `stack-encrypt` feature turns on jiff and rust_decimal, so the three types exist whenever it is on. Dates are from `-009999-01-01` to `9999-12-31`, and instants from `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`. `=` on `NumericEq` normalises the scale (`1.5 = 1.50`) and on `TimestampEq` compares to the microsecond, truncating (never rounding) the nanoseconds below it; each value decrypts as it was stored. The Go SDK's `encrypt/eql` table marks the six producible, from `encrypt.Date`, `time.Time` and `encrypt.Decimal`. diff --git a/.changeset/eql-v4-json-storage-only.md b/.changeset/eql-v4-json-storage-only.md new file mode 100644 index 0000000000..17148d622e --- /dev/null +++ b/.changeset/eql-v4-json-storage-only.md @@ -0,0 +1,14 @@ +--- +"@cipherstash/eql": minor +--- + +**Stack Encrypt can now write EQL v4's storage-only JSON type, `Json` (`public.eql_v4_json`).** A `Json` value stores a JSON document as one ciphertext, with no index: `{v, i, c}`, where `c` holds the document's JSON text sealed as one text leaf. It shows the size of the document and nothing else. Use it for a document that is stored and read back whole. `JsonSearch` stays the type for a document that is searched. + +`eql-bindings` (the Rust crate released with this package): + +- `v4::json::Json` implements `EncryptTarget` and `DecryptSource` for `v4::plaintext::JsonPlaintext`, and for an `Option` of it. `JsonPlaintext` is Stack Encrypt's wipeable JSON document (`stack_encrypt::json::JsonPlaintext`): build it with `JsonPlaintext::from(value)` or `JsonPlaintext::parse(text)`. +- The target table lists `Json` as producible, with the plaintext kind `json`, no index and no query. The by-name dispatch (`encryption::targets`) seals a document handed over as UTF-8 JSON text, in a text or bytes value, and opens it back to its text. Text that is not a document by Stack Encrypt's rules is refused before any key is requested (`TargetError::Json`, with a code and none of the text). +- On decrypt, a `c` that opens but does not hold JSON text is `Error::OpenedType`: the value was sealed as another type. +- The Go type `eql.JSON` is listed as producible too. + +Before, the table marked `Json` as not producible, because how a document becomes one sealed leaf was not decided. The SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md new file mode 100644 index 0000000000..a2bea966e3 --- /dev/null +++ b/.changeset/eql-v4-match-short-words.md @@ -0,0 +1,36 @@ +--- +'@cipherstash/eql': minor +--- + +**EQL v4's match types now index each two-letter word as a whole word, so a two-letter surname such as "Ng" is searchable** (#1309). `eql-bindings`' `EqlMatch` is the match configuration of `TextMatch`, `TextSearch`, and `TextSearchOre`. `EqlMatch` now turns on Stack Encrypt's `MatchOptions::short_words`. + +A stored value's filter contains the 3-grams of the whole text. A 3-gram is a run of three characters, such as "mik" in "Mike". The filter now also contains each word of exactly two characters, as one more token. Words are split on space, comma, semicolon, colon, and exclamation mark. + +The word token is hashed under a domain of its own. Like a 3-gram, it sets 6 positions in the same 2048-bit filter. + +- "Ng" can now be stored in `TextMatch`. Before, `TextMatch` refused it, because "Ng" has no 3-gram. +- A `TextSearch` value of "Ng" now stores a filter, not the empty filter. +- `@@` with the query "ng" finds the rows that contain the word "Ng", such as "Ng", "Mike Ng", and "NG, Anna". The query does not find "Nguyen". + +A query asks for its two-letter words only when the whole query is one two-letter word. A query of three characters or more asks for its 3-grams alone, as it would without word tokens. So "Mike Ng" finds "Mike Ng" and "Mike Nguyen". A name typed in part, such as "ke Ng" or "san fr", still finds its row. + +Every query path follows this rule, so a query's filter and its verify agree. The paths are: + +- a field reference's `matches`; +- the query twins' `EncryptTarget`; +- the by-name query dispatch that a binding runs; +- `verify`. + +A query twin's filter has a new field type, `v4::terms::QueryBloomFilter`. A query twin is the struct that contains a query's terms. The new type is the `bf` of `TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, `TextSearchQuery`, and `TextSearchOreQuery`. `QueryBloomFilter` has the JSON and JSON Schema of `BloomFilter`. Only fields of the `v4` module change, and that module is not released yet. + +Text with no token at all, such as one letter or nothing, is handled as before. `TextMatch` refuses it. The search types store it with the empty filter. + +**The v4 match format now includes short-word tokens.** A filter of text holding a two-letter word gains that word's bits; text with none derives the filter it did. EQL v4 is unreleased, so this is the format it ships with: a v4 value written by an earlier build that holds a two-letter word lacks the word's bits, and a query naming that word does not find it until the value is re-encrypted. + +**What it reveals.** Each stored value gains one more token for each two-letter word it contains. The token uses the same pseudorandom function (PRF), the same filter, and the same containment rule. No two-character piece of a longer word is indexed. + +The word token is unique to the word. Someone who groups tokens across rows can tell the rows that contain "Ng" from the rows that contain "Nguyen", and count them. Without the word token, they see only the 3-gram `" ng"` that both names share. + +A query of one two-letter word shows which word it asks for. A longer query sends no word token. + +No SQL function changes (one doc comment in the bundle is reworded), and the TypeScript types do not change. diff --git a/.changeset/eql-v4-order-term-shape.md b/.changeset/eql-v4-order-term-shape.md new file mode 100644 index 0000000000..904a2ce26d --- /dev/null +++ b/.changeset/eql-v4-order-term-shape.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**An `eql_v4` order term is one hex string, and every `eql_v4` domain checks its shape when it is written.** A block ORE term (`ob`, and the `lo` and `hi` bounds of a block ORE range) is the lowercase hex of the whole ore-rs ciphertext, `"ob": "0202…"`, where it was a one-element array. Every `eql_v4` domain carrying `ob` must now hold a string starting `0202` or `0203`, and one carrying `op` a string starting `00` or `01`: an EQL v3 term or a term of the wrong scheme is refused with `check_violation` at the write or cast, not at the first comparison. The check reads only the prefix, so its cost does not grow with the term. In `eql-bindings`, a v4 `ob` field is Stack Encrypt's `OreBlockTerm` and an `op` field its `OpeTerm`, typed by the plaintext they order (`DateOrdOre::ob` is an `OreBlockTerm`), and reading a payload checks the term's structure. This change leaves the `eql_v3` bundle as it was. A database that installed an earlier `eql_v4` bundle keeps its stored domains across an install, so it must drop its stored order domains first: see [U-003](../../docs/upgrading/v3.1.md#u-003-an-order-term-is-one-hex-string-checked-when-it-is-written). diff --git a/.changeset/eql-v4-ordered-date-timestamp-numeric.md b/.changeset/eql-v4-ordered-date-timestamp-numeric.md new file mode 100644 index 0000000000..9c7dd99294 --- /dev/null +++ b/.changeset/eql-v4-ordered-date-timestamp-numeric.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**Stack Encrypt produces the EQL v4 ordered date, timestamp and numeric types** (`eql-bindings`, `stack-encrypt` feature): `DateOrd`, `DateOrdOpe`, `DateOrdOre`, `TimestampOrd`, `TimestampOrdOpe`, `TimestampOrdOre`, `NumericOrd`, `NumericOrdOpe` and `NumericOrdOre`. A date orders by its day, a timestamp by the microsecond (truncated, as `TimestampEq`'s `=` is) and a decimal by value, so `1.5` and `1.50` order as equal. `v4::plaintext::Date`, `Timestamp` and `Decimal` are Vitamin C's types, re-exported through Stack Encrypt at the same path, with `OutOfRange` for a jiff `Timestamp` outside the range. The Go SDK's `encrypt/eql` table marks the nine producible. diff --git a/.changeset/eql-v4-ordered-ope-types.md b/.changeset/eql-v4-ordered-ope-types.md new file mode 100644 index 0000000000..27a8fb5a77 --- /dev/null +++ b/.changeset/eql-v4-ordered-ope-types.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**Stack Encrypt produces the OPE-ordered EQL v4 types `IntegerOrd`, `SmallintOrd`, `BigintOrd`, `RealOrd`, `DoubleOrd`, `TextOrd` and their `OrdOpe` twins** (`eql-bindings`, `stack-encrypt` feature). Their `op` term orders by ADR-0002's order key, so `<`, `<=`, `>`, `>=` and `ORDER BY eql_v4.ord_term(col)` compare integers by value, floats as PostgreSQL's `float8` does and text by its fold (case and accents folded). `=` on text reads `TextEq`'s equality term. `TextSearch` stays unproducible, with a reason: its query carries a match term that short text cannot make. diff --git a/.changeset/eql-v4-owned-targets.md b/.changeset/eql-v4-owned-targets.md new file mode 100644 index 0000000000..75e92d59f2 --- /dev/null +++ b/.changeset/eql-v4-owned-targets.md @@ -0,0 +1,13 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package, now supports Stack Encrypt's owned API for the EQL v4 types. + +- Every EQL v4 type that Stack Encrypt produces implements `EncryptTarget` and `DecryptSource`. Every derived query type implements `EncryptTarget`. +- A Rust program can write `email.encrypt_into_with_context(&keyset, column)` and `String::decrypt_from(stored, &keyset)`. The owned traits take the plaintext by value and wipe it. +- The by-name dispatch (`encryption::targets`) runs each type through these traits. +- An `Option` of an EQL type stores a database NULL for `None`. +- A type encrypted from an `Option` of its plaintext still seals a null, as before. + +The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/.changeset/eql-v4-smallint.md b/.changeset/eql-v4-smallint.md new file mode 100644 index 0000000000..5438f7c9eb --- /dev/null +++ b/.changeset/eql-v4-smallint.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**Stack Encrypt produces the EQL v4 types `Smallint` and `SmallintEq`** (`eql-bindings`, `stack-encrypt` feature), from `i16`. `SmallintEq`'s equality term is the integer one, so a smallint and an integer of the same value under one column share it. The `date`, `timestamp` and `numeric` types now say they wait for a choice of Rust plaintext type, not for an engine kind. diff --git a/.changeset/eql-v4-text-search-optional-terms.md b/.changeset/eql-v4-text-search-optional-terms.md new file mode 100644 index 0000000000..e59f4e40f2 --- /dev/null +++ b/.changeset/eql-v4-text-search-optional-terms.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/eql': minor +--- + +**An EQL v4 text search query carries only the terms its operator reads.** `eql_v4.query_text_search` and `eql_v4.query_text_search_ore` now require at least one of their terms (`hm`, `op` or `ob`, `bf`) instead of all of them, so `col = $1` and `col < $1` work on text too short to cut a 3-gram, which has no match term. Each extractor over such a query raises (`invalid_parameter_value`) wherever it reads the operand when the query lacks the term it reads, or holds it as JSON `null` or an empty array, naming the domain, the term and the operators that compare it: `=` without `hm`, `<` without `op`, `@@` without `bf`. So a missing term raises rather than matching no row silently, or every row; the raise is at evaluation, so a generic plan that never reaches the predicate returns no row and no error. Stored `eql_v4_text_search` values still carry every term. This change leaves the `eql_v3` domains as they were. With it, **Stack Encrypt produces `TextSearch`** (`eql-bindings`, `stack-encrypt` feature): `TextSearchQuery`'s terms are `Option`s, built per index through `TextSearchEqualityQuery`, `TextSearchOrderQuery` and `TextSearchMatchQuery`, and the stored value carries every term: text too short for a 3-gram stores the empty filter (`"bf": []`, the new `v4::terms::SearchBloomFilter` field type), so `=` and `<` find it and no `@@` query does, where `TextMatch` still refuses it. `TextSearchQuery`'s `Option` terms and `TextSearch`'s `SearchBloomFilter` change the fields of the unreleased `v4` module only; no published `eql-bindings` has it. See [U-001](../../docs/upgrading/v3.1.md#u-001-a-text-search-query-carries-only-the-terms-its-operator-reads) for what a hand-built query must carry, the raise, and the rollback. diff --git a/.changeset/stack-auth-crate-0-44.md b/.changeset/stack-auth-crate-0-44.md new file mode 100644 index 0000000000..d82232e333 --- /dev/null +++ b/.changeset/stack-auth-crate-0-44.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/auth': patch +--- + +The native binaries are built from the `stack-auth` crate at its new version, 0.44.0 (it was 0.43.0). The crate changes that version carries are the ones this release already lists; the version number is what lets the crate publish to crates.io beside them. The package's API is unchanged. diff --git a/.changeset/stack-auth-doc-links.md b/.changeset/stack-auth-doc-links.md new file mode 100644 index 0000000000..14dc3d0082 --- /dev/null +++ b/.changeset/stack-auth-doc-links.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/auth': patch +--- + +Fix broken links in the documentation comments of the `stack-auth` crate that this package is built from, including the address of the published list of compromised eMudhra intermediate certificates that the certificate blocklist is based on. There is no change in behaviour. diff --git a/.changeset/stack-encrypt-owned-scalars.md b/.changeset/stack-encrypt-owned-scalars.md new file mode 100644 index 0000000000..450b783af4 --- /dev/null +++ b/.changeset/stack-encrypt-owned-scalars.md @@ -0,0 +1,13 @@ +--- +--- + +Stack Encrypt's Rust scalar API now consumes plaintext and returns an opaque +`Ciphertext`, with separate methods for omitted and supplied context. Owned +`EncryptInto` / `DecryptFrom` conversions use explicit context capabilities. +The stored sealed-leaf format is unchanged. + +Low-level structural encryption and decryption use `encrypt_tree` and +`decrypt_tree`, returning and opening a tree of individually sealed leaves. + +This is a Rust-only release, versioned by release-plz from the conventional +commit. No npm package needs a version bump; EQL changes only adapt tests. diff --git a/.claude/skills/misuse-resistance/EVIDENCE.md b/.claude/skills/misuse-resistance/EVIDENCE.md new file mode 100644 index 0000000000..e6c34ef216 --- /dev/null +++ b/.claude/skills/misuse-resistance/EVIDENCE.md @@ -0,0 +1,31 @@ +# Evidence + +The studies behind each rule in [SKILL.md](SKILL.md). Cite these when a rule is challenged in review. Fuller notes, with the source of each figure, are in the vitaminc repository at `docs/research/misuse-resistance.md`. + +## Why the API carries the burden + +- **Lazar et al. 2014**, *Why does cryptographic software fail?* (APSys). Of 269 crypto CVEs, 83% were applications misusing libraries; 17% were in the libraries. The sample is CVEs tagged CWE-310 (cryptographic issues), so library bugs filed under other weakness classes are outside the count. +- **Oliveira et al. 2014**, *It's the psychology stupid* (ACSAC). Security is not part of developers' everyday heuristics. Primed developers found about twice as many vulnerabilities. +- **Acar et al. 2016**, *You get where you're looking for* (IEEE S&P). Developers using Stack Overflow produced the most functional and least secure code, and rated insecure solutions as secure. +- **Perry et al. 2023**, *Do users write more insecure code with AI assistants?* (CCS). Participants with an AI assistant wrote less secure code, including for encryption, and were more confident it was secure. +- **Elsayed et al. 2026**, *An empirical security evaluation of LLM-generated cryptographic Rust code* (arXiv:2604.27001). 23.3% of 240 samples compiled; of those, 57% had vulnerabilities, chiefly nonce reuse and hallucinated APIs. +- **Blessing et al. 2021** (arXiv:2107.04940). In eight C/C++ libraries, 37.2% of vulnerabilities were memory-safety or resource-management errors. 27.2% were cryptographic. Only 3.6% to 11.1% of the severe ones were cryptographic. The largest class is one Rust prevents when `unsafe` is absent, so `#![forbid(unsafe_code)]` is a rule here, not a preference. The study excluded memory-safe languages, so its proportions do not transfer to Rust crates directly. +- **Kern 2024**, *Developer ecosystems for software safety* (ACM Queue 22(1) / CACM 67(6)). At Google, making the ecosystem rather than the developer responsible for safety invariants, through vocabulary types and pre-submit conformance checks, took XSS and SQL injection close to zero. Developer education alone did not reduce defect rates. + +## Per rule + +| Rule | Evidence | +|---|---| +| 1. Secure by default | Fischer et al. 2021 (CCS): re-ranking search results by security raised secure and functional outcomes with no behaviour change. Green & Smith 2016: defaults safe and never ambiguous. | +| 2. Tasks, not primitives | Nadi et al. 2016 (ICSE): Java developers found crypto APIs too low-level and asked for task-based ones. Bernstein et al. 2012: NaCl's `crypto_box` offers no algorithm choices. | +| 3. Own the periphery | Acar et al. 2017 (IEEE S&P): calls into the library were mostly secure; failures came from key storage, password-based derivation, and insecure inputs copied from examples. Egele et al. 2013 (CCS): 88% of 11,748 Android apps misused crypto, through mistakes such as ECB mode, constant keys and constant IVs. | +| 4. Secrets as types | Blessing et al. 2021: 11.3% of vulnerabilities in eight crypto libraries were exposure of sensitive information, the class a secret type addresses. (Indirect: the study does not test secret types.) Memory-safety errors, the largest class at 37.2%, are a separate problem that `#![forbid(unsafe_code)]` addresses; see above. | +| 5. Invalid states unrepresentable | Russell's hard-to-misuse scale: "won't compile" outranks every runtime and documentation measure. Kern 2024 (CACM / ACM Queue): at Google, changing injection-sink APIs to require vocabulary types took XSS from tens per year per application to low single digits across all framework applications, and SQL injection to a nonissue; the residual is a tracked list of legacy exemptions. Georgiev et al. 2012 (CCS): certificate validation broke where libraries exposed confusing options. | +| 6. Promise only what you deliver | Oliveira et al. 2018 (SOUPS) and Brun et al. 2023 (TOSEM): APIs with misleading names or hidden preconditions caused vulnerabilities regardless of experience. Albertini et al. 2022 (USENIX Security): callers assumed AEAD key commitment that the primitive did not give. | +| 7. Errors reveal nothing | Padding-oracle and partitioning-oracle attacks (Len, Grubbs & Ristenpart 2021) turn distinguishable failures into plaintext recovery. | +| 8. Warn at point of use | Gorski et al. 2018 (SOUPS): API warnings nearly doubled secure outcomes; code that triggered a warning was 15 times more likely to be fixed. Gorski et al. 2020 (CHI): the five parts of a warning. Vance et al. 2018 (CHI): repeated identical warnings stop being processed. Kern 2024: exemptions survive as a counted allowlist, not as individual review judgements. | +| 9. Secure, complete examples | Acar et al. 2017: code copied from Stack Overflow was about three times more likely to be functional on the symmetric tasks, and insecure inputs in examples were copied with it. Fischer et al. 2017 (IEEE S&P): insecure Stack Overflow snippets propagated into Play Store apps. | +| 10. Keep it small | Blessing et al. 2021: about one CVE per thousand lines added to OpenSSL, with ρ = 0.8 between lines added and CVEs introduced; LibreSSL and BoringSSL removed 22% and 70% of the code and with it 25% and 40.6% of the vulnerabilities. Both forks then grew back to OpenSSL's size at Heartbleed, so minimalism needs a review step, not a founding intention. | +| 11. Evolve loudly | Holmwood 2022 (linux.conf.au): Keyczar's replacement by Tink as the model of a breaking change with a migration path. Kern 2024: the rollout is deprecate, migrate, then enforce; the old path ends as a denied lint with a counted exemption list. | + +Experience does not protect against footguns: Acar et al. 2017 found Python, security and library experience did not predict success, and Brun et al. 2023 found long-time professionals made as many mistakes as novices. diff --git a/.claude/skills/misuse-resistance/RUST.md b/.claude/skills/misuse-resistance/RUST.md new file mode 100644 index 0000000000..e9b452a679 --- /dev/null +++ b/.claude/skills/misuse-resistance/RUST.md @@ -0,0 +1,153 @@ +# Misuse resistance in Rust + +Techniques for reaching each rung of the ladder in [SKILL.md](SKILL.md). The snippets use only `std` so they show the pattern; in production, reach for a vetted crate for the secret type itself (`vitaminc-protected`, or `zeroize` plus `subtle`). Cryptographic internals are `todo!()`, so a copied snippet fails loudly instead of shipping a placeholder: do the same in your own examples. + +## Rung 1: impossible to get wrong + +Remove the parameter. If the library generates the nonce, no caller can reuse one. A random 96-bit nonce still bounds how much one key may seal: past about 2³² messages the chance of a repeat is no longer negligible (NIST SP 800-38D), so a long-lived key must be rotated, or the cipher must use a longer nonce (XChaCha20-Poly1305) or a nonce-misuse-resistant mode (AES-GCM-SIV). The caller still cannot get the nonce wrong; the library owns that limit too. + +```rust +pub struct Ciphertext { nonce: [u8; 12], sealed: Vec } + +pub struct Cipher { /* key, rng */ } + +/// Opaque: says that sealing failed, not why. +pub struct EncryptError; + +impl Cipher { + // No `nonce` argument: the cipher draws a fresh one per call. Drawing it can + // fail (the OS RNG is unavailable), so the call returns an error, not a panic. + pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Result { + let nonce = self.fresh_nonce()?; + let sealed = self.seal(&nonce, plaintext, aad)?; + Ok(Ciphertext { nonce, sealed }) + } + + fn fresh_nonce(&self) -> Result<[u8; 12], EncryptError> { todo!("draw from the CSPRNG") } + fn seal(&self, _nonce: &[u8; 12], _plaintext: &[u8], _aad: &[u8]) -> Result, EncryptError> { todo!("AEAD seal") } +} +``` + +Make the valid value the only value. Private fields plus one constructor mean every instance passed the check. A blanket implementation over a sealed trait means no downstream type can supply its own, divergent, implementation. + +```rust +mod sealed { pub trait Sealed {} } + +/// Implemented only inside this crate. +pub trait Algorithm: sealed::Sealed { const NAME: &'static str; } + +pub struct Aes256Gcm; +impl sealed::Sealed for Aes256Gcm {} +impl Algorithm for Aes256Gcm { const NAME: &'static str = "AES-256-GCM"; } +``` + +## Rung 2: won't compile + +Put the invariant in the type. State the invariant first, in one sentence a reviewer can test; a type that says "verified" without saying under which key promises more than it delivers (rule 6). + +- **Newtypes over raw bytes.** `Key([u8; 32])`, never `&[u8]`. A key, a nonce and a ciphertext should not be interchangeable. +- **Fixed-size arrays for fixed lengths.** A `[u8; 32]` argument makes the length check infallible and removes the error path; a const generic `[u8; N]` does the same for a family of sizes. Take runtime-length material through a separate, fallible `try_from_bytes` that rejects weak inputs. +- **Typestate.** Encode protocol steps as types, so the unsafe order does not type-check. Carry "by whom" in the type too: a message verified under the wrong key is then a type error, not a review question. + +```rust +use std::marker::PhantomData; + +/// The role a verifying key was loaded for. One marker per role, assigned where +/// the key is loaded from configuration, so a message verified under a key of +/// another role has another type. +pub trait Role {} +pub struct Issuer; +impl Role for Issuer {} + +pub struct VerifyingKey { /* public key */ role: PhantomData } + +pub struct Unverified { message: Vec, signature: [u8; 64] } +pub struct Verified { message: Vec, role: PhantomData } + +pub struct BadSignature; + +impl Unverified { + /// Anyone may hold a message they received; only `verify` turns it into a `Verified`. + pub fn new(message: Vec, signature: [u8; 64]) -> Self { + Self { message, signature } + } + + // The caller supplies a key, never the check: the library owns the + // verification, so there is no predicate to stub out with `|_| true`. + // The result carries the key's role, so "verified" always says by whom. + pub fn verify(self, key: &VerifyingKey) -> Result, BadSignature> { + key.check(&self.message, &self.signature)?; + Ok(Verified { message: self.message, role: PhantomData }) + } +} + +impl VerifyingKey { + fn check(&self, _message: &[u8], _signature: &[u8; 64]) -> Result<(), BadSignature> { + todo!("signature verification") + } +} + +/// Only messages verified under the issuer's key can be processed. A message +/// verified under a key of another role has another type and does not compile +/// here. `Verified` has private fields, so the only way to obtain one is a +/// signature check the library performs. +pub fn process(message: Verified) -> usize { message.message.len() } +``` + +- **Consume one-shot values.** Take `self` by value for anything that must be used once (a nonce, a one-time key, a request token), so a second use is a move error. +- **Withhold dangerous traits.** A secret type implements no `Copy` (a copy has no owner to wipe it on drop), no `Default` (a default key is an all-zero key), no `Deref`, no derived `PartialEq` (it is not constant-time), no `Display`, and no `Serialize` unless through an explicitly named export type. +- **Post-monomorphisation checks.** A `const` assertion can reject a generic parameter at compile time. Use a named associated `const` item, not an inline `const { }` block: trybuild does not report inline-const failures. +- **Test the guarantee.** Every rung-2 claim gets a compile-fail test (trybuild) showing the misuse does not compile. Without one, a refactor can silently drop it to rung 6 or 7. + +## Rung 3: fails the build + +A check that blocks the merge is as strong as a type check: the mistake cannot reach `main`. A warning that nothing denies is read once, then tuned out, so it counts as rung 7. + +- `#[must_use]` on results, tags, and anything whose silent drop is a bug, with `#![deny(unused_must_use)]` in the crate root. +- `#[deprecated(note = "use X instead: ")]` names the replacement, with `#![deny(deprecated)]` once callers have migrated. +- Ship a `clippy.toml` snippet with `disallowed-methods` / `disallowed-types` for downstream users (for example, banning a non-cryptographic RNG in key-handling code). Run clippy with `-D warnings` in CI. +- Every escape hatch (`risky_*`, `hazmat`, `*_unchecked`) has an allowlist of call sites that CI checks. A new call site fails CI until a reviewer adds it, with a reason. + +## Rung 4: the simplest use is correct + +- The shortest constructor yields the secure configuration. Options exist only to make it stricter, or sit behind an explicitly named alternative. +- Prefer one function with no choices over a builder with secure defaults: a builder invites changing them. + +## Rung 5: the name says how to use it + +Name escape hatches so they are obvious and greppable: `risky_unwrap`, `risky_ref`, a `hazmat` module, an `insecure-*` feature, `*_unchecked`. Obvious, not easy: a caller who needs a legacy algorithm should find the door, and a reviewer should find every use with one search. A search is a human step, so the allowlist in rung 3 is what makes the count hold. + +## Rung 6: fails loudly at runtime + +- Return `Result` with an error that reveals nothing about the secret. Cipher failures are one opaque error: a wrong key, a wrong AAD and a tampered ciphertext are indistinguishable. +- Refuse weak input (short keys, empty contexts) at construction, once, then carry the proof in the type. +- Return errors rather than panicking on conditions that depend on a secret: a panic is an observable side channel. + +## Secret types: the full checklist + +A type holding a secret: + +- wipes on drop (`Zeroize` + `ZeroizeOnDrop`, or a wrapper that does it); +- prints an opaque `Debug`, no `Display`; +- exposes its contents only through named, greppable methods, and offers `map`-style combinators so most code never unwraps; +- compares in constant time, if at all; +- serialises only through an explicit export type; +- for process-lifetime secrets, lives in memory that is both locked against swap and excluded from core dumps, since nothing drops a static or a killed process. These are two separate protections: `mlock` keeps pages out of swap but does not keep them out of a dump, which needs its own call (`madvise(MADV_DONTDUMP)` on Linux and Android). Check that both succeeded. + +## Errors + +- `Display` and `Debug` on error types never include plaintext, keys, or values derived from them. Report the path or position (`field "email"`), not the value. Redact messages that come from user-supplied types. Check what library errors carry before forwarding them: `std::env::VarError::NotUnicode` holds the variable's raw bytes. +- Mark error enums `#[non_exhaustive]` so variants can be added without a breaking change. + +## Features + +Optional functionality goes behind cargo features. Dangerous functionality goes behind a feature whose name says so, off by default. + +## What the compiler does not check + +"If it compiles, it is secure" holds only under assumptions. State them in the crate root and check them in CI: + +- No `unsafe`: `#![forbid(unsafe_code)]` in every crate that does not need it, and `cargo geiger` (or an equivalent) on dependencies. Memory-safety bugs were the largest class in the C libraries Blessing et al. 2021 studied; Rust prevents them only where `unsafe` is absent. Where a crate needs `unsafe` (memory locking, FFI), confine it to one module, give each block a `// SAFETY:` comment, run the module under Miri, and count the blocks. +- No unbounded escape hatch: every `risky_*` call site is on the allowlist (rung 3). +- No `#[allow]` on the lints above without a reason on the same line. +- A change that adds any of these blocks review until a second person has read it. An agent writing the code does not change that. diff --git a/.claude/skills/misuse-resistance/SKILL.md b/.claude/skills/misuse-resistance/SKILL.md new file mode 100644 index 0000000000..5d29960210 --- /dev/null +++ b/.claude/skills/misuse-resistance/SKILL.md @@ -0,0 +1,73 @@ +--- +name: misuse-resistance +description: Misuse-resistant API design for cryptography and sensitive data. Use when designing or reviewing a public API that handles keys, secrets, ciphertext, nonces or randomness; when writing docs or examples for a security library; or when adding warnings or errors to one. +--- + +# Misuse resistance + +Internal skill. It lives in `.claude/skills/` on purpose: `skills/` ships to customers inside the `stash` tarball, and this skill must not. + +This skill is a copy. The source is `.claude/skills/misuse-resistance/` in [cipherstash/vitaminc](https://github.com/cipherstash/vitaminc), at commit `5dbbafaa1` on `main` (24 November 2026). `RUST.md` and `EVIDENCE.md` are unchanged. `SKILL.md` differs in this note only. To update the copy, copy the three files again, then restore this note. Propose a change to a rule in vitaminc, not here, so the two copies stay the same. + +A **footgun** is an API whose obvious use is insecure. Most cryptographic failures are footguns fired at the call site: in one study, 83% of crypto CVEs were applications misusing correct libraries. That count covers only CVEs tagged as cryptographic, so library bugs filed under other tags, such as Heartbleed, are outside it. The people firing them, developers and coding agents alike, optimise for code that works, copy examples verbatim, and rate their insecure code as secure. Security therefore has to come from the API itself: the shortest path that works must be the secure path. + +Design for two outcomes at once, **secure** and **functional**. An API that is secure but too hard to finish a task with sends its users to Stack Overflow or a model for a footgun. (Keyczar produced the most secure solutions of five libraries tested, and the fewest working ones.) + +## The ladder + +Ranks the ways a rule can be enforced, best first. Put every rule on the highest rung you can reach. Adapted from Rusty Russell's hard-to-misuse scale. + +1. **Impossible to get wrong.** The wrong thing cannot be expressed: there is no nonce parameter to reuse. +2. **Won't compile.** +3. **Fails the build**: a `deny`-level lint, a compile-fail test, a conformance check that runs before merge. A warning that nothing denies is read once, then tuned out (Vance 2018), so it counts as rung 7. +4. **The simplest use is correct**: the default is secure. +5. **The name says how to use it**: `risky_unwrap`, a `hazmat` module. +6. **Fails loudly at runtime**, on first use. +7. **Documented.** +8. **Documented, but the obvious use is wrong.** A footgun. + +Below rung 6, a mistake ships silently. Treat rungs 7 and 8 as bugs to fix. + +This skill is rung 7. Every rule it enforces only by text is one a mistake can ship past. Treat it as a stopgap. Where it tells a caller to avoid something the API allows, raise that item into the API or into CI. Then delete the sentence. + +## Rules + +Each rule states the target. The studies behind each are in [EVIDENCE.md](EVIDENCE.md). + +1. **Secure by default.** The zero-configuration call is the secure call. Callers choose an algorithm, mode, nonce, IV, padding or key size only when the task genuinely needs it, and then every choice offered is safe. +2. **Offer tasks, not primitives.** Name operations for what the caller is doing ("encrypt this record for this tenant"). Primitives live in a lower, clearly named layer. +3. **Own the periphery.** The library provides, typed, everything a caller would otherwise improvise: key generation, key loading and storage, randomness, nonces, password-based derivation, secret comparison, encoding, and wiping. A secure core call fed an improvised input is still a vulnerability, and this is where most real failures are. +4. **Make secrets a type.** A secret lives in a type that wipes on drop, prints opaquely, compares in constant time if at all, and leaves only through a named, greppable escape hatch. +5. **Make invalid states unrepresentable.** Parse once into a type that proves validity (key length, non-empty context, verified signature, authenticated ciphertext) and accept only that type. +6. **Promise only what you deliver.** Names and types claim exactly the guarantee provided. Where a guarantee stops (an AEAD that does not commit to its key, a position that is not authenticated), say so at the type, where the caller looks. +7. **Errors reveal nothing.** Errors never carry plaintext, keys or secret-derived values. Cryptographic failures are one opaque error: a wrong key, a wrong AAD and tampering look the same. Context comes from paths and positions. +8. **Warn at the point of use.** A footgun that cannot be removed (a legacy algorithm, a compatibility mode) warns when used, or requires an explicit opt-in. A warning carries a classification, a title, the code location, and a link to the secure alternative. Keep warnings rare and specific so they are not tuned out. Escape hatches are obvious but effortful: a named feature, a `hazmat` module, a `risky_` prefix. Every escape hatch has an allowlist of call sites that CI enforces: a new use fails CI until a reviewer adds it with a reason. The length of that list is the residual risk, so count it per release. +9. **Every example is secure and complete.** Each example is the production path, inputs included: real key generation, real randomness, real error handling. An example labelled "insecure, for illustration" is copied anyway, so publish only secure ones. Compile-check every example in CI, and use `todo!()` for anything elided so a copied snippet fails loudly. +10. **Keep it small.** Fewer features, options and dependencies. Complexity tracks vulnerability count. +11. **Evolve loudly.** Deprecations name their replacement, and migrations are mechanical. A breaking change is acceptable when the upgrade path is smooth. Finish every migration by denying the old path (rung 3), so it cannot return. Anything left on it is an exemption on the allowlist, not the default. + +When rules conflict with each other or with other goals (flexibility, performance, `no_std`), name the trade-off, choose explicitly, and record the choice where reviewers will find it: an ADR or the type's doc comment. + +## Designing an API + +1. Write the invariant each type will guarantee, in one sentence a reviewer can test ("every `Verified` passed a signature check under the issuer's key"). A type with no stated invariant cannot be checked against rule 6. +2. Write the task as the caller would state it, then list every input the caller must supply. +3. For each input, list its footguns: wrong source, wrong length, reuse, leaking through logs, `Debug` or errors, non-constant-time comparison, accidental serialisation, wrong order of steps. +4. Place each footgun on the ladder, then raise it as far as it will go. Removing the input altogether (rule 3) beats every other rung. What cannot be raised in the API gets a CI check (rung 3), not a sentence in the docs. +5. Write the caller's secure example before the implementation. If it is longer or harder than the insecure code a caller could write with other tools, simplify the API until it is not. +6. List what the change adds: public items, options, features, dependencies, lines. For each, say why it cannot be removed (rule 10). +7. Add a compile-fail test for every rung-2 guarantee, a CI check for every rung-3 one, and a test for every rung-6 refusal. + +Done when every caller-supplied input has its footgun list, every footgun sits on rung 6 or higher, and each has a test. Also count the residual: record the number of `risky_*` call sites, `unsafe` blocks and allowlist exemptions per release. That number must not rise. + +## Reviewing an API or change + +Check every public item in scope (type, function, trait, feature flag, example, doc comment) against all eleven rules. For each finding, report: the item, the rule, the rung it sits on now, the rung it could reach, and the concrete misuse (these inputs lead to this insecure outcome). Before reporting a finding, check the project's ADRs and design notes: a documented, deliberate trade-off is not a footgun. Also report every new `unsafe` block, `#[allow]` or `risky_*` call site the change adds, as a finding. Each needs a reason on the allowlist, or it blocks the change. + +Done when every public item in scope has been checked against every rule, with items that have no findings listed as such. Every finding that cannot be raised in the API names the CI check that will catch it instead. A review that ends in prose only has left the item on rung 7. + +## Rust and vitaminc + +For Rust techniques at each rung (newtypes, typestate, sealed traits, const generics, withheld traits, compile-fail tests, the assumptions behind "if it compiles, it is secure"), read [RUST.md](RUST.md). + +In Rust, the `vitaminc` skill provides ready-made types for rules 3, 4 and 5: secret wrappers, randomness, encryption, key wrapping and keyed hashing. Reach for them before writing your own. diff --git a/.claude/skills/vitaminc/RECIPES.md b/.claude/skills/vitaminc/RECIPES.md new file mode 100644 index 0000000000..5701ae62fa --- /dev/null +++ b/.claude/skills/vitaminc/RECIPES.md @@ -0,0 +1,287 @@ +# vitaminc recipes + +One recipe per task. Each is complete, compiles, and is the production path: copy it as written. Imports use the individual crates; with the facade crate, `vitaminc_protected::X` is `vitaminc::protected::X`, and so on. + +## Hold a secret + +Wrap the secret the moment it exists, and keep it wrapped until the last call that needs it. + +```rust +use std::env::VarError; +use vitaminc_protected::{Controlled, Protected}; +use zeroize::Zeroize; + +/// Says that the token could not be read, and nothing about its value. +#[derive(Debug)] +pub struct TokenUnavailable; + +/// Read a token from the environment straight into a `Protected`. `VarError` +/// holds the raw value when it is not Unicode, so it is wiped here and never returned. +fn api_token() -> Result, TokenUnavailable> { + Protected::generate_ok(|| match std::env::var("API_TOKEN") { + Ok(token) => Ok(token), + Err(VarError::NotPresent) => Err(TokenUnavailable), + Err(VarError::NotUnicode(raw)) => { + raw.into_encoded_bytes().zeroize(); + Err(TokenUnavailable) + } + }) +} + +/// Transform without unwrapping. The closure owns the bare value, so it returns +/// it (here as bytes, in the same allocation) rather than dropping it unwiped. +fn token_bytes(token: Protected) -> Protected> { + token.map(String::into_bytes) +} + +/// To read a value without taking it, borrow it. The wrapper keeps ownership +/// and still wipes the token when it is dropped. +fn token_len(token: &Protected) -> usize { + token.risky_ref().len() +} + +/// At the boundary to an API that takes a plain `&str`, borrow with `risky_ref`. +/// Keep the borrow inside one call, never store it. +fn send(token: &Protected, client: impl Fn(&str)) { + client(token.risky_ref()); +} +``` + +## Compare secrets + +`Protected` has no `PartialEq`. Compare through `Equatable`, which is constant-time. + +```rust +use vitaminc_protected::{Equatable, Protected}; + +fn tag_matches( + presented: &Equatable>, + expected: &Equatable>, +) -> bool { + presented == expected +} + +let a: Equatable> = Equatable::new([7; 32]); +let b: Equatable> = Equatable::new([7; 32]); +assert!(tag_matches(&a, &b)); +``` + +## Generate random values + +```rust +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +fn random_secret() -> Result, RandomError> { + let mut rng = SafeRand::from_entropy()?; + Protected::random(&mut rng) +} + +/// A uniform index in `0..len`, for choosing from a list. `next_below` panics on a +/// zero bound, since `0..0` has nothing to draw, so an empty list is refused here. +fn random_index(rng: &mut SafeRand, len: u32) -> Option { + (len > 0).then(|| rng.next_below(len)) +} +``` + +Derive `Generatable` to generate a whole struct of random fields: + +```rust +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +#[derive(Generatable)] +struct SessionSecrets { + signing: Protected<[u8; 32]>, + encryption: Protected<[u8; 32]>, +} + +fn new_session() -> Result { + SessionSecrets::random(&mut SafeRand::from_entropy()?) +} +``` + +## Generate a password + +Use the `vitaminc-password` types. Each draws its characters uniformly and holds them wrapped. The length is a const generic, and a length below the type's minimum fails compilation. `generate` gives the minimum length; `random` with a `SafeRand` gives any longer one. + +```rust +use vitaminc_password::{AlphaNumericPassword, RandomError}; +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, SafeRand}; + +/// 22 letters and digits, about 131 bits. +fn new_password() -> Result, RandomError> { + Ok(AlphaNumericPassword::generate()?.into_protected_string()) +} + +/// A longer password, for a service account. +fn new_service_password(rng: &mut SafeRand) -> Result, RandomError> { + Ok(AlphaNumericPassword::<32>::random(rng)?.into_protected_string()) +} +``` + +## Encrypt a value or a struct + +Build the cipher at startup from a key that outlives the process (see "Wrap a data key" below), and pass it to every call. `Aes256Cipher` is not `Sync`, so build one per thread or task from the same key rather than sharing one across threads. A key generated inside the function that encrypts is lost when it returns, and so is everything sealed under it. Encrypt under associated data (AAD) naming the record the ciphertext belongs to. Decryption must present the same AAD, so a ciphertext copied onto another record fails to open. Nonces are generated for you. + +Describe the AAD with a type of your own that implements `IntoContext`, as `UserRecord` does below, and pass it at both sites. The write and the read then cannot disagree, and the parts are encoded unambiguously. `encrypt` also accepts a bare `&str`, so `""`, a typo or a value copied from another record compiles; the type is what stops that. + +Each sealed leaf (each encrypted field, each sequence element) draws a random 96-bit nonce, and nothing counts them. Keep the leaves sealed under one key, across every cipher instance and restart, well below 2³², and rotate to a new data key before that (see "Wrap a data key" below). + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{ + decrypt, encrypt, Aes256Cipher, AesCipherText, DecodeError, Decrypt, DecryptError, Encrypt, + EncryptError, Unspecified, +}; + +/// The record a user ciphertext belongs to. The one place its AAD is spelled. +struct UserRecord(u64); + +impl<'a> IntoContext<'a> for UserRecord { + fn into_context(self) -> ContextPiece<'a> { + ("users", self.0).into_context() + } +} + +#[derive(Encrypt, Decrypt)] +struct User { + #[aead(passthrough)] // stored in the clear: only for non-sensitive fields + id: u64, + email: String, + date_of_birth: String, +} + +/// Seal a user for storage. `cipher` is built at startup, one per thread or task. +fn seal_user(cipher: &Aes256Cipher, user: &User) -> Result> { + encrypt(user, cipher, UserRecord(user.id)) +} + +/// Open the record stored under `id`. Take `id` from the lookup, not from the stored +/// value: the passthrough copy is unauthenticated. Under another record's id this fails. +fn open_user( + cipher: &Aes256Cipher, + id: u64, + stored: AesCipherText, +) -> Result> { + decrypt(cipher, stored, UserRecord(id)) +} +``` + +To encrypt a single secret, pass the `Protected` itself. It is walked inside the wrapper and decrypts back into one. The AAD has no id, so a unit type names the one place the value lives: + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{ + decrypt, encrypt, Aes256Cipher, AesCipherText, DecodeError, DecryptError, EncryptError, + Unspecified, +}; +use vitaminc_protected::Protected; + +/// The one stored GitHub integration token. The one place its AAD is spelled. +struct GithubToken; + +impl<'a> IntoContext<'a> for GithubToken { + fn into_context(self) -> ContextPiece<'a> { + ("integrations", "github/token").into_context() + } +} + +fn seal_token(cipher: &Aes256Cipher, token: Protected) -> Result> { + encrypt(token, cipher, GithubToken) +} + +fn open_token( + cipher: &Aes256Cipher, + stored: AesCipherText, +) -> Result, DecryptError> { + decrypt(cipher, stored, GithubToken) +} +``` + +## Wrap a data key under a key-encryption key + +Generate the data key once, when its owner (a tenant, a table) is created, and store only the wrapped form. At every startup, unwrap it and build the cipher the encrypt recipes take. `kek` is the key-encryption key the service holds for its whole lifetime; it is never generated per call. It is built from 32 bytes held in the secret store, passed straight to `Key::from`. + +Wrap each data key under AAD naming its owner and its version. Under one KEK, a wrapped key copied onto another tenant's record then fails to unwrap rather than opening as that tenant's key. The version is how a tenant rotates: before the leaves sealed under one data key near the nonce budget (see the encrypt recipe), generate version 2, encrypt new values under it, and keep version 1 only to open what it sealed. + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{Aes256Cipher, AesCipherText, Key}; +use vitaminc_random::{Generatable, SafeRand}; + +/// The tenant and version a wrapped data key belongs to. +struct DataKeyOwner<'t> { + tenant_id: &'t str, + version: u32, +} + +impl<'a> IntoContext<'a> for DataKeyOwner<'a> { + fn into_context(self) -> ContextPiece<'a> { + (("tenants/dek", self.tenant_id), self.version).into_context() + } +} + +/// Run at startup, on the root key's bytes fetched from the secret store. `Key` takes a +/// plain array (it has no constructor from `Protected` yet) and wraps it at once: fetch +/// straight into this call, and keep no other copy of the bytes. +fn key_encryption_cipher(root_key: [u8; 32]) -> Result> { + Ok(Aes256Cipher::new(&Key::from(root_key))?) +} + +/// Run once, when the tenant is created. Store the result with the tenant. +fn new_data_key( + kek: &Aes256Cipher, + rng: &mut SafeRand, + owner: DataKeyOwner<'_>, +) -> Result> { + let dek = Key::random(rng)?; + Ok(dek.wrap(kek, owner)?) +} + +/// Run at every startup, on the stored result of `new_data_key` for the same owner. +fn data_cipher( + kek: &Aes256Cipher, + owner: DataKeyOwner<'_>, + wrapped: AesCipherText, +) -> Result> { + let dek = Key::from_wrapped(kek, wrapped, owner)?; + Ok(Aes256Cipher::new(&dek)?) +} +``` + +## Keyed hash, blind index, or equality term + +An unkeyed hash of a low-entropy value (an email, a phone number) is reversible by guessing. Derive a keyed term instead, under a context naming the index and its version; `nonempty!` refuses an empty context at compile time. Writes and queries must use the same input type and context. The key is what makes the terms unguessable, so it is generated once, kept in the secret store, and never written into the source. + +```rust +use vitaminc_hmac::HmacSha256Prf; +use vitaminc_prf::{PrfKeyInit, PrfValue}; +use vitaminc_protected::{nonempty, Protected}; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +/// Run once, when the index is created. Put the result in the secret store. +fn new_index_key(rng: &mut SafeRand) -> Result, RandomError> { + Protected::random(rng) +} + +/// Run at startup, on the key bytes as the secret store's read returns them, already wrapped. +fn index_key_from_secret_store( + bytes: Protected>, +) -> Result> { + // Rejects keys shorter than the minimum length instead of deriving weak terms. + Ok(HmacSha256Prf::try_from_bytes(bytes)?) +} + +async fn email_term(prf: &HmacSha256Prf, email: &str) -> Result<[u8; 32], Box> { + Ok(email.prf_with_context(prf, nonempty!("users/email/exact/v1")).await?) +} + +// The index's first run: a fresh key, keyed directly. Later runs load it instead. +let mut rng = SafeRand::from_entropy().unwrap(); +let prf = HmacSha256Prf::new(new_index_key(&mut rng).unwrap()); +let a = futures::executor::block_on(email_term(&prf, "ada@example.com")).unwrap(); +let b = futures::executor::block_on(email_term(&prf, "ada@example.com")).unwrap(); +assert_eq!(a, b); +``` diff --git a/.claude/skills/vitaminc/SKILL.md b/.claude/skills/vitaminc/SKILL.md new file mode 100644 index 0000000000..800aac9040 --- /dev/null +++ b/.claude/skills/vitaminc/SKILL.md @@ -0,0 +1,67 @@ +--- +name: vitaminc +description: Using the vitaminc Rust crates for secrets and cryptography. Use when Rust code holds keys, passwords, tokens or other secrets; generates random values or passwords; encrypts or decrypts values or structs; wraps keys; derives keyed hashes or searchable index terms; or compares secrets. +--- + +# vitaminc + +Internal skill. It lives in `.claude/skills/` on purpose: `skills/` ships to customers inside the `stash` tarball, and this skill must not. + +This skill is a copy. The source is `.claude/skills/vitaminc/` in [cipherstash/vitaminc](https://github.com/cipherstash/vitaminc), at commit `5dbbafaa1` on `main` (24 November 2026). `RECIPES.md` is unchanged. `SKILL.md` differs in this note only. To update the copy, copy the two files again, then restore this note. Propose a change to a rule or a recipe in vitaminc, not here, so the two copies stay the same. + +vitaminc is a suite of Rust crates that replace common cryptography footguns with types. When Rust code touches a secret, use the vitaminc type for the job instead of a raw value or a hand-rolled routine. + +The compiler then checks the code under three assumptions. There is no `unsafe`. Every `risky_*` call is one the project has listed and reviewed. No `#[allow]` disables the lints that enforce this. Outside those assumptions the reviewer is checking again, not the compiler. + +For the reasoning behind these types, and for designing APIs of your own, see the `misuse-resistance` skill. + +## Install + +Use the facade crate with a feature per capability, and import through it (`vitaminc::protected::Protected`): + +```sh +cargo add vitaminc --features protected,random,encrypt,context +``` + +Or add individual crates (`cargo add vitaminc-protected`). All crates release together under one version. Deriving `Encrypt`/`Decrypt` also needs a direct `vitaminc-aead` dependency, because the generated code names that crate. + +## Task map + +| Task | Use | In place of | +|---|---|---| +| Hold a key, token, password or other secret | `Protected` (`protected`) | `String`, `Vec`, `[u8; N]`, `Zeroizing` | +| Hold a key for the whole process | `Locked` (`protected`) | a `static` or lazily initialised byte array | +| Compare secrets or tags | `Equatable>`, `TimingSafeEq` (`protected`) | `==` | +| Hash secret input | `ProtectedDigest` (`protected`) | a digest fed raw secret bytes | +| Require a non-empty label or context | `NonEmpty`, `nonempty!` (`protected`) | `&str` | +| Generate random bytes, keys or structs | `SafeRand` + `Generatable` (`random`) | `rand::thread_rng`, `rand::random` | +| Pick a random index | `SafeRand::next_below` (`random`) | `rng.gen::() % n` | +| Generate a password | `Password`, `AlphaNumericPassword`, `AlphaPassword` + `into_protected_string` (`password`) | `rand`'s `Alphanumeric` sampler, or characters drawn by hand | +| Encrypt a value or struct | `encrypt` / `decrypt`, `Aes256Cipher`, `#[derive(Encrypt, Decrypt)]` (`encrypt`) | an AEAD crate with nonces managed by hand | +| Name what a ciphertext or index term belongs to | a type of your own implementing `IntoContext` (`context`) | a `format!` string built at each call site | +| Wrap a data key under a key-encryption key | `Key::wrap` / `Key::from_wrapped` (`encrypt`) | encrypting key bytes as ordinary data | +| Keyed hash, blind index, equality term | `HmacSha256Prf` + `PrfValue::prf_with_context` (`hmac`, `prf`) | an unkeyed hash, or HMAC with no context | +| HMAC with the key held in AWS KMS | `AwsKmsHmac` (`aws-kms`) | fetching the key into process memory | +| Order-revealing or normalised index terms | `vitaminc-ore`, `vitaminc-normalize` (`ore`, `normalize`) | encoding values for comparison by hand | + +Working code for each common task is in [RECIPES.md](RECIPES.md). Read the recipe before writing the code, and copy it as written. For rows without a recipe, read the crate's docs on docs.rs. + +## Rules + +- **Wrap at the source.** A secret becomes `Protected` the moment it is read or generated (`Protected::generate_ok`, `Protected::random`) and stays wrapped until the last call that needs it. Transform it with `map`, `zip` and `flatten`, which keep the result wrapped. Their closures receive the bare value and own it: return it, or something that still holds it, rather than dropping it inside the closure, where nothing wipes it. To read a value without taking it, borrow with `risky_ref` while the wrapper keeps ownership, and the wrapper still wipes it on drop. +- **Unwrap only at a boundary.** `risky_unwrap` hands the plain value to code outside vitaminc, along with the duty to wipe it and keep it out of logs. Use it only at the call into an external API that must own the value. Prefer `risky_ref` there, kept inside that one call. +- **Errors carry no secret.** An error from the code that reads a secret may hold the value (`std::env::VarError::NotUnicode` holds the raw variable). Map it to an error of your own that says nothing about the value before it can reach a log. +- **Bind every ciphertext to its place.** Pass associated data naming what the ciphertext belongs to as the third argument to `encrypt` and `decrypt`, and spell it as a type: one newtype per kind of record, implementing `IntoContext`, that names the record and carries its id (see the encrypt recipe). The write and the read then cannot disagree, and a ciphertext moved to another record fails to open. `()` is for values that truly belong nowhere. The parameter also accepts a bare `&str`, so `""`, a typo, or a value copied from another record all compile. That is a gap in vitaminc, not a design choice: never pass a string. +- **Name every derivation.** Give `prf_with_context` a context naming the index and its version, checked non-empty at compile time with `nonempty!("users/email/exact/v1")`, and use the same input type and context for writes and for queries. +- **Keys come from a generator, an unwrap or the secret store**: generate a data key once with `Key::random(&mut SafeRand)`, store it wrapped, and load it with `Key::from_wrapped`. The root key-encryption key is the one key built from bytes: fetch its 32 bytes from the secret store at startup and pass them straight to `Key::from`, keeping no other copy. No vitaminc API fetches an AES key from a KMS (`AwsKmsHmac` computes HMACs only), so the secret store is the caller's code. A key written into the source, such as `Key::from([0u8; 32])`, is a test fixture. Rule 3 of `misuse-resistance` says key loading is the library's job, so the caller-written secret store and `Key::from` taking a plain array are both gaps in vitaminc, not design choices. +- **Rotate before the nonce budget runs out.** `Aes256Cipher` draws a random 96-bit nonce for every sealed leaf (each encrypted field and each sequence element), and nothing counts them. Keep the leaves sealed under one key, across every cipher instance and restart, well below 2³² (NIST SP 800-38D). Past that, the chance of a repeated nonce is no longer negligible, and a repeat under AES-GCM exposes plaintext and the authentication key. Give each tenant or table its own data key, version it (`dek/1`, `dek/2`), and wrap a new one before the count gets close. +- **Log the error kind, never the value.** Cipher failures are deliberately the opaque `Unspecified`: a wrong key, a wrong AAD and a tampered ciphertext look the same. + +## Behaviour to know + +- `#[aead(passthrough)]` stores a field in the clear by design: it is neither encrypted nor authenticated, so it can be read, edited or removed in storage while every encrypted field beside it still decrypts. Use it only for non-sensitive fields, treat what it returns as untrusted input, and never let it decide authorization, tenancy or which record to trust. A value that must be readable but tamper-evident belongs in the associated data. +- In an encrypted sequence, each element is bound to the sequence but not to its index, and the element count is not authenticated. If order or completeness matters, put it in the value or the associated data. +- `Aes256Cipher` is not `Sync` (its nonce generator is a `RefCell`). Build one per thread or per task rather than sharing one. +- `Protected` is never `Copy`. Duplicate it with an explicit `clone()`; each clone is wiped when dropped. +- `Locked` is best-effort by default: when the OS refuses to lock memory, the value still exists and `lock_error()` says why. Call `require_locked()`, or set `LockPolicy::Strict` at startup, when locking is mandatory. +- `vitaminc-password` types hold their characters in a `Protected` array and have no `Display`, equality or raw constructor. `into_protected_string` exports a `Protected`, allocated once at full length so no unwiped copy is left behind. `into_unprotected_string` returns a plain `String` that nothing wipes: use it only where an external API must own one. The length is a const generic with a minimum (20, 22 or 23 by alphabet) that fails compilation below it. diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5831a661eb..621d001a2c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -22,3 +22,10 @@ /languages/typescript/packages/auth/ @cipherstash/developers /languages/typescript/packages/profile/ @cipherstash/developers /languages/typescript/packages/stack-auth-wasm/ @cipherstash/developers + +# vitaminc's AEAD crates, moved from cipherstash/vitaminc, and the value +# conformance corpus their tests read. Not published from here yet. +/packages/vitaminc-aead/ @cipherstash/developers +/packages/recipher-frame/ @cipherstash/developers +/packages/vitaminc-aead-derive/ @cipherstash/developers +/conformance/vitaminc-aead/ @cipherstash/developers diff --git a/.github/actions/build-ffi-binding/action.yml b/.github/actions/build-ffi-binding/action.yml index ba7bca9e2d..6cf5dadade 100644 --- a/.github/actions/build-ffi-binding/action.yml +++ b/.github/actions/build-ffi-binding/action.yml @@ -55,7 +55,7 @@ runs: # Edit either and the Rust hash is unchanged, so the cache hit skips # the build step below and the job proceeds on a stale index.node. # - # The last two are NOT in this package. `crates/protect-ffi/Cargo.toml` + # The EQL entries are NOT in this package. `crates/protect-ffi/Cargo.toml` # carries `eql-bindings = { path = "../../../../../../packages/eql/crates/eql-bindings" }` # — an in-tree path dependency that compiles into `index.node` and into # the wasm build below. A path dep has no registry checksum, so a @@ -67,14 +67,24 @@ runs: # observed, not theoretical: the crate went 3.0.4 -> 4.0.0 -> 3.0.5 # across three commits and neither key here changed by a byte.) # - # `crates/**` rather than the one crate, deliberately. `eql-bindings` - # has no path deps of its own TODAY, so the narrower glob would be exact - # — and would silently stop being exact the moment it gains one on a - # sibling in that workspace, which is the same hole one level down. The - # cost of the wider glob is a spurious miss when an unrelated EQL crate - # changes; the cost of the narrower one is a stale binary. Guarded by - # `scripts/__tests__/ffi-binding-action.test.mjs`, which discovers the - # path deps from the manifest rather than trusting this comment. + # The files cargo compiles from that crate, not the crate directory and + # not `packages/eql/crates/**`. protect-ffi builds eql-bindings with no + # features, so its `v4`, `encryption` and `encoding` modules (feature + # `stack-encrypt`) never reach the binding, and its tests, docs and + # generated `bindings/` / `schema/` are not compile inputs at all. The + # wider glob hashed all of that, plus eql-codegen and the other crates + # beside it: each such edit missed this cache, and every workflow whose + # `paths:` copies the glob started its suites over a change that cannot + # reach them. An EQL v4 pull request ran every TypeScript integration + # suite that way. + # + # The list is derived, not remembered. + # `scripts/__tests__/ffi-binding-action.test.mjs` walks the path + # dependencies from the manifest, follows each crate's modules from + # `src/lib.rs` under the features it is built with, and fails both + # ways: a compiled file this key misses (a new module, a new path dep, + # a feature turned on), and a file beside those crates that it hashes + # and cargo does not read. # # The EQL workspace root manifest comes with it: cargo reads it for the # crate's workspace context, so a `.workspace = true` added to @@ -87,7 +97,12 @@ runs: 'languages/typescript/packages/protect-ffi/Cargo.lock', 'languages/typescript/packages/protect-ffi/package.json', 'languages/typescript/packages/protect-ffi/mise.toml', - 'packages/eql/crates/**', + 'packages/eql/crates/eql-bindings/Cargo.toml', + 'packages/eql/crates/eql-bindings/src/lib.rs', + 'packages/eql/crates/eql-bindings/src/sql.rs', + 'packages/eql/crates/eql-bindings/src/from_v2/**', + 'packages/eql/crates/eql-bindings/src/v3/**', + 'packages/eql/crates/eql-bindings/sql/**', 'packages/eql/Cargo.toml') }} # Always, hit or miss: `lib/` is `tsc` over `src/`, which is seconds, and @@ -165,7 +180,7 @@ runs: # never reads. ffi-binding-action.test.mjs walks the tsconfig's imports # and fails if this stops being the complete input set. # - # `packages/eql/**` is here for the reason spelled out on the native key + # The EQL entries are here for the reason spelled out on the native key # above, and it is NOT redundant with it: wasm-pack compiles the same # `eql-bindings` path dependency for wasm32 into # `protect_ffi_inline.js`, which is the bundle @@ -176,7 +191,12 @@ runs: hashFiles('languages/typescript/packages/protect-ffi/crates/**', 'languages/typescript/packages/protect-ffi/Cargo.toml', 'languages/typescript/packages/protect-ffi/Cargo.lock', - 'packages/eql/crates/**', + 'packages/eql/crates/eql-bindings/Cargo.toml', + 'packages/eql/crates/eql-bindings/src/lib.rs', + 'packages/eql/crates/eql-bindings/src/sql.rs', + 'packages/eql/crates/eql-bindings/src/from_v2/**', + 'packages/eql/crates/eql-bindings/src/v3/**', + 'packages/eql/crates/eql-bindings/sql/**', 'packages/eql/Cargo.toml', 'languages/typescript/packages/protect-ffi/dist/wasm/*.d.ts', 'languages/typescript/packages/protect-ffi/src/errors.ts', diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000..f36468fefa --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,20 @@ +# Copilot instructions for cipherstash/stack + +The project instructions are in `AGENTS.md`. When reviewing a pull request, +follow its "Review guidelines", in particular these known non-findings, +which are deliberate design decisions and not defects: + +- A sealed container's membership, order and length are not authenticated: + which entries a stored map holds, and a stored sequence's order, length + and duplicates, are not bound into any AAD, because stored values are + database rows and columns that come back in any order and in part. A + target that refuses a container's shape is a shape mismatch + (`Error::OpenedType`), not tampering (`Error::Aead`). +- A passthrough field is stored in the clear and is not authenticated, + except a plan's context field, which every other field is sealed under. +- Two leaves sealed under the same context are interchangeable between rows; + binding a value to its row is the caller's choice of context. + +A leaf that is not bound to its context, map key, role (single value or +sequence element), type tag or wire version is still a defect. See +`packages/stack-encrypt/docs/adr/0010-what-a-stored-value-authenticates.md`. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7a83f16156..a9169cbaed 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -226,8 +226,9 @@ updates: # stack-encrypt behind its optional `stack-encrypt` feature. Those crates # declare these `{ workspace = true }`, so their requirements come from # the root Cargo.toml even when built here. The root entry below ignores - # them because they move by hand with cipherstash-suite: the root - # manifest pins recipher and cllw-ore with `=`, and so does the Go guest. + # them because they move by hand: the root manifest pins + # zerokms-keyset, clww-ore and ore-rs with `=`, and the Go guest pins + # zerokms-keyset with `=`. # Without these lines this entry bumped them in this lockfile and, to # satisfy the exact pins, rewrote the root Cargo.toml without touching # the root Cargo.lock or the guest's pin, breaking every root `--locked` @@ -237,8 +238,9 @@ updates: # the lockfile from moving these crates apart from the root's. # scripts/__tests__/dependabot-eql-inherited-ignores.test.mjs fails when # the root entry ignores a crate this entry does not. - - dependency-name: "recipher" - - dependency-name: "cllw-ore" + - dependency-name: "zerokms-keyset" + - dependency-name: "clww-ore" + - dependency-name: "ore-rs" - dependency-name: "zerokms-protocol" - dependency-name: "vitaminc*" # Major bumps are reviewed and applied manually, not by Dependabot. @@ -294,14 +296,59 @@ updates: ignore: # Released from cipherstash-suite: stack-auth's API carries their types, # so they move in lockstep with the suite, by hand. The guests pin them - # with `=`; the root Cargo.toml pins recipher and cllw-ore with `=`, and - # gives cts-common and zerokms-protocol caret requirements. + # with `=`; the root Cargo.toml pins zerokms-keyset with `=`, and gives + # cts-common and zerokms-protocol caret requirements. - dependency-name: "cts-common" - dependency-name: "zerokms-protocol" - - dependency-name: "recipher" - - dependency-name: "cllw-ore" - # vitaminc is pinned at 0.5.0 across the crates and the guests; the - # guests' `FfiValue: Decrypt` bound fails if two versions resolve. + - dependency-name: "zerokms-keyset" + # The order schemes, from cipherstash/ore.rs, moved by hand with + # vitaminc: a new release can change every stored order term. + - dependency-name: "clww-ore" + - dependency-name: "ore-rs" + # vitaminc is pinned at 0.8.0 across the crates. The encrypt guest + # takes it only through stack-encrypt's re-exports, so it cannot + # resolve a second version; one would fail at `OwnedFrame: Decrypt`. + - dependency-name: "vitaminc*" + # Major bumps are reviewed and applied manually, not by Dependabot. + - dependency-name: "*" + update-types: + - version-update:semver-major + + # ── Cargo (recipher-js, the Rust half of @cipherstash/recipher) ── + # The recipher-js workspace and the value bridge's test addon, a workspace + # of its own that depends on the bridge by path. Grouped by dependency + # name, so one PR moves a crate in both lockfiles: + # scripts/__tests__/recipher-js-lock-parity.test.mjs fails when they + # resolve different napi or vitaminc crates. + - package-ecosystem: cargo + directories: + - /languages/typescript/packages/recipher-js + - /languages/typescript/packages/recipher-js/value-napi/tests/addon + # Lockfile only, like the other cargo entries: the addon shares a crate + # with the workspace by path. + versioning-strategy: lockfile-only + schedule: + interval: monthly + cooldown: + default-days: 7 + open-pull-requests-limit: 3 + labels: + - dependencies + - supply-chain + commit-message: + prefix: "chore" + include: scope + groups: + recipher-js-cargo: + group-by: dependency-name + patterns: + - "*" + update-types: + - minor + - patch + ignore: + # The bridge reads values into the plaintext model the engine uses, so + # vitaminc moves with the engine, by hand. - dependency-name: "vitaminc*" # Major bumps are reviewed and applied manually, not by Dependabot. - dependency-name: "*" @@ -309,8 +356,19 @@ updates: - version-update:semver-major # ── Go (languages/golang) ────────────────────────────────────── + # One entry for the four modules, grouped by dependency name, so one PR + # moves a dependency in all of them. The nested modules replace the SDK + # with ../.. and build against its dependencies, so a bump to the SDK's + # go.sum alone would break their builds. - package-ecosystem: gomod - directory: /languages/golang + directories: + - /languages/golang + - /languages/golang/encrypt/encrypttest + - /languages/golang/encrypt/example + - /languages/golang/examples/s3 + groups: + go-modules: + group-by: dependency-name schedule: interval: monthly cooldown: @@ -327,6 +385,13 @@ updates: - dependency-name: "*" update-types: - version-update:semver-major + # The nested modules require the SDK, and the example requires + # encrypttest, at the zero pseudo-version, replaced by the directory in + # this checkout. The release pins that placeholder to the version it + # tags (scripts/go-release-pin-encrypttest.sh) and refuses a go.mod + # without it, so a bump to a tagged version would stop every release. + - dependency-name: "github.com/cipherstash/stack/languages/golang" + - dependency-name: "github.com/cipherstash/stack/languages/golang/encrypt/encrypttest" # ── pip (.github/impact-gate — the advisory ImpactGate toolchain) ── # impact.yml installs this hashed requirements.txt with `--require-hashes diff --git a/.github/workflows/bench-eql.yml b/.github/workflows/bench-eql.yml index 19a675899f..6422ddb9a1 100644 --- a/.github/workflows/bench-eql.yml +++ b/.github/workflows/bench-eql.yml @@ -64,8 +64,13 @@ on: - "packages/eql/docker/**" - "packages/eql/README.md" - "packages/eql/SUPABASE.md" + - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" + - "packages/vitaminc-aead/**" + - "packages/recipher-frame/**" + - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/crap-crates.yml b/.github/workflows/crap-crates.yml index 6ce34e7aff..abd61a1040 100644 --- a/.github/workflows/crap-crates.yml +++ b/.github/workflows/crap-crates.yml @@ -21,6 +21,7 @@ on: - packages/stack-auth/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - Cargo.toml - Cargo.lock - mise.toml @@ -56,10 +57,13 @@ env: CARGO_NET_GIT_FETCH_WITH_CLI: true NEXTEST_PROFILE: ci +# cargo-crap 0.6.1's prebuilt GNU/Linux binary needs GLIBC 2.39 (Ubuntu 24.04). +# Keep the runner and its mise cache on that image. The runner is the 16 vCPU +# RunsOn label with `image=ubuntu24-full-x64`. The gate itself is unchanged. jobs: crap-stack-auth: name: CRAP (stack-auth) - runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 45 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -74,16 +78,19 @@ jobs: working_directory: . cache: true # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs - cache_key_prefix: mise-v1-ubuntu-2204 + cache_key_prefix: mise-v1-ubuntu-2404 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + - name: Check the CRAP executable before collecting coverage + run: cargo crap --version + - name: Run the CRAP gate run: mise run crap:stack-auth -- --format github crap-stack-encrypt: name: CRAP (stack-encrypt) - runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 45 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -97,9 +104,12 @@ jobs: working_directory: . cache: true # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs - cache_key_prefix: mise-v1-ubuntu-2204 + cache_key_prefix: mise-v1-ubuntu-2404 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + - name: Check the CRAP executable before collecting coverage + run: cargo crap --version + - name: Run the CRAP gate run: mise run crap:stack-encrypt -- --format github diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 04dd89c40e..7b4dbdf9e8 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -1,4 +1,4 @@ -name: Fuzz (crates) +name: Fuzz # libFuzzer fuzzing for the stack crates' untrusted-input parsers (the # detached `packages/*/fuzz/` crates and the `fuzz:*` mise tasks). Ported from @@ -14,6 +14,12 @@ name: Fuzz (crates) # cache, so coverage compounds; it is minimised with `cargo fuzz cmin`, and # any crash reproducer is uploaded as an artifact. # +# * go-fuzz-campaign (schedule and manual, never on PRs): the same run for +# the Go fuzz targets in languages/golang (`mise run go:fuzz`). Those +# targets fuzz the ABI of the WASI guests from the host side, and the +# decoders of the frame codec. Their regression replay is plain +# `go test`, in tests-golang.yml. +# # cargo-fuzz needs nightly; the tasks run `cargo +nightly fuzz`. Pull requests # are the only filtered event, so `push` has no filter to mirror; recorded in # scripts/__tests__/workflow-paths-filter-parity.test.mjs. @@ -24,6 +30,9 @@ on: - packages/stack-auth/** - packages/stack-kms/** - packages/stack-encrypt/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - Cargo.toml - Cargo.lock - mise.toml @@ -60,6 +69,42 @@ env: CARGO_NET_GIT_FETCH_WITH_CLI: true jobs: + # cargo-fuzz has no --locked, and a build without it re-resolves a stale + # Cargo.lock in memory, so the harnesses would build against whatever + # versions are newest that day while the job stays green. This job checks + # each fuzz crate's committed lockfile instead. It runs on the schedule too, + # so a lockfile that goes stale on the default branch still fails a run. + fuzz-lockfiles: + name: fuzz lockfiles are current + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2404 + + - name: Resolve every fuzz crate against its committed lockfile + run: | + status=0 + for manifest in packages/*/fuzz/Cargo.toml; do + if cargo metadata --locked --format-version 1 --manifest-path "$manifest" > /dev/null; then + echo "ok: ${manifest%/Cargo.toml}/Cargo.lock" + else + echo "::error file=${manifest%/Cargo.toml}/Cargo.lock::stale; run cargo metadata --manifest-path $manifest and commit the lockfile" + status=1 + fi + done + exit "$status" + fuzz-regression: name: fuzz regression (${{ matrix.slug }}) # Not on the nightly schedule, which is the campaign's. A manual dispatch @@ -77,7 +122,9 @@ jobs: - { task: "fuzz:sealed-value", slug: sealed-value } - { task: "fuzz:term-decode", slug: term-decode } - { task: "fuzz:check-record", slug: check-record } - - { task: "fuzz:plan-build", slug: plan-build } + - { task: "fuzz:json-wire", slug: json-wire } + - { task: "fuzz:json-text", slug: json-text } + - { task: "fuzz:label-parse", slug: label-parse } steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: @@ -125,7 +172,9 @@ jobs: - { task: "fuzz:sealed-value", slug: sealed-value, dir: packages/stack-encrypt, target: sealed_value_decode } - { task: "fuzz:term-decode", slug: term-decode, dir: packages/stack-encrypt, target: term_decode } - { task: "fuzz:check-record", slug: check-record, dir: packages/stack-encrypt, target: check_record } - - { task: "fuzz:plan-build", slug: plan-build, dir: packages/stack-encrypt, target: plan_build } + - { task: "fuzz:json-wire", slug: json-wire, dir: packages/stack-encrypt, target: json_wire_decode } + - { task: "fuzz:json-text", slug: json-text, dir: packages/stack-encrypt, target: json_text } + - { task: "fuzz:label-parse", slug: label-parse, dir: packages/stack-encrypt, target: label_parse } steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: @@ -152,7 +201,7 @@ jobs: # most recent prior corpus by prefix. The committed seeds come from the # checkout and merge with the restored corpus at run time. - name: Restore the corpus - uses: actions/cache/restore@v4 + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 with: path: ${{ matrix.dir }}/fuzz/corpus/${{ matrix.target }} key: fuzz-corpus-${{ matrix.slug }}-${{ github.run_id }} @@ -177,7 +226,7 @@ jobs: # crash input lives in artifacts/, not corpus/. - name: Save the corpus if: always() - uses: actions/cache/save@v4 + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 with: path: ${{ matrix.dir }}/fuzz/corpus/${{ matrix.target }} key: fuzz-corpus-${{ matrix.slug }}-${{ github.run_id }} @@ -189,3 +238,90 @@ jobs: name: fuzz-artifacts-${{ matrix.slug }} path: ${{ matrix.dir }}/fuzz/artifacts/** if-no-files-found: ignore + + # The Go fuzz targets in languages/golang: the guests' exports called with + # pointer/length pairs a correct host never passes, and their buffer + # registry driven with frees one never makes (internal/guest/hostile.go). + # Their seeds and committed corpus replay in every `go test`, which + # tests-golang.yml runs on pull requests, so this job is the campaign only. + # One job per target, as the cargo campaign has, so each gets the whole + # timeout whatever max_total_time a dispatch asks for. + # scripts/__tests__/crates-ci.test.mjs fails when a Fuzz* function in + # languages/golang is missing from the matrix. Each target's generated + # corpus lives in GOCACHE/fuzz and persists across runs in the Actions + # cache. A failing input is written to the package's testdata/fuzz/ and + # uploaded. + go-fuzz-campaign: + name: go fuzz campaign (${{ matrix.slug }}) + if: github.event_name != 'pull_request' + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # `guest` is the guest build that the package of the target runs. The + # targets of the frame codec, in encrypt/frame, run no guest. + include: + - { target: FuzzGuestExportPairs, slug: encrypt-export-pairs, guest: "wasm:guest:build:deterministic" } + - { target: FuzzGuestBufferRegistry, slug: encrypt-buffer-registry, guest: "wasm:guest:build:deterministic" } + - { target: FuzzAuthGuestExportPairs, slug: auth-export-pairs, guest: "wasm:auth-guest:build" } + - { target: FuzzUnmarshal, slug: frame-value, guest: "" } + - { target: FuzzUnmarshalCipherText, slug: frame-ciphertext, guest: "" } + - { target: FuzzUnmarshalStorage, slug: frame-storage, guest: "" } + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2404 + + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + if: matrix.guest != '' + with: + workspaces: | + languages/golang/encrypt/guest + languages/golang/auth/guest + key: go-fuzz-${{ matrix.slug }} + + - name: Build the guest (${{ matrix.slug }}) + if: matrix.guest != '' + run: mise run ${{ matrix.guest }} + + - name: Find the Go fuzz cache + id: gocache + run: echo "dir=$(cd languages/golang && go env GOCACHE)/fuzz" >> "$GITHUB_OUTPUT" + + - name: Restore the corpus + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.gocache.outputs.dir }} + key: go-fuzz-corpus-${{ matrix.slug }}-${{ github.run_id }} + restore-keys: go-fuzz-corpus-${{ matrix.slug }}- + + - name: Fuzz ${{ matrix.slug }} + env: + GO_FUZZ: ${{ matrix.target }} + GO_FUZZTIME: ${{ github.event.inputs.max_total_time || '120' }}s + run: mise run go:fuzz + + - name: Save the corpus + if: always() + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.gocache.outputs.dir }} + key: go-fuzz-corpus-${{ matrix.slug }}-${{ github.run_id }} + + - name: Upload the failing input + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: go-fuzz-failures-${{ matrix.slug }} + path: languages/golang/**/testdata/fuzz/** + if-no-files-found: ignore diff --git a/.github/workflows/integration-drizzle.yml b/.github/workflows/integration-drizzle.yml index 32a268a460..1921405312 100644 --- a/.github/workflows/integration-drizzle.yml +++ b/.github/workflows/integration-drizzle.yml @@ -104,8 +104,22 @@ on: # `.github/actions/build-ffi-binding` hash them, so an edit here misses # that cache and rebuilds the bundle the `integration/wasm/**` suites # load. Same argument as the two entries above, same guard. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' pull_request: branches: ['**'] # Repeated verbatim: GitHub Actions does not support YAML anchors/aliases. @@ -198,8 +212,22 @@ on: # `.github/actions/build-ffi-binding` hash them, so an edit here misses # that cache and rebuilds the bundle the `integration/wasm/**` suites # load. Same argument as the two entries above, same guard. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' jobs: integration: diff --git a/.github/workflows/integration-prisma-next.yml b/.github/workflows/integration-prisma-next.yml index 22d4017a38..ae74698766 100644 --- a/.github/workflows/integration-prisma-next.yml +++ b/.github/workflows/integration-prisma-next.yml @@ -56,12 +56,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' pull_request: branches: ['**'] # Repeated verbatim: GitHub Actions does not support YAML anchors/aliases. @@ -104,12 +118,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' jobs: integration: diff --git a/.github/workflows/integration-protect-ffi.yml b/.github/workflows/integration-protect-ffi.yml index 70ed1cbbb3..b13831f367 100644 --- a/.github/workflows/integration-protect-ffi.yml +++ b/.github/workflows/integration-protect-ffi.yml @@ -85,7 +85,17 @@ on: # cache and rebuilds the binding — without these entries it would be # rebuilt and no suite that loads it would start. Pinned by # scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' - '.github/workflows/integration-protect-ffi.yml' - '.github/actions/build-ffi-binding/**' @@ -124,7 +134,17 @@ on: # cache and rebuilds the binding — without these entries it would be # rebuilt and no suite that loads it would start. Pinned by # scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' - '.github/workflows/integration-protect-ffi.yml' - '.github/actions/build-ffi-binding/**' diff --git a/.github/workflows/integration-supabase.yml b/.github/workflows/integration-supabase.yml index 067a8c749d..477599ce94 100644 --- a/.github/workflows/integration-supabase.yml +++ b/.github/workflows/integration-supabase.yml @@ -83,12 +83,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' pull_request: branches: ['**'] paths: @@ -163,12 +177,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' jobs: integration: diff --git a/.github/workflows/kani.yml b/.github/workflows/kani.yml new file mode 100644 index 0000000000..b3f7665005 --- /dev/null +++ b/.github/workflows/kani.yml @@ -0,0 +1,180 @@ +name: Kani (storage reader) + +# Proves, rather than tests, the pieces recipher-frame's storage reader +# is built from. The reader parses bytes that may be corrupt or tampered with: +# +# - the header is refused exactly as its rules say; +# - a count never exceeds the bytes left; +# - a scalar, an object's key and a map's key are read at the cursor and in +# bounds, from any position, and a wide scalar is read whole or refused; +# - the depth bound is 128; +# - two map keys are one key exactly when their values (integers, across +# every pair of widths) or bytes (text and bytes) are equal, and keys of +# different kinds are never one key. +# +# The harnesses are in packages/recipher-frame/src/storage/proofs.rs and +# build only under `cfg(kani)`. They take about ten minutes, two at a time, +# so they do not run on every pull request that touches the crates: +# +# * pull_request: when the reader or its proofs change (storage.rs, +# storage/, the crate manifest), when the vitaminc-aead modules the +# reader calls change (leaf.rs, tags.rs, frame.rs), or this workflow. +# * schedule: nightly on the default branch, and only when something the +# reader compiles from (the frame and aead sources, their manifests, the +# root manifest and lockfile) differs from the commit of the last +# successful scheduled run. Kani is deterministic, so a run over +# unchanged inputs proves nothing new. With no such run to compare with, +# the proofs run. +# * workflow_dispatch: always. +# +# Kani installs its own pinned nightly and CBMC (`cargo kani setup`). Both, +# and the kani binaries, stay in this job and its cache; no other workflow +# or mise task installs them. Pull requests are the only filtered event, so +# `push` has no filter to mirror; recorded in +# scripts/__tests__/workflow-paths-filter-parity.test.mjs. + +on: + pull_request: + paths: + - packages/recipher-frame/src/storage.rs + - packages/recipher-frame/src/storage/** + - packages/recipher-frame/Cargo.toml + - packages/vitaminc-aead/src/leaf.rs + - packages/vitaminc-aead/src/tags.rs + - packages/vitaminc-aead/src/frame.rs + - .github/workflows/kani.yml + schedule: + # Nightly at 05:41 UTC. Scheduled runs fire from the default branch only. + - cron: "41 5 * * *" + workflow_dispatch: {} + +defaults: + run: + shell: bash + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # The one pin for Kani. A bump changes the nightly and CBMC it installs. + KANI_VERSION: "0.67.0" + CARGO_TERM_COLOR: always + +jobs: + # On a scheduled run: did anything the reader compiles from change since + # the last successful scheduled run? On every other event the answer is + # yes, without looking. + changes: + name: Kani inputs changed + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 5 + permissions: + contents: read + # Lists this workflow's earlier runs. + actions: read + outputs: + relevant: ${{ steps.check.outputs.relevant }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + if: github.event_name == 'schedule' + with: + persist-credentials: false + # History without file contents: enough to compare two trees. + fetch-depth: 0 + filter: blob:none + + - name: Look for a change to the reader's inputs + id: check + env: + EVENT_NAME: ${{ github.event_name }} + GH_TOKEN: ${{ github.token }} + BRANCH: ${{ github.ref_name }} + run: | + if [ "$EVENT_NAME" != schedule ]; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The commit the last successful scheduled run checked. Comparing + # trees, not listing commits by date, sees a change however it was + # merged and however long ago it was written, and a missed or + # failed night is compared against again the next night. + last=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow kani.yml \ + --event schedule --branch "$BRANCH" --status success --limit 1 \ + --json headSha --jq '.[0].headSha // empty' || true) + if [ -z "$last" ] || ! git cat-file -e "$last^{commit}" 2>/dev/null; then + echo "No earlier successful scheduled run to compare with; running the proofs." + echo "relevant=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + changed=$(git diff --no-renames --name-only "$last" HEAD -- \ + packages/recipher-frame/src \ + packages/recipher-frame/Cargo.toml \ + packages/vitaminc-aead/src \ + packages/vitaminc-aead/Cargo.toml \ + Cargo.toml Cargo.lock .github/workflows/kani.yml) + if [ -n "$changed" ]; then + echo "Changed since $last:"; echo "$changed" + echo "relevant=true" >> "$GITHUB_OUTPUT" + else + echo "Nothing the proofs read changed since $last; they would repeat that run." + echo "relevant=false" >> "$GITHUB_OUTPUT" + fi + + kani: + name: Kani (storage reader) + needs: changes + if: needs.changes.outputs.relevant == 'true' + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + # About ten minutes of proofs, plus Kani's setup when the cache misses. + # Anything past this is a hang. + timeout-minutes: 45 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # The kani binaries, CBMC under ~/.kani, and the crates the proofs + # fetch. Keyed on the Kani version and the lockfile. Kani's nightly is + # not cached: ~/.kani/kani-/toolchain is a symlink into + # ~/.rustup/toolchains, which the next step checks. + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: | + ~/.cargo/bin/cargo-kani + ~/.cargo/bin/kani + ~/.kani/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + key: ${{ runner.os }}-kani-${{ env.KANI_VERSION }}-${{ hashFiles('Cargo.lock') }} + restore-keys: ${{ runner.os }}-kani-${{ env.KANI_VERSION }}- + + # The runner's stable Rust builds kani-verifier; Kani then proves with + # its own nightly. A fixed-string, whole-word match, so a cached + # 10.67.0 or 0.67.01 is not taken for 0.67.0. A restored ~/.kani on a + # fresh runner has a dangling toolchain link, so the setup also runs + # when the nightly's rustc is missing; it reinstalls the nightly. + - name: Install Kani + run: | + installed=$(cargo kani --version 2>/dev/null || true) + if ! grep -qwF "$KANI_VERSION" <<<"$installed"; then + cargo install --locked kani-verifier --version "$KANI_VERSION" + cargo kani setup + elif [ ! -x "$HOME/.kani/kani-$KANI_VERSION/toolchain/bin/rustc" ]; then + cargo kani setup + fi + cargo kani --version + test -x "$HOME/.kani/kani-$KANI_VERSION/toolchain/bin/rustc" + + # `cargo kani` has no --locked, and would re-resolve a stale lockfile + # in memory, so check the committed one first. + - name: Check Cargo.lock is current + run: cargo metadata --locked --format-version 1 > /dev/null + + # Two at a time: the map key proofs each solve over 128-bit values, + # and a 16 GB runner is not sure to hold four of them at once. + - name: Prove + run: cargo kani -p recipher-frame --features serde -j 2 --output-format terse diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 26ef909fbc..5c161ebd6f 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -1,17 +1,25 @@ name: Mutants +# For now this gate is off for every pull request except one into main, and +# a manual dispatch sweeps each crate: see the job's `if:` and #2017. +# # Gates pull requests on mutation testing of the lines they change in -# stack-auth and stack-encrypt. Ported from cipherstash-suite's `mutants.yml`. +# stack-auth, stack-encrypt, stack-encrypt-jsonpath (the path grammar, moved +# out of stack-encrypt), and vitaminc-aead, recipher-frame and +# vitaminc-aead-derive (imported from cipherstash/vitaminc, which gated them +# the same way). Ported from cipherstash-suite's `mutants.yml`. # # cargo-mutants rewrites small pieces of logic (flip `<` to `<=`, replace a # body with `Default::default()`) and reruns the tests; a mutant that survives # is a line the suite does not pin down. Scoped with `--in-diff` to the PR's # own changes: a full sweep is far too slow for a per-PR gate (stack-encrypt: -# ~60 min). Run one locally with `mise run mutants:`. Features, the test +# ~60 min). A full sweep of every opted-in crate is a manual dispatch of this +# workflow, one job per crate; stack-auth and stack-encrypt also have a local +# `mise run mutants:`. Features, the test # filter (which drops the trybuild `ui` binary), excludes and timeouts live in # .cargo/mutants.toml, so the gate and the local tasks agree. # -# Scoped to the two crates with `-p`: the baseline runs the unmutated tests of +# Scoped to those crates with `-p`: the baseline runs the unmutated tests of # those packages only. A diff touching only other crates yields no mutants and # passes. # @@ -22,11 +30,16 @@ name: Mutants on: # No branch filter: a stacked PR (a feature branch as base) must run this - # gate too. + # gate too. For now, the job's `if:` skips it on every pull request whose + # base is not main (#2017). pull_request: paths: - packages/stack-auth/** - packages/stack-encrypt/** + - packages/stack-encrypt-jsonpath/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - Cargo.toml - Cargo.lock - mise.toml @@ -63,9 +76,38 @@ env: jobs: mutants: - name: Mutants gate + # One job on a pull request, mutating the diff across every crate; one + # job per crate on a manual dispatch, which sweeps each crate whole. + # The pull request's check keeps the name "Mutants gate". The name reads + # the event, not the matrix: a job the `if:` skips never expands its + # matrix, and its check would show this expression's text as its name. + name: ${{ github.event_name == 'pull_request' && 'Mutants gate' || format('Mutants sweep ({0})', matrix.crate) }} + # For now, off for every pull request except one into main, to save + # runner time while the milestone's work lands in next. The release + # pull request (next into main) stays skipped. A manual dispatch still + # sweeps each crate whole. #2017 turns the gate back on by restoring + # this condition: + # + # if: github.event_name != 'pull_request' || !(github.head_ref == 'next' && github.base_ref == 'main') + # + # That condition skips only the release pull request (next into main). + # It is safe only when every line of the release diff was mutated on its + # way into next. The release diff gives thousands of mutants and cannot + # finish inside the timeout. + # + # While the gate is off, pull requests merge into next untested. So + # before the release pull request, dispatch this workflow on next to + # sweep each crate whole, and fix every mutant that survives. #2017 + # lists that step. + if: github.event_name != 'pull_request' || (github.base_ref == 'main' && github.head_ref != 'next') runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache - timeout-minutes: 120 + # A crate's sweep runs four mutants at a time; vitaminc-aead (about a + # thousand mutants) and stack-encrypt are the slowest. + timeout-minutes: ${{ matrix.crate == 'all' && 120 || 240 }} + strategy: + fail-fast: false + matrix: + crate: ${{ fromJSON(github.event_name == 'pull_request' && '["all"]' || '["stack-auth","stack-encrypt","stack-encrypt-jsonpath","vitaminc-aead","recipher-frame","vitaminc-aead-derive"]') }} permissions: contents: read # Posts and updates the report comment on the PR. @@ -73,6 +115,12 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: + # On a pull request, the PR's head rather than GitHub's test merge + # commit: cargo-mutants applies `pr.diff` to the checked-out tree + # and refuses a hunk whose lines do not match it, and the diff + # below is taken between the base and this head. Empty on a + # manual dispatch, which checks out the default ref. + ref: ${{ github.event.pull_request.head.sha || '' }} # Full history, to diff the PR against its base for `--in-diff`. fetch-depth: 0 persist-credentials: false @@ -90,16 +138,35 @@ jobs: - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 # PR only: a manual dispatch has no base to diff against, so it sweeps - # both crates instead (see the next step). + # each crate whole instead, one matrix job per crate. + # + # The base comes from the API at run time, not from the event payload. + # For a pull request whose base branch is itself the head of another + # open pull request (a stacked PR, or any PR into `next` while `next` + # has a PR into `main`), GitHub has been seen to build the test merge + # commit against the other PR's merge commit and to report the other + # PR's base in `github.base_ref`. The diff was then everything between + # `main` and `next`, and the gate ran for two hours on a Go-only + # change. `gh pr view` returns the base the PR page shows. The diff is + # taken between that base and the PR's head, which is what the checkout + # step put in the tree, so the hunks' line numbers are the tree's. - name: Compute the PR diff if: github.event_name == 'pull_request' env: - BASE_REF: ${{ github.base_ref }} + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PAYLOAD_BASE_REF: ${{ github.base_ref }} run: | - git fetch --no-tags origin "$BASE_REF" - git diff "origin/$BASE_REF" > pr.diff - echo "Changed lines under mutation:" - cat pr.diff + base=$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --json baseRefName,baseRefOid --jq '"\(.baseRefName) \(.baseRefOid)"') + base_ref=${base% *} + base_sha=${base#* } + echo "Base: $base_ref at $base_sha (the event payload said '$PAYLOAD_BASE_REF'); head: $HEAD_SHA" + git fetch --no-tags origin "$base_sha" + test "$(git rev-parse HEAD)" = "$HEAD_SHA" || { echo "the checkout is not the PR head"; exit 1; } + git diff "$base_sha...HEAD" > pr.diff + echo "Files under mutation:" + grep '^diff --git' pr.diff | sed 's|^diff --git a/.* b/| |' || echo " (none)" # Never fails the job: the enforce step below is the gate, and the # comment must be posted first. @@ -107,14 +174,14 @@ jobs: id: mutants continue-on-error: true env: - EVENT_NAME: ${{ github.event_name }} + CRATE: ${{ matrix.crate }} run: | set +e - crates=(-p stack-auth -p stack-encrypt) - if [ "$EVENT_NAME" = "pull_request" ]; then + crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath -p vitaminc-aead -p recipher-frame -p vitaminc-aead-derive) + if [ "$CRATE" = "all" ]; then cargo mutants --no-shuffle -vV "${crates[@]}" --in-diff pr.diff else - cargo mutants --no-shuffle -vV "${crates[@]}" + cargo mutants --no-shuffle -vV -p "$CRATE" -j 4 fi echo "exit_code=$?" >> "$GITHUB_OUTPUT" @@ -131,7 +198,7 @@ jobs: timeout=$(count timeout.txt) { echo '' - echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth + stack-encrypt)" + echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive)" echo if [ ! -d "$out" ]; then # No output dir: either nothing to mutate (exit 0) or the run diff --git a/.github/workflows/prisma-example-readme-e2e.yml b/.github/workflows/prisma-example-readme-e2e.yml index 12f6d103e9..5503522c03 100644 --- a/.github/workflows/prisma-example-readme-e2e.yml +++ b/.github/workflows/prisma-example-readme-e2e.yml @@ -39,12 +39,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this walkthrough green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' pull_request: branches: - '**' @@ -72,12 +86,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this walkthrough green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' jobs: walkthrough: diff --git a/.github/workflows/prisma-next-e2e.yml b/.github/workflows/prisma-next-e2e.yml index ea5e0f36bb..3d97ef252c 100644 --- a/.github/workflows/prisma-next-e2e.yml +++ b/.github/workflows/prisma-next-e2e.yml @@ -38,12 +38,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' pull_request: branches: - '**' @@ -72,12 +86,26 @@ on: # EQL wire types are linked into the `index.node` this job encrypts # through. The native cache key in `.github/actions/build-ffi-binding` # hashes both, so an edit here misses that cache and the binding gets - # rebuilt — correctly. Without these two entries the miss never happens, + # rebuilt — correctly. Without these entries the miss never happens, # because the workflow does not trigger at all: a payload-encoding change # under packages/eql/crates merges with this suite green by absence. # Pinned by scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' + # The SQL this suite installs. `stash eql install` and the Prisma + # Next baseline migration read the bundle from `@cipherstash/eql`, a + # workspace package, so an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' jobs: e2e: diff --git a/.github/workflows/release-golang.yml b/.github/workflows/release-golang.yml index f59494a61e..d313cd44c8 100644 --- a/.github/workflows/release-golang.yml +++ b/.github/workflows/release-golang.yml @@ -1,15 +1,23 @@ name: Release (Go) -# Tags a release of the Go module (languages/golang) that `go get` can use. +# Tags a release of the Go modules that `go get` can use: the SDK +# (languages/golang) and its test module (languages/golang/encrypt/encrypttest), +# at one version. # -# The module embeds three WASI guests built from Rust (encrypt/wasm, -# encrypt/eql/wasm, auth/wasm). They are gitignored on main, and Go fetches a -# module version as the files committed at its tag, so a tag on a main commit -# would build and then fail at `NewClient` with ErrGuestNotBuilt. This -# workflow builds the guests at the commit it runs on, commits them on a -# release-only commit that no branch points at, tags that commit -# `languages/golang/v` (the prefix Go requires for a module in a -# subdirectory) and pushes the tag alone. main stays free of binaries. +# They embed five WASI guests built from Rust. The SDK embeds the three +# production guests (encrypt/wasm, encrypt/eql/wasm, auth/wasm). The test +# module embeds the two deterministic-kms test builds +# (encrypt/encrypttest/wasm), which give an application's tests a client with +# no ZeroKMS; it is a module of its own so that only a program that imports it +# downloads them. The guests are gitignored on main, and Go fetches a module +# version as the files committed at its tag, so a tag on a main commit would +# build and then fail at `NewClient` with ErrGuestNotBuilt, and at +# `encrypttest.NewClient` with its own not-built error. This workflow builds +# the guests at the commit it runs on, commits them on a release-only commit +# that no branch points at, with the test module's go.mod pinned to the SDK +# version, tags that commit `/v` for each module +# in MODULES (the prefix Go requires for a module in a subdirectory) and +# pushes the tags alone. main stays free of binaries. # # The GitHub release it creates carries the EQL v4 SQL bundle the module's # EQL types are stored in, built from the same commit, so one release page @@ -17,22 +25,35 @@ name: Release (Go) # # gh workflow run release-golang.yml -f version=0.1.0-alpha.1 --ref # -# The ref must carry the EQL v4 bundle (packages/eql's v4 build), or the -# build job stops at "Build the EQL SQL bundles". A version with a pre-release -# suffix may be cut from any branch and is published as a GitHub pre-release; -# a final version is cut from main only (scripts/go-release-version.mjs). +# The ref must have the EQL v4 bundle (the v4 build of packages/eql). Without +# it, the build job stops at "Build the EQL SQL bundles". The file +# languages/golang/CHANGELOG.md at the ref must have a `## []` section. +# That section becomes the release notes. Without it, the run stops at the +# `notes` job. # -# Three jobs, split by what they may touch: +# A version with a pre-release suffix can be released from any branch. The +# workflow publishes it as a GitHub pre-release. A final version can be released +# only from main. # +# Four jobs, split by what they may touch: +# +# - `notes` holds no write token and runs no third-party code: it takes the +# version's section of languages/golang/CHANGELOG.md +# (scripts/go-release-notes.mjs, Node built-ins only) and refuses a version +# that has none. `build` waits for it, so a missing section stops the +# release before anything is built. `publish` puts its output on the +# release page; that is safe because nothing in this job could have +# written it but the script. # - `build` holds no write token. It is the only job that runs third-party # code (the toolchain installs, cargo build scripts and proc macros, the Go # tests), and it hands the guests, their hashes and the SQL to `publish` as # an artifact, with the git tree it built and tested as a job output. # - `publish` holds `contents: write` and runs only git and gh. It rebuilds # the release commit from the artifact, refuses it unless its tree is the one -# `build` tested, pushes the tag and creates the release. -# - `verify` is read-only again: it asks the Go proxy for the version, which -# fetches it, and checks the guests in the module zip are the ones built. +# `build` tested, pushes the tags and creates the release. +# - `verify` is read-only again: it asks the Go proxy for each module at the +# version, which fetches it, and checks the guests in each module zip are +# the ones built. # # A version is immutable once the proxy has fetched it, so a tag is never # moved or deleted. If `publish` or `verify` fails after the tag is pushed, @@ -63,14 +84,73 @@ env: languages/golang/encrypt/wasm/stack_encrypt_guest.wasm languages/golang/encrypt/eql/wasm/stack_encrypt_guest_eql.wasm languages/golang/auth/wasm/stack_auth_guest.wasm + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm + + # The Go modules a release tags, by directory. Each gets the tag + # `/v` (the prefix Go requires for a module in a + # subdirectory) on the one release commit. encrypt/encrypttest is a module + # of its own so that only a program that imports it downloads the test + # builds of the engine it embeds; its go.mod is pinned to this version on + # the release commit (scripts/go-release-pin-encrypttest.sh). + MODULES: >- + languages/golang + languages/golang/encrypt/encrypttest concurrency: group: release-golang cancel-in-progress: false jobs: + notes: + name: Release notes from the CHANGELOG + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 5 + env: + VERSION: ${{ inputs.version }} + outputs: + notes: ${{ steps.notes.outputs.notes }} + steps: + # Only the files this job reads: the two scripts (Node built-ins only), + # the CHANGELOG, and the go.mod the version check reads. + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + scripts/go-release-notes.mjs + scripts/go-release-version.mjs + languages/golang/CHANGELOG.md + languages/golang/go.mod + + # First, so a malformed version (`v0.1.0`, say) is refused as one, not + # reported as a CHANGELOG with no section for it. `build` checks it + # again, since that is the job that builds the version. + - name: Check the version and the ref + run: node scripts/go-release-version.mjs "$VERSION" "$GITHUB_REF" + + # A multi-line output needs a delimiter no line of the notes can be, + # so it is random. Empty notes are refused here too, whatever the + # script's exit status: the release page is the one place they show. + - name: Take this version's section of the CHANGELOG + id: notes + run: | + set -euo pipefail + node scripts/go-release-notes.mjs "$VERSION" > notes.md + if ! grep -q '[^[:space:]]' notes.md; then + echo "::error::scripts/go-release-notes.mjs gave no notes for $VERSION" + exit 1 + fi + delimiter="notes_$(openssl rand -hex 16)" + { + echo "notes<<$delimiter" + cat notes.md + echo "$delimiter" + } >> "$GITHUB_OUTPUT" + build: name: Build and test the release + needs: notes runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 90 env: @@ -93,11 +173,13 @@ jobs: - name: Refuse a tag that already exists run: | - tag="languages/golang/v$VERSION" - if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then - echo "::error::$tag already exists; a Go module version is immutable once fetched. To finish a failed release, re-run its failed jobs instead." - exit 1 - fi + for dir in $MODULES; do + tag="$dir/v$VERSION" + if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + echo "::error::$tag already exists; a Go module version is immutable once fetched. To finish a failed release, re-run its failed jobs instead." + exit 1 + fi + done # The tag check misses a version whose tag was deleted after the proxy # fetched it. The proxy goes on serving that version and sum.golang.org @@ -110,15 +192,26 @@ jobs: # Here and not in `publish`, so a re-run of `publish` that finds its own # earlier tag is not refused. - name: Refuse a version the Go proxy already lists + # A module the proxy has never fetched, such as encrypttest before its + # first release, answers 404 (or 410): it has no versions, so nothing + # is listed. Any other failure fails closed. run: | set -euo pipefail - module=github.com/cipherstash/stack/languages/golang - list=$(curl -fsS --retry 3 "https://proxy.golang.org/$module/@v/list") \ - || { echo "::error::could not read the Go proxy's version list for $module"; exit 1; } - if grep -qxF "v$VERSION" <<< "$list"; then - echo "::error::the Go proxy already lists $module v$VERSION; its contents are fixed even though the tag is gone. Release a new version." - exit 1 - fi + body=$(mktemp) + for dir in $MODULES; do + module="github.com/cipherstash/stack/$dir" + code=$(curl -sS --retry 3 -o "$body" -w '%{http_code}' "https://proxy.golang.org/$module/@v/list") \ + || { echo "::error::could not read the Go proxy's version list for $module"; exit 1; } + case "$code" in + 200) list=$(cat "$body") ;; + 404 | 410) list="" ;; + *) echo "::error::could not read the Go proxy's version list for $module (HTTP $code)"; exit 1 ;; + esac + if grep -qxF "v$VERSION" <<< "$list"; then + echo "::error::the Go proxy already lists $module v$VERSION; its contents are fixed even though the tag is gone. Release a new version." + exit 1 + fi + done # No cache: this job builds the binaries that are published, and a # poisoned restore would ship in them. scripts/lint-no-workflow-caching.mjs @@ -170,8 +263,30 @@ jobs: mise run wasm:guest:build:eql mise run wasm:auth-guest:build - # Hashed before the test builds and the tests run, and checked again - # after them below, so the guests committed are the ones tested. + # The test builds ship too: package encrypttest embeds them. Every + # stack-encrypt build writes the same cargo output and differs only in + # where its task copies it, so the production guests are hashed before + # the test builds run and checked after: a task that copied a seeded + # build over a production guest stops the release here, rather than + # being hashed and tagged as production. + - name: Build the test guests + run: | + set -euo pipefail + read -ra guests <<< "$GUESTS" + production=() + for guest in "${guests[@]}"; do + case "$guest" in + */encrypttest/wasm/*) ;; + *) production+=("$guest") ;; + esac + done + sha256sum "${production[@]}" > "$RUNNER_TEMP/production.sha256" + mise run wasm:guest:build:deterministic + mise run wasm:guest:build:eql:deterministic + sha256sum -c "$RUNNER_TEMP/production.sha256" + + # Hashed before the tests run, and checked again after them below, so + # the guests committed are the ones tested. - name: Hash the guests run: | set -euo pipefail @@ -180,18 +295,23 @@ jobs: sha256sum "${guests[@]}" > release-out/guests.sha256 cat release-out/guests.sha256 - # The deterministic test builds the hermetic Go tests load. - - name: Build the test guests - run: | - mise run wasm:guest:build:deterministic - mise run wasm:guest:build:eql:deterministic - - name: Go tests against the guests being released run: mise run go:test - name: Check the tests ran against the guests being released run: sha256sum -c release-out/guests.sha256 + # In the tree, encrypttest requires the SDK at the zero pseudo-version + # and replaces it with ../..; a consumer ignores the replace, so the + # release commit names the version it tags. Staged for the commit + # below. `publish` runs the same script before it commits, and refuses + # a tree that differs. + - name: Pin the encrypttest module to this version + run: | + set -euo pipefail + scripts/go-release-pin-encrypttest.sh "$VERSION" + git add languages/golang/encrypt/encrypttest/go.mod + # The release commit, made here only to prove it: `publish` makes it # again from the artifact and must arrive at the same tree. Built from # `git archive` of that commit, so only committed files take part, as @@ -217,6 +337,18 @@ jobs: git archive HEAD languages/golang | tar -x -C "$fetched" (cd "$fetched" && sha256sum -c "$GITHUB_WORKSPACE/release-out/guests.sha256") (cd "$fetched/languages/golang" && GOWORK=off GOFLAGS=-mod=readonly go build ./...) + (cd "$fetched/languages/golang/encrypt/encrypttest" && GOWORK=off GOFLAGS=-mod=readonly go build ./...) + # That build runs under the replace, which a consumer ignores, so it + # cannot show what the pinned requirement says. Go's own parser + # reads it back: the SDK at exactly this version. Whether that + # version resolves cannot be asked before the tag exists; verify + # downloads both modules after the push. + pinned=$(cd "$fetched/languages/golang/encrypt/encrypttest" && go mod edit -json \ + | jq -r '.Require[] | select(.Path == "github.com/cipherstash/stack/languages/golang") | .Version') + if [ "$pinned" != "v$VERSION" ]; then + echo "::error::the encrypttest module on the release commit requires the SDK at '$pinned', not v$VERSION" + exit 1 + fi echo "tree=$tree" >> "$GITHUB_OUTPUT" echo "release tree $tree" @@ -241,7 +373,7 @@ jobs: publish: name: Tag and release - needs: build + needs: [notes, build] runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 15 # Required reviewers set on this environment in the repository settings @@ -272,6 +404,14 @@ jobs: name: go-release path: release-out + # The same pin the build job made before it committed: run from this + # commit's own script, not from the artifact. + - name: Pin the encrypttest module to this version + run: | + set -euo pipefail + scripts/go-release-pin-encrypttest.sh "$VERSION" + git add languages/golang/encrypt/encrypttest/go.mod + # The artifact comes from a job that ran third-party code after it wrote # guests.sha256, so the manifest is data to check, not a list of paths # to trust: a line naming any other file would put that file in the @@ -313,31 +453,42 @@ jobs: exit 1 fi - # A tag already there is accepted only if an earlier attempt of this - # run pushed it: the same tree, on top of the same source commit. - - name: Push the tag + # One tag for each module, on the one release commit. A tag already + # there is accepted only if an earlier attempt of this run pushed it: + # the same tree, on top of the same source commit. The rest are pushed + # together, atomically, so a module is never tagged without the other. + - name: Push the tags env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - tag="languages/golang/v$VERSION" - if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then - git fetch -q --no-tags --depth=1 origin "+refs/tags/$tag:refs/existing-release" - existing=$(git rev-parse 'refs/existing-release^{commit}') - parent=$(git cat-file -p "$existing" | sed -n 's/^parent //p') - if [ "$(git rev-parse "$existing^{tree}")" = "$TREE" ] && [ "$parent" = "$GITHUB_SHA" ]; then - echo "$tag was pushed by an earlier attempt of this run; keeping it" - exit 0 + push=() + for dir in $MODULES; do + tag="$dir/v$VERSION" + if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + git fetch -q --no-tags --depth=1 origin "+refs/tags/$tag:refs/existing-release" + existing=$(git rev-parse 'refs/existing-release^{commit}') + parent=$(git cat-file -p "$existing" | sed -n 's/^parent //p') + if [ "$(git rev-parse "$existing^{tree}")" = "$TREE" ] && [ "$parent" = "$GITHUB_SHA" ]; then + echo "$tag was pushed by an earlier attempt of this run; keeping it" + continue + fi + echo "::error::$tag already exists and is not this run's release commit" + exit 1 fi - echo "::error::$tag already exists and is not this run's release commit" - exit 1 + git tag -a "$tag" -m "Go module $dir v$VERSION (built from $GITHUB_SHA)" + push+=("refs/tags/$tag") + done + if [ "${#push[@]}" -gt 0 ]; then + git push --atomic "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "${push[@]}" fi - git tag -a "$tag" -m "Go module v$VERSION (built from $GITHUB_SHA)" - git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/$tag" + # The CHANGELOG section arrives through the environment, never + # interpolated into the script, so its text is data to the shell. - name: Create the GitHub release env: GH_TOKEN: ${{ github.token }} + NOTES: ${{ needs.notes.outputs.notes }} run: | set -euo pipefail tag="languages/golang/v$VERSION" @@ -348,11 +499,14 @@ jobs: exit 0 fi { + printf '%s\n\n### Install\n\n' "$NOTES" echo "Go module \`github.com/cipherstash/stack/languages/golang\` v$VERSION, built from $GITHUB_SHA." echo echo '```sh' echo "go get github.com/cipherstash/stack/languages/golang@v$VERSION" echo "go install github.com/cipherstash/stack/languages/golang/cmd/stashgen@v$VERSION" + echo "# for your tests: an offline client (encrypttest.NewClient), at the same version" + echo "go get github.com/cipherstash/stack/languages/golang/encrypt/encrypttest@v$VERSION" echo '```' echo echo "Values this version writes are stored in EQL v4 columns. Install EQL v4 into PostgreSQL with the attached \`eql-v4-install.sql\` (\`psql -f eql-v4-install.sql\`)." @@ -405,17 +559,27 @@ jobs: GOFLAGS: "" run: | set -euo pipefail - module=github.com/cipherstash/stack/languages/golang - # guests.sha256 names paths from the repository root; the module - # zip starts at languages/golang. - sed 's# languages/golang/# #' release-out/guests.sha256 > "$RUNNER_TEMP/module.sha256" + manifest="$PWD/release-out/guests.sha256" cd "$(mktemp -d)" - for attempt in 1 2 3 4 5 6; do - if dir=$(go mod download -json "$module@v$VERSION" | jq -er .Dir); then - (cd "$dir" && sha256sum -c "$RUNNER_TEMP/module.sha256") - exit 0 + pick="$GITHUB_WORKSPACE/scripts/go-release-module-guests.sh" + for module_dir in $MODULES; do + module="github.com/cipherstash/stack/$module_dir" + # guests.sha256 names paths from the repository root; each + # module's zip starts at its directory, and holds only its own. + # shellcheck disable=SC2086 # MODULES is a word list. + "$pick" "$manifest" "$module_dir" $MODULES > "$RUNNER_TEMP/module.sha256" \ + || { echo "::error::no guest belongs to $module"; exit 1; } + resolved="" + for attempt in 1 2 3 4 5 6; do + if dir=$(go mod download -json "$module@v$VERSION" | jq -er .Dir); then + (cd "$dir" && sha256sum -c "$RUNNER_TEMP/module.sha256") + resolved=yes + break + fi + sleep 20 + done + if [ -z "$resolved" ]; then + echo "::error::the Go proxy did not resolve $module v$VERSION" + exit 1 fi - sleep 20 done - echo "::error::the Go proxy did not resolve v$VERSION" - exit 1 diff --git a/.github/workflows/release-plz.yml b/.github/workflows/release-plz.yml index 3e65aee137..8a5130e683 100644 --- a/.github/workflows/release-plz.yml +++ b/.github/workflows/release-plz.yml @@ -275,7 +275,7 @@ jobs: run: | set -euo pipefail publish_needed=false - for crate in stack-auth stack-profile stack-kms stack-encrypt stack-encrypt-derive; do + for crate in stack-auth stack-profile stack-kms stack-encrypt stack-encrypt-derive stack-encrypt-jsonpath; do version="$(grep -m1 '^version = ' "packages/${crate}/Cargo.toml" | cut -d'"' -f2)" # crates.io 403s curl's default User-Agent. published="$(curl -fsSL --retry 3 -H "User-Agent: cipherstash-stack-release (https://github.com/cipherstash/stack)" "https://crates.io/api/v1/crates/${crate}/versions" | jq -r '.versions[].num' | grep -Fx "$version" || true)" diff --git a/.github/workflows/storage-corpus.yml b/.github/workflows/storage-corpus.yml new file mode 100644 index 0000000000..60c503f93e --- /dev/null +++ b/.github/workflows/storage-corpus.yml @@ -0,0 +1,48 @@ +name: Storage corpus (append-only) + +# recipher-frame's storage profile corpus (testdata/storage-v1.json, and +# a storage-vN.json for each later version) pins the bytes customers keep. +# A row the corpus already had must stay, unchanged, in every later release. +# The Rust tests hold the code to the corpus; this holds the corpus to itself: +# scripts/storage_corpus_append_only.py compares each corpus on the pull +# request's base branch with the one in the pull request, as parsed JSON, and +# fails on a removed or changed row, header or version. It moved here from +# cipherstash/vitaminc with the crate. +# +# Pull requests only, so `push` has no filter to mirror; recorded in +# scripts/__tests__/workflow-paths-filter-parity.test.mjs. + +on: + pull_request: + paths: + - packages/recipher-frame/testdata/** + - packages/recipher-frame/scripts/** + - .github/workflows/storage-corpus.yml + +defaults: + run: + shell: bash + +permissions: + contents: read + +jobs: + append-only: + name: Storage corpus is append-only + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + # The check reads the corpus at the merge base, so it needs the base + # branch's history, not a shallow clone. + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Test the check + run: python3 -m unittest discover -s packages/recipher-frame/scripts -p 'test_storage_corpus_append_only.py' + + - name: Check the corpus against the base branch + env: + BASE_REF: ${{ github.base_ref }} + run: python3 packages/recipher-frame/scripts/storage_corpus_append_only.py --base "origin/$BASE_REF" diff --git a/.github/workflows/supply-chain-vitaminc-aead.yml b/.github/workflows/supply-chain-vitaminc-aead.yml new file mode 100644 index 0000000000..cb2fceb8c9 --- /dev/null +++ b/.github/workflows/supply-chain-vitaminc-aead.yml @@ -0,0 +1,132 @@ +name: Supply chain (vitaminc-aead) + +# cargo deny and cargo vet over vitaminc-aead, recipher-frame and +# vitaminc-aead-derive and their dependency graph ONLY. Their config is +# supply-chain/vitaminc-aead/ (see its README.md). The rest of the root +# workspace is not checked by either tool; that is #1842. +# +# Neither tool compiles anything: both read `cargo metadata` and Cargo.lock, +# so each job takes about a minute, most of it setup. +# +# Pull requests that change the three crates, the lockfile or the config +# run both jobs. The nightly schedule runs cargo deny only, on the default +# branch: a RustSec advisory published against a version already in +# Cargo.lock has no pull request to fail. cargo vet reads only the tree, so +# a scheduled run of it would find nothing a pull request did not. Pull +# requests are the only filtered event, so `push` has no filter to mirror; +# recorded in scripts/__tests__/workflow-paths-filter-parity.test.mjs. + +on: + pull_request: + paths: + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** + - supply-chain/vitaminc-aead/** + - Cargo.toml + - Cargo.lock + - mise.test.toml + - .github/workflows/supply-chain-vitaminc-aead.yml + schedule: + # Nightly at 05:13 UTC. Scheduled runs fire from the default branch only. + - cron: "13 5 * * *" + workflow_dispatch: {} + +defaults: + run: + shell: bash + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # cargo-deny and cargo-vet are pinned in mise.test.toml, which mise loads + # only in the test environment. Both jobs call them directly, never + # through `mise run` or `mise x`, so mise-action installs only what each + # job names in install_args. + MISE_ENV: test + CARGO_TERM_COLOR: always + +jobs: + deny: + name: cargo deny (vitaminc-aead crates) + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 15 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + install_args: rust cargo-binstall cargo:cargo-deny + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2404 + + # `--manifest-path` on a workspace member checks that package's graph, + # not the workspace's. `--locked` refuses to touch Cargo.lock, so the + # graph checked is the one the pull request ships. + - name: cargo deny check, one crate at a time + run: | + status=0 + for crate in vitaminc-aead recipher-frame vitaminc-aead-derive; do + echo "::group::$crate" + cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ + --manifest-path "packages/$crate/Cargo.toml" check || status=1 + echo "::endgroup::" + done + exit "$status" + + vet: + name: cargo vet (vitaminc-aead crates) + if: github.event_name != 'schedule' + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 15 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + install_args: rust cargo-binstall cargo:cargo-vet + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2404 + + # The filter drops every other root workspace member, so the graph + # vetted is the three crates and their dependencies. `--locked` reads + # imports.lock as committed rather than fetching the registries. + - name: cargo vet + id: vet + run: | + cargo vet --locked --store-path supply-chain/vitaminc-aead \ + --filter-graph "$(cat supply-chain/vitaminc-aead/filter-graph)" + + # imports.lock keeps only the imported audits the committed graph + # needs, so a bump to a version a trusted registry already audits + # still fails `--locked`. Re-running without it fetches the registries: + # if that passes, the fix is to commit the refreshed imports.lock. + # Only after the vet step itself failed: a failed setup step leaves no + # cargo-vet to re-run. + - name: Say which kind of failure this is + if: failure() && steps.vet.outcome == 'failure' + run: | + store=supply-chain/vitaminc-aead + if cargo vet --store-path "$store" --filter-graph "$(cat "$store/filter-graph")" >/dev/null 2>&1; then + echo "::error title=stale imports.lock::A trusted registry already audits every version here. Run the command in $store/README.md without --locked and commit $store/imports.lock." + else + echo "::error title=unaudited dependency::A version here has neither an audit nor an exemption. See $store/README.md." + fi + exit 1 diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index 9facafed04..c6ea81eec1 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -100,16 +100,23 @@ on: - "packages/eql/docker/**" - "packages/eql/README.md" - "packages/eql/SUPABASE.md" - # The `rust-crates` job's encryption steps compile these by PATH + # The `rust-crates` and `rust-encryption-postgres` jobs' encryption + # steps compile these by PATH # (`eql-bindings`' `stack-encrypt` feature): stack-encrypt, its derive # and stack-kms through `path =`, and stack-auth and stack-profile # through `workspace = true` entries the root `Cargo.toml` resolves to - # paths. The mise-task derivation in eql-workflow-filters.test.mjs + # paths, and the vitaminc-aead crates through the patch table in + # packages/eql/Cargo.toml. The mise-task derivation in eql-workflow-filters.test.mjs # cannot see them (a task body names a cargo package, not a path); the # manifest walk in eql-suite-ci.test.mjs does, and fails when one of them # is missing from this list. + - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" + - "packages/vitaminc-aead/**" + - "packages/recipher-frame/**" + - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -208,8 +215,13 @@ jobs: - "packages/eql/docker/**" - "packages/eql/README.md" - "packages/eql/SUPABASE.md" + - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" + - "packages/vitaminc-aead/**" + - "packages/recipher-frame/**" + - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -503,6 +515,72 @@ jobs: run: | mise run test:sqlx:partition + # The Rust encryption suite against a live database, once per supported + # PostgreSQL version: the JSON tree family's oracle (containment over the + # encrypted column against native `jsonb @>` over the plaintexts), its + # walks and orderings, and the plan-shape test that holds the planner to + # the GIN and btree indexes with every setting at its default. Plan choice + # is a per-version property of the planner, which is why this is a matrix + # and not a step of `rust-crates`. PR and manual dispatch run PG 17 alone; + # a push or the schedule runs the full set, like the SQLx jobs (see + # `setup`). Listed in `ci-required`'s `needs`, like every job here: the + # step it replaced sat inside `rust-crates`, which is. + rust-encryption-postgres: + name: "Rust encryption with PostgreSQL ${{ matrix.postgres-version }}" + needs: [changes, setup] + # Exclusion, not an allowlist — see the note on `build-archive`. + if: >- + github.event_name != 'pull_request' + || needs.changes.outputs.relevant == 'true' + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + postgres-version: ${{ fromJSON(needs.setup.outputs.pg-versions) }} + services: + encryption-postgres: + # Docker's public ECR mirror avoids Docker Hub's anonymous pull limit. + image: public.ecr.aws/docker/library/postgres:${{ matrix.postgres-version }} + env: + POSTGRES_PASSWORD: postgres + # Container port only: Docker picks the host port, and the test step + # reads it from `job.services`, so the number is written once. + ports: + - 5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + cache: true + working_directory: packages/eql + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2204 + # Restores what `rust-crates` saves (the stack-encrypt feature tree) + # and never saves itself: a matrix of fast jobs racing one key would + # overwrite it with whichever finished first. + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + with: + workspaces: packages/eql + shared-key: rust-crates + save-if: false + # The task takes the connection from EQL_TEST_DATABASE_URL alone, and + # the host port in it comes from the service, so the two cannot + # disagree. + - name: Test Rust encryption with PostgreSQL ${{ matrix.postgres-version }} + env: + EQL_TEST_DATABASE_URL: "host=localhost port=${{ job.services.encryption-postgres.ports['5432'] }} user=postgres password=postgres dbname=postgres" + run: mise run test:encryption:postgres + # docs:validate + Clean-DB v3 install smoke. Both are version-relevant, so # they follow the event's PG set (PG17 on PR; 14-17 in the queue). Moved out # of the old per-version test job so they run ONCE per version, not per shard. @@ -630,31 +708,6 @@ jobs: || needs.changes.outputs.relevant == 'true' runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 15 - services: - encryption-postgres: - image: postgres:17 - # Docker Hub refuses pulls without a login after too many from one - # address, and RunsOn machines reach that limit. One expression, not - # `username:` and `password:` keys: GitHub rejects an empty value for - # either key ("Unexpected value ''"), which fails the job on a fork's - # pull request. With either secret empty this gives `{}`, and the - # runner then pulls without a login. - credentials: >- - ${{ secrets.DOCKER_HUB_USERNAME != '' && secrets.DOCKER_HUB_PASSWORD != '' - && fromJSON(format('{{"username":{0},"password":{1}}}', - toJSON(secrets.DOCKER_HUB_USERNAME), toJSON(secrets.DOCKER_HUB_PASSWORD))) - || fromJSON('{}') }} - env: - POSTGRES_PASSWORD: postgres - # Container port only: Docker picks the host port, and the test step - # reads it from `job.services`, so the number is written once. - ports: - - 5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: @@ -690,20 +743,20 @@ jobs: rustup component add --toolchain "${active_rust_toolchain}" rustfmt clippy mise run test:crates - # The three encryption checks are mise tasks rather than raw cargo here, - # so `eql-suite-ci.test.mjs` counts them among the cargo tasks a root + # The block ORE timing harness's ciphertext generator is a detached + # workspace with its own Cargo.lock that no job builds, so its lock is + # checked here rather than left to drift until someone runs the harness. + - name: Check the timing harness's Cargo.lock + run: cargo metadata --locked --format-version 1 --manifest-path tests/timing/ore_block_v2/ctgen/Cargo.toml > /dev/null + + # The encryption checks are mise tasks rather than raw cargo here, so + # `eql-suite-ci.test.mjs` counts them among the cargo tasks a root # workflow must reach, and `eql-workflow-filters.test.mjs` derives the - # paths they read. The database task takes the connection from - # EQL_TEST_DATABASE_URL alone, and the host port in it comes from the - # service, so the two cannot disagree. + # paths they read. The database half runs in `rust-encryption-postgres` + # below, once per supported PostgreSQL version. - name: Test Rust text equality run: mise run test:encryption - - name: Test Rust text equality with PostgreSQL - env: - EQL_TEST_DATABASE_URL: "host=localhost port=${{ job.services.encryption-postgres.ports['5432'] }} user=postgres password=postgres dbname=postgres" - run: mise run test:encryption:postgres - - name: Compile Rust text equality for WASI without HTTP run: mise run check:encryption:wasi @@ -714,6 +767,21 @@ jobs: run: | mise run types:check + # rustdoc for eql-bindings, warnings as errors, in each feature set a + # reader can get: the default (no Stack Encrypt), `targets` (what docs.rs + # builds, from `[package.metadata.docs.rs]`), and every feature. A broken + # or ambiguous intra-doc link compiles and passes every test; only + # rustdoc reports it, and docs.rs would publish the page with the link + # missing. + - name: Build eql-bindings' rustdoc with warnings as errors + env: + RUSTDOCFLAGS: -D warnings + run: | + set -euo pipefail + cargo doc --locked --no-deps -p eql-bindings + cargo doc --locked --no-deps -p eql-bindings --features targets + cargo doc --locked --no-deps -p eql-bindings --all-features + # Publish gate for eql-bindings (the one crate we ship to crates.io via # release-plz). `--dry-run` packages + compiles the crate exactly as # crates.io would, catching publish-blockers — missing `license`/metadata, @@ -828,6 +896,8 @@ jobs: run: mise run test:installer_complete - name: Symbol-order cross-check (v3) run: mise run test:symbol_order_v3 + - name: v4 isolation gate and its self-test + run: mise run test:v4_isolation - name: Build-ordering helper unit tests run: mise run test:build_ordering_helpers @@ -1156,8 +1226,9 @@ jobs: ci-required: name: "ci-required" needs: [changes, setup, build-archive, test, validate, schema, rust-crates, - codegen, self-contained-v3, matrix-coverage, splinter, docs-static, - known-failures, doc-anchors, e2e] + rust-encryption-postgres, codegen, self-contained-v3, + matrix-coverage, splinter, docs-static, known-failures, + doc-anchors, e2e] if: always() runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 10 diff --git a/.github/workflows/tests-bench.yml b/.github/workflows/tests-bench.yml index f470d05375..2e6238f795 100644 --- a/.github/workflows/tests-bench.yml +++ b/.github/workflows/tests-bench.yml @@ -20,6 +20,9 @@ on: - 'languages/typescript/packages/stack-drizzle/**' - 'languages/typescript/packages/test-kit/**' - 'languages/typescript/packages/cli/src/installer/**' + # The SQL the installer applies comes from `@cipherstash/eql`, a + # workspace package; an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' - 'local/**' - '.github/workflows/tests-bench.yml' - '.github/actions/integration-setup/**' @@ -38,6 +41,9 @@ on: - 'languages/typescript/packages/stack-drizzle/**' - 'languages/typescript/packages/test-kit/**' - 'languages/typescript/packages/cli/src/installer/**' + # The SQL the installer applies comes from `@cipherstash/eql`, a + # workspace package; an EQL release bump edits only this directory. + - 'packages/eql/packages/eql/**' - 'local/**' - '.github/workflows/tests-bench.yml' - '.github/actions/integration-setup/**' diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index c36ba2c75b..86f2ad9c30 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -21,8 +21,14 @@ on: - packages/stack-profile/** - packages/stack-kms/** - packages/stack-encrypt/** + - conformance/stack-encrypt/** + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -36,6 +42,7 @@ on: - .cargo/config.toml - .config/nextest.toml - pnpm-lock.yaml + - lychee.toml - .github/workflows/tests-crates.yml push: branches: [main] @@ -44,8 +51,14 @@ on: - packages/stack-profile/** - packages/stack-kms/** - packages/stack-encrypt/** + - conformance/stack-encrypt/** + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -56,6 +69,7 @@ on: - .cargo/config.toml - .config/nextest.toml - pnpm-lock.yaml + - lychee.toml - .github/workflows/tests-crates.yml workflow_dispatch: {} @@ -128,11 +142,20 @@ jobs: - name: nextest run: mise x --env test -- cargo nextest run --locked --workspace --all-features + # The run above turns every feature on at once; this tests the AEAD + # crates' optional features one at a time. The run above tests the AES + # cipher with aws-lc-rs only. This also tests it with the RustCrypto + # backend, and runs stack-encrypt's heap_hygiene test with it. + - name: vitaminc-aead feature combinations + run: mise run test:vitaminc-aead:features + - name: doctests run: mise run test:doc # Rustdoc with warnings as errors, one `doc:` task per crate. # `test:doc` runs the examples; only this sees a broken intra-doc link. + # Each task builds the public docs, then the docs of private items too, + # so a broken link in a private module's docs also fails. - name: rustdoc run: mise run doc @@ -142,7 +165,7 @@ jobs: run: cargo build --locked -p stack-encrypt --examples # The crates release-plz publishes. `--dry-run` packages and compiles - # each the way crates.io would (all five together, so each resolves the + # each the way crates.io would (all six together, so each resolves the # others from cargo's temporary local registry rather than from # crates.io), catching a publish-blocker on the PR instead of in # release-crates on main: missing metadata, a runtime path dependency @@ -153,8 +176,164 @@ jobs: # `--allow-dirty` tolerates files earlier steps leave in the tree. Once a # version is on crates.io, cargo warns rather than fails on a dry run of # it. + # + # One failure is a warning, not an error: a dependency cargo cannot find + # on crates.io at all, when that dependency is named in + # `awaiting_first_publish`. Those are crates of this workspace that will + # be published but have not been yet, so no packaged build can resolve + # them until they are. `cargo publish` refuses the crate that needs one + # at release time, so nothing can ship by mistake. The crate that needs + # it is dropped with a warning and the rest are packaged again, so they + # are still verified. Any other failure fails the step, including a + # dependency on a crate that is `publish = false` for good, such as + # stack-guest-abi. Remove a name from the list once it is on crates.io. - name: Verify the stack-* crates package cleanly for crates.io - run: cargo publish --locked --dry-run --allow-dirty -p stack-profile -p stack-auth -p stack-kms -p stack-encrypt-derive -p stack-encrypt + run: | + set -euo pipefail + crates=(stack-profile stack-auth stack-kms stack-encrypt-jsonpath stack-encrypt-derive stack-encrypt) + awaiting_first_publish=(recipher-frame) + target_dir="$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.target_directory')" + while [ "${#crates[@]}" -gt 0 ]; do + args=() + for crate in "${crates[@]}"; do args+=(-p "$crate"); done + # cargo's own status is kept in `status`: `|| status=$?` reads it + # before anything else runs. + status=0 + out="$(cargo publish --locked --dry-run --allow-dirty "${args[@]}" 2>&1)" || status=$? + printf '%s\n' "$out" + if [ "$status" -eq 0 ]; then + exit 0 + fi + missing="$(sed -n 's/^ *no matching package named `\([^`]*\)` found$/\1/p' <<<"$out" | head -n 1)" + needs="$(sed -n 's/^ *required by package `\([^ `]*\) v.*$/\1/p' <<<"$out" | head -n 1)" + awaiting=0 + for crate in "${awaiting_first_publish[@]}"; do + if [ "$crate" = "$missing" ]; then awaiting=1; fi + done + if [ -z "$missing" ] || [ -z "$needs" ] || [ "$awaiting" -eq 0 ]; then + exit "$status" + fi + remaining=() + for crate in "${crates[@]}"; do + if [ "$crate" != "$needs" ]; then remaining+=("$crate"); fi + done + if [ "${#remaining[@]}" -eq "${#crates[@]}" ]; then + exit "$status" + fi + echo "::warning title=${needs} not verified against crates.io::${needs} depends on ${missing}, a crate of this workspace that is waiting for its first publish, so it cannot be packaged against crates.io. cargo publish refuses ${needs} until ${missing} is published. The other crates are verified without it." + crates=("${remaining[@]}") + # The attempt left its temporary registry of packaged crates + # behind; the next one must start without it, or cargo finds a + # crate there with no checksum and stops. + rm -rf -- "${target_dir}/package" + done + + # vitaminc-aead's tests on wasm32-wasip1, the target the Go guests build + # for, with wasmtime as the test runner. On that target the `aes` feature + # uses RustCrypto's aes-gcm. The task says which tests it skips and why. + vitaminc-aead-wasip1: + name: vitaminc-aead tests on wasm32-wasip1 + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 30 + env: + RUSTFLAGS: "-D warnings" + # wasmtime is pinned in mise.test.toml, which mise loads only in the + # test environment. + MISE_ENV: test + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # No install_args, as in `rust`: this installs (and caches) the whole + # test toolset, wasmtime with it. + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2404 + + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + + - name: vitaminc-aead tests on wasm32-wasip1 (wasmtime) + run: mise run test:vitaminc-aead:wasip1 + + # rustdoc checks intra-doc links but never fetches a URL, so this checks + # the web links in the crates' docs with lychee. It reads every crate under + # packages/ except EQL, which has its own docs checks. lychee.toml holds + # the shared settings and the addresses CI cannot fetch. + doc-links: + name: links in the Rust docs + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # A Rust file is mostly code, and its test strings hold URLs that are + # not links (`http://localhost:3001/`, `https://kms/0`). This copies + # only the doc comments of each file, as Markdown, to one file per + # source file. Every other line becomes blank, so a reported line + # number is the line in the source. + - name: Extract the doc comments + run: | + out="$RUNNER_TEMP/rust-docs" + git ls-files -z 'packages/*.rs' ':(exclude)packages/eql' | + while IFS= read -r -d '' file; do + mkdir -p "$out/$(dirname "$file")" + awk '{ + if (match($0, /^[ \t]*\/\/[\/!]/)) { + line = substr($0, RLENGTH + 1) + sub(/^ /, "", line) + print line + } else { + print "" + } + }' "$file" > "$out/$file.md" + done + + # lychee from its release, checked against the SHA-256 of that release + # asset (the `digest` GitHub records for it), so the binary that runs + # is the one that was reviewed. To move to a new version, change both + # lines together. + - name: Install lychee + env: + LYCHEE_VERSION: v0.24.2 + LYCHEE_SHA256: 1f4e0ef7f6554a6ed33dd7ac144fb2e1bbed98598e7af973042fc5cd43951c9a + run: | + set -euo pipefail + dir="$RUNNER_TEMP/lychee" + mkdir -p "$dir" + asset=lychee-x86_64-unknown-linux-gnu.tar.gz + curl -sSfL -o "$dir/$asset" \ + "https://github.com/lycheeverse/lychee/releases/download/lychee-${LYCHEE_VERSION}/${asset}" + echo "${LYCHEE_SHA256} $dir/$asset" | sha256sum --check --strict + tar -xzf "$dir/$asset" -C "$dir" --strip-components=1 lychee-x86_64-unknown-linux-gnu/lychee + echo "$dir" >> "$GITHUB_PATH" + + # The doc comments' intra-doc links (`crate::Foo`) read as relative + # file paths, which rustdoc checks already, so only web links are + # checked here. + - name: Check the web links in the doc comments + env: + GITHUB_TOKEN: ${{ github.token }} + run: >- + lychee --config lychee.toml + --scheme https --scheme http + "$RUNNER_TEMP/rust-docs/**/*.md" + + # The crates' Markdown: READMEs (some are a crate's docs), changelogs, + # ADRs and guides. Links to files in the repository are checked too. + - name: Check the links in the crates' Markdown + env: + GITHUB_TOKEN: ${{ github.token }} + run: lychee --config lychee.toml 'packages/*/**/*.md' node-bindings: name: node bindings, napi typings, stack-auth-wasm diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 727015047d..4b53760efc 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -16,7 +16,15 @@ name: Tests (Go) # go-lint golangci-lint, Linux only. # go-binding-cross # the same Go tests on macOS and Windows, against the guests -# Linux built, after checking their sha256. +# Linux built, after checking their sha256. For now, a pull +# request into any branch but main runs macOS only (#2017). +# eql-postgres +# the Go module's PostgreSQL tests, against PostgreSQL 17 with +# the EQL v4 bundle built from this tree installed: rows the Go +# SDK stores in every EQL type it produces, found by the queries +# it derives, through EQL's operators; and a few hundred random +# values in every ordered type, which must order as their +# plaintexts do. # live the Go live tests and the stack-encrypt examples, against real # ZeroKMS with the repository's CS_* credentials. # @@ -31,14 +39,39 @@ on: - packages/stack-profile/** - packages/stack-kms/** - packages/stack-encrypt/** + - conformance/stack-encrypt/** + # encrypt/frame's tests read the value corpus. + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** + # eql-postgres installs the EQL v4 bundle `mise run build` writes from + # these, so a SQL change starts the Go test that runs against it. + - packages/eql/src/** + - packages/eql/tasks/** + - packages/eql/crates/eql-codegen/** + - packages/eql/Cargo.toml + - packages/eql/mise.toml + # The Go tests read the cross-language fixtures the EQL suite writes, + # which are derived under EQL's lockfile. + - packages/eql/tests/encryption/** + - packages/eql/Cargo.lock - languages/golang/** - scripts/check-wasm-imports.py - scripts/go-binding-test.sh + - scripts/go-nested-modules.sh + - scripts/stack-conformance.sh + - scripts/stack-conformance-selection.mjs + - scripts/stack-eql-conformance.mjs + - scripts/stack-conformance-evidence.mjs + - scripts/stack-lifecycle-conformance.mjs + - scripts/stack-exchange-conformance.mjs - Cargo.toml - Cargo.lock - .cargo/** @@ -56,14 +89,39 @@ on: - packages/stack-profile/** - packages/stack-kms/** - packages/stack-encrypt/** + - conformance/stack-encrypt/** + # encrypt/frame's tests read the value corpus. + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** + # eql-postgres installs the EQL v4 bundle `mise run build` writes from + # these, so a SQL change starts the Go test that runs against it. + - packages/eql/src/** + - packages/eql/tasks/** + - packages/eql/crates/eql-codegen/** + - packages/eql/Cargo.toml + - packages/eql/mise.toml + # The Go tests read the cross-language fixtures the EQL suite writes, + # which are derived under EQL's lockfile. + - packages/eql/tests/encryption/** + - packages/eql/Cargo.lock - languages/golang/** - scripts/check-wasm-imports.py - scripts/go-binding-test.sh + - scripts/go-nested-modules.sh + - scripts/stack-conformance.sh + - scripts/stack-conformance-selection.mjs + - scripts/stack-eql-conformance.mjs + - scripts/stack-conformance-evidence.mjs + - scripts/stack-lifecycle-conformance.mjs + - scripts/stack-exchange-conformance.mjs - Cargo.toml - Cargo.lock - .cargo/** @@ -90,6 +148,7 @@ env: RUSTFLAGS: "-D warnings" RUST_BACKTRACE: full CARGO_TERM_COLOR: always + STACK_CONFORMANCE_REQUIRED: "1" CARGO_NET_GIT_FETCH_WITH_CLI: true jobs: @@ -108,6 +167,18 @@ jobs: with: persist-credentials: false + # Native EQL conformance uses the EQL workspace's toolchain. Install it + # before root setup, so ordinary guest commands retain the root pin. + # Its local DATABASE_URL must not enable database tests in this job. + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: packages/eql + env: false + cache: true + cache_key_prefix: mise-v1-ubuntu-2204 + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 with: version: 2026.4.0 @@ -133,6 +204,7 @@ jobs: . languages/golang/encrypt/guest languages/golang/auth/guest + packages/eql # The HTTP-free core compiles for wasm32-wasip1 with no JS-host backend # and no native HTTP/TLS stack in its graph: the invariant the wazero @@ -155,11 +227,12 @@ jobs: - name: stack-encrypt guest release build and import-surface gate run: mise run wasm:guest:build - # The deterministic-kms TEST build, under encrypt/testdata where no - # build or embed sees it: the Go tests open the record fixture Rust - # sealed through it, and run round trips with no ZeroKMS. The tests - # skip when it is absent, so a build that forgets this step would pass - # with less coverage, which is why the job builds it unconditionally. + # The deterministic-kms TEST build, under encrypt/encrypttest/wasm, + # which package encrypttest embeds: the Go tests open the record + # fixture Rust sealed through it, and run round trips with no ZeroKMS. + # The encrypt package's tests skip when it is absent, so a build that + # forgets this step would pass with less coverage, which is why the job + # builds it unconditionally. encrypttest's own tests fail without it. - name: stack-encrypt guest deterministic test build run: mise run wasm:guest:build:deterministic @@ -186,7 +259,7 @@ jobs: # same bytes rather than a stale or rebuilt guest. - name: Record the guests' checksums run: | - for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/testdata/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/testdata/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do + for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do (cd languages/golang && openssl dgst -sha256 "$guest" | awk '{print $NF}' > "$guest.sha256" && echo "$guest sha256 $(cat "$guest.sha256")") done @@ -197,12 +270,12 @@ jobs: path: | languages/golang/encrypt/wasm/stack_encrypt_guest.wasm languages/golang/encrypt/wasm/stack_encrypt_guest.wasm.sha256 - languages/golang/encrypt/testdata/stack_encrypt_guest_deterministic.wasm - languages/golang/encrypt/testdata/stack_encrypt_guest_deterministic.wasm.sha256 + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm.sha256 languages/golang/encrypt/eql/wasm/stack_encrypt_guest_eql.wasm languages/golang/encrypt/eql/wasm/stack_encrypt_guest_eql.wasm.sha256 - languages/golang/encrypt/testdata/stack_encrypt_guest_eql_deterministic.wasm - languages/golang/encrypt/testdata/stack_encrypt_guest_eql_deterministic.wasm.sha256 + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm + languages/golang/encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm.sha256 languages/golang/auth/wasm/stack_auth_guest.wasm languages/golang/auth/wasm/stack_auth_guest.wasm.sha256 if-no-files-found: error @@ -215,11 +288,74 @@ jobs: - name: Go binding env: STACK_ENCRYPT_TESTS_REQUIRE_LOCK: "1" + STACK_CONFORMANCE_OUTPUT: ${{ runner.temp }}/stack-conformance-go.json run: | ulimit -l "$(ulimit -H -l)" echo "RLIMIT_MEMLOCK: $(ulimit -l) KiB" mise run go:test + - name: Required lifecycle and key-I/O conformance + env: + STACK_CONFORMANCE_REPORT_DIR: ${{ runner.temp }}/lifecycle-conformance + run: mise run test:conformance:lifecycle + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: lifecycle-conformance + path: ${{ runner.temp }}/lifecycle-conformance/*.json + if-no-files-found: error + + - name: Required EQL and JSON conformance + env: + STACK_CONFORMANCE_REPORT_DIR: ${{ runner.temp }}/eql-conformance-fast + run: mise run test:conformance:eql + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: eql-conformance-fast + path: ${{ runner.temp }}/eql-conformance-fast/*.json + if-no-files-found: error + + - name: Fresh Go scalar artifacts open in Rust + env: + STACK_CONFORMANCE_INPUT: ${{ runner.temp }}/stack-conformance-go.json + run: | + test -s "$STACK_CONFORMANCE_INPUT" + mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance + + # Both directions, in a fresh directory: Rust and Go each write values + # of every kind, records with terms, opaque blobs and EQL rows, and the + # other opens them and derives the same query terms. The task fails on + # a missing guest or runner and on an empty output, and its report + # records the producers, engines, guests and storage versions. + - name: Required fresh cross-language artifact exchange + env: + STACK_CONFORMANCE_REPORT_DIR: ${{ runner.temp }}/exchange-conformance + run: mise run test:conformance:exchange + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: exchange-conformance + path: ${{ runner.temp }}/exchange-conformance/*.json + if-no-files-found: error + + # The Rust suite opens the committed v4_rows.json, + # v4_smallint_rows.json and v4_json_rows.json, whose ciphertexts the Go + # SDK sealed when each file was last regenerated. This also hands it the rows the Go SDK + # seals in this run, so a Go guest and a native Rust build that stop + # agreeing on today's ciphertexts fail here rather than when someone + # next regenerates a file. Both filters are exact, so each test named + # here is one that reads the rows handed to it. The toolchain is the + # root's pin, as for the guests. + - name: Rows the Go SDK seals today open in Rust + run: | + rows="$RUNNER_TEMP/v4_rows.json" + smallint_rows="$RUNNER_TEMP/v4_smallint_rows.json" + json_rows="$RUNNER_TEMP/v4_json_rows.json" + (cd languages/golang && CGO_ENABLED=0 EQL_V4_ROWS_OUT="$rows" EQL_V4_SMALLINT_ROWS_OUT="$smallint_rows" EQL_V4_JSON_ROWS_OUT="$json_rows" go test -count=1 -run '^(TestV4RowsMatchTheCommittedFixture|TestV4SmallintRowsMatchTheCommittedFixture|TestV4JSONRowsMatchTheCommittedFixture)$' ./encrypt) + test -s "$rows" && test -s "$smallint_rows" && test -s "$json_rows" + EQL_V4_ROWS="$rows" EQL_V4_SMALLINT_ROWS="$smallint_rows" EQL_V4_JSON_ROWS="$json_rows" cargo test --locked --manifest-path packages/eql/Cargo.toml -p eql-encryption-tests --test v4_types -- --exact rows_the_go_sdk_sealed_open_in_rust smallint_rows_the_go_sdk_sealed_open_in_rust json_rows_the_go_sdk_sealed_open_in_rust + # What is encrypted is fixed before the program ships: every generated # file is committed, and this fails when `go generate` would change # one. It runs the real stashgen against the guest just built, so it @@ -230,6 +366,11 @@ jobs: working-directory: languages/golang run: | CGO_ENABLED=0 go generate ./... + # The nested modules (encrypt/example holds generated code) are + # outside `./...`, so each runs its own go generate. + ../../scripts/go-nested-modules.sh | while IFS= read -r nested; do + (cd "$nested" && CGO_ENABLED=0 go generate ./...) + done git diff --exit-code -- . untracked="$(git status --porcelain -- .)" if [ -n "$untracked" ]; then @@ -272,7 +413,14 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-latest, windows-latest] + # Windows is off for a pull request into any branch but main, to save + # runner time while the milestone's work lands in next. A pull + # request into main, a push, and a manual dispatch still run it. #2017 + # restores `os: [macos-latest, windows-latest]` for every event. + # The list is chosen when the run starts, and a change of base starts + # no run. So a pull request moved onto main needs a new push, or a + # rerun, before Windows runs for it. + os: ${{ fromJSON((github.event_name != 'pull_request' || github.base_ref == 'main') && '["macos-latest","windows-latest"]' || '["macos-latest"]') }} runs-on: ${{ matrix.os }} timeout-minutes: 30 steps: @@ -313,7 +461,7 @@ jobs: - name: The guests are the ones Linux built and checked run: | cd languages/golang - for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/testdata/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/testdata/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do + for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do want=$(cat "$guest.sha256") got=$(openssl dgst -sha256 "$guest" | awk '{print $NF}') if [ "$want" != "$got" ]; then @@ -326,11 +474,116 @@ jobs: - name: Go binding run: scripts/go-binding-test.sh languages/golang + # The Go SDK's rows and queries inside PostgreSQL with EQL installed: the + # path a program using the SDK runs. Its own job because it builds the EQL + # v4 bundle under packages/eql's mise config, which pins its own Rust; the + # guests are the ones wasi-check built and checked. + eql-postgres: + env: + MISE_ENV: test + name: Go rows and queries in PostgreSQL with EQL v4 + needs: wasi-check + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 30 + services: + postgres: + # Docker's public ECR mirror avoids Docker Hub's anonymous pull limit. + image: public.ecr.aws/docker/library/postgres:17 + env: + POSTGRES_PASSWORD: postgres + # Container port only: Docker picks the host port, and the test step + # reads it from `job.services`, so the number is written once. + ports: + - 5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # The root config for Go, and EQL's for the build of its bundle. + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2204 + + # mise caches Rust symlinks, not ~/.rustup. A cache hit can leave a + # toolchain directory without cargo and still report "all tools + # installed". The step above exports RUSTUP_TOOLCHAIN=1.94.1, and the + # EQL step below compiles cargo:sqlx-cli with it when the cache does not + # hold that tool, so the root toolchain is repaired before that step: + # after it, the build fails with "Missing manifest in toolchain". + - name: Restore the root Rust toolchain behind the cached mise link + run: | + mise install --force rust + mise x -- cargo --version + + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: packages/eql + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2204 + + # The same repair for EQL's own toolchain, before cargo is used. + - name: Restore the EQL Rust toolchain behind the cached mise link + run: | + mise -C packages/eql install --force rust + mise -C packages/eql x -- cargo --version + + # `mise run build` compiles eql-codegen to write the bundle. + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + with: + workspaces: packages/eql + + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: wasm-guests + path: languages/golang + + - name: The guests are the ones wasi-check built and checked + run: | + cd languages/golang + for guest in encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm; do + want=$(cat "$guest.sha256") + got=$(openssl dgst -sha256 "$guest" | awk '{print $NF}') + if [ "$want" != "$got" ]; then + echo "$guest checksum mismatch: artifact says $want, file is $got" >&2 + exit 1 + fi + echo "$guest sha256 $got" + done + + # Builds the bundle from the tree, installs it, and runs the tests; a + # skip fails the task, so a missing guest or database cannot pass. + - name: Go rows, queries and required JSON conformance through EQL v4 + env: + EQL_TEST_DATABASE_URL: "host=localhost port=${{ job.services.postgres.ports['5432'] }} user=postgres password=postgres dbname=postgres sslmode=disable" + STACK_CONFORMANCE_REPORT_DIR: ${{ runner.temp }}/eql-conformance-postgres + run: mise run go:test:postgres + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: eql-conformance-postgres + path: ${{ runner.temp }}/eql-conformance-postgres/*.json + if-no-files-found: error + # Round trips through real ZeroKMS. The Go live tests skip without their # STACK_ENCRYPT_TEST_* variables, so the secrets pre-flight runs first and # turns a missing credential into a failure rather than a silent skip. The - # stack-encrypt examples read CS_* through `StackCipher::new()`; tests-crates - # builds them, and this job runs them. + # stack-encrypt examples read CS_* through + # `StackCipher::with_detected_credentials()`; tests-crates builds them, and + # this job runs them. live: name: Go live tests and stack-encrypt examples needs: wasi-check @@ -379,7 +632,7 @@ jobs: - name: The guests are the ones the wasi-check job built and checked run: | cd languages/golang - for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/testdata/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/testdata/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do + for guest in encrypt/wasm/stack_encrypt_guest.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_deterministic.wasm encrypt/eql/wasm/stack_encrypt_guest_eql.wasm encrypt/encrypttest/wasm/stack_encrypt_guest_eql_deterministic.wasm auth/wasm/stack_auth_guest.wasm; do want=$(cat "$guest.sha256") got=$(openssl dgst -sha256 "$guest" | awk '{print $NF}') if [ "$want" != "$got" ]; then @@ -391,9 +644,17 @@ jobs: # The whole package, not a `-run` filter: live tests are the ones that # call `liveClient`, and not all of them are named `TestLive*`. + # ./encrypt/... stops at the nested modules (encrypt/encrypttest, + # encrypt/example), so each runs too: a live test added to one of them + # would otherwise never run here. - name: Go live tests working-directory: languages/golang - run: CGO_ENABLED=0 go test -v ./encrypt/... + run: | + set -euo pipefail + CGO_ENABLED=0 go test -v ./encrypt/... + ../../scripts/go-nested-modules.sh | while IFS= read -r nested; do + (cd "$nested" && CGO_ENABLED=0 go test -v ./...) + done - name: stack-encrypt examples run: | diff --git a/.github/workflows/tests-recipher-js.yml b/.github/workflows/tests-recipher-js.yml new file mode 100644 index 0000000000..ef5f62a4f2 --- /dev/null +++ b/.github/workflows/tests-recipher-js.yml @@ -0,0 +1,177 @@ +name: Tests (recipher-js) + +# `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine: +# its detached Cargo workspace (the napi-rs 3 addon `recipher-js`, and the +# value bridge `recipher-value-napi`) and the suites that load the addon. +# +# This workflow runs every test the package has: `test:cargo`, `build:debug` +# (napi-rs's CLI, which also writes the committed `native.d.ts`), +# `test:addon`, and `test` (the suites that need no addon, and the typecheck +# with the type tests). tests.yml's live jobs skip a change that touches only +# this package, so nothing else runs them for it. Every test here +# is offline, over the engine's deterministic test keys, so the job takes no +# credentials. +# +# The engine crates and the root Cargo.toml are in the filter: the crate +# depends on stack-encrypt by path, and stack-encrypt's `workspace = true` +# dependencies resolve against the root manifest. + +on: + pull_request: + paths: + - languages/typescript/packages/recipher-js/** + - packages/stack-auth/** + - packages/stack-profile/** + - packages/stack-kms/** + - packages/stack-encrypt/** + - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** + - Cargo.toml + - mise.toml + - pnpm-lock.yaml + # The last step runs `turbo run test`, which reads turbo.json. + - turbo.json + - .github/workflows/tests-recipher-js.yml + push: + branches: [main] + paths: + - languages/typescript/packages/recipher-js/** + - packages/stack-auth/** + - packages/stack-profile/** + - packages/stack-kms/** + - packages/stack-encrypt/** + - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** + - Cargo.toml + - mise.toml + - pnpm-lock.yaml + # The last step runs `turbo run test`, which reads turbo.json. + - turbo.json + - .github/workflows/tests-recipher-js.yml + workflow_dispatch: {} + +permissions: + contents: read + +defaults: + run: + shell: bash + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + RUST_BACKTRACE: full + CARGO_TERM_COLOR: always + CARGO_NET_GIT_FETCH_WITH_CLI: true + # The bridge's frame suite (value-napi/tests/frames.cjs) refuses to + # regenerate its pinned frames when this is set, so a stray + # RECIPHER_UPDATE_FIXTURES cannot re-pin a regression here. + STACK_CONFORMANCE_REQUIRED: "1" + +jobs: + recipher-js: + name: cargo checks, the addon, and its suites (Linux) + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache + # The slowest run so far took under three minutes. A run that is still + # going at ten is stuck, not slow: stop it rather than pay for 45. + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # At the repository root: the root mise.toml pins rust 1.94.1. + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + install_args: rust + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2204 + + # As in tests-crates.yml: a cached toolchain can lack the components + # mise.toml declares. A no-op when they are there. + - name: Add rustfmt and clippy to the pinned toolchain + run: rustup component add rustfmt clippy + + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + with: + workspaces: languages/typescript/packages/recipher-js -> target + + - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + run_install: false + + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: 22 + cache: 'pnpm' + + # node-pty falls back to `node-gyp rebuild` on Linux during any + # workspace install. See scripts/__tests__/workflow-node-gyp.test.mjs. + - name: Install node-gyp + run: npm install -g node-gyp + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # `cargo test --locked`, `cargo fmt --check` and clippy, with every + # feature. The tests include the checks that the addon links no + # eql-bindings, and that a build with its default features (the + # release build) has no test cipher. They also run the value bridge's + # Node suites against its test addon. + - name: cargo checks + run: pnpm --filter @cipherstash/recipher run test:cargo + + # The debug addon, with the test cipher, as `recipher.node`. napi-rs + # writes the addon's TypeScript declarations to `native.d.ts`, which is + # committed: the package's TypeScript imports its types from it. + - name: Build the addon + run: pnpm --filter @cipherstash/recipher run build:debug + + # The build must leave the tracked tree as it found it. Nothing else + # regenerates `native.d.ts`, so a change to a `#[napi]` item that is not + # rebuilt and committed would leave declarations that disagree with the + # addon; `git status` also catches an untracked file the build leaves. + - name: Guard the committed declarations and Cargo.lock against drift + run: | + dirty=$(git status --porcelain -- languages/typescript/packages/recipher-js) + if [ -n "$dirty" ]; then + echo "$dirty" + git diff -- languages/typescript/packages/recipher-js + echo "::error::the recipher-js build changed tracked files or left untracked ones. Run 'pnpm --filter @cipherstash/recipher run build:debug' and commit native.d.ts and Cargo.lock; ignore other build outputs in the package's .gitignore." + exit 1 + fi + + # Builds the TypeScript (tsup) first: one suite runs the ESM and the + # CommonJS build in one process. + - name: Suites that load the addon + run: pnpm --filter @cipherstash/recipher run test:addon + + # The value bridge's test addon is a workspace of its own, which + # `test:cargo` does not reach, so it is checked by its manifest. Its + # clippy shares the directory `tests/node.rs` builds it in. It has no + # tests, and without them `--all-targets` would report its module entry + # point unused. + - name: The value bridge's test addon + working-directory: languages/typescript/packages/recipher-js + run: | + cargo fmt --manifest-path value-napi/tests/addon/Cargo.toml --check + cargo clippy --locked --manifest-path value-napi/tests/addon/Cargo.toml \ + --target-dir target/napi-test-addon -- -D warnings + + # The package's `test`: the suites that need no addon, and the + # typecheck with the type tests. tests.yml's live jobs skip a change + # that touches only this package, so this workflow runs it. + - name: Suites that need no addon, and the typecheck + run: pnpm exec turbo run test --filter @cipherstash/recipher diff --git a/.github/workflows/tests-rust.yml b/.github/workflows/tests-rust.yml index 3d05d70ecc..e7f47fef3f 100644 --- a/.github/workflows/tests-rust.yml +++ b/.github/workflows/tests-rust.yml @@ -29,7 +29,7 @@ on: # languages/typescript/packages/protect-ffi at all. The workspace root manifest comes with it: # cargo reads it for the crate's workspace context, so a # `.workspace = true` added to eql-bindings becomes a compile input - # with no other trace. Same two entries as the native cache key in + # with no other trace. The same entries as the native cache key in # `.github/actions/build-ffi-binding`, which is where the list is derived # from — pinned by # scripts/__tests__/wasm-build-inputs-paths-filter.test.mjs. @@ -37,7 +37,17 @@ on: # This is the only copy: `push:` below is `branches: [main]` with no # `paths:`, so main runs a superset of what PRs run (recorded as a # deliberate asymmetry in workflow-paths-filter-parity.test.mjs). - - 'packages/eql/crates/**' + # Only the eql-bindings files cargo compiles into the binding, as + # the cache key lists them: not its tests, docs or generated + # bindings, not the `v4` / `encryption` modules behind a feature + # protect-ffi never enables, and not the other EQL crates. + # ffi-binding-action.test.mjs derives the list from the manifests. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' - 'packages/eql/Cargo.toml' - '.github/workflows/tests-rust.yml' push: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 554e71f6d5..126b1dc00d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -8,7 +8,8 @@ on: branches: - "**" # Plan documents under docs/plans/ need none of these jobs. Later patterns - # win, so the negation has to come after the catch-all. + # win, so the negation has to come after the catch-all. While this filter + # stands, `tests-required` must not be a required check: see that job. paths: - '**' - '!docs/plans/**' @@ -52,8 +53,257 @@ jobs: - name: Biome check (format + lint) run: pnpm run code:check + # Which of the jobs below this pull request can affect. Runs on every event + # and must always succeed: the live jobs `needs:` it, and `tests-required` + # reads its result. + # + # The live jobs build two native bindings, start Postgres, and spend + # CipherStash credentials; until this job existed they ran on every pull + # request, including ones that changed only Go, the Stack Encrypt crates or + # EQL's SQL. The question asked here is the reverse of a `paths:` allowlist: + # the jobs run UNLESS every changed file is one they provably cannot read. + # An allowlist that forgets a directory stops a suite from running on the + # change that breaks it; this list, if it forgets one, only runs the suite + # when it did not need to. + # + # dorny/paths-filter cannot re-include a path after excluding it in one list + # (`predicate-quantifier: every` makes a file match only if it matches every + # pattern), so the question is split in two: + # `rest` — any changed file outside the excluded trees, and + # `direct` — any changed file inside them that the jobs do read. + # The jobs run when either is true. `tests-workflow-gate.test.mjs` holds + # both lists: every exclusion must be a path no gated job reads, and every + # build input of the FFI binding must be selected by one or the other. + changes: + name: Detect JS-relevant changes + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 10 + outputs: + js: ${{ steps.r.outputs.js }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # Only a pull request has a base to diff against. Every other event + # takes the default below and runs everything. + - id: rest + if: github.event_name == 'pull_request' + uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3 + with: + predicate-quantifier: every + filters: | + js: + - '**' + # Plans, ADRs and guides (`direct` selects the guides the jobs + # read); plan-docs-unread-by-tests.test.mjs holds the + # plans half for the `paths:` filter above. + - '!docs/**' + # The Go module, and Rust crates these jobs do not test. The auth + # and profile bindings compile stack-auth and stack-profile, which + # stay in. The auth binding also compiles the vitaminc-aead + # crates, through crates.io's `vitaminc` 0.10, but nothing these + # jobs run reaches them: tests-crates.yml builds and tests the + # bindings and those crates when either changes. + - '!languages/golang/**' + - '!packages/stack-encrypt/**' + - '!packages/stack-encrypt-derive/**' + - '!packages/stack-encrypt-jsonpath/**' + - '!packages/stack-kms/**' + - '!packages/stack-guest-abi/**' + - '!packages/vitaminc-aead/**' + - '!packages/recipher-frame/**' + - '!packages/vitaminc-aead-derive/**' + - '!packages/stack-auth/fuzz/**' + # The TypeScript SDK on Stack Encrypt. Nothing these jobs build + # depends on it, and tests-recipher-js.yml runs its tests. + - '!languages/typescript/packages/recipher-js/**' + # Dependabot's config and the repo tooling's own tests. Their + # readers (`test:scripts`, the supply-chain test) run in + # `repo-checks`, which is not gated. `biome.json` stays in: the + # auth and profile packages run Biome in their `test` script. + - '!.github/dependabot.yml' + - '!scripts/__tests__/**' + # EQL's SQL sources, test suites, codegen and tasks. What the + # jobs do read from here is selected by `direct` below. + - '!packages/eql/**' + # Changeset prose. `.changeset/config.json` is read by the CLI's + # release-train test, so only the entries are excluded. + - '!.changeset/*.md' + # Other workflows. Everything that reads them runs in + # `repo-checks`, which is not gated. + - '!.github/workflows/**' + # Agent instructions, and config for Rust tools these jobs never run. + - '!AGENTS.md' + - '!CLAUDE.md' + - '!CONTEXT-MAP.md' + - '!mise.test.toml' + - '!.cargo/mutants.toml' + - '!.cargo-crap.toml' + - '!.config/nextest.toml' + - '!release-plz.toml' + - '!cliff.toml' + + - id: direct + if: github.event_name == 'pull_request' + uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3 + with: + filters: | + js: + - '.github/workflows/tests.yml' + # The Protect upgrade guide, which `e2e-tests` reads: + # e2e/tests/protect-upgrade-guide.e2e.test.ts holds the guide's + # claims to the suites it describes. + - 'docs/migration/**' + # The eql-bindings files cargo compiles into the protect-ffi + # binding, as `.github/actions/build-ffi-binding` hashes them, + # and the EQL workspace manifest cargo reads for them. + - 'packages/eql/crates/eql-bindings/Cargo.toml' + - 'packages/eql/crates/eql-bindings/src/lib.rs' + - 'packages/eql/crates/eql-bindings/src/sql.rs' + - 'packages/eql/crates/eql-bindings/src/from_v2/**' + - 'packages/eql/crates/eql-bindings/src/v3/**' + - 'packages/eql/crates/eql-bindings/sql/**' + - 'packages/eql/Cargo.toml' + # `@cipherstash/eql`, the SQL bundle the CLI installs and the + # package `pnpm test` runs. + - 'packages/eql/packages/eql/**' + + # The event arrives through `env:`, not an interpolated `${{ }}`, so + # tests-workflow-gate.test.mjs can run this script once per event. + - id: r + env: + EVENT_NAME: ${{ github.event_name }} + REST: ${{ steps.rest.outputs.js }} + DIRECT: ${{ steps.direct.outputs.js }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" != "pull_request" ]; then + echo "js=true" >> "$GITHUB_OUTPUT" + elif [ "$REST" = "true" ] || [ "$DIRECT" = "true" ]; then + echo "js=true" >> "$GITHUB_OUTPUT" + else + echo "js=false" >> "$GITHUB_OUTPUT" + fi + + # Checks of the repository itself: lint scripts, the release gate, and the + # suites that read workflow files and repo config. None needs a binding, a + # database or credentials, and between them they read nearly every file in + # the tree, so this job is never gated. They ran in `run-tests` once per Node + # leg until the live jobs were gated; a pull request changing only a + # workflow would then have run none of the guards on it. + repo-checks: + name: Repo checks + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 15 + steps: + - name: Checkout Repo + uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v6.1.0 + name: Install pnpm + with: + run_install: false + + - name: Install Node.js + uses: actions/setup-node@v6.5.0 + with: + node-version: 22 + cache: 'pnpm' + + # node-pty's install hook falls back to `node-gyp rebuild` when no + # linux-x64 prebuild matches; pnpm/action-setup v6 no longer ships it. + - name: Install node-gyp + run: npm install -g node-gyp + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint — no hardcoded package-manager runners + run: pnpm run lint:runners + + # The typecheck gates in `run-tests` only mean something if they compile + # source. A tsconfig + # with no `include` globs `**/*`, which sweeps the package's own `dist/` + # into the program — and whether `dist/` exists during a gate depends on + # what an earlier step built transitively, so the gate compiles a + # different program in CI than it does locally. + - name: Lint — typecheck gates compile source, not build output + run: pnpm run lint:typecheck-scope + + # Deleting or renaming a package leaves `packages/` references + # dangling in docs and CI config. Nothing else catches it (#760 review). + - name: Lint — no references to deleted package directories + run: pnpm run lint:package-paths + + # `eql-bindings` emits EQL payloads; `@cipherstash/eql` carries the SQL + # that stores them. Both live here now and release at one lockstep + # version. A registry pin on either lets them drift apart — it compiles, + # it passes every suite, and it fails in a customer's database. + - name: Lint — EQL resolves in-tree, not from a registry + run: pnpm run lint:eql-pins + + # THE SAME GATE release.yml RUNS, one merge earlier. + # + # `changeset publish` publishes every public workspace package whose + # version is absent from npm — with no dependency ordering, and a failed + # publish returns a result rather than throwing, so it does not stop the + # siblings that depend on it. A merge can therefore ARM a release that + # cannot succeed, and this repository has done it. `@cipherstash/eql` is + # published from cipherstash/encrypt-query-language, so a version bumped + # in this workspace cannot be published from here — while `languages/typescript/packages/cli` + # and `languages/typescript/packages/stack-prisma` carry it in RUNTIME dependencies, so pnpm + # packs whatever version this tree holds into both tarballs. Bump it past + # what the registry carries and both ship a range no published version + # satisfies, in tarballs that publish fine. That is what the hand-applied + # 3.0.5 bump did; upstream has since released 3.0.5 and it cleared on its + # own. The CONDITION is what this step is for — the verdict is whatever it + # prints on the day. + # + # The gate in release.yml blocks the publish, which is the load-bearing + # half. This step is the half that says so BEFORE the merge rather than + # after it, which is the difference between a red pull request and a red + # main. Same script, same verdict, no second copy to drift. + # + # It talks to the registry, in a job that already installs the whole + # workspace from it — so this adds a class of dependency the job does not + # already have, only a few more requests. A lookup that fails for any + # reason other than a 404 throws rather than being read as "published". + - name: Lint — this tree can be published, and installed + run: pnpm run release:gate + + + # bench-index-expressions checks that the shipped EQL bundle in + # `dist/` is a verbatim copy of the committed one. `dist/` is a build + # output, and nothing before this step builds it, so build it here. + # EQL_DIST_REQUIRED makes that check fail, not skip, if `dist/` is + # missing, so dropping this build cannot silently disable it. + - name: Build @cipherstash/eql + run: pnpm exec turbo run build --filter @cipherstash/eql + + - name: Test — lint script self-tests + run: pnpm run test:scripts + env: + EQL_DIST_REQUIRED: '1' + + # protect-ffi's JS suite reads the root workflows (lintWiring, + # integrationSuiteCi) and passes with no binding built, which is a + # property it asserts. `run-tests` runs it too, through `pnpm test`; + # it runs here as well so that a change to a workflow alone, which the + # live jobs skip, still meets it. + - name: Test — protect-ffi workflow wiring + run: pnpm exec turbo run test --filter @cipherstash/protect-ffi + + # The e2e suites that read only files: workflow hardening and the skill + # map. The rest of `e2e/` builds and runs packages, in `e2e-tests`. + - name: Test — supply-chain and skill-map checks + working-directory: e2e + run: pnpm exec vitest run tests/supply-chain.e2e.test.ts tests/skill-map-parity.e2e.test.ts + run-tests: name: Run Tests (Node ${{ matrix.node-version }}) + needs: changes + if: needs.changes.outputs.js == 'true' runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 25 strategy: @@ -291,61 +541,6 @@ jobs: - name: Typecheck (stash init's scaffolded client) run: pnpm exec turbo run typecheck:scaffold --filter stash - - name: Lint — no hardcoded package-manager runners - run: pnpm run lint:runners - - # The gates above only mean something if they compile source. A tsconfig - # with no `include` globs `**/*`, which sweeps the package's own `dist/` - # into the program — and whether `dist/` exists during a gate depends on - # what an earlier step built transitively, so the gate compiles a - # different program in CI than it does locally. - - name: Lint — typecheck gates compile source, not build output - run: pnpm run lint:typecheck-scope - - # Deleting or renaming a package leaves `packages/` references - # dangling in docs and CI config. Nothing else catches it (#760 review). - - name: Lint — no references to deleted package directories - run: pnpm run lint:package-paths - - # `eql-bindings` emits EQL payloads; `@cipherstash/eql` carries the SQL - # that stores them. Both live here now and release at one lockstep - # version. A registry pin on either lets them drift apart — it compiles, - # it passes every suite, and it fails in a customer's database. - - name: Lint — EQL resolves in-tree, not from a registry - run: pnpm run lint:eql-pins - - # THE SAME GATE release.yml RUNS, one merge earlier. - # - # `changeset publish` publishes every public workspace package whose - # version is absent from npm — with no dependency ordering, and a failed - # publish returns a result rather than throwing, so it does not stop the - # siblings that depend on it. A merge can therefore ARM a release that - # cannot succeed, and this repository has done it. `@cipherstash/eql` is - # published from cipherstash/encrypt-query-language, so a version bumped - # in this workspace cannot be published from here — while `languages/typescript/packages/cli` - # and `languages/typescript/packages/stack-prisma` carry it in RUNTIME dependencies, so pnpm - # packs whatever version this tree holds into both tarballs. Bump it past - # what the registry carries and both ship a range no published version - # satisfies, in tarballs that publish fine. That is what the hand-applied - # 3.0.5 bump did; upstream has since released 3.0.5 and it cleared on its - # own. The CONDITION is what this step is for — the verdict is whatever it - # prints on the day. - # - # The gate in release.yml blocks the publish, which is the load-bearing - # half. This step is the half that says so BEFORE the merge rather than - # after it, which is the difference between a red pull request and a red - # main. Same script, same verdict, no second copy to drift. - # - # It talks to the registry, in a job that already installs the whole - # workspace from it — so this adds a class of dependency the job does not - # already have, only a few more requests. A lookup that fails for any - # reason other than a 404 throws rather than being read as "published". - - name: Lint — this tree can be published, and installed - run: pnpm run release:gate - - - name: Test — lint script self-tests - run: pnpm run test:scripts - - name: Create .env file in ./languages/typescript/packages/stack/ run: | touch ./languages/typescript/packages/stack/.env @@ -399,6 +594,8 @@ jobs: e2e-tests: name: Run E2E Tests + needs: changes + if: needs.changes.outputs.js == 'true' runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache # The migration harness's live Runs take most of this job's time; the # limit covers them plus the job's other suites, with headroom. @@ -555,7 +752,7 @@ jobs: run: | docker run -d --name pg18-upgrade -e POSTGRES_PASSWORD=password \ -p 127.0.0.1::5432 \ - postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 + public.ecr.aws/docker/library/postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 # Probe over TCP: the init-time server listens on the socket only. for _ in $(seq 1 60); do docker exec pg18-upgrade pg_isready -h 127.0.0.1 -U postgres -q && break @@ -589,6 +786,8 @@ jobs: # a silent fallback to the NAPI module is impossible. wasm-e2e-tests: name: Run WASM E2E Tests (Deno) + needs: changes + if: needs.changes.outputs.js == 'true' runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 35 @@ -733,6 +932,8 @@ jobs: run-tests-bun: name: Run Tests (Bun) + needs: changes + if: needs.changes.outputs.js == 'true' runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache timeout-minutes: 15 continue-on-error: true @@ -826,3 +1027,34 @@ jobs: (cd "$dir" && bunx --bun vitest run) || true fi done + + # One check that summarises the run, for a branch rule to require. A gated + # job reports `skipped` on a pull request that cannot affect it, which a + # rule requiring that job by name would wait on forever; this job reads + # `skipped` as a pass and anything but `success` otherwise as a failure. + # + # It does not report on a pull request that changes only `docs/plans/**`: + # the workflow-level `paths` filter at the top of this file stops the + # whole workflow from starting, and GitHub leaves a required check from a + # workflow it never started pending. Before a branch rule requires this + # check, remove that filter (and `plan-docs-unread-by-tests.test.mjs`, + # which exists because of it), or plans-only pull requests cannot merge. + tests-required: + name: tests-required + needs: [lint, changes, repo-checks, run-tests, e2e-tests, wasm-e2e-tests, run-tests-bun] + if: always() + runs-on: runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache + timeout-minutes: 10 + steps: + - name: Assert every needed job passed or was skipped + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + set -euo pipefail + echo "needed results: $RESULTS" + for r in $RESULTS; do + case "$r" in + success|skipped) ;; + *) echo "a needed job reported '$r'"; exit 1 ;; + esac + done diff --git a/.github/workflows/udeps.yml b/.github/workflows/udeps.yml index ed05f96d0b..3123e765ae 100644 --- a/.github/workflows/udeps.yml +++ b/.github/workflows/udeps.yml @@ -16,7 +16,11 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -35,7 +39,11 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** + - packages/vitaminc-aead/** + - packages/recipher-frame/** + - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/.gitignore b/.gitignore index 8b0370b593..857fe70f78 100644 --- a/.gitignore +++ b/.gitignore @@ -118,8 +118,13 @@ languages/golang/auth/wasm/*.wasm languages/golang/encrypt/wasm/*.sha256 languages/golang/encrypt/eql/wasm/*.sha256 languages/golang/auth/wasm/*.sha256 -# The deterministic-kms TEST build of the stack-encrypt guest, from `mise run -# wasm:guest:build:deterministic`; under testdata so no binary embeds it. +# The deterministic-kms TEST builds of the stack-encrypt guest, from `mise run +# wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic`. +# Package encrypttest embeds them; the release commits them on the tag. +languages/golang/encrypt/encrypttest/wasm/*.wasm +languages/golang/encrypt/encrypttest/wasm/*.sha256 +# Where those builds went before they moved to encrypttest/wasm. A checkout +# that built them there still has them, and they must not show as untracked. languages/golang/encrypt/testdata/*.wasm languages/golang/encrypt/testdata/*.sha256 # Raw migration harness reports, transcripts, credentials and workspace copies. diff --git a/.plain-language.json b/.plain-language.json new file mode 100644 index 0000000000..ef6dfc8efd --- /dev/null +++ b/.plain-language.json @@ -0,0 +1 @@ +{ "names": ["CipherStash", "ZeroKMS", "EQL", "PostgreSQL"] } diff --git a/.vscode/settings.json b/.vscode/settings.json index eb7dfff52a..8643ea1b8f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "conventionalCommits.scopes": ["protect", "examples"] + "conventionalCommits.scopes": ["protect", "examples"], + "rust-analyzer.cargo.features": ["stack-encrypt/dynamic"] } diff --git a/AGENTS.md b/AGENTS.md index 6252615a79..bc19d19552 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,14 +85,16 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l - `languages/typescript/packages/utils`: Shared config (`utils/config`) and logger (`utils/logger`) - `languages/typescript/packages/bench`: Performance / index-engagement benchmarks (private, not published) - `languages/typescript/packages/protect-ffi`: Native FFI bindings to the CipherStash Client SDK (`@cipherstash/protect-ffi`) — the Rust core that `languages/typescript/packages/stack` encrypts and decrypts through, absorbed from `cipherstash/protectjs-ffi`. Contains a **nested Cargo workspace** (`crates/`) and six per-platform binary packages under `platforms/*`, each published as `@cipherstash/protect-ffi-` and linked here via `workspace:*`. Also holds the repo's live FFI integration suite at `integration-tests/` — a private workspace member (`@cipherstash/ffi-integration-tests`) enrolled by its own literal entry in `pnpm-workspace.yaml`, needing Docker and credentials, and deliberately carrying **no `test` script** so `pnpm test` cannot reach it. See the "Working on protect-ffi" notes below before touching it — its default `test` and `build` are deliberately Rust-free. -- `packages/eql`: The Encrypt Query Language subtree — the SQL bundle that stores and queries encrypted payloads — absorbed from `cipherstash/encrypt-query-language`. **The directory is the subtree root, not the package.** It was imported at a *verbatim prefix* so its repo-root-relative paths (mise tasks, `Doxyfile`, `sync-generated.mjs`) keep resolving, which puts the npm package `@cipherstash/eql` two levels down at `packages/eql/packages/eql` — the same shape as `languages/typescript/packages/protect-ffi/platforms/*`, and enrolled the same way, by an explicit `packages/eql/packages/*` glob in `pnpm-workspace.yaml`. The subtree root deliberately carries no `package.json`. Also contains a **nested Cargo workspace** at `packages/eql/crates/` (`eql-bindings`, published in lockstep with the npm package, plus `eql-domains` / `eql-codegen` / `eql-tests-macros`, which are not), a SQLx test crate at `packages/eql/tests/sqlx`, an unpublished encryption test crate at `packages/eql/tests/encryption` (real encryption with a fake key source, the executable Rustdoc example at `packages/eql/crates/eql-bindings/src/encryption/example.rs`, plus optional PostgreSQL coverage), an ~900-line `mise.toml` task surface, its own `AGENTS.md`, and `docs/`. See the "Working on EQL" notes below before touching it. +- `packages/eql`: The Encrypt Query Language subtree — the SQL bundle that stores and queries encrypted payloads — absorbed from `cipherstash/encrypt-query-language`. **The directory is the subtree root, not the package.** It was imported at a *verbatim prefix* so its repo-root-relative paths (mise tasks, `Doxyfile`, `sync-generated.mjs`) keep resolving, which puts the npm package `@cipherstash/eql` two levels down at `packages/eql/packages/eql` — the same shape as `languages/typescript/packages/protect-ffi/platforms/*`, and enrolled the same way, by an explicit `packages/eql/packages/*` glob in `pnpm-workspace.yaml`. The subtree root deliberately carries no `package.json`. Also contains a **nested Cargo workspace** at `packages/eql/crates/` (`eql-bindings`, published in lockstep with the npm package, plus `eql-domains` / `eql-codegen` / `eql-tests-macros`, which are not), a SQLx test crate at `packages/eql/tests/sqlx`, an unpublished encryption test crate at `packages/eql/tests/encryption` (real encryption with a fake key source, the executable Rustdoc example at `packages/eql/crates/eql-bindings/src/encryption/example.rs`, the Rust examples of `packages/eql/crates/eql-bindings/README.md` run as doctests, plus optional PostgreSQL coverage), an ~900-line `mise.toml` task surface, its own `AGENTS.md`, and `docs/`. See the "Working on EQL" notes below before touching it. **Repository ownership:** EQL now lives in `cipherstash/stack`. File and update EQL issues in this repository, never in the historical `cipherstash/encrypt-query-language` repository. Old upstream issue and PR links are provenance only. -- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". +- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates and the three node binding crates below. See "Working on the Rust crates". +- `packages/vitaminc-aead`, `packages/recipher-frame`, `packages/vitaminc-aead-derive`: vitaminc's AEAD crates, imported from `cipherstash/vitaminc` with their history at the code of their crates.io 0.10.0 release (`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). They define the value types Stack Encrypt seals, the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`), and the derive macros. `vitaminc-aead` and `vitaminc-aead-derive` keep their crates.io names, because vitaminc crates that stay on crates.io depend on `vitaminc-aead`; the frame crate was `vitaminc-aead-frame` and is now `recipher-frame`, since only crates here depend on it. All three keep the MIT licence, are members of the root workspace, and are `publish = false` with `release = false` in `release-plz.toml`: crates.io's 0.10.0 was published from vitaminc, and they publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` carries a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). The cross-language value conformance corpus their tests read is `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here: the storage corpus append-only check (`storage-corpus.yml`), the Kani proofs of the storage reader (`kani.yml`), `cargo deny` and `cargo vet` over their dependency graph only (`supply-chain-vitaminc-aead.yml`, config in `supply-chain/vitaminc-aead/`; the rest of the workspace is #1842), and mutation testing (`mutants.yml`). See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). -- `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport` and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing and the `record` wire model). A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` builds the seeded TEST build the hermetic Go tests use; the `.wasm` files they embed are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, tags it `languages/golang/vX.Y.Z` and pushes the tag alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), and a final version dispatched from anywhere but `main`; a pre-release may come from a branch. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those three guests: the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. +- `languages/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset`, `Ciphertext`, and `Json` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). The bridge converts JSON documents too. `JsRef::to_json` writes a JavaScript value as a document's JSON text, with the JavaScript number rules. `JsBuilder::build_json` builds a decrypted document. The addon's `json.rs` contains only the `Json` class, and passes the text to the engine's `JsonPlaintext`. A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) contains only `Result`, `RecipherError`, the loader, stand-ins for a build that did not load, and the types that the generated signatures name. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The types are in `src/kinds.ts` and `src/value-types.ts`. `native.d.ts` imports those types, so a module that `native.d.ts` imports from must never load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. Two kinds of call throw: a method called without its object (#1801), and `new` on a class whose type has no constructor (`Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, which an application makes with `RcDate.from(text)` and the like, each returning a `Result`). Every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. +- `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the frame codec `encrypt/frame` and its value types `encrypt/value`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing, the `record` wire model, and `wasmtestrun`, the wazero runner that `wasm:auth-guest:test` runs the auth guest's wasm32 tests under). `encrypt/frame` encodes and decodes the bytes that the Go module exchanges with its guests, and the storage profile; it was vitaminc's Go package `vcffi`. `encrypt/value` declares the value types that the codec reads and writes (`Date`, `Decimal`, `Int128`, `Uint128`, `UUID`, `Object` and the rest); it was vitaminc's `vcvalue`, and imports nothing outside the standard library. `encrypt` names those types with aliases (`encrypt.Date` is `value.Date`), and `encrypt.Encryptable` and `encrypt.Encoder` are aliases of `frame`'s. The Rust crate `recipher-frame` implements the same encodings. The tests of `encrypt/frame` check it against `conformance/vitaminc-aead/value-conformance.json` and `packages/recipher-frame/testdata/storage-v1.json`. A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), and a final version dispatched from anywhere but `main`. A pre-release may come from a branch. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `examples/s3` is a fourth, also never tagged: it encrypts S3 object bodies with a plain `encrypt` field through the AWS SDK for Go v2, and `mise run go:example:s3` runs its tests end to end against S3Mock in Docker (they skip in CI, which has no bucket). `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. - `e2e/*`: Cross-package end-to-end tests (package managers, supply chain, Prisma example README) - `e2e/migration-guide`: Unpublished, separately installed npm examples for the Protect/EQL v2 to Stack/EQL v3 guide. See its README before running; Postgres requires a disposable database and DynamoDB persistence is in memory. - `languages/typescript/examples/*`: Working apps (basic, prisma, supabase-worker) @@ -253,7 +255,8 @@ EQL versions installed** in the database. rather than listing it, so a task added there tomorrow is covered. `typecheck` is the deliberate exception: it *should* run under `turbo run - typecheck`, and does, from `tests.yml`, on every PR. It needs no credentials + typecheck`, and does, from `tests.yml`, on every PR that can reach the JS + side (see "`tests.yml` gates its live jobs" below). It needs no credentials and no database, and its tsconfig sets `checkJs` so the suite's two `.cjs` fixtures are compiled too — one of them is a real `AccessKeyStrategy` call site, and a `tests/**/*.ts` scope would leave it checked by nothing but the @@ -702,22 +705,86 @@ monorepo, which is where the silent failures are. - **Changesets for `@cipherstash/eql` go in the repo-root `.changeset/`.** The subtree's own `.changeset/` was deleted with the import; there is no second one to put them in by mistake. +- **The JSON tree family is EQL v4 only and spans two crates.** The engine + half is `packages/stack-encrypt/src/json/` (the `Json` index, `JsonDocument`, + the query terms); the SQL is `packages/eql/src/v3/json_tree/` under + `-- ONLY EQL VERSION: 4`; the EQL types are hand-written in + `packages/eql/crates/eql-bindings/src/v4/json_tree.rs`; and the live + oracle, containment over the encrypted column against PostgreSQL's own + `jsonb @>` over the plaintexts, is `packages/eql/tests/encryption/tests/json_tree.rs`, + run by `mise run test:encryption:postgres`. The design and its + implementation notes are `docs/plans/2026-10-17-json-tree-index.md`. + Tests that read a stored document without PostgreSQL use + `stack_encrypt::eql_simulator`, Rust copies of the EQL read functions + (`json_tree_children`, `json_tree_subtree`). Production code never calls + them. The functions are behind the `eql-simulator` feature. + stack-encrypt's own tests turn it on with a dev-dependency on the crate + itself. The EQL encryption test crate turns it on in its `Cargo.toml`. A + change to how a read finds or walks entries changes the SQL and the + simulator together. + In v4 it carries v3's names for the searchable JSON document: the target + `JsonSearch` stores `public.eql_v4_json_search`, queried with + `eql_v4.query_json` and `eql_v4.query_json_leaf`, with entries + `public.eql_v4_json_entry`; `json_tree` names the implementation only (the + SQL directory, the Rust structs, the SQL functions). The v3 SteVec SQL + that owns those names in v3 (`src/v3/json/` and the generated + `json_entry_` cross files) is `-- ONLY EQL VERSION: 3`, so no bundle + carries both. + A change to the derivations on one side (a PAE domain, the header layout, + the projection shape) is a change to the other: the Postgres suite is + what holds them together. ## Working on the Rust crates The stack-* crates came from `cipherstash/cipherstash-suite`, which still owns -`cipherstash-client`, `cts-common`, `zerokms-protocol`, `recipher` and -`cllw-ore`. Here those come from crates.io, and `Cargo.lock` holds their -exact versions. In the root `Cargo.toml`, `recipher` and `cllw-ore` are -pinned with `=`. `cts-common` and `zerokms-protocol` take caret +`cipherstash-client`, `cts-common`, `zerokms-protocol` and `zerokms-keyset` +(published as `recipher` up to 0.3.3). Here those come from crates.io, and +`Cargo.lock` holds their exact versions. In the root `Cargo.toml`, +`zerokms-keyset` is pinned with `=`, and so are the order +schemes `clww-ore` (formerly `cllw-ore`) and `ore-rs`, which live in +`cipherstash/ore.rs`: a new release of either can change every stored order +term. `cts-common` and `zerokms-protocol` take caret requirements, because the published `stack-auth` inherits them, and an exact pin would stop the suite sharing one `cts-common` with it. -- **Three Cargo workspaces, not one.** The root workspace (the six stack-* - crates and the three node binding crates), protect-ffi's and EQL's. The root - `Cargo.toml` excludes the other two, and they pin their own vitaminc. The - three fuzz crates and the two Go guests are detached workspaces too, each - with its own `Cargo.lock`. +vitaminc's AEAD crates (`vitaminc-aead`, `recipher-frame`, +`vitaminc-aead-derive`) live here, in `packages/`, and are not published from +here yet. The AES-256-GCM cipher is in `vitaminc-aead`, behind its `aes` +feature, so nothing here uses `vitaminc-encrypt` 0.10. The other vitaminc +crates come from crates.io at 0.10, and three of them depend on +`vitaminc-aead`: `vitaminc-normalize`, `vitaminc-prf` and `vitaminc-ore`, +with the `vitaminc` umbrella crate, `clww-ore` and `ore-rs` above them. So every Cargo workspace that resolves +`vitaminc-aead` 0.10 carries a `[patch.crates-io]` table, with relative paths, +that makes those crates build against the copies here. A workspace must have +exactly one `vitaminc-aead` 0.10, and it must be the path crate: check with +`cargo tree -i vitaminc-aead@0.10.0`. A new workspace that resolves it needs the +same table. The patch covers the 0.10 line only, so the `vitaminc-aead` 0.5.1 +that `cts-common` reaches through `vitaminc` 0.5.1 still comes from crates.io, +and a change to these crates must keep their version on 0.10 until they are +published from here. + +`cargo publish` drops `[patch]` tables, so a crate published from here +(`stack-encrypt`, `stack-kms`, `stack-auth`) depends on crates.io's +`vitaminc-aead` 0.10.x, not on the copies. A change made in the copies +reaches a published crate only once the copies are published from here, +which the plan schedules before the next `stack-encrypt` release. + +- **Three Cargo workspaces, not one.** The root workspace (the seven stack-* + crates, the three AEAD crates and the three node binding crates), + protect-ffi's and EQL's. The root `Cargo.toml` excludes the other two. EQL's + patches `vitaminc-aead` to the copies here, as the root does; protect-ffi's + resolves no `vitaminc-aead` 0.10. The + TypeScript SDK's crates (`languages/typescript/packages/recipher-js`, napi-rs 3: + the addon `crate` and the value bridge `value-napi`) are a detached workspace + too, with its own `Cargo.lock`, depending on stack-encrypt by path. The value + bridge's test addon (`value-napi/tests/addon`) is one more, built by that + crate's own `tests/node.rs`. The + three fuzz crates, the two Go guests and the EQL v4 block ORE timing + harness's ciphertext generator + (`packages/eql/tests/timing/ore_block_v2/ctgen`) are detached workspaces + too, each with its own `Cargo.lock`. None of them has a Dependabot entry. + CI builds the generator nowhere, so `test-eql.yml` checks its lock with + `cargo metadata --locked`, and `run.sh` builds it with `--locked`. - **The toolchain is pinned in the root `mise.toml`:** Rust 1.94.1 (the `stack-encrypt` `tests/ui` trybuild snapshots record its diagnostics) and Go 1.26.10, the module's `go` minimum (#1300: the first 1.26 patch whose @@ -725,7 +792,7 @@ exact pin would stop the suite sharing one `cts-common` with it. `mise.toml` overrides the Rust pin in its folder. protect-ffi's does not pin Rust, so the root pin applies there. - **The cargo tools are pinned in `mise.test.toml`, not `mise.toml`:** - nextest, llvm-cov, crap, mutants, fuzz and udeps. EQL and protect-ffi + nextest, llvm-cov, crap, mutants, fuzz, udeps, deny and vet. EQL and protect-ffi inherit the root `mise.toml`, so a cargo tool there would be built in their jobs too. Reach them with `mise x --env test -- …`, as the tasks do; CI jobs that use them set `MISE_ENV: test`. @@ -745,10 +812,17 @@ exact pin would stop the suite sharing one `cts-common` with it. - **CI:** `tests-crates.yml` (fmt, clippy, nextest including the trybuild `tests/ui` binary, doctests, rustdoc, the node bindings and `stack-auth-wasm`), `tests-golang.yml` (WASI checks, the guests, the Go - module on Linux, macOS and Windows, and the live tests), `crap-crates.yml`, - `mutants.yml`, `fuzz.yml`, `miri.yml` and `udeps.yml`. + module on Linux, macOS and Windows (macOS only, for now, on a pull request + into any branch but `main`: #2017. A pull request moved onto `main` needs a + new push before Windows runs), its PostgreSQL tests against the EQL v4 + bundle built from the tree — `mise run go:test:postgres` locally, which also + runs the Rust and Go EQL/JSON conformance lane and so needs `psql` and the + `MISE_ENV=test` cargo tools — and the live tests), `crap-crates.yml`, + `mutants.yml`, `fuzz.yml`, `miri.yml`, `udeps.yml`, and for the three + AEAD crates `kani.yml`, `supply-chain-vitaminc-aead.yml` and + `storage-corpus.yml`. `scripts/__tests__/crates-ci.test.mjs` fails when a mise task in the root - `mise.toml` or the five crate `tasks.toml` files loses its last CI caller. + `mise.toml` or the crate `tasks.toml` files it includes loses its last CI caller. - **Auth refresh cancellation soak:** `tests-auth-refresh.yml` runs a short, seeded, virtual-time soak on every PR and the long run on auth changes and Version Packages PRs. `release-plz.yml` also requires the long run before @@ -769,6 +843,17 @@ mise run fuzz:access-key -- -runs=0 # replay seed corpus only (CI regr CI is split into a blocking per-PR regression replay and a nightly, non-blocking bug-finding campaign (`.github/workflows/fuzz.yml`). +The guests' ABI (the `(ptr, len)` checks, which compile only for wasm32) is +fuzzed from Go instead: `Fuzz*` targets in `languages/golang/encrypt` and +`languages/golang/auth` call the real guests through wazero, `go test` +replays their seeds, and `mise run go:fuzz` fuzzes them (nightly in +`fuzz.yml`'s `go-fuzz-campaign`, one matrix row per target). +The AEAD crates have no fuzz targets of their own. stack-encrypt's targets +(`check_record`, `term_decode`) reach parts of them, and `fuzz.yml` replays +those when the AEAD crates change. Go fuzzes the decoders of its frame codec +with three targets in `languages/golang/encrypt/frame`: `FuzzUnmarshal`, +`FuzzUnmarshalCipherText`, and `FuzzUnmarshalStorage`. `go test` replays +their seeds, and the nightly `go-fuzz-campaign` job fuzzes them. Full walkthrough — layout, adding a target, the CI split — in [`docs/fuzzing.md`](docs/fuzzing.md). For cargo-fuzz mechanics (sanitizers, corpus, crash triage) use the Trail of Bits `cargo-fuzz` skill rather than a @@ -784,22 +869,56 @@ buffers from them. Its unit tests run under Miri with strict provenance: mise run miri:stack-guest-abi # nightly + the miri component ``` -Only the native half (the buffer registry, headers, status table) is -interpretable; the wasm32-only `abi` and `transport` modules read the wasm -`memory_size` intrinsic, so their hostile-input behaviour is pinned from the -Go side (`mise run go:test`). +That covers the code that turns a host `(ptr, len)` pair into a slice +(`memory.rs`, run over a buffer the test owns), the buffer registry, and the +reclaim of the transport's response buffers, as well as the headers and the +status table. Miri cannot run wasm, so the `memory_size` intrinsic and the +host imports stay outside it. The code that calls them (`abi.rs`, +`transport::send`, and the guests' own `abi.rs` and `host.rs`) reads through +no host pointer itself: it hands each one, or each address the host wrote into +an out-slot, to the checked code (`memory`, the buffer registry, or the +transport's response reclaim). Its hostile-input behaviour is pinned from the +Go side (`mise run go:test`). Keep new pointer handling in +`stack-guest-abi`, where Miri reaches it, not in a guest. + +Miri and the sanitizers do not run on the AEAD crates. All three +`#![deny(unsafe_code)]`, and vitaminc ran neither on them: it ran both on +`vitaminc-protected`, which has the `unsafe` and stays in vitaminc. A crate +that adds `unsafe` needs both. + +### Kani + +`recipher-frame`'s storage reader parses bytes that may be corrupt or +tampered with. Its proof harnesses (`src/storage/proofs.rs`, built only +under `cfg(kani)`) prove the pieces it is built from: the header, counts, +scalar and key reads, the depth bound and map-key identity. + +```bash +cargo install --locked kani-verifier --version 0.67.0 && cargo kani setup +cargo kani -p recipher-frame --features serde -j 2 # ~10 min +``` + +`kani.yml` runs them on a pull request that changes the reader or its +proofs, and nightly when anything they compile from changed in the last day. +Kani installs its own nightly and CBMC; the version pin is in `kani.yml`, +not `mise.test.toml`, so no other job installs it. ### Mutation testing -The stack crates that opt in (stack-auth, stack-encrypt) are mutation-tested +The crates that opt in (stack-auth, stack-encrypt, stack-encrypt-jsonpath, +vitaminc-aead, recipher-frame, vitaminc-aead-derive) are mutation-tested with cargo-mutants; config in `.cargo/mutants.toml`. CI (`mutants.yml`) gates every PR touching them with `--in-diff`: only the lines the PR changes are mutated, and -a surviving mutant fails the job. A full sweep is slow and is run locally: +a surviving mutant fails the job. For now the gate runs only on a pull +request into main, and not on the release pull request. #2017 turns it +back on for every pull request. A full sweep of every one of them is a +manual dispatch of `mutants.yml`, one job per crate. stack-auth and +stack-encrypt can also be swept locally: ```bash mise run mutants:stack-auth # ~15 min mise run mutants:stack-encrypt # ~60 min -mise run mutants # every crate with a mutants: task +mise run mutants # both of the above ``` A non-equivalent surviving mutant means the test suite does not distinguish @@ -810,6 +929,63 @@ replacement such as `Some(Default::default())` for `Some(())`. Document the reason and match the specific replacement so a reachable, behavior-changing mutation in the same function stays covered. +### Misuse resistance + +Read `.claude/skills/misuse-resistance/SKILL.md` before you design or review +a public API of the stack-* crates. Read it too before you write a doc +example for one, or add a warning or an error to one. The skill ranks the +ways a rule can be enforced, from "impossible to get wrong" down to +"documented". It gives eleven rules for an API that handles keys, secrets or +ciphertext. The skill is a copy from `cipherstash/vitaminc`. Its first +section says which commit it was copied from, and how to update it. + +### vitaminc + +Read `.claude/skills/vitaminc/SKILL.md` before you write or review Rust that +has a key, a token, a plaintext, or another secret. That covers the stack-* +crates, the Go guests, and every language binding crate. The skill maps each +task to its vitaminc type, such as `Protected` in place of a `String`. +`RECIPES.md` beside it has working code. The skill is a copy from +`cipherstash/vitaminc`, and its first section says how to update it. + +The recipes are written for vitaminc 0.10 and its individual crates. Two +places in this repository differ: + +- **protect-ffi** pins `vitaminc = "=0.1.0-pre4.2"`, in + `languages/typescript/packages/protect-ffi/crates/protect-ffi/Cargo.toml`. + Some recipes use items that version does not have, such as + `SafeRand::next_below`. Do not copy a recipe into protect-ffi until that + pin moves to 0.10. +- **The Go encrypt guest** (`languages/golang/encrypt/guest`) has no vitaminc + dependency of its own. The guest takes vitaminc through `stack-encrypt`'s + re-exports, so it cannot build against a second vitaminc. Do not add one. + +In the root Cargo workspace, a recipe needs these changes before it compiles: + +- The workspace has the `vitaminc` facade crate but no direct + `vitaminc-random` or `vitaminc-password`. Write `vitaminc::random::X` for + `vitaminc_random::X`. +- The password recipe needs the facade's `password` feature. The workspace + does not turn it on. Adding it is a dependency change to review. +- `#[derive(Generatable)]` needs `vitaminc-random` as a direct dependency, + because the code it generates names that crate. +- `futures::executor::block_on` needs the `executor` feature of `futures`. + `stack-encrypt` and `stack-guest-abi` build `futures` without it. +- The "Compare secrets" and "Keyed hash" recipes end with statements outside + any function. Put those lines in a function or a `#[test]`. + +Two rules the skill does not state yet: + +- A type with a secret in it derives `OpaqueDebug` (`vitaminc-protected`), + as `DataKey` in `packages/stack-kms/src/key.rs` and `JsonPlaintext` in + `packages/stack-encrypt/src/json/plaintext.rs` do. Do not write + `impl Debug` by hand to hide a value. The derive masks a field or, with + `#[non_sensitive]`, shows it as it is. Write `Debug` by hand only to show + something the derive cannot, such as a count or a length. That text must + still show no secret. +- Use a type the engine or vitaminc already has before you wrap it in a new + one. + ## Designing a language SDK Read [`docs/sdk-design-principles.md`](docs/sdk-design-principles.md) before you @@ -959,6 +1135,16 @@ pnpm changeset:publish `languages/typescript/packages/cli/tests/e2e/**` run via `pnpm --filter stash test:e2e` (requires a build). See `languages/typescript/packages/cli/AGENTS.md` for when to add or update them. +- **`tests.yml` gates its live jobs on what a pull request changes.** Its + `changes` job skips `run-tests`, `e2e-tests`, `wasm-e2e-tests` and + `run-tests-bun` when every changed file sits in a tree they cannot read + (the Go module, the Stack Encrypt crates, EQL's SQL and Rust outside the + compiled `eql-bindings` files, docs, other workflows). A test that reads a + path in one of those trees would be skipped on the change that breaks it: + `scripts/__tests__/tests-workflow-gate.test.mjs` scans for that and fails. + Checks that read the whole tree (the lint scripts, `test:scripts`, the + release gate, the suites that read workflow files) run in the ungated + `repo-checks` job instead. ## Bundling and Deployment Notes @@ -1019,6 +1205,40 @@ pnpm changeset:publish A skills-only change is **not** internal: `skills/` ships inside the `stash` tarball, so it needs a `stash` patch changeset. +## Review guidelines + +These apply to every agent that reviews a pull request here, human-prompted +or automated (Codex, Copilot, CodeRabbit, Claude Code's `/code-review`). + +### Known non-findings + +These are deliberate design decisions, recorded in ADRs. Do not report them +as defects or security issues, and do not change code to "fix" them. If a +change seems to need one reversed, say so and link the ADR. + +- **A sealed container's membership, order and length are not + authenticated.** Each leaf is bound to its context, its map key, its role + (single value or sequence element), its type tag and the wire version. But + which entries a stored map holds, and a stored sequence's order, length + and duplicates, are deliberately not bound: stored values are database + rows and columns, which come back in any order and in part. A target that + refuses a container's shape (a missing field, say) is a shape mismatch, + `Error::OpenedType`, not tampering, `Error::Aead`. Stricter authentication + will be opt-in, through named types. See + `packages/stack-encrypt/docs/adr/0010-what-a-stored-value-authenticates.md` + and `vitaminc-aead`'s ADR 0002, + `packages/vitaminc-aead/docs/adr/0002-leaves-are-authenticated-container-membership-and-order-are-not.md`. +- **A passthrough field is not authenticated.** It is stored in the clear, + by definition, and comes back as the store holds it. A plan's context + field is the exception: every other field is sealed under it, so a change + to it is caught. Same ADR. +- **Two leaves sealed under the same context are interchangeable between + rows.** Binding a value to its row is the caller's choice of context (a + row id or tenant in it). Same ADR. + +A finding that a *leaf* is not bound to its context, key, role, type or +version is a real defect: report it. + ## Useful Links - `README.md` for quickstart and feature overview diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ec96903942..a902291e64 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to CipherStash Stack -Thank you for your interest in contributing to the CipherStash Stack for TypeScript! This document walks you through the repository's structure, how to build and run the project locally, and how to make contributions effectively. +Thank you for your interest in contributing to CipherStash Stack. This document walks you through the repository's structure, how to build and run the project locally, and how to make contributions effectively. ## I want to report a bug, or make a feature request @@ -20,6 +20,7 @@ This is a [Turborepo](https://turbo.build/) monorepo managed with [pnpm](https:/ │ │ ├── cli/ <-- The `stash` CLI │ │ └── ... <-- stack-drizzle, stack-supabase, stack-prisma, nextjs, migrate, wizard, ... │ └── examples/ <-- Runnable example apps +├── languages/golang/ <-- Go SDK, stashgen and credential packages ├── packages/eql/ <-- EQL (@cipherstash/eql and its Rust crates) ├── e2e/ <-- Cross-package end-to-end tests ├── skills/ <-- Agent skills @@ -29,6 +30,8 @@ This is a [Turborepo](https://turbo.build/) monorepo managed with [pnpm](https:/ See [AGENTS.md](./AGENTS.md) for a detailed layout, key APIs, environment variables, and gotchas — it's written for coding agents but is the most complete developer reference in the repo. +For the Go module, start with [languages/golang/README.md](languages/golang/README.md). + ### `languages/typescript/packages/stack` **@cipherstash/stack** is the main package published to npm. It contains the encryption client and all integrations (Drizzle, Supabase, DynamoDB, secrets, identity). This is likely where you'll spend most of your time. @@ -44,6 +47,7 @@ The `languages/typescript/examples/` directory contains applications demonstrati - **Node.js** >= 22 - **pnpm** (the version pinned in `package.json`'s `packageManager` field) - CipherStash credentials if you want to run integration tests or examples (see [AGENTS.md](./AGENTS.md) for the required environment variables) +- For Go work: mise and the Go and Rust toolchains pinned in `mise.toml` ### 1. Clone the Repo @@ -76,6 +80,31 @@ pnpm run dev Then navigate to one of the examples in `languages/typescript/examples/` and follow its README. +### Go module + +The Go module is in `languages/golang/`, outside the pnpm workspace. Its +`encrypt` and `auth` packages embed WASI guests built from Rust. In a source +checkout, build those guests before running the Go suite: + +```bash +mise run wasm:guest:build +mise run wasm:guest:build:eql +mise run wasm:guest:build:deterministic +mise run wasm:guest:build:eql:deterministic +mise run wasm:auth-guest:build +mise run go:test +``` + +For EQL v4 PostgreSQL coverage, set `EQL_TEST_DATABASE_URL` to a disposable +database and run `mise run go:test:postgres`. The task builds the EQL v4 bundle +from this tree and installs it into that database, so it replaces the EQL there. +It needs `psql`, the Rust test tools (`mise install --env test`) and both +deterministic guests. It refuses to run while a fixture-update variable, such as +`STACK_ENCRYPT_UPDATE_FIXTURES`, is set. Go examples that connect to ZeroKMS need +CipherStash credentials. The [Go module guide](languages/golang/README.md) +links to the SDK, generator, credentials, examples and release notes. Commit +generated `*_stash.go` files when changing Go model tags; CI checks for drift. + ## Making Changes 1. **Create a new branch** from `main`: diff --git a/Cargo.lock b/Cargo.lock index d95f26510e..058bba2b46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -27,6 +27,7 @@ dependencies = [ "cfg-if", "cipher", "cpufeatures 0.2.17", + "zeroize", ] [[package]] @@ -80,6 +81,15 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "alloca" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -95,6 +105,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "anyhow" version = "1.0.101" @@ -180,9 +202,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.18.0" +version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -191,9 +213,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.44.0" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" dependencies = [ "cc", "cmake", @@ -284,6 +306,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "base85-simd" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbd16ef96137ca89cc38b0acb5bee36fada9707c044bc9c753f55c816bfa719" + [[package]] name = "bit-set" version = "0.11.1" @@ -354,6 +382,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "block-modes" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e2211b0817f061502a8dd9f11a37e879e79763e3c698d2418cf824d8cb2f21e" + [[package]] name = "borsh" version = "1.8.1" @@ -411,6 +445,12 @@ version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -491,9 +531,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chacha20" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.0", @@ -503,9 +543,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.43" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", "num-traits", @@ -513,6 +553,33 @@ dependencies = [ "windows-link", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half 2.7.1", +] + [[package]] name = "cipher" version = "0.4.4" @@ -536,16 +603,42 @@ dependencies = [ ] [[package]] -name = "cllw-ore" -version = "0.5.0" +name = "clap" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "476f300d37a5029d3d9dd57145d4db50a23f40ae9b4d1374c44543978b906191" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clww-ore" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf8966d3aa4130c1d5afd09de3be042765061879e8be0d5c156e9078b0148db" dependencies = [ "blake3", "hex", "subtle", "thiserror 1.0.69", - "unicode-normalization", + "vitaminc-ore", + "vitaminc-protected 0.10.0", "zeroize", ] @@ -714,6 +807,39 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "criterion" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" +dependencies = [ + "alloca", + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools 0.13.0", + "num-traits", + "oorandom", + "page_size", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" +dependencies = [ + "cast", + "itertools 0.13.0", +] + [[package]] name = "critical-section" version = "1.2.0" @@ -744,6 +870,12 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -805,14 +937,14 @@ dependencies = [ "url", "utoipa", "uuid", - "vitaminc", + "vitaminc 0.5.1", ] [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" dependencies = [ "cmov", ] @@ -987,6 +1119,26 @@ dependencies = [ "serde", ] +[[package]] +name = "env_filter" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +dependencies = [ + "env_filter", + "log", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1267,6 +1419,17 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403" +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -1744,9 +1907,9 @@ dependencies = [ [[package]] name = "itertools" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] @@ -1757,6 +1920,39 @@ version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +[[package]] +name = "jiff" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e" +dependencies = [ + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "jni" version = "0.21.1" @@ -2169,6 +2365,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -2179,6 +2389,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.0" @@ -2194,6 +2413,27 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2242,6 +2482,39 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "ore-rs" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebac11f6f3ceaec9994a27b00666385301e6b650ba8973f852430b9f7bd4ba5" +dependencies = [ + "aes", + "block-modes", + "byteorder", + "hex", + "num", + "rand 0.10.1", + "subtle-ng", + "thiserror 1.0.69", + "vitaminc-context 0.10.0", + "vitaminc-hmac", + "vitaminc-ore", + "vitaminc-prf", + "vitaminc-protected 0.10.0", + "vitaminc-random 0.10.0", + "zeroize", +] + +[[package]] +name = "page_size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -2283,9 +2556,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" @@ -2317,6 +2590,15 @@ version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -2439,7 +2721,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.10.5", "proc-macro2", "quote", "syn 2.0.114", @@ -2451,6 +2733,28 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +[[package]] +name = "quickcheck" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95c589f335db0f6aaa168a7cd27b1fc6920f5e1470c804f814d9cd6e62a0f70b" +dependencies = [ + "env_logger", + "log", + "rand 0.10.1", +] + +[[package]] +name = "quickcheck_macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a28b8493dd664c8b171dd944da82d933f7d456b829bfb236738e1fe06c5ba4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + [[package]] name = "quinn" version = "0.11.9" @@ -2505,7 +2809,7 @@ dependencies = [ "once_cell", "socket2 0.6.5", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.52.0", ] [[package]] @@ -2630,24 +2934,21 @@ dependencies = [ ] [[package]] -name = "recipher" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14e156e2d485b51cc67c19241e7d81ad524bda9fd4f77791b698ab10c8e26e9" +name = "recipher-frame" +version = "0.10.0" dependencies = [ - "aes", - "cmac", - "getrandom 0.2.17", - "hex", - "hex-literal", - "opaque-debug", - "rand 0.8.8", - "rand_chacha 0.3.1", + "borsh", + "criterion", + "jiff", + "quickcheck", + "quickcheck_macros", + "rmp-serde", + "rust_decimal", "serde", - "serde_cbor", - "sha2 0.10.9", - "thiserror 1.0.69", - "zeroize", + "serde_bytes", + "serde_json", + "vitaminc-aead 0.10.0", + "vitaminc-protected 0.10.0", ] [[package]] @@ -2782,6 +3083,23 @@ dependencies = [ "serde", ] +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.3", + "serde", + "serde_json", + "wasm-bindgen", +] + [[package]] name = "rustc-hash" version = "2.1.1" @@ -2807,7 +3125,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3012,7 +3330,7 @@ version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" dependencies = [ - "half", + "half 1.8.3", "serde", ] @@ -3237,7 +3555,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stack-auth" -version = "0.43.0" +version = "0.44.0" dependencies = [ "aquamarine", "axum", @@ -3267,8 +3585,8 @@ dependencies = [ "tracing-subscriber", "url", "uuid", - "vitaminc", - "vitaminc-protected", + "vitaminc 0.10.0", + "vitaminc-protected 0.10.0", "web-time", "zeroize", "zerokms-protocol", @@ -3290,7 +3608,7 @@ dependencies = [ "tempfile", "tokio", "url", - "vitaminc-protected", + "vitaminc-protected 0.10.0", "zeroize", ] @@ -3316,58 +3634,90 @@ dependencies = [ [[package]] name = "stack-encrypt" -version = "0.2.0" +version = "0.3.0" dependencies = [ "base64ct", - "cllw-ore", + "base85-simd", + "clww-ore", + "futures", + "jiff", "miette", + "ore-rs", + "proptest", + "rand 0.10.1", + "recipher-frame", + "rmp-serde", + "rust_decimal", "serde", + "serde_derive", "serde_json", + "serdect", + "sha2 0.11.0", "stack-auth", + "stack-encrypt", "stack-encrypt-derive", + "stack-encrypt-jsonpath", "stack-kms", + "temp-env", "thiserror 1.0.69", "tokio", "trybuild", "uuid", - "vitaminc-aead", - "vitaminc-aead-value", - "vitaminc-encrypt", + "vitaminc 0.10.0", + "vitaminc-aead 0.10.0", "vitaminc-hmac", + "vitaminc-normalize", + "vitaminc-ore", "vitaminc-prf", - "vitaminc-protected", + "vitaminc-protected 0.10.0", "zeroize", "zerokms-protocol", ] [[package]] name = "stack-encrypt-derive" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", "serde_json", "stack-encrypt", + "stack-encrypt-jsonpath", "syn 3.0.9", "tokio", + "zeroize", +] + +[[package]] +name = "stack-encrypt-jsonpath" +version = "0.3.0" +dependencies = [ + "miette", + "serde", + "serde_json", + "stack-auth", + "thiserror 1.0.69", + "zeroize", ] [[package]] name = "stack-guest-abi" version = "0.0.0" dependencies = [ + "futures", "miette", "proptest", + "recipher-frame", "serde_json", "thiserror 1.0.69", - "vitaminc-aead-value", - "vitaminc-protected", + "vitaminc-aead 0.10.0", + "vitaminc-protected 0.10.0", "zeroize", ] [[package]] name = "stack-kms" -version = "0.1.0" +version = "0.2.0" dependencies = [ "async-mutex", "base16ct", @@ -3376,8 +3726,7 @@ dependencies = [ "futures", "lazy_static", "miette", - "opaque-debug", - "recipher", + "proptest", "reqwest", "rustls", "serde", @@ -3394,15 +3743,16 @@ dependencies = [ "tracing", "url", "uuid", - "vitaminc", - "vitaminc-protected", + "vitaminc 0.10.0", + "vitaminc-protected 0.10.0", "zeroize", + "zerokms-keyset", "zerokms-protocol", ] [[package]] name = "stack-profile" -version = "0.43.0" +version = "0.44.0" dependencies = [ "dirs", "gethostname", @@ -3443,6 +3793,12 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "subtle-ng" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "734676eb262c623cec13c3155096e08d1f8f29adce39ba17948b18dad1e54142" + [[package]] name = "syn" version = "2.0.114" @@ -3645,6 +4001,16 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tinyvec" version = "1.10.0" @@ -3973,6 +4339,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.23" @@ -4136,14 +4508,26 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ - "vitaminc-aead", - "vitaminc-context", + "vitaminc-aead 0.5.1", + "vitaminc-context 0.5.1", "vitaminc-encrypt", - "vitaminc-protected", - "vitaminc-random", + "vitaminc-protected 0.5.1", + "vitaminc-random 0.5.1", "vitaminc-traits", ] +[[package]] +name = "vitaminc" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" +dependencies = [ + "vitaminc-aead 0.10.0", + "vitaminc-context 0.10.0", + "vitaminc-protected 0.10.0", + "vitaminc-random 0.10.0", +] + [[package]] name = "vitaminc-aead" version = "0.5.1" @@ -4152,10 +4536,36 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive", - "vitaminc-context", - "vitaminc-protected", - "vitaminc-random", + "vitaminc-aead-derive 0.5.1", + "vitaminc-context 0.5.1", + "vitaminc-protected 0.5.1", + "vitaminc-random 0.5.1", + "zeroize", +] + +[[package]] +name = "vitaminc-aead" +version = "0.10.0" +dependencies = [ + "aes-gcm", + "aws-lc-rs", + "bytes", + "futures-executor", + "futures-util", + "jiff", + "quickcheck", + "quickcheck_macros", + "rust_decimal", + "serde", + "serde_json", + "thiserror 2.0.18", + "trybuild", + "uuid", + "vitaminc-aead-derive 0.10.0", + "vitaminc-context 0.10.0", + "vitaminc-prf", + "vitaminc-protected 0.10.0", + "vitaminc-random 0.10.0", "zeroize", ] @@ -4171,13 +4581,14 @@ dependencies = [ ] [[package]] -name = "vitaminc-aead-value" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d78cdadbc6374c3bd7c19fb4d99abca693b96953b18fef8c608efbe092cf3ea" +name = "vitaminc-aead-derive" +version = "0.10.0" dependencies = [ - "vitaminc-aead", - "vitaminc-protected", + "proc-macro2", + "quote", + "syn 3.0.9", + "vitaminc 0.10.0", + "vitaminc-aead 0.10.0", "zeroize", ] @@ -4188,7 +4599,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7df52501fe33cdb3ee9e155b5242fac184c037d147e58c96e5143ed011252a8" dependencies = [ "mutants", - "vitaminc-protected", + "vitaminc-protected 0.5.1", +] + +[[package]] +name = "vitaminc-context" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "431a7fb023688dba855e52b9c4e44c942418dde8ea08a2b115cf6a7f762fa5b9" +dependencies = [ + "mutants", + "quickcheck", + "vitaminc-protected 0.10.0", ] [[package]] @@ -4199,35 +4621,69 @@ checksum = "9fbd0e1748055e381e02033e08af385de879c4dcf32e0f6739ac0c0cf0c6f13d" dependencies = [ "aes-gcm", "aws-lc-rs", - "vitaminc-aead", - "vitaminc-protected", - "vitaminc-random", + "vitaminc-aead 0.5.1", + "vitaminc-protected 0.5.1", + "vitaminc-random 0.5.1", "zeroize", ] [[package]] name = "vitaminc-hmac" -version = "0.5.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15fe558a5e92d4f2b3f811c5b67d863d9255da5f66d08a71d4f0dd3d0011c563" +checksum = "b031c7e62ab28f716df69c5e2137267c93e8d2aa36e4f31a12ac5b193baaa3d1" dependencies = [ "hmac", "sha2 0.11.0", "vitaminc-prf", - "vitaminc-protected", + "vitaminc-protected 0.10.0", + "zeroize", +] + +[[package]] +name = "vitaminc-normalize" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" +dependencies = [ + "thiserror 2.0.18", + "unicode-general-category", + "unicode-normalization", + "vitaminc-aead 0.10.0", + "vitaminc-protected 0.10.0", +] + +[[package]] +name = "vitaminc-ore" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1d92d394e577ee424b4f35479a101896aecbce98f00c37bca5af1aa0d3b2c0" +dependencies = [ + "jiff", + "rust_decimal", + "thiserror 2.0.18", + "unicode-general-category", + "unicode-normalization", + "vitaminc-aead 0.10.0", + "vitaminc-context 0.10.0", + "vitaminc-normalize", + "vitaminc-prf", + "vitaminc-protected 0.10.0", "zeroize", ] [[package]] name = "vitaminc-prf" -version = "0.5.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712d31d46d76b38c6b62deb35f516fc5636a35f90f39c0213d0ca9a052b4400b" +checksum = "078c13f43f5a9fefdd6f4cb337327a432b3b136c168f558fd525d1dd14685541" dependencies = [ "mutants", "thiserror 2.0.18", - "vitaminc-context", - "vitaminc-protected", + "vitaminc-aead 0.10.0", + "vitaminc-context 0.10.0", + "vitaminc-normalize", + "vitaminc-protected 0.10.0", ] [[package]] @@ -4243,7 +4699,24 @@ dependencies = [ "serde_bytes", "subtle", "thiserror 2.0.18", - "vitaminc-protected-derive", + "vitaminc-protected-derive 0.5.1", + "zeroize", +] + +[[package]] +name = "vitaminc-protected" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2153981f290343dffa8f618277c46a13b5a1e8131b4120760e9a1795ae1cb55b" +dependencies = [ + "bitvec", + "digest 0.11.3", + "libc", + "serde", + "serde_bytes", + "subtle", + "thiserror 2.0.18", + "vitaminc-protected-derive 0.10.0", "zeroize", ] @@ -4258,6 +4731,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "vitaminc-protected-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32eb239bc9aae16ef0320076934f3f592606960d42d0b5fdadafc0298f635221" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "vitaminc-random" version = "0.5.1" @@ -4268,8 +4753,23 @@ dependencies = [ "getrandom 0.4.2", "rand 0.10.1", "thiserror 2.0.18", - "vitaminc-protected", - "vitaminc-random-derives", + "vitaminc-protected 0.5.1", + "vitaminc-random-derives 0.5.1", + "zeroize", +] + +[[package]] +name = "vitaminc-random" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae7eccb46ddc6f199cf5c934469fd5b199514f42e11579c46882b784ed992c8" +dependencies = [ + "chacha20", + "getrandom 0.4.2", + "rand 0.10.1", + "thiserror 2.0.18", + "vitaminc-protected 0.10.0", + "vitaminc-random-derives 0.10.0", "zeroize", ] @@ -4284,6 +4784,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "vitaminc-random-derives" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48c940c93c9ddb04a66d81ca42ca574826ddbbeece6a7c87c5d1ab31893e692" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "vitaminc-traits" version = "0.5.1" @@ -4295,8 +4806,8 @@ dependencies = [ "rmp-serde", "serde", "thiserror 2.0.18", - "vitaminc-protected", - "vitaminc-random", + "vitaminc-protected 0.5.1", + "vitaminc-random 0.5.1", "zeroize", ] @@ -4649,24 +5160,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -4715,30 +5208,13 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", + "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.42.2" @@ -4757,12 +5233,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -4781,12 +5251,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -4805,24 +5269,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -4841,12 +5293,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -4865,12 +5311,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -4889,12 +5329,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -4913,12 +5347,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.7.14" @@ -5134,6 +5562,26 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "zerokms-keyset" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b29117bf96605cf6ddb18b4050a9aa10b0256c72bb0a0f8f7ef4835ca9c6c12" +dependencies = [ + "aes", + "cmac", + "getrandom 0.2.17", + "hex-literal", + "opaque-debug", + "rand 0.8.8", + "rand_chacha 0.3.1", + "serde", + "serde_cbor", + "sha2 0.10.9", + "thiserror 1.0.69", + "zeroize", +] + [[package]] name = "zerokms-protocol" version = "0.12.31" diff --git a/Cargo.toml b/Cargo.toml index b1ccc99399..98419fe3a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,17 +1,28 @@ [workspace] resolver = "2" -# The stack-* crates imported from cipherstash-suite, and the three node -# bindings that wrap them. The root is one of three Cargo workspaces in this -# repository: EQL and protect-ffi keep their own, and pin their own vitaminc -# (see `exclude`). +# The stack-* crates imported from cipherstash-suite, the three node bindings +# that wrap them, and the three AEAD crates moved from cipherstash/vitaminc. +# The root is one of three Cargo workspaces in this repository: EQL and +# protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead to the +# copies here, as this workspace does; protect-ffi resolves no vitaminc-aead +# 0.10. members = [ "packages/stack-auth", "packages/stack-profile", "packages/stack-kms", "packages/stack-encrypt", "packages/stack-encrypt-derive", + "packages/stack-encrypt-jsonpath", "packages/stack-guest-abi", + # The AEAD crates moved from cipherstash/vitaminc. vitaminc-aead and + # vitaminc-aead-derive keep their crates.io names, and are not published + # from here yet; see the patch table at the end. recipher-frame was + # vitaminc-aead-frame: only crates in this repository depend on it, so it + # could take a name of its own. + "packages/vitaminc-aead", + "packages/recipher-frame", + "packages/vitaminc-aead-derive", "languages/typescript/packages/auth", "languages/typescript/packages/profile", "languages/typescript/packages/stack-auth-wasm", @@ -34,7 +45,7 @@ exclude = [ [workspace.package] # Used by the node binding crates, which take `version.workspace`. The # published crates (stack-auth, stack-profile, stack-kms, stack-encrypt, -# stack-encrypt-derive) carry their own version. +# stack-encrypt-derive, stack-encrypt-jsonpath) carry their own version. version = "0.35.0" edition = "2021" authors = [ @@ -69,19 +80,29 @@ incremental = true # but cannot subtract them, and `stack-kms` / `stack-encrypt` need stack-auth # without `http`. Consumers that want the default transport re-enable it with # `features = ["http"]`. -stack-auth = { path = "./packages/stack-auth", version = "0.43.0", default-features = false } -stack-profile = { path = "./packages/stack-profile", version = "0.43.0" } +stack-auth = { path = "./packages/stack-auth", version = "0.44.0", default-features = false } +stack-profile = { path = "./packages/stack-profile", version = "0.44.0" } # Suite crates, from crates.io; Cargo.lock holds the exact versions. # cts-common and zerokms-protocol take caret requirements because the # published stack-auth inherits them: an exact pin would stop the suite # unifying stack-auth with a later compatible cts-common, and a second copy -# breaks the shared Crn, Region and WorkspaceId types. recipher and cllw-ore -# feed only unpublished crates, so they stay exact. +# breaks the shared Crn, Region and WorkspaceId types. zerokms-keyset (the +# crate published as `recipher` up to 0.3.3) is pinned exactly and moved by +# hand. cts-common = { version = "0.43.0", default-features = false } zerokms-protocol = "0.12.31" -recipher = "=0.3.1" -cllw-ore = { version = "=0.5.0", default-features = false } +zerokms-keyset = "=0.3.4" +# The two order-preserving schemes Stack Encrypt's order terms encrypt +# through. Both implement vitaminc-ore's `OrderScheme` against vitaminc 0.10: +# `clww-ore` (cllw-ore renamed) for CLWW ORE and OPE, and ore-rs's +# `BlockOre` for block ORE, which routes a value to its 6-bit fixed-width +# engine (up to ten bytes) or its chained one (wider, or variable length), +# the terms EQL v4's `_ord_ore` domains store. +# vitaminc is a plain dependency of both from here, not a feature. Both are +# pinned exactly: a new release can change every stored order term. +clww-ore = { version = "=0.8.0", default-features = false } +ore-rs = { version = "=0.12.0", default-features = false } # External dependencies, with the suite's feature lists. base64 = "0.22.0" @@ -110,7 +131,13 @@ rustls = { version = "0.23", default-features = false, features = ["std", "tls12 rustls-platform-verifier = "0.6" rustls-webpki = { version = "0.103", default-features = false, features = ["alloc"] } serde = { version = "1.0", features = ["derive"] } +# Named on its own only so a crate can turn on one of its features. +# stack-encrypt turns on `deserialize_in_place`, which every derive in the +# build then writes. +serde_derive = "1.0" serde_json = { version = "1.0.132" } +# Constant-time hex (through base16ct) for serde over the order terms. +serdect = { version = "0.3", default-features = false, features = ["alloc"] } thiserror = "1.0.56" tokio = { version = "1.47.1", features = ["full"] } tracing = { version = "0.1", features = ["log"] } @@ -128,13 +155,33 @@ web-time = "1.1" zeroize = { version = "1.8.1", features = ["derive"] } # This is needed because lock_api 0.4.6 was breaking things and the branch forces the use of 0.4.12 temp-env = { git = "https://github.com/cipherstash/temp-env", branch = "main" } -vitaminc = { version = "0.5.1", features = ["random", "protected", "encrypt"] } -vitaminc-aead = "0.5.1" -# The dynamic value model (`FfiValue`) and its FFI transport codec, shared by -# every language binding. Optional in stack-encrypt (the `dynamic` feature). -# 0.5.1 adds `ValueKind`, the field-type vocabulary a dynamic plan declares. -vitaminc-aead-value = "0.5.1" -vitaminc-encrypt = "0.5.1" -vitaminc-hmac = "0.5.1" -vitaminc-prf = "0.5.1" -vitaminc-protected = "0.5.1" +vitaminc = { version = "0.10.0", features = ["random", "protected"] } +# The AEAD crates live in this repository (packages/vitaminc-aead*, +# packages/recipher-frame). +vitaminc-aead = { path = "./packages/vitaminc-aead", version = "0.10.0" } +# The transport frame and ciphertext codec every language binding carries +# across its FFI boundary. Optional in stack-encrypt (the `dynamic` feature). +recipher-frame = { path = "./packages/recipher-frame", version = "0.10.0" } +vitaminc-hmac = "0.10.0" +# Normalized equality terms (Unicode 16 NFC text, one integer encoding for +# every width), which `vitaminc-prf`'s `normalize` feature derives over. +vitaminc-normalize = "0.10.0" +# The text order key: the system ADR-0002's fold, pinned to Unicode 16, +# which text ORE and OPE terms are derived over (ADR-0009). +vitaminc-ore = { version = "0.10.0", features = ["prf"] } +vitaminc-prf = { version = "0.10.0", features = ["normalize"] } +vitaminc-protected = "0.10.0" + +# vitaminc-aead and vitaminc-aead-derive moved here from cipherstash/vitaminc +# and are not published from here yet. The vitaminc crates that stay on +# crates.io (the `vitaminc` umbrella, vitaminc-normalize, -prf, -ore and +# -encrypt) and the order schemes clww-ore and ore-rs depend on vitaminc-aead +# 0.10. This table makes +# them build against the copy here, so the build has one vitaminc-aead 0.10, +# and its types are the ones stack-encrypt passes into them. It applies only +# to the 0.10 line: the vitaminc-aead 0.5.1 that cts-common reaches through +# vitaminc 0.5.1 still comes from crates.io. Every other workspace that +# resolves these crates carries the same table. +[patch.crates-io] +vitaminc-aead = { path = "./packages/vitaminc-aead" } +vitaminc-aead-derive = { path = "./packages/vitaminc-aead-derive" } diff --git a/README.md b/README.md index 973fd6086a..ced941405e 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,9 @@ npx stash init > The Stack also ships a `stash` CLI for auth, schema, and database setup. See the [SDK reference][reference]. +Building in Go? Start with the [Go SDK guide](languages/golang/README.md) for +typed field encryption, generated methods and EQL v4 PostgreSQL queries. + ## What's in the Stack ### 🔐 Searchable encryption diff --git a/SECURITY.md b/SECURITY.md index d462f5fd59..b037162ea2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -21,6 +21,7 @@ This repository is the CipherStash Stack monorepo for JavaScript/TypeScript. It | `@cipherstash/protect-ffi-darwin-arm64`
`@cipherstash/protect-ffi-darwin-x64`
`@cipherstash/protect-ffi-linux-arm64-gnu`
`@cipherstash/protect-ffi-linux-x64-gnu`
`@cipherstash/protect-ffi-linux-x64-musl`
`@cipherstash/protect-ffi-win32-x64-msvc` | Prebuilt per-platform binaries for `@cipherstash/protect-ffi`. Installed as optional dependencies; one is selected at load time for the host platform | | `@cipherstash/auth` | Authentication strategies for CipherStash (napi-rs native binding, with a WASM build for edge runtimes, plus the `./next` and `./start` framework adapters) — imported from `cipherstash/cipherstash-suite` with the `stack-auth` crate it wraps | | `@cipherstash/auth-darwin-arm64`
`@cipherstash/auth-darwin-x64`
`@cipherstash/auth-linux-arm64-gnu`
`@cipherstash/auth-linux-x64-gnu`
`@cipherstash/auth-linux-x64-musl`
`@cipherstash/auth-win32-x64-msvc` | Prebuilt per-platform binaries for `@cipherstash/auth`. Installed as optional peer dependencies; one is selected at load time for the host platform | +| `@cipherstash/recipher` | The TypeScript SDK on the Stack Encrypt engine (`languages/typescript/packages/recipher-js`): a napi-rs native addon over the `stack-encrypt` crate. Private and not published to npm yet; in scope for reports against the source | | `@cipherstash/eql` | Encrypt Query Language — the PostgreSQL SQL bundle (`eql_v3` schema: domains, operators, index-term extractors) that stores and queries encrypted payloads, plus its generated TypeScript types. Applied by `stash eql install` and by the Prisma Next adapter's migrations. Released in lockstep with the `eql-bindings` Rust crate, which emits the payloads this SQL reads | This repository also carries the source of the **`eql-bindings`** Rust crate @@ -28,17 +29,37 @@ This repository also carries the source of the **`eql-bindings`** Rust crate lockstep with `@cipherstash/eql`. It is in scope for security reports on the same terms as the npm packages above. -It also carries the source of five Rust crates published to crates.io, +It also carries the source of six Rust crates published to crates.io, **`stack-auth`** and **`stack-profile`** (`packages/stack-auth`, -`packages/stack-profile`) and **`stack-kms`**, **`stack-encrypt`** and -**`stack-encrypt-derive`** (`packages/stack-kms`, `packages/stack-encrypt`, -`packages/stack-encrypt-derive`), and of the **Go module** at +`packages/stack-profile`) and **`stack-kms`**, **`stack-encrypt`**, +**`stack-encrypt-derive`** and **`stack-encrypt-jsonpath`** +(`packages/stack-kms`, `packages/stack-encrypt`, +`packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`), and of the **Go modules** at `languages/golang` (`encrypt` and `auth`, over WASI guests built -from the stack-* crates), released by `.github/workflows/release-golang.yml` -as `languages/golang/vX.Y.Z` tags. All of these are in scope +from the stack-* crates) and `languages/golang/encrypt/encrypttest`, released +by `.github/workflows/release-golang.yml` as `languages/golang/vX.Y.Z` and +`languages/golang/encrypt/encrypttest/vX.Y.Z` tags. All of these are in scope for security reports on the same terms as the npm packages above. -The five stack-* crates are licensed under the PolyForm Internal Use License +It also carries the source of three Rust crates moved from +`cipherstash/vitaminc`: **`vitaminc-aead`**, **`recipher-frame`** and +**`vitaminc-aead-derive`** (`packages/vitaminc-aead`, +`packages/recipher-frame`, `packages/vitaminc-aead-derive`). They define +the value types Stack Encrypt seals, how each is encoded, and how a value is +sealed. Their crates.io releases up to 0.10.0 were published from +`cipherstash/vitaminc`, the frame crate's under its old name +`vitaminc-aead-frame`, and they are not published from this repository yet. +Every build that uses `vitaminc-aead` 0.10 uses the copies here; the 0.5.1 +and 0.2.0-pre that some builds still reach come from crates.io. The three +crates are licensed under MIT, and are in scope for security reports on the +same terms as the npm packages above. + +The `encrypttest` module ships test builds of the +engine whose keys derive from a published seed. Those keys are not secret by +design: the package is for tests only. A way for a production client to load +a test build, or for a test build to reach ZeroKMS, is in scope. + +The six stack-* crates are licensed under the PolyForm Internal Use License 1.0.0 (each crate's `LICENSE`), not the repository's MIT licence: they may be used for internal business operations only, and not redistributed. That includes the optional `stack-encrypt` feature of the MIT-licensed @@ -61,10 +82,11 @@ in scope as documentation/code-example issues. > seven `@cipherstash/protect-ffi*` packages, all seven `@cipherstash/auth*` > packages and `@cipherstash/eql`, is published from this repository by > `.github/workflows/release.yml`; the `eql-bindings`, `stack-auth`, -> `stack-profile`, `stack-kms`, `stack-encrypt` and `stack-encrypt-derive` -> crates are published from here by `.github/workflows/release-plz.yml` (the -> first version of each of the last three was published by hand, because -> crates.io configures Trusted Publishing on an existing crate). The Go module +> `stack-profile`, `stack-kms`, `stack-encrypt`, `stack-encrypt-derive` and +> `stack-encrypt-jsonpath` crates are published from here by +> `.github/workflows/release-plz.yml` (the first version of each of the last +> four was, or will be, published by hand, because crates.io configures +> Trusted Publishing on an existing crate). The Go module > is released from here by `.github/workflows/release-golang.yml`, as > `languages/golang/vX.Y.Z` tags that `go get` fetches through the Go module > proxy. EQL moved here at the Phase 5 cutover in diff --git a/biome.json b/biome.json index 2ae6966643..a01fb84f57 100644 --- a/biome.json +++ b/biome.json @@ -10,8 +10,6 @@ "!languages/typescript/packages/protect-ffi/lib", "!languages/typescript/packages/protect-ffi/target", "!languages/typescript/packages/protect-ffi/src/eql-v3-types", - "!packages/stack-encrypt/tests/fixtures/record_lowering.json", - "!packages/eql/tests/encryption/fixtures/ste_vec_selectors.json", "!packages/eql/crates/eql-bindings/bindings", "!packages/eql/crates/eql-bindings/schema", "!packages/eql/packages/eql/src/generated", @@ -42,6 +40,7 @@ "!languages/typescript/packages/auth/LICENSE", "!languages/typescript/packages/profile/index.d.ts", "!languages/typescript/packages/profile/native.d.ts", + "!languages/typescript/packages/recipher-js/native.d.ts", "!languages/golang", "!**/*.grit", "!**/*.yml", diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md new file mode 100644 index 0000000000..300bb29a6c --- /dev/null +++ b/conformance/stack-encrypt/README.md @@ -0,0 +1,338 @@ +# Stack Encrypt conformance + +This directory holds a shared test contract for Stack Encrypt bindings. The +[implementation plan](../../docs/plans/2026-10-31-stack-encrypt-conformance.md) +sets out the wider work; [coverage.md](coverage.md) maps existing evidence and +gaps. These profiles are **experimental**, not certification of an entire SDK. + +## Files + +Each file in `v1/` is named `..json`. `` is the exact +`profile` value in the file's header, so searching for a profile ID finds every +file that belongs to it. `v1/` is the corpus format version, which is separate +from each profile's own version. `` is one of: + +- `cases`: the shared, language-neutral cases that every runner executes. When + an expectation is a category rather than bytes, such as an error class or a + retrieval count, it is written in the case itself. +- `expected.`: frozen outputs keyed by the case IDs in `cases`, + produced by ``. `rust-native` is the native Rust engine. Only the + producer regenerates this file, deliberately; runners compare against it. +- `inputs.`: extra inputs keyed by case ID that only `` needs, + such as Go host values that have no language-neutral form. +- `enrollment`: the profile's requirement IDs mapped onto existing compiled + tests that are its evidence, rather than cases of its own. + +Every file has a `version` and `profile` header. An `expected` file also names +its `producer`, and an `inputs` file names its `runner`. +`scripts/__tests__/stack-conformance-ci.test.mjs` fails on a file that breaks +these rules. + +| File | Role | Rust reader | Go reader | +|---|---|---|---| +| `record-scalars-v1.cases.json` | cases | `tests/conformance.rs` | `conformance_test.go` | +| `record-scalars-v1.expected.rust-native.json` | expected | `tests/conformance.rs` (writes it) | `conformance_test.go` | +| `record-declarations-v1.cases.json` | cases | `tests/declarations.rs` | `declaration_conformance_test.go` | +| `record-declarations-v1.inputs.go.json` | Go inputs | — | `declaration_conformance_test.go` | +| `record-reads-v1.cases.json` | cases | `tests/read_conformance.rs` | `read_conformance_test.go` | +| `record-runtime-v1.cases.json` | cases | `tests/runtime_conformance.rs` | `runtime_conformance_test.go` | +| `record-contexts-v1.cases.json` | cases | `tests/context_conformance.rs` | `context_conformance_test.go` | +| `record-contexts-v1.expected.rust-native.json` | expected | `tests/context_conformance.rs` (writes it) | `context_conformance_test.go` | +| `record-context-boundaries-v1.cases.json` | cases | `tests/context_conformance.rs` | `context_conformance_test.go` | +| `record-bindings-v1.cases.json` | cases | `tests/binding_conformance.rs` | `binding_conformance_test.go` | +| `record-bindings-v1.expected.rust-native.json` | expected | `tests/binding_conformance.rs` (writes it) | `binding_conformance_test.go` | +| `record-values-v1.cases.json` | cases | `tests/value_conformance.rs` | `value_conformance_test.go` | +| `record-query-refusals-v1.cases.json` | cases | `tests/query_refusal_conformance.rs` | `query_refusal_conformance_test.go` | +| `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | +| `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, issue #2010) | +| `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, issue #2010) | +| `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | +| `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | +| `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | +| `lifecycle-v1.enrollment.json` | enrollment | `scripts/stack-lifecycle-conformance.mjs` runs the tests it names | `scripts/stack-lifecycle-conformance.mjs` runs the tests it names | +| `fixture-enrollment.json` | index | `tests/common/mod.rs` | `fixture_conformance_test.go` | + +Rust readers are under `packages/stack-encrypt/`; Go readers are under +`languages/golang/encrypt/`; EQL's are under `packages/eql/`. + +### Other readers + +These files read or copy cases, and are not runners: + +| File | Profile | What it reads | +|---|---|---| +| `languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json` | `record-values-v1` | The frames of the corpus cases that the TypeScript value bridge must write. `tests/frames.cjs` regenerates it with `RECIPHER_UPDATE_FIXTURES=1`, and `scripts/__tests__/recipher-js-frame-parity.test.mjs` holds it to the corpus. | +| `scripts/__tests__/stack-exchange-conformance.test.mjs` | `record-values-v1` | The IDs of the positive cases, to build test artifacts. | +| `scripts/__tests__/stack-eql-conformance.test.mjs` | `eql-json-v1` | The documents and the reasons of `invalid_documents`. | +`fixture-enrollment.json` is the one file not named after a profile: it maps +requirement IDs of several profiles onto existing fixtures and tests (see +[the fixture contract](fixture-contract.md)), and +`scripts/stack-conformance-selection.mjs` reads it to choose the Go tests that +`mise run test:conformance` runs. + +## Run + +From the repository root, with the pinned mise tools installed: + +```sh +mise run wasm:guest:build:deterministic +mise run wasm:guest:build +mise run test:conformance +``` + +No credentials or database are required. The task refuses a missing test guest. +It runs native Rust against frozen vectors, Go against the same vectors, then +native Rust against the ciphertexts Go has just produced. It never regenerates +expectations. CI also runs the Go cases on its other supported host platforms. +The same task runs the shared declaration acceptance/rejection corpus in both +languages, with native observations of normalization. It also runs the shared +runtime, read, context, value-boundary, query-refusal and raw-frame cases, and +enrolls the existing value-kind, context-field and query-operator +fixtures described below. It ends with the fresh artifact exchange in both +directions (`test:conformance:exchange`, which also needs the deterministic +EQL guest). Set no fixture-update variables when checking conformance. + +The task runs the single-value cases in native Rust only, because the Go +runner of that profile is pending. + +The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner +is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface +used by generated code. Testing public SDK declarations is a separate layer. +Python and TypeScript runners are pending; their absence is not a passing result. + +## Fresh artifact exchange + +The [exchange contract](exchange-contract.md) defines `artifact-exchange-v1`: +in one run, Rust writes and Go opens, and Go writes and Rust opens, every +value kind at its edges, a structural record with passthrough and index +terms, whole-value opaque blobs and EQL v4 rows. Decrypted values and the +consumer's own derived query terms are compared, never ciphertext bytes. +`mise run test:conformance:exchange` fails on a missing runner or guest and +on an empty fresh output, and its report records the producer SDKs, engines, +backends, guests and storage versions. It lists the one released-version +combination the API plan requires, Go rc.3 data read by this checkout, as not +yet run; the others wait on the compatibility policy. Python and TypeScript +are listed as not enrolled. + +## Lifecycle, cleanup and key I/O + +The [lifecycle contract](lifecycle-contract.md) maps native/Go ownership, +cancellation, partial-output cleanup, diagnostics, validation-before-I/O and +batching evidence. Run `mise run test:conformance:lifecycle` on a supported Unix +host with the normal and deterministic guests built. Reports retain known +cleanup gaps and unobserved behavior alongside the passing requirements. + +## EQL and JSON operations + +The [EQL/JSON contract](eql-json-contract.md) enrolls resolver capabilities, +document writes, queries, extraction reads, subtree reads, reads of one +child checked against its parent, element-match, and predicate matching. The +contract reuses the native, Go, and independent PostgreSQL suites. The +contract also shares write and predicate case data. Run `mise run test:conformance:eql` and the separate +required `test:conformance:eql:postgres` task; see the contract for guest builds, +disposable database setup, intentional SQL differences and version reports. + +## Context composition and expectations + +The [context contract](context-contract.md) covers ordered scopes, bindings, canonical +context encodings, typed/generated API calls, stored-context expectations, +tampering and preflight boundaries. The required command runs the new +`context_conformance` Rust binary and `TestContextConformance` / +`TestContextBoundaries` Go runners, together with native `plan_grammar` and +existing context-field fixture tests. + +## Existing value-kind and query-operator fixtures + +The [fixture contract](fixture-contract.md) defines `record-value-kinds-v1` and +`record-query-operators-v1`. Their [enrollment index](v1/fixture-enrollment.json) +maps stable requirement IDs to the existing Rust and Go tests. The fixtures +remain under `packages/stack-encrypt/tests/fixtures`; no vectors are copied. + +These profiles cover the represented narrow/128-bit integers, dates, +timestamps, decimals, equality/order terms, query operand metadata, match +verification and fetch limits. They preserve typed Rust and generated Go API +checks. The task runs the existing tests directly, and a missing guest fails +when conformance is required. The ordinary CI suites already execute them. + +This is representative fixture coverage, not an exhaustive type/operator +matrix. The value-boundary and query-refusal profiles below widen it, and the +exchange profile above writes the wider kinds fresh in both directions. The +EQL/JSON profiles are described below. + +## Value boundaries, query refusals and raw frames + +Three profiles close the gaps the representative profiles left. The +[value contract](values-contract.md) defines `record-values-v1` in +`v1/record-values-v1.cases.json`: every kind at its edges, sealed and SQL nulls for the +fixed-width kinds, exact write conversions between widths, write +refusals between kinds, `undefined` on a typed field, frozen typed frames, and +the Go-only host conversions the host refuses before the engine. The +[query-refusal contract](query-refusals-contract.md) defines +`record-query-refusals-v1` in `v1/record-query-refusals-v1.cases.json`: one plan, every +scalar operator against every field capability that does not answer it, +the range shapes, other-kind values and nulls the contract lists, each refusal's +class and diagnostic, no key I/O, and the stage at which a typed Rust +query refuses the same query. The [raw-frame contract](raw-frames-contract.md) +defines `record-raw-frames-v1` in `v1/record-raw-frames-v1.cases.json`: stored batches as +transport bytes, so repeated keys and malformed leaves reach both decoders, +and the table of error classes (transport, leaf, shape, authenticated, +invalid declaration, unsupported host conversion). The runners are +`value_conformance`, `query_refusal_conformance` and `raw_frame_conformance` +in the Rust crate and `TestValueConformance`, `TestQueryRefusalConformance` +and `TestRawFrameConformance` in the Go module; `test:conformance` runs all +six. + +## Single values + +The [single-value contract](single-value-contract.md) defines +`single-value-v1` in `v1/single-value-v1.cases.json`, and the terms used here. +The profile encrypts one value as one ciphertext through the run-time +interface of the engine, and decrypts it again. Each case gives a value, the +kind declared for it, and a context. The cases cover: + +- every scalar kind +- the exact conversions that a declared kind makes +- JSON documents +- the one stored form of a string and a document +- batches of single-value calls merged into one key request +- the refusals of an array, an object, a passthrough, a null, `undefined`, + and a value of another kind + +`v1/single-value-v1.expected.rust-native.json` freezes three things for each +case: the frame of the input, the plaintext that the leaf is sealed with, and +a ciphertext that every runner must open. + +The native runner is `single_value_conformance` in the Rust crate. +`test:conformance` runs it. The runner also compares the run-time interface +with the typed interface. The Go runner is pending. The Go runner will be +written with the single-value calls of the Go SDK (issue #2010). + +## `record-reads-v1` contract + +The [read contract](read-contract.md) defines cases in `v1/record-reads-v1.cases.json` for +malformed stored records, authenticated read-type failures and context preflight. +The native runner observes retrieval stages. Go exercises the same cases through +an uninitialised guest and a configured cipher, plus the normal record adapter +for representable cases. The contract records the static-context combination +that the host refuses before calling the guest. The runners are `tests/read_conformance.rs` in the Rust +crate and `encrypt/read_conformance_test.go` in the Go module. + +## `record-runtime-v1` contract + +The [runtime contract](runtime-contract.md) defines cases in `v1/record-runtime-v1.cases.json`: +missing and explicit null values, SQL-null omission, sealed-null storage and +equality, typed batch round trips, write validation and lossless query conversions. +The runners are `packages/stack-encrypt/tests/runtime_conformance.rs` and +`languages/golang/encrypt/runtime_conformance_test.go`. Native Rust also checks +data-key call counts; Go host source validation preserves shared structured diagnostics. + +## `record-declarations-v1` contract + +The [declaration grammar](declaration-grammar.md) defines the engine's current +record-plan syntax, defaults, context rules, kind/index table and null policies. +`v1/record-declarations-v1.cases.json` contains cases, including malformed frames and all +22 kinds against five scalar indexes. The resolver is explicitly `none`; EQL +targets need their own profile. + +The runners are `packages/stack-encrypt/tests/declarations.rs` and +`languages/golang/encrypt/declaration_conformance_test.go`. Both call the engine +without a cipher. Valid-frame declaration diagnostics agree exactly; malformed +frames document the different native-parser and WASI-boundary classifications. +Native Rust also checks normalization observations. Go's checker does not expose +the parsed plan, so it asserts acceptance and diagnostics against both release +and deterministic guests. Representable cases also exercise `Checker.Check` +through explicit host plan fixtures in `v1/record-declarations-v1.inputs.go.json`. + +## `record-scalars-v1` contract + +`v1/record-scalars-v1.cases.json` has a corpus format `version`, a semantic `profile`, a public +deterministic-provider `seed`, a record `context`, a `field`, an exact list of +`required_capabilities`, and uniquely identified `cases`. Unknown fields, +versions, profiles, capabilities and input types fail. Every case must run. + +The profile fixes a one-field record with ciphertext (`c`) and equality (`eq`) +outputs. Its field context is the record context followed by the field name. +Each case declares the field's `kind` and a typed `input`. `input.text` is the +literal string value, canonical base-10 integer, `true`/`false`, or empty text +for null, as determined by `input.type`. Runners construct real typed host +values, preserving integer width. JSON numbers are deliberately not used for +values: future TypeScript runners must not pass 64-bit integers through Number. + +The initial positives cover int32 and int64 bounds, uint64 max, an integer +above JavaScript's safe-integer limit, Unicode text and empty text. For each: + +1. The encoded typed frame must equal the frozen frame, including its type. +2. Record encryption and opening must preserve both value and type. +3. An equality query must produce one exact `eq` operand, encoded as `bytes`, + without an EQL domain. Its bytes must equal the frozen equality term and + the term stored with the record. +4. The frozen native owned-scalar ciphertext must open through the record + path. Native Rust additionally opens it through the owned scalar API. +5. Fresh Go ciphertext must open in Rust through both paths. Ciphertext bytes + themselves are not compared: encryption is randomized. +6. Opening with `wrong` appended to the record context (before the field name) + must refuse key retrieval as forbidden. + This expectation uses `stack_kms::DeterministicSource`, whose descriptor + binding models ZeroKMS's refusal. It is distinct from an AEAD failure and + does not imply every provider returns the same error shape. + +Negative cases have `expected_error` and exercise the equality query only. +They require the exact engine diagnostic `code`, `reason`, and field name; +Go must also expose `ErrEncoding`. Native Rust verifies rejection occurs +before data-key generation or retrieval. String/bool inputs for an integer +field and a null query are currently covered. Error prose is not contractual. + +Boolean equality is not admitted by the current engine. Boolean scalar +encryption, nullable records, other numeric kinds, bytes, JSON, EQL targets, +other operators, declarations, cancellation and provider failures need later +profiles or cases. The full SQL behavior is not part of this initial profile. + +## Artifacts and evolution + +`v1/record-scalars-v1.expected.rust-native.json` is a frozen artifact set produced by the Rust owned scalar API. +It records `version`, `profile`, `producer`, and a case-ID map containing hex +`frame`, `ciphertext` and `equality` bytes. The map must contain exactly every +positive case; missing or extra cases fail. Every key and plaintext here is +public test material. The provider seed is not a production key mechanism. + +The runners accept `STACK_CONFORMANCE_OUTPUT` to export fresh artifacts; Rust +accepts `STACK_CONFORMANCE_INPUT` to validate another producer. The task isolates +these variables and sets `STACK_CONFORMANCE_REQUIRED=1`, preventing a missing +Go test guest from turning conformance into a skipped test. Ordinary Go test +runs may skip this suite when the guest has not been built. + +To intentionally create or update native artifacts: + +```sh +STACK_CONFORMANCE_UPDATE=1 mise x --env test -- cargo nextest run --locked \ + -p stack-encrypt --all-features --test conformance +mise run test:conformance +``` + +Review the case and artifact diff together. Never regenerate artifacts merely +to make a regression pass. + +A case ID names one input and one operation. Today every reader of every +profile is in this repository. Until that changes, an engine change may change +what a case expects in place, for example from refused to accepted. It may +also rename or remove a case. The pull request that does so updates every +reader and lists each case it changed, renamed or removed. + +Once code outside this repository reads a profile, its case IDs and +expectations are fixed. A change to them then needs a new profile. + +The readers of a profile are the files in the table under [Files](#files), and +the [other readers](#other-readers) below it. To check that none is missed, +search the repository for the profile ID, such as +`git grep -l record-values-v1`. That also finds a test that copies part of a +case. + +Corpus version 1 is a test format, not a production wire version. +Ciphertext/storage versions remain owned by their existing codecs. + +Both runners currently share the Rust engine. This checks host value conversion, +native/WASI interoperability and regressions against frozen evidence; it cannot +detect every bug shared by both paths. Independent SQL oracles exist for the +EQL/JSON profiles; the Go rc.3 combination the API plan requires is not yet +run, and the rest of the release-version matrix waits on the compatibility +policy. Both have their place in the exchange report. diff --git a/conformance/stack-encrypt/context-contract.md b/conformance/stack-encrypt/context-contract.md new file mode 100644 index 0000000000..33ab093c25 --- /dev/null +++ b/conformance/stack-encrypt/context-contract.md @@ -0,0 +1,166 @@ +# Context composition + +`record-contexts-v1` (`v1/record-contexts-v1.cases.json`) specifies composition for the current +record API. `record-context-boundaries-v1` (`v1/record-context-boundaries-v1.cases.json`) specifies +stored-context expectations and refusal boundaries. Both are required in Rust +and Go. Python and TypeScript must implement these profiles when their runners +are added; their absence is not conformance evidence. + +## Current semantics + +A field's base is a plain label: the record's declared label followed by the +field's identity. A context-field record obtains the record label from each +row's stored field. Go generated types declare either a literal context or a +context field. + +Caller input has two distinct purposes: + +- A **base label** supplies a missing base for a query or a contextless plan. + For a record storing its own context, an expected label checks that stored + value. It does not replace or extend it. A caller label on a plan with a + literal base is refused. +- A **scope** appends to the resolved field context for encryption, + decryption and search. Each part appends in order. Rust + `DeclaredContext::default().with(7u64).with(nonempty!("eu"))` and Go + `.Scope(uint64(7)).Scope("eu")` produce `((label)/7u64)/eu`. + Rust `DeclaredContext::from(())` and Go `.Scope()` append nothing. A Rust + `DeclaredContext` containing several parts appends all of those parts. + Go `Extend` is the deprecated name of `Scope`. Earlier text called a + scope an extension. +- A **binding** appends after every scope, for encryption and decryption + only. It is in the stored context, which the data key and the AAD derive + under, and in no query context, which the search terms derive under. Rust + `Scope::new(7u64).bind(9u64)` and Go `.Scope(uint64(7)).Bind(uint64(9))` + produce the stored context `((label)/7u64)/9u64` and the query context + `(label)/7u64`. A query with a binding is refused before any key is + requested. Rust refuses a bare `Bind` at compile time. A binding inside a + `CallerContext` or `DeclaredContext` is refused when the query is awaited + (`PlanError::BindInQuery`). The dynamic path refuses a query on a plan + with a `bind` key (`bind_in_query`). An empty binding is refused on every + path before any key is requested (Rust `PlanError::EmptyPart`, dynamic + `empty_binding`, Go `ErrEncoding`). An empty scope part stays allowed in + the dynamic grammar and Go `Scope`, as before. `bind` is a reserved + plan-level key, so no field is called that. `record-bindings-v1` + (`v1/record-bindings-v1.cases.json`) specifies this, and both languages + are required to run it. + +Grouping is significant. Rust +`DeclaredContext::from(NonEmpty::from(7u64).with("eu"))` adds one composite +part, producing `(label)/(7u64/eu)`. This has different AAD and +terms from separate scopes. Nested `ContextPiece` values are supported by +Rust's lower-level context APIs; the dynamic record grammar and Go `Scope` +accept scalar parts only. Their refusal of a grouped part is part of the +supported API boundary, not permission to flatten it. + +Previously, repeated `.extend` calls on the Rust chain, which is now +removed, replaced earlier parts. Records +written by those chains still require the +**last extension alone** when opening them; callers must explicitly retain that +old context when reading and querying old records. A query using repeated +extensions now succeeds with different terms, silently missing old rows. +Re-encrypt and re-index old rows to adopt the appended context. This change +does not rewrite ciphertext or migrate stored terms. + +The native base and each appended scalar retain their type and structure. +`7i32`, `7i64`, `7u64`, text `eu`, and bytes `6575` do not collapse to one AAD +or PRF context. Descriptor rendering is deliberately coarser in some cases: +text and bytes can render alike, as can positive signed and unsigned integers. +A matching descriptor alone therefore does not prove matching AAD. Empty text +is accepted by dynamic record/Go extension APIs when the base remains nonempty; +Rust's `NonEmpty` constructor rejects an empty standalone extension. The +composition runner records this API difference instead of bypassing it. + +## Composition evidence + +Each case has a unique `id`, `base` (`literal` or `field`), nonempty `label`, and +ordered `parts`. Each part is `{ "type": ..., "text": ... }`: string, int32, +int64, uint64, or bytes (hex). Integers are decimal strings, never JSON numbers. +Every case encrypts and queries the string `hello` in the `text` field, using +the public all-zero deterministic-provider test seed. + +`v1/record-contexts-v1.expected.rust-native.json` is keyed by exactly those case IDs. It pins the +resolved context frame, the field context frame sent in a plan, descriptor, +AAD, PRF bytes, one Rust ciphertext and equality term. Rust checks actual descriptors sent to the key provider, fresh typed and +dynamic writes, queries, opens, and frozen ciphertexts. The typed side runs +the engine's combinators under a declared context with one part for each +part of the case, so a later part cannot replace an earlier one unnoticed. + +Go observes the actual plan buffer at the `se_encrypt_record` WASM boundary +through a test-only function wrapper. It compares the field context in those +bytes with the frozen native plan-context frame, then opens the Rust ciphertext. +It compares fresh stored and query terms, both variadic and repeated extensions, +and generated `Note` (field base) and `LiteralNote` (literal base) methods. +Go does not expose a separate descriptor/AAD encoder: matching the actual plan +and successful authenticated cross-opening provide indirect evidence for those +observations. Native Rust checks the canonical descriptor/AAD/PRF bytes directly. +Ciphertext bytes are randomized and are not compared for equality. + +Regenerate deliberately with `STACK_ENCRYPT_UPDATE_FIXTURES=1` and the native +`context_conformance` binary. Required conformance rejects fixture updates. +Changes to frozen context encodings require compatibility review. + +## Expectations and boundaries + +Boundary cases specify rows' `tenants`, the caller's `expected` label (the empty +string explicitly means no expectation in this corpus), a mutation of the last +stored row, an `outcome`, and `native_retrievals`. All properties are required; +null is not an alternative spelling for omission or the empty string. + +Cases cover unrestricted reads, matching expectations, late mismatches, empty +batches, changed stored labels with and without matching expectations, and +missing/empty stored contexts late in a batch. A two-row ciphertext-tampering +case reaches AEAD after retrieval in both languages and returns no partial +plaintext. Generated Go opening exercises the boundary cases too, except that +an absent member cannot be represented by a generated Go struct and is tested +at the raw-tree boundary. Typed Rust opening, through the combinators, holds +no expected context, so it runs the cases that need none: the unrestricted +read and the three tampering cases. + +The separate `queries` array specifies a caller `context`, an `outcome` and +whether the query `matches` the stored term for `tenants/acme`. Missing and +invalid contexts refuse; another tenant produces a valid nonmatching query. +Rust data-plan queries and generated Go query methods execute these cases. +Key-independent refusals must make no retrieval. An empty valid batch also makes none. Changing the stored +label does not confer permission to open the ciphertext even if the caller's +expectation matches the replacement label. + +Native `CountingSource` checks exact data-key call counts. Its fake provider +does not authenticate descriptors, so a tampered context fails AEAD after one +retrieval. Go's deterministic provider authenticates the descriptor and refuses +the same tampering with `ErrForbidden`. An uninitialised Go checker separately +proves the key-free preflight boundary. This is not a claim that Go exposes +provider call counters. + +The earlier read profile continues to cover context storage shape and exact +structured diagnostics. The enrolled `record-context-fields-v1` fixture +retains generated Go expectation, query, tampering and single-field update +checks and Rust typed/dynamic cross-opening. The required native `plan_grammar` +binary additionally covers, through the data plan, a missing context (a +query on a context-field plan that names none, and an empty caller scope), +conflicting sources, invalid labels, caller-derived queries and an empty +scope on an empty batch. Each refusal is made before any key is requested. + +## Bindings + +`record-bindings-v1` specifies the split between the query context and the +stored context. Each case has a unique `id`, a nonempty `label`, ordered +`scopes`, and nonempty ordered `bind` parts, in the part form above. Every +case encrypts and queries the string `hello` in the `text` field, with the +all-zero deterministic seed. + +`v1/record-bindings-v1.expected.rust-native.json` pins, per case, the +descriptor of the stored context, the equality term, one ciphertext, and the +contexts text a plan prints. Rust checks that the term equals the term of the +same plan with no binding, that the key is requested under the stored +context's descriptor, that a query on the bound plan is refused, that the +frozen ciphertext opens under its binding and under no other, and the +contexts text. Go seals and opens through `Scope` and `Bind`, compares its +term and the cipher's contexts text with the vector, opens the Rust +ciphertext, and refuses a query through a cipher with a binding. + +## Future roles + +This profile describes the current shared context: it feeds the data-key +descriptor, ciphertext AAD and index PRF context. The split between the +stored context and the query context is in the bindings profile above. +Neither profile asserts plaintext erasure in Go, Python or TypeScript heaps. diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md new file mode 100644 index 0000000000..90b5706558 --- /dev/null +++ b/conformance/stack-encrypt/coverage.md @@ -0,0 +1,268 @@ +# Coverage map + +Snapshot: PR #1404 at `b684a217e`, including the JSON matching work through #1452. +This is an inventory of evidence, not a claim that every suite was rerun here. +Paths are relative to the repository root. New profile cases run from `v1/`. + +| Requirement | Existing evidence | Remaining work | +|---|---|---| +| Scalar value widths and lossless transport | Initial scalar cases, [value-kind requirements](fixture-contract.md#value-kind-requirements) and the [value boundary profile](values-contract.md) (`v1/record-values-v1.cases.json`: every kind's edges, float specials, bytes, decimal and timestamp precision, sealed/SQL nulls per kind, exact write conversions between widths, cross-kind write refusals, `undefined` on a typed field, Go host conversions); every positive case written fresh by each runner and opened by the other ([exchange profile](exchange-contract.md)) | Python/TS mappings; dates before year 1 and the timestamp range ends | +| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). One value of a kind known only at run time, as one ciphertext: the [single-value profile](single-value-contract.md), run by native Rust (`v1/single-value-v1.cases.json`: every scalar kind, exact conversions, JSON documents, batches, and the refusals, with the plaintext of each leaf and a frozen ciphertext). `packages/stack-encrypt/tests/single_value.rs` compares the run-time interface with the typed interface. JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix; the Go runner of the single-value profile (issue #2010), and Python and TypeScript runners | +| Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/record-declarations-v1.cases.json` shared by native Rust and Go; native normalization observations; existing record lowering suites; `packages/stack-encrypt/tests/owned_equivalence.rs`, which seals one mixed, searchable record three ways: through a hand-written owned target, the owned derive, and the data plan. All three use one provider that records its requests. The test compares the descriptors and the term bytes, and checks that each way decrypts the records of the others | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes | +| Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | +| Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | +| Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures | +| Fresh cross-language storage | `.github/workflows/tests-golang.yml` exports fresh Go EQL rows for Rust, the storage-only `Json` documents among them; initial scalar artifact exchange; fixed storage-blob vectors read by both Rust (`opaque_blob.rs`) and Go (`TestOpaqueReadsARustWrittenBlob`); the [exchange profile](exchange-contract.md): values, records, blobs and EQL rows written fresh and opened in both Rust/Go directions, with producer, engine, backend and storage versions in the report | Python/TypeScript pairs and backends when their runners exist; supported released versions once the compatibility policy is defined; fresh exchange of searchable JSON documents, and of `Json` documents from Rust to Go; a SQL lane storing one language's fresh rows through the other | +| JSON queries, extraction and tampering | `packages/stack-encrypt/tests/json_tree_vectors.rs`; `packages/eql/tests/encryption/tests/json_tree.rs`; `languages/golang/encrypt/json_tree_test.go`, `json_postgres_test.go` | Formal operation profile; JSON vectors consumed by all runners | +| Element and predicate matching | Go `json_elements_test.go`, `json_match_test.go` and corresponding PostgreSQL tests; Rust/SQL predicate suites | Map exact supported grammar and documented semantic differences to case IDs | +| Generated SDK declarations | Go stashgen and generated-code fixture tests | Python and TypeScript public-API runners; compiler/type-checker cases | +| Validation before key I/O and batching | Rust `tests/common::CountingSource` and record/query tests; guest preflight tests | Requirement-by-requirement coverage; common provider observations | +| Binding lifecycle and cleanup | `packages/stack-guest-abi`; Go `cancel_test.go`, `step_test.go`, guest memory tests | Native Python/TS and WASM backend-specific matrices; no blanket host-erasure claim | +| Version/capability negotiation | Existing ABI status table and target/operator discovery | Normative supported-version rules; reject unknown required capabilities | + +Python and future TypeScript runners have no evidence in this checkout. Their +absence is a delivery gap, not a test skip that counts toward certification. + +## Runtime checkpoint + +`v1/record-runtime-v1.cases.json` adds shared cases for typed writes and reads, null storage, +batches, equality queries and lossless numeric conversion. See the +[runtime contract](runtime-contract.md) for exact observations and limits. +Native data-key counters cover zero-call preflight failures and single-call +batches; Go provider-call instrumentation remains open. + +| Existing evidence | Shared case IDs | Retained assertions | +|---|---|---| +| Native SQL-null record tests | `sql-missing`, `sql-null`, `sql-mixed-batch`, `sql-all-absent` | Wider declarations and malformed stored-record behavior | +| Native sealed-null padding/equality tests | `sealed-mixed-batch`, `sealed-int64`, `sealed-uint64`, `sealed-float64` | Other integer widths, bool ciphertext, dates, timestamps and decimals | +| Go generated `null_test.go` | Same sealed/SQL semantics | Pointer mapping, generated methods, EQL envelopes, reading null into nonpointer fields | +| Native source validation tests | `late-wrong-type`, `late-missing`, `unknown-field` | Repeated keys, unsupported frame shapes and more output kinds | +| Existing shared value-kind/operator fixtures | Runtime query cases cover selected conversion edges | Full type/operator matrices, generated SDK calls and verification | + +## Read checkpoint + +`v1/record-reads-v1.cases.json` adds cases for stored-shape validation, authenticated types +and context preflight. The [read contract](read-contract.md) distinguishes native +shape/pending stages and the guest's earlier `check_record` diagnostics. Native +data-key counters and Go's uninitialised guest verify preflight boundaries. + +| Existing evidence | Shared case IDs | Retained assertions | +|---|---|---| +| Native `a_stored_record_that_does_not_fit` | `missing-field`, `missing-ciphertext`, `field-not-map`, `plaintext-under-c`, `row-not-map`, `late-missing-field` | Repeated keys, other passthrough fields and output kinds | +| Native typed read/null tests | `authenticated-int32-as-*`, `authenticated-null-as-required`, `authenticated-null-as-sql`, `sql-absent-*` | Wider types and declaration combinations | +| Go `context_field_test.go`, native context tests | `context-unrestricted`, `context-expected`, `context-mismatch`, `context-late-mismatch`, `context-drop-tenant`, `context-tenant-*` | Generated APIs, queries, extension composition and stored-context tampering | +| Native and guest context-source validation | `static-context-with-expectation` | Other source combinations and empty-batch behavior | + +These are overlap mappings, not grounds for deleting whole mixed-purpose tests. +Repeated-key trees cannot be emitted by Go's map-based tree encoder; the +[raw-frame profile](raw-frames-contract.md) covers that boundary with +transport bytes both runners decode. + +## Consolidation policy + +The value-kind/query-operator enrollment adds named requirements for the +existing fixtures through [the enrollment index](v1/fixture-enrollment.json). +The conformance command selects their original runners; CI guards the mapping +and selection. Typed Rust comparisons, generated Go methods, verification and +fetch-limit checks stay in those runners. No fixture is copied and no existing +assertion is removed. Shared negative cases and fresh exchange of the wider +value kinds remain open. + +Shared semantic expectations should be maintained once and executed by each +language runner. Conformance can replace duplicate case tables and fixture +maintenance. It does not eliminate the need to execute the Rust and Go paths. +Enrollment alone deleted no test; the [consolidations](#consolidations) below +record each duplicate table that was later removed, with the shared cases +and the fault evidence that replaced it. + +| Existing evidence | Relationship to conformance | Consolidation action | +|---|---|---| +| Rust `dynamic/record.rs` plan-refusal tests | Their inputs and diagnostic outcomes are shared declaration cases | Removed; the message naming its field stays in `a_plan_refusal_names_its_field_in_the_message` (see [consolidations](#consolidations)) | +| Rust kind/index admission tests | The corpus has the complete 22-kind/five-index acceptance matrix | Share case data; retain direct tests that compare declaration admission with actual term execution | +| Rust `value_kinds.rs`, Go `value_kinds_test.go` | Enrolled as `record-value-kinds-v1`, retaining the shared fixture and generated SDK calls | Extend the existing fixture/requirements for missing boundaries; retain typed and generated-code assertions | +| Rust `query_operators.rs`, Go `query_test.go` | Enrolled as `record-query-operators-v1`, including verification and target limits | Add shared refusal cases separately; retain host/generated query mapping tests | +| Go checker and host validation tests in `guest_test.go` | Exercise host rejection and diagnostic forwarding through public checker methods | Keep adapter-specific assertions; representable declaration cases also use `Checker.Check`, while raw frames observe the guest boundary | +| Native scalar/record round trips and cross-opening | Some behavior overlaps, but existing tests cover more types and API paths | Replace only exact duplicates after matching requirements and execution paths | + +Keep Rust compile-fail, ownership/zeroization, batching, fuzz/property, and +implementation regression tests. Keep Go generation, host type conversion, +error wrapping, cancellation and guest lifecycle tests. Keep independent +PostgreSQL oracles and live-provider tests. These observe guarantees a shared +engine corpus cannot prove by itself. + +For each removal, link the old assertion to stable case IDs, compare coverage +and failure behavior, and run both runners in CI. Preserve unrelated assertions +from mixed tests. Enroll Python and TypeScript against the existing corpus so +adding a language does not create another copy of the expected behavior. + +## Context checkpoint + +The [context contract](context-contract.md) adds 18 shared composition cases and +eleven shared read boundary cases and four query cases, plus enrollment of the +existing record-lowering +context-field fixture. Rust typed writes, queries and opens (the engine's +combinators) and Go generated methods execute the composition cases. Required +native plan-grammar tests cover a missing context, conflicting sources and an +empty scope on an empty batch, through the data plan. Existing context tests +remain: no mixed-purpose Rust or Go test is removed. + +Go proves canonical AAD indirectly through its actual guest plan frame and native +ciphertext opening; provider-call instrumentation remains a separate gap. +Nested composite extensions remain a native API capability rather than an +unsupported feature silently advertised by the Go/dynamic record profile. + +## EQL/JSON checkpoint + +The [EQL/JSON contract](eql-json-contract.md) and its enrollment index cover +resolver/catalog capabilities, JSON writes and queries, request-bound reads, +reads of one child checked against its parent, element-match, and +predicate-match. Existing Rust, Go, and PostgreSQL suites stay in place. The common document and predicate-refusal tables now live in +`v1/eql-json-v1.cases.json`: Rust and Go execute them, retaining native key-call checks, +Go diagnostic mapping and all extra cases from the original suites. + +The database lane preserves independent plaintext oracles and generated +properties. Required test inventory/no-skip checks and engine/guest/SQL identity +reports make enrollment observable. This consolidates data and requirements; +it does not replace adapter tests or claim whole-database authentication. +Fresh JSON artifact exchange, released-version matrices and Python/TypeScript +runners remain open; the scalar EQL rows are exchanged fresh in both +directions by the exchange profile. + +## Value, refusal and raw-frame checkpoint + +Three shared corpora close the boundary gaps the representative profiles +left: `v1/record-values-v1.cases.json` (the [value contract](values-contract.md)), +`v1/record-query-refusals-v1.cases.json` (the [query-refusal contract](query-refusals-contract.md)) +and `v1/record-raw-frames-v1.cases.json` (the [raw-frame contract](raw-frames-contract.md)). +Each runs in native Rust and Go WASI under `test:conformance`. + +| Existing evidence | Shared case IDs | Retained assertions | +|---|---|---| +| `value_kinds.json` and its runners | `i8-*`, `u8-*`, `i16-*`, `u16-*`, `u32-*`, `i128-*`, `u128-*`, `f32-*`, `f64-*`, `bytes-*`, `decimal-*`, `date-*`, `timestamp-*`, `sealed-*`, `sql-*`, `*-given-*` | Typed Rust term comparisons and generated Go methods | +| Native `dynamic/query.rs` refusal tests, Go `TestVerifyAndTargetLimitRefuseWhatIsNotAMatchQuery` | Every `record-query-refusals-v1` case | Tree-notation inputs, the hand-built match options, generated query methods | +| Native typed refusal tests in `tests/op.rs` | The `typed` entries | A refusal in a batch of two queries, and the refusal on a case-sensitive field | +| Native `a_stored_record_that_does_not_fit`, the read profile | `shape-*`, `authenticated-*`, `success-*` | Mutation vocabulary over real ciphertext | +| Guest `test_frame` and `last_error` tests | `transport-*`, `leaf-*` | Plan-frame boundary cases, ABI status mapping | + +Unsupported combinations the corpora record rather than skip: a repeated +key in a stored record is a transport refusal in both decoders, and the engine's own `field_repeated` +and `repeated_key` guards are reached natively alone; the Go host refuses +the zero `Date`, a decimal scale above 28, a timestamp outside the +decoder's range and non-value Go types before the engine. `NaN` and +negative-zero decimals are excluded as host-dependent. + +## Lifecycle checkpoint + +The [lifecycle contract](lifecycle-contract.md) enrolls native pending/KMS tests, +heap observations, guest ABI cleanup, Go cancellation/memory tests and public SDK +diagnostics. New probes cover unpolled and in-flight drops, provider failure, +cleanup after a late authenticated type failure, and chunk concurrency/drop. +The owned `Vec` to `Vec` conversion is enrolled under the same +requirements. The conversion's tests cover: + +- dropping a collection before it is polled +- dropping a collection while its key request is running +- one logical batch of key requests for each collection, and none for an + empty collection +- wiping the source `Vec` through its guard +- wiping the elements already decrypted, when a later element fails + +The owned conversion is a native Rust API. Go reaches batching through its +record interface, and the runtime profile covers that interface. +Existing runtime/read/context vectors retain their provider-call counters. + +This adds required execution and explicit observation limits; it removes no +backend-specific tests. The known Go post-decryption shadow-stack gap and native +heap-observer exclusions stay visible in reports. Logical batching is distinct +from downstream chunking and unobserved live HTTP behavior. Python and TypeScript +lifecycle evidence is pending. + +## Exchange checkpoint + +The [exchange contract](exchange-contract.md) defines `artifact-exchange-v1` +over `v1/artifact-exchange-v1.cases.json`: in one run and a fresh directory, Rust writes and Go +opens, and Go writes and Rust opens, every positive value-boundary case, a +structural record with a passthrough field and equality/order terms, three +opaque blobs and the EQL v4 `profiles` rows. Consumers compare decrypted +values and their own derived query terms; ciphertext bytes are never +compared. The task fails on a missing runner or guest and on an empty fresh +output, and its report records producer SDKs, engines, backends, guests, +lockfiles and storage versions, and lists the released-version combination +the API plan requires (Go rc.3 data read by this checkout) as not yet run. +No frozen artifact changes. + +| Direction | Kinds | Consumer evidence | +|---|---|---| +| Go to Rust | `values`, `record`, `blobs`, `eql-rows` | `fresh_artifact_exchange` (`STACK_EXCHANGE_INPUT`), `rows_the_go_sdk_sealed_open_in_rust` (`EQL_V4_ROWS`) | +| Rust to Go | `values`, `record`, `blobs`, `eql-rows` | `TestArtifactExchange` (`STACK_EXCHANGE_INPUT`), `TestV4RowsTheRustSuiteSealedOpenInGo` (`EQL_V4_RUST_ROWS`) | +| Python, TypeScript | none | No runner exists; reported as not enrolled | + +Open: fresh JSON document exchange, the remaining EQL types, a SQL lane +that stores one language's fresh rows through the other, and the +a lane that runs the required Go rc.3 combination, and the other +released-version rows once the compatibility policy is defined. + +## Consolidations + +Each row is one old assertion table whose literal expectations are now held +by a shared corpus and executed by both language runners. A row was removed +only after a fault was introduced by hand into the engine and the named +replacement runner failed on it under `STACK_CONFORMANCE_REQUIRED=1`; the +fault was then reverted. "Fails on" names the fault and the case the runner +reported. Where an old table mixed shared rows with shapes the corpus cannot +spell, only the shared rows were removed and the test's doc comment says what +stays. Every shared case in these rows runs natively through the Rust binary +named and through the Go guest (`TestDeclarationConformance` on both guests, +`TestRuntimeConformance`, `TestReadConformance`, `TestQueryRefusalConformance`). + +Five cases were enrolled so the old rows had a one-to-one home rather than a +neighbour: `output-not-string`, `passthrough-with-index` and `target-number` +in `v1/declarations.json`; `ore-block-between-long-low` and +`ore-block-between-nul-high` in `v1/query-refusals.json`. + +| Old test (file) | Shared case IDs | Replacement runner | Fails on | +|---|---|---|---| +| `every_refusal_names_its_field_and_reason::a_malformed_plan` (`src/dynamic/record.rs`), 24 rows, removed; its check that the message names the field stays in `a_plan_refusal_names_its_field_in_the_message`, since the corpus compares payloads, not messages | `root-null`, `root-list`, `empty-plan`, `field-not-object`, `unknown-key`, `frame-duplicate-key` (a field given twice; the frame refuses a repeated key before the plan is read, and a key repeated inside a spec stays in the kept `a type given twice` and `a context_field key given twice` rows), `missing-context`, `missing-outputs`, `outputs-with-target`, `outputs-string`, `output-unknown`, `outputs-empty`, `output-duplicate`, `passthrough-with-ciphertext`, `target-number`, `type-unknown`, `type-uint32-match`, `type-bool-ore`, `context-bare-label`, `context-bool`, `mixed-prefix`, `shared-identity`, `context-empty` | `declarations::shared_declaration_grammar` | `missing_context` reported as `unknown_key`: `missing-context`; a label refusal reported as another reason: `context-bare-label`, `context-one-segment`, `context-segment-*`, `context-nested-extension`, `context-field-static-label` | +| `every_refusal_names_its_field_and_reason::a_null_is_refused_as_its_key` (`record.rs`), 6 rows, removed; the message check stays as above | `context-null`, `outputs-null`, `target-null`, `type-null`, `context-field-null`, `field-null` | `declarations::shared_declaration_grammar` | `present` reading a null as an absent key: `outputs-null`, `target-null`, `target-options-null`, `type-null`, `null-mode-null` | +| `every_refusal_names_its_field_and_reason::a_missing_or_null_index_payload_is_the_default` (`record.rs`), removed | `match-default-bare`, `match-default-null`, `match-default-empty`, `unit-output-null-eq` | `declarations::shared_declaration_grammar` (normalization) | a non-default option substituted for a missing match payload: `match-default-bare`, `match-default-null` | +| `given_a_plan_value::refuses_a_malformed_plan_before_any_field_is_built` (`record.rs`), 17 rows, removed | `root-null`, `empty-plan`, `field-not-object`, `unknown-key`, `missing-context`, `missing-outputs`, `outputs-empty`, `output-not-string`, `output-unknown`, `output-duplicate`, `passthrough-with-ciphertext`, `passthrough-with-index`, `frame-duplicate-key`, `context-bool`, `context-empty` | `declarations::shared_declaration_grammar` | as the first row; the old rows asserted the error variant alone, the corpus asserts code, reason and field | +| `given_a_plan_value::refuses_a_field_context_that_is_not_a_label` (`record.rs`), 6 of 9 rows removed; the integer, bytes and extended one-segment shapes stay | `context-bare-label`, `context-one-segment`, `context-segment-slash`, `context-segment-digit`, `context-nested-extension` | `declarations::shared_declaration_grammar` | a label refusal reported as another reason: every `context_not_label` case | +| `every_refusal_names_its_field_and_reason::a_source_that_does_not_fit` (`record.rs`), 3 of 9 rows removed; the passthrough, repeated-key and non-object shapes stay | `required-missing`, `late-missing`, `unknown-field`, `sql-missing-with-unknown-field`, `required-fractional-float`, `late-wrong-type` | `runtime_conformance::shared_record_runtime_profile` | a missing field tolerated by every null mode: `required-missing`; the declared type not checked on a required field: `required-null`; `unknown_field` reported as `field_missing`: `unknown-field` | +| `given_a_source_that_does_not_fit_the_plan::encrypt_and_check_source_refuse_it_alike_with_no_key_request` (`record.rs`), 3 of 11 rows and the two matching `encrypt` checks removed | as the row above; the runner also asserts no data key is generated on a refusal | `runtime_conformance::shared_record_runtime_profile` | as the row above | +| `every_refusal_names_its_field_and_reason::a_stored_record_that_does_not_fit` (`record.rs`), 5 of 7 rows removed; the repeated-field row stays (the engine guard is reached natively alone, see the raw-frame contract), and so does the record that is one leaf: the read profile stores every record as a batch, so `row-not-map` reaches the batch-row arm and not the whole-record one | `missing-field`, `field-not-map`, `missing-ciphertext`, `plaintext-under-c`, `context-tenant-no-payload` | `read_conformance::shared_record_read_profile` (`check_record` and `decrypt`, with the retrieval counter) | `outputs_not_map` and `no_ciphertext_node` reported as other reasons: `field-not-map`, `missing-ciphertext`; a missing field tolerated by every null mode: `missing-field`, `late-missing-field`, `context-drop-tenant`; `passthrough` and `no_passthrough_node` reported as other reasons: `plaintext-under-c`, `context-tenant-no-payload` | +| `given_a_field_that_stores_a_null::a_null_in_a_field_with_no_null_mode_is_refused` (`record.rs`), removed | `required-null` | `runtime_conformance::shared_record_runtime_profile` | the declared type not checked on a required field: `required-null` | +| `given_a_field_that_stores_a_null::a_stored_null_is_refused_through_a_plan_that_has_no_null` (`record.rs`), removed | `authenticated-null-as-required` (the refusal), `sealed-null` and `sealed-boundaries` (a value opens through the sealing plan) | `read_conformance::shared_record_read_profile`, `runtime_conformance::shared_record_runtime_profile` | a sealed null accepted by a plan with no null mode: `authenticated-null-as-required` | +| `given_a_field_that_stores_a_null::a_row_with_every_field_left_out_is_an_empty_record` (`record.rs`), removed | `sql-all-absent`, `sql-null` | `runtime_conformance::shared_record_runtime_profile` | an explicit SQL null not left out of the record: `sql-null` | +| `given_a_field_that_stores_a_null::a_stored_record_may_leave_out_only_a_sql_field` (`record.rs`), removed | `sql-absent-as-required`, `sql-absent-as-sealed` | `read_conformance::shared_record_read_profile` | a missing field tolerated by every null mode: `sql-absent-as-required`, `sql-absent-as-sealed` | +| `a_query_the_field_does_not_answer_is_refused_naming_the_field` (`src/dynamic/query.rs`), 10 rows, removed | `eq-on-match-only`, `matches-on-equality-only`, `eq-on-order-only`, `lt-text-for-integer`, `lt-fraction-for-integer`, `between-scalar`, `between-one-bound`, `between-mixed-bounds`, `no-such-field` | `query_refusal_conformance::shared_query_refusal_profile` (`check_query` and `query_term` alike) | `operator_not_answered` reported as `unknown_operator`: `eq-on-match-only`; `not_a_range` reported as `field_type`: `between-scalar`; `no_such_field` reported as `unknown_field`: `no-such-field` | +| `the_typed_paths_query_refusals_are_made_before_any_term` (`query.rs`), 6-row table removed; renamed `folded_equivalents_derive_one_term` for the one-term assertions that stay | `lt-unassigned`, `between-unassigned-high`, `between-unassigned-low`, `matches-too-short`, `matches-unassigned`, `eq-unassigned` | `query_refusal_conformance::shared_query_refusal_profile` | the upper bound of a range not folded before a term: `between-unassigned-high` | +| `block_ore_refuses_text_it_has_no_term_for_before_any_term` (`query.rs`), refusal rows removed; the accepted texts' index assertion stays as `accepted_block_ore_text_derives_a_block_ore_term`, since the corpus records that a case is accepted, not which index answers it | `ore-block-too-long`, `ore-block-trailing-nul`, `ore-block-between-long-high`, `ore-block-between-long-low`, `ore-block-between-nul-low`, `ore-block-between-nul-high` | `query_refusal_conformance::shared_query_refusal_profile` | the length refusal reported as the NUL refusal: `ore-block-too-long` | +| `TestAQueryTheFieldDoesNotAnswerIsRefused` (`languages/golang/encrypt/query_test.go`), 5-row table, the inverted range and the short match text removed; renamed `TestVerifyAndTargetLimitRefuseWhatIsNotAMatchQuery` for the `Verify`/`TargetLimit` refusals that stay | `matches-on-integer`, `lte-on-match-only`, `unknown-operator`, `between-scalar`, `lt-text-for-integer`, `inverted-range`, `matches-too-short` | `TestQueryRefusalConformance` | the host dropping the diagnostic's `reason`: every refusal case; the engine faults above, through the same engine the guest embeds | +| `TestAPlanRefusalNamesItsReason` (`languages/golang/encrypt/guest_test.go`), removed | `output-duplicate` as a frame, on both guests (its host plan in `v1/go-declarations.json` is refused by `Validate` before the engine, so the frame is what observes the engine's reason; `TestCheckerRefusesAnIndexedUntypedField` still reaches the engine through `engineCheck`) | `TestDeclarationConformance` | the host dropping the diagnostic's `reason`: `output-duplicate` and every other refusal case | + +Considered and kept, with the reason: + +- `given_a_stored_record_that_does_not_fit_the_plan::decrypt_and_check_record_refuse_it_before_any_key_is_retrieved`: + eight of its thirteen shapes are read cases, but the five that are not (a + passthrough inside the ciphertext subtree, a passthrough field carrying a + ciphertext, a field, an output and a key given twice) are the engine guards + the transport reaches natively alone, and the test is the module's + load-bearing forged-plaintext check with its retrieval counter. +- `refuses_fields_under_different_contexts_or_extensions` and + `refuses_two_fields_keyed_under_one_identity`: each holds one shared row + beside shapes the corpus has not got (one field extended and one not; two + passthrough fields sharing a label). +- `tests/op.rs` typed refusals (`a_match_query_with_no_tokens_is_refused_before_any_term_or_keyset`, + `a_match_query_is_cut_in_nfc_and_refuses_text_with_no_normal_form`, + `an_inverted_range_is_a_query_like_any_other`): the corpus's `typed` entries + record the typed query's refusal stage, not its batch, case-sensitive + and bound-order assertions. +- Go `TestPlanCheckAnswersWithoutACipher`, `TestQueryTermRefusesWhatTheFieldDoesNotAnswerBeforeState`, + `TestGuestRefusesMalformedInputsBeforeState`, `TestCheckerRefusesAnIndexedUntypedField`: + their rows are shared declaration and refusal cases, but each is about the + uninitialised instance answering `ErrEncoding` before `ErrState`, or the + host rule refusing before the engine, which the corpus runners do not observe. +- Everything in the retained list above: compile-fail, ownership and + zeroization, batching, property, frozen-bytes, generated-code, host + conversion, error wrapping, cancellation, guest lifecycle, PostgreSQL and + live-provider tests. diff --git a/conformance/stack-encrypt/declaration-grammar.md b/conformance/stack-encrypt/declaration-grammar.md new file mode 100644 index 0000000000..5f29065e17 --- /dev/null +++ b/conformance/stack-encrypt/declaration-grammar.md @@ -0,0 +1,307 @@ +# Record declaration grammar + +Use this contract when a binding lowers an SDK declaration to the engine's record +plan. Send the complete plan to the engine checker before executing it. + +For example, this declaration seals and equality-indexes an int64 field: + +```json +{ + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int64" + } +} +``` + +Run the executable cases with `mise run test:conformance`, after building the +deterministic test guest as described in [README.md](README.md). +`ciphertext-untyped`, `index-only`, and every `type-*-eq` case exercise these forms. + +## Scope and authority + +`record-declarations-v1` describes the engine at PR #1404's `b684a217e`, not future +SDK syntax. It is an experimental conformance profile, not a new production wire +version. The input is a Vitamin C **typed transport frame**. JSON below is a +readable projection; it cannot distinguish every integer width or carry bytes. + +The executable authority is `stack_encrypt::dynamic::record::Plan::from_frame_with`, with the +selected target resolver. Native `record::Plan::from_frame` and the Go guest without EQL use +`NoTargets`. The corpus fixes that resolver explicitly as `none`. It checks +target syntax and unavailable-target refusals; it does not certify EQL targets. + +The full contract has three parts: frame validity, the structural grammar below, +and the semantic constraints. A shape-only JSON Schema would not enforce the +context, index, null or resolver rules. SDK tooling must ask the engine instead +of implementing those rules again. Test runners convert fixture values and +observe results; they do not provide another semantic validator. + +## Structural grammar + +This is a typed grammar. `Object{...}` denotes a transport object, `List` a +transport array, `?` an optional member, and `|` an alternative. Literal words +denote text values. Each object has exactly the listed keys, except `Plan`, whose +non-reserved keys are field names. Object key order is unrestricted. + +```text +Plan = Object{ + "context_field"?: Text, + "bind"?: NonEmptyList, + (FieldName: FieldSpec)+ +} +FieldName = Text except "context_field" and "bind" + +FieldSpec = Object{ + "context": FieldContext, + ("outputs": NonEmptyList | "target": Target), + "type"?: ValueKind, + "null"?: "sealed" | "sql" +} + +FieldContext = Label | [FieldContext, ContextScalar] +Label = NonEmptyList +ContextScalar = Text | Bytes | Int32 | Int64 | UInt32 | UInt64 + +UnitOutput = "c" | "passthrough" | "eq" | "ore" | "ope" | "ore_block" +Output = UnitOutput | Object{UnitOutput: Null} + | "match" | Object{"match": Null | MatchOptions} + | "json" | Object{"json": Null | JsonOptions} + +MatchOptions = Object{ + "tokenizer"?: Tokenizer, + "downcase"?: Bool, + "short_words"?: Bool, + "k"?: Integer, + "m"?: Integer +} +Tokenizer = "standard" | Object{"standard": Null} + | Object{"ngram": Integer} + +Target = NonEmptyText | Object{ + "name": NonEmptyText, + "options"?: JsonOptions +} +JsonOptions = Object{ + "sealed_root"?: Bool, + "ordered"?: List +} + +ValueKind = "bool" + | "int8" | "int16" | "int32" | "int64" | "int128" + | "uint8" | "uint16" | "uint32" | "uint64" | "uint128" + | "float32" | "float64" | "decimal" | "date" | "timestamp" + | "string" | "bytes" | "array" | "object" | "uuid" | "json" +``` + +`outputs` and `target` are exclusive and one must be present. Present optional +members must have the declared type: `"type": null` is not omission. +The explicit null alternatives for enum payloads are exceptions, pinned by the +`unit-output-null-*` and `match-default-*` cases. Unknown keys and output/type +names fail; no unknown option is ignored. + +`Integer` here means an integer-valued transport tag accepted by the option's +integer reader, within its bounds. It does not mean a floating-point value that +happens to be integral. Width is not an option's identity. Context integer width, +in contrast, is part of context identity and must survive parsing unchanged. + +Every object key must be unique, including keys nested inside options. The frame +must contain exactly one complete value within the codec's depth and size bounds. +Duplicate keys, truncation and trailing data fail before declaration semantics. +Do not change these codec rules in this specification. + +## Context semantics + +Try the `Label` alternative before decomposing an extension. A flat text list +is a label; `["users", "region", "value"]` has three segments. It is not the +extended context `[["users", "value"], "region"]`. Extensions nest to the left. +An extension is scalar, so `[["users", "value"], ["tenant"]]` is refused. +Bare `"users/value"` is not a field label. + +A plain segment is nonempty and cannot contain `/`, parentheses, control +characters, or the invisible format characters listed by `Label::check_segment` +in `packages/stack-encrypt/src/descriptor.rs`. It cannot start with `b64:`, `-`, +or an ASCII digit. That shared label rule is referenced rather than reimplemented +by a binding. It applies to label segments, not SDK variable names. + +Without `context_field`: + +- Every field label has at least two segments. +- The last segment is the field's identity. All preceding segments form the + plan label, which must agree across fields. +- All fields have the same ordered extension values, including their types. +- Sealed/indexed field identities cannot collide. The field's map key and its + identity may differ; renaming a map key does not implicitly change its label. + +With `context_field`: + +- Its value names a declared field, whose sole output is `passthrough`. +- That field declares `string` or omits `type`; omission resolves to `string`. +- Every field label has exactly one segment: its identity. +- Extensions still agree across fields. No target field is admitted. +- At execution, each record supplies the named field's label value. Its validity + and the opener's expected-context constraint are runtime requirements. + +With `bind`: + +- Its value is a nonempty list of scalar parts, each nonempty. An empty part + is refused (`empty_binding`), and so is an explicit empty list. A grouped + part, a list inside the list, is refused (`bind`). +- Every field's stored context is its label, extended, then the parts in + order. No query context includes them, so a query on the plan is refused + (`bind_in_query`). A target field is bound as any other field is: its + EQL value stores the label's column, and not the parts. +- The key is reserved, like `context_field`: a field named `bind` is refused + (`bind`). + +The grammar does not add call-time context roles or defaults. Context composition +is observed by `extended-context`, `flat-label-is-not-extension`, the +`typed-extension-*` cases, and the mixed-context refusals. + +## Output and kind semantics + +An output list is nonempty. Output keys are unique after reading their options: +two differently configured match indexes still collide on `match`. +`passthrough` is always the sole output. Ciphertext is explicit; an index-only +declaration does not implicitly acquire `c`. + +Every field with a scalar index declares `type`. Ciphertext-only and passthrough +fields may omit it. Declaring a kind checks values during execution; it does not +select a different leaf encoding. + +| Declared kind | `eq` | `match` | `ore`, `ope`, `ore_block` | +|---|---|---|---| +| bool | Refused | Refused | Refused | +| int8, uint8 | Admitted | Refused | Refused | +| Other integer widths | Admitted | Refused | Admitted | +| float32, float64, decimal, date, timestamp | Admitted | Refused | Admitted | +| string | Admitted | Admitted | Admitted | +| bytes | Admitted | Refused | Refused | +| uuid | Admitted | Refused | Refused | +| array, object, json | Refused | Refused | Refused | + +An index is admitted only over a kind one of its operators answers. Bytes +and UUIDs have no order term: no ordering operator compares them, so a term +would be stored and never queried. The order indexes are refused on bytes +and UUIDs as `index_not_admitted`. + +The corpus explicitly tests all 22 kinds against all five scalar indexes. +`array` and `object` may still be sealed without indexes. A `json` field requires +a document target. A raw `json` output has a recognized syntax but is refused as +`json_index_pending`; it is not an alternative to a document target. + +Match defaults are 3-grams, `downcase: true`, `short_words: false`, `k: 3`, and +`m: 256`. Every missing option takes its default. The bounds are: + +- `3 <= k <= 16`. +- `m` is a power of two from 32 through 65536. +- N-gram length is nonzero and representable by the implementation's integer reader. +- `short_words: true` requires n-grams of length at least three. + +Standard tokenization cannot enable short words. An invalid option fails when +the declaration is checked, before values or keys are needed. + +## Null semantics + +Omitting `null` keeps the field required. A typed field then refuses null values; +an untyped value's ability to represent null is not an implicit nullable column. +`null` is a storage policy, distinct from a null option payload or a missing key. + +| Policy | Declaration requirements | Runtime meaning | +|---|---|---| +| `sql` | Any non-passthrough field | Missing/null source leaves no encrypted field output; the host stores SQL NULL | +| `sealed` | A fixed-width bool, number, decimal, date, timestamp or UUID; only equality indexes, if any | Missing/null source is sealed with type-appropriate padding; equality uses the field's null term | + +Text, bytes and composite kinds cannot request sealed null. Passthrough cannot +request either policy. These cases check declaration admissibility only; runtime +padding, queries, missing values and round trips retain their existing tests. + +## Targets and JSON options + +Target syntax is parsed before resolver lookup. `options` takes JSON-index +options; a null options object or unknown option is an invalid target. +`sealed_root` defaults to true, and `ordered` to an empty set. +Paths are parsed by `JsonPath::parse`; ordered paths cannot select array positions. +Repeated equivalent paths collapse into the set. + +Under this profile's `none` resolver, every otherwise valid target produces +`stack_encrypt::target_none` with its target name. A missing target capability +must never silently turn into a ciphertext-only field. + +For a resolver that supplies EQL types, additional existing rules apply: the +target must be producible, its column label has exactly two segments, and the +plan has no context field. Extensions and `bind` parts come after a target +field's label, as they do for any other field; the EQL value stores the +label's column alone. An explicit kind matches the +target's plaintext kind; otherwise that kind is inferred. Only a document target +accepts JSON options. Sealed-null rules include the target's own indexes. +Those resolver-dependent outcomes and normalization need an EQL profile; this +corpus does not claim they have been verified across bindings. + +## Normalization observations + +The native runner observes the parsed plan directly. Its `normalized` fixture +field is a test report, not a canonical production serialization: + +- `label` and `context_field` identify the resolved context source. +- `extension` lists typed scalar parts, preserving width and order. +- `fields` retains transport field order, label segments, resolved kind, + null policy and output order. +- Unit output aliases become bare keys. Default match options become `"match"`. + Non-default match options are explicit; `short_words` is emitted only when true. + +No binding should sort production fields, flatten contexts, coerce context +integers, or infer omitted ciphertext outputs from these observations. +`frame-field-order` checks field order independently of the JSON projection. + +The Go plan-check export returns success or a diagnostic, not a normalized plan. +Its runner therefore verifies acceptance and diagnostics. It does not claim an +independent observation of normalization or add a production export for testing. + +## Diagnostics and corpus format + +The corpus is `v1/record-declarations-v1.cases.json`. Its version, profile and resolver are +required. Case IDs are unique and stable. Every case contains exactly one input: + +- `{"json": value}` converts JSON objects in lexical key order. Nonnegative + integer tokens become uint64; tokens beginning with `-` (including `-0`) + become int64. Decimal/exponent tokens become finite float64. Integer tokens + outside the corresponding 64-bit range and non-finite floats are invalid + corpus inputs; runners must refuse them without rounding. + Arrays preserve order. This is fixture conversion, not SDK policy. +- `{"frame_hex": text}` supplies exact transport bytes, including typed contexts, + original field order and malformed frames that JSON cannot represent. + +`accepted` is mandatory. Refused cases require `expected_error`, containing the +native engine diagnostic code and structured payload. Accepted cases may include +`normalized`. Runners reject unknown corpus keys and contradictory outcomes. + +A malformed transport frame also has `boundary_error`. The native parser reports +`stack_encrypt::dynamic_plan` with `not_a_frame`; the WASI frame check reports +`stack_guest_abi::malformed_input` before reaching that parser. Both runners verify +the frame really is malformed. Valid-frame declaration errors must agree exactly +on code and payload; Go also requires `ErrEncoding`. Error prose is not contractual. + +Cases isolate a failure where practical. This profile does not define universal +error precedence for declarations containing several independent faults. +Neither runner initializes a cipher to check declarations. The Go checker has +no credentials and uses a refusing transport. + +## Evidence and limits + +The corpus covers accepted and refused cases, including the complete +scalar kind/index matrix. The native runner also checks selected normalization +observations. Existing codec tests own exhaustive frame validity, depth limits, +and integer-reader behavior. Existing EQL tests own resolver/catalog behavior. +Runtime operations and language-specific declarations remain separate layers. + +See [coverage.md](coverage.md) for the consolidation policy. New Python and +TypeScript runners can adopt these inputs and expectations without copying the +engine's validation rules. + +The Go runner checks both the release and deterministic guests. Go-specific +`v1/record-declarations-v1.inputs.go.json` supplies explicit `record.Plan` inputs for the subset +representable by that host model, keyed by the shared case ID. Those cases also +run through production `Checker.Check` (Validate, Wire and the engine), with the +same acceptance outcome. Raw malformed frames and shapes the Go plan cannot +express remain engine-boundary checks. diff --git a/conformance/stack-encrypt/eql-json-contract.md b/conformance/stack-encrypt/eql-json-contract.md new file mode 100644 index 0000000000..ed25f0e23b --- /dev/null +++ b/conformance/stack-encrypt/eql-json-contract.md @@ -0,0 +1,136 @@ +# EQL and JSON operation profiles + +These experimental profiles enroll the existing EQL v4 JSON tree operations. +They do not describe EQL v3 SteVec, or certify an entire SDK. The +[enrollment index](v1/eql-json-v1.enrollment.json) names mandatory compiled tests; +[shared cases](v1/eql-json-v1.cases.json) supply document text and predicate refusals to +native Rust and Go. Python and TypeScript have no enrolled runner yet. + +## Requirements and evidence + +| Requirement | Contract | Existing evidence retained | +|---|---|---| +| `eql-resolver-catalog-v1` | The resolver names catalog domains, their producibility and operators. Unknown names, unavailable EQL builds and unsupported capabilities are refused. JSON options require a JSON target. | Native `targets` and `json_tree_data_plan`; Go catalog and plain-guest refusal tests | +| `json-write-v1` | JSON documents, including scalar roots, empty containers, JSON null and integer boundaries, round-trip as values. SQL null stores no document. Invalid text is refused without exposing it; native tests observe no key request. Typed and dynamic plans agree on search terms and can open each other's output. | Native typed/data-plan suites, Go raw and generated typed document APIs; existing seeded derivation fixture | +| `json-query-v1` | Containment, reverse containment, equality at a path, ordered bounds, selectors and child operations derive their documented operand shapes. Unsupported requests fail. | Native engine/EQL operand comparisons, Go generated queries, independent PostgreSQL `jsonb` containment oracles | +| `json-request-bound-reads-v1` | Extraction and subtree/wildcard reads open against the prepared path, column, position and bounds. Wrong requests and detectable tampering fail. | Native adversarial read suite, EQL request/open tests, Go selector reads, PostgreSQL extraction/subtree and hostile-row suites | +| `json-extraction-v1` | Single-node extraction opens the requested scalar. | Native scalar extraction, Go selectors and PostgreSQL plaintext extraction oracle | +| `json-subtree-v1` | Complete bounded subtrees and wildcard reads match plaintext queries. | Native/EQL prepared reads and Go/PostgreSQL read paths | +| `json-child-v1` | Your app opens one entry that `json_tree_children` returned, checked against the parent path that prepared the read. The check covers the entry's selector, depth, parent tag, and self tag: the one its decrypted key or index gives under the parent's token. The entry opens to its value and its authenticated key or index. The check refuses another node's child, an entry at another depth, a top-level field under a sealed root, and a parent path with a wildcard. A child with members does not open alone. | Native child reads and data-path reads, EQL typed child open, Go raw and generated `Children` (with and without a binding), PostgreSQL `json_tree_children` oracle | +| `json-tamper-v1` | Detectable mixed-document, truncated-chain and substituted-column answers are refused. | Native and PostgreSQL adversarial suites; Go observes wrong-column rejection | +| `json-element-match-v1` | Every condition must hold on one element. Ordering paths and resolver capability are required; a probe beyond the declared bound raises rather than silently truncating. | Native operator/capability tests, Go generated member APIs, SQL domain and independent plaintext predicate tests | +| `json-predicate-match-v1` | Supported text compiles to existing operators; refusals preserve reason, construct and byte offset, with no caller text in diagnostics. Missing and null paths obey the documented truth rules. | Shared negative corpus, native compiler/property tests, Go generated `Match`, SQL `jsonb_path_match` and handwritten-operator oracles | + +The index is an evidence inventory, not a second copy of every existing test. +Native execution retains whole binaries, including their unindexed properties +and regressions. Go selects the exact enrolled tests and rejects missing passes, +failures and skips, including skipped subtests. Native inventory checks reject +missing names, filtered tests and a wrong `#[ignore]` state before execution. +Only the PostgreSQL lane executes the database tests marked `#[ignore]`. + +## Predicate grammar + +The current grammar in `packages/stack-encrypt/src/dynamic/json_query.rs` and +`json_predicate.rs` is the executable specification. This profile pins: + +```text +predicate := comparison | exists(path) | exists(path ? (filter)) + | (predicate) | !(predicate) + | predicate && predicate | predicate || predicate +comparison := path op value | value op path +op := == | != | <> | < | <= | > | >= +path := $ followed by .key, ."quoted key", or [*] steps +value := JSON scalar literal | $variable | $"quoted variable" +filter := comparison on @ or @.member, optionally joined with && +``` + +Negation binds before `&&`, which binds before `||`. Variables are a JSON +object; absence of `vars` means an empty object. Scalar literals are strings, +numbers, booleans and null; objects/arrays cannot be comparison values. +Orderings and multi-condition element filters require numbers or strings and +configured ordered paths. A filter requires a wildcard in its outer path; +its member cannot contain a wildcard. Predicate nesting is limited to 32. +A wildcard bound must be positive; its probe prevents an undersized bound from +silently producing a partial answer. + +Arithmetic, regex, `starts with`, `is unknown`, mode words, methods, `.*`, `.**`, +slices, `last`, path-to-path/value-to-value comparisons, array positions, +filters outside `exists`, and `||`, `!`, `!=` or nested `exists` inside filters +are unsupported. `!=` at a wildcard is refused. The corpus pins representative +syntax, unsupported-construct, variable, type, depth and path diagnostics. +Existing parser tests retain the wider grammar matrix and adapter-specific +invalid-input checks; the shared corpus is not an exhaustive grammar fuzzer. +Offsets are UTF-8 byte offsets, not character indices. Each refusal also names +`at_text`, the suffix beginning at that offset. Omitted `vars` exercises absent +variables rather than an explicit empty object. + +## Nulls, oracles and intentional differences + +SQL null (no encrypted document), JSON null (a document/node), and an absent +path are distinct. The SQL predicate suites compare both selected rows and +three-valued answers. An absent path does not satisfy a comparison. Ordering a +JSON null can produce SQL unknown where plaintext jsonpath returns false; +the compiled predicate adds the null test under negation where it affects +selected rows. This exception is checked explicitly, not normalized away. + +The independent oracles use PostgreSQL `jsonb @>`, `<@`, `jsonb_path_query` and +`jsonb_path_match`, alongside handcrafted plaintext conditions. They do not +calculate expected results from encrypted operands. Their supported-domain +assumptions and exceptions remain explicit: + +- Paths are literal. There is no lax implicit array unwrapping or scalar-to-array + wrapping. Use `[*]` and keep array shapes consistent. +- Keep one scalar kind at an ordered path. Terms do not preserve the plaintext + type distinctions used by jsonpath's cross-kind comparisons. +- Order terms fold text case/accents and compare numbers as float64. Equality in + a multi-condition element filter uses those terms; standalone `==` is exact. +- Reverse containment excludes the plaintext root-scalar-in-root-array special + case; the generated oracle logs how many such comparisons it excludes. +- Storage and projection list order is randomized. Compare projections as sets + and stored selector collections as multisets. The existing deterministic + `packages/stack-encrypt/tests/fixtures/json_tree_vectors.json` pins a seeded + permutation, tags and tokens, not a production ordering promise. Fresh + ciphertext bytes are not equality fixtures. +- Read authentication detects substituted paths, wrong columns, mixed-document + subtrees, forged tags and incomplete returned chains. It does not establish + database completeness or row identity: withholding a whole answer can look + like no node, and another row's node at the same path can open. Those limits + have named native evidence in the index. + +## Required execution and identity + +From the repository root: + +```sh +mise run wasm:guest:build +mise run wasm:guest:build:deterministic +mise run wasm:guest:build:eql +mise run wasm:guest:build:eql:deterministic +mise run test:conformance:eql + +# A disposable database: this command installs/replaces EQL v4 there. +EQL_TEST_DATABASE_URL='host=localhost port=5432 user=postgres password=postgres dbname=postgres' \ + mise run test:conformance:eql:postgres +``` + +No CipherStash credentials are required. Both lanes are required in +`tests-golang.yml` (the PostgreSQL lane is called by `go:test:postgres`); conformance changes trigger them. The database lane rebuilds +SQL from this tree, installs exactly the bundle whose SHA-256 it records, and +passes the same connection to both languages. It fails without a database or +required guests. Required mode deliberately applies to every Go test using +`deterministicEQLClient`, including tests outside the enrollment index. A fast-lane pass alone is not SQL conformance. + +Reports include the native engine and EQL binding package versions, root/EQL +lockfile hashes, corpus/enrollment hashes, deterministic guest hashes, executed +requirement test names, and (for PostgreSQL) the installed EQL version and schema name, the expected schema name, PostgreSQL version and actual SQL bundle hash. Development bundles can +report `DEV`; their hash distinguishes them. CI uploads reports and fails if +none were produced. Locally set `STACK_CONFORMANCE_REPORT_DIR` to retain them; +the same report is always printed after success. These describe this checkout +and its guest artifacts, not a claim of compatibility across released versions. + +Required checks reject all fixture-update environment variables. Extending a +language binding means running the applicable shared cases and providing its +own adapter evidence for each claimed requirement. The scalar EQL v4 rows are +exchanged fresh in both directions by the [exchange profile](exchange-contract.md); +fresh JSON document exchange, a release compatibility matrix, and +Python/TypeScript runners remain separate work. diff --git a/conformance/stack-encrypt/exchange-contract.md b/conformance/stack-encrypt/exchange-contract.md new file mode 100644 index 0000000000..bb714c189a --- /dev/null +++ b/conformance/stack-encrypt/exchange-contract.md @@ -0,0 +1,168 @@ +# Fresh artifact exchange + +`artifact-exchange-v1` is the profile under which one runner writes +artifacts and another opens them, in the same run, with nothing frozen in +between. The scalar profile proved fresh Go-to-Rust opening for one field. +This profile widens that to every value kind at its edges, structural +records with index terms, whole-value opaque blobs and EQL rows, in both +directions between the runners that exist: native Rust and Go over WASI. +Python and TypeScript have no runner; the report lists them as not +enrolled, and their absence is a gap, not a pass. + +The corpus is [`v1/artifact-exchange-v1.cases.json`](v1/artifact-exchange-v1.cases.json). The runners are +`packages/stack-encrypt/tests/exchange_conformance.rs` +(`fresh_artifact_exchange`) and +`languages/golang/encrypt/exchange_conformance_test.go` +(`TestArtifactExchange`) for values, records and blobs; and for EQL rows, +`rows_rust_seals_open_in_the_go_sdk` and `rows_the_go_sdk_sealed_open_in_rust` +in `packages/eql/tests/encryption/tests/v4_types.rs` with +`TestV4RowsMatchTheCommittedFixture` and `TestV4RowsTheRustSuiteSealedOpenInGo` +in `languages/golang/encrypt/eql_v4_test.go`. The task that drives them is +`scripts/stack-exchange-conformance.mjs`: + +```sh +mise run wasm:guest:build:deterministic +mise run wasm:guest:build:eql:deterministic +mise run test:conformance:exchange +``` + +## What is exchanged + +| Kind | Producer writes | Consumer checks | +|---|---|---| +| `values` | One record per positive case of `v1/record-values-v1.cases.json` (the value-boundary corpus), under the plan that case declares, with context `["conformance", "exchange"]`: the sealed leaf and every declared index term; nothing for a SQL null | The record opens to the case's typed input. Every stored term equals the term the consumer's own query of the same value derives (`eq` for equality, `lt` for an order index), and the `equal_query` spelling derives the same equality term. | +| `record` | The rows of the corpus's one record: a passthrough `int64` id (held on the host by Go, lowered as a `passthrough` output by Rust), text, `uint32`, decimal, date and timestamp fields with equality and order terms, a SQL-null text field and a sealed-null `float32` field, under context `["conformance", "exchange", "people"]` | The passthrough carried equals the corpus input; every sealed field opens to its input, a sealed null opens as null and a SQL null is absent from storage and opens as null; every stored term equals the consumer's derived query term | +| `blobs` | A whole struct (`name`, `age`, `tags`, optional `nickname`) as one opaque ciphertext under `["conformance", "exchange", "blob"]`, field `value`. Rust writes it through `OpaqueBlob`. Go writes it through the generated opaque path, as a blob in the storage profile, sealed as the one `bytes` field | The ciphertext opens and decodes to the corpus value through the other SDK's opaque reader (`OpaqueBlob` or `gensupport.Opaque`). A nil Go slice and an empty Rust `Vec` are one value; Rust's `Some` marker and Go's bare pointer are one value | +| `eql-rows` | The EQL v4 `profiles` rows: every column of the committed fixture's plaintexts sealed afresh, Rust through eql-bindings' typed targets, Go through its generated code | Each column opens to the plaintext through the other side's typed target, and each equality column's stored `hm` equals the term the consumer's own equality query derives for that plaintext (the generated `*Eq` query in Go, the typed `*EqQuery` target in Rust) | + +Each kind runs Go to Rust and Rust to Go. Ciphertext bytes are never +compared: encryption is randomized, and agreement is shown by opening and +by deriving the same query terms. + +## Artifact and manifest format + +A producer writes one JSON file: + +```text +{ "version": 1, "profile": "artifact-exchange-v1", + "producer": { "language", "sdk", "sdk_version", "backend", + "engine": { "name", "version", "guest_sha256" }, + "key_source": { "kind": "deterministic", "seed" }, + "profiles": [..], "capabilities": [..], "toolchain" }, + "values": { : { "c": , "terms": { : } } }, + "record": { : { "passthrough": { : {type, text} }, + "fields": { : { "c", "terms" } } } }, + "blobs": { : } } +``` + +`producer` records the SDK (`stack-encrypt` and its crate version; the Go +module path and its build version), the engine (the crate version natively; +the SHA-256 of the deterministic guest the Go runner loaded), the backend +(`native` or `wasi`), the key source (the deterministic test provider and +the corpus seed; no live credentials exist here), the profiles the +artifacts claim and the capabilities they exercise. Both consumers refuse a +file of another version or profile, another language's own output, another +seed, or a capability list that differs from the corpus, and require every +artifact set to hold exactly the corpus's cases. Unknown fields are refused +in both languages. + +EQL rows travel in the shape of the committed `v4_rows.json` fixture (seed, +table, rows of plaintext and stored envelopes) with a `producer` object the +committed fixtures do not carry: `language`, `sdk` and `sdk_version` +(`eql-bindings` and its version; the Go module path and its build version), +`backend`, `engine` (the stack-encrypt version natively; the SHA-256 of the +deterministic EQL guest under WASI) and `schema` (`eql_v4`). Each EQL +consumer refuses rows without it or written by its own language, and the +task requires it before any consumer runs. + +## Required execution + +`mise run test:conformance:exchange` (the `scripts/stack-exchange-conformance.mjs` +script, also run at the end of `test:conformance`) refuses every +fixture-update variable, `EQL_UPDATE_FIXTURES` included (the Go EQL producer +rewrites its committed rows under it), requires both deterministic guests to be present +and nonempty, requires the `go` and Rust toolchains, and only then creates a +fresh temporary directory. It runs each producer with its output variable +set (`STACK_EXCHANGE_OUTPUT`, `EQL_V4_RUST_ROWS_OUT`, `EQL_V4_ROWS_OUT`), +checks every output is nonempty and of the right shape and producer, and +runs each consumer with its input variable set (`STACK_EXCHANGE_INPUT`, +`EQL_V4_RUST_ROWS`, `EQL_V4_ROWS`). Producer caches are bypassed: nextest +reruns its binaries, Go runs with `-count=1`, and the fresh directory is +new every run: a passing run removes it once the report is written, and a +failing one, a failure while reading the lockfiles or writing the report +included, keeps it and prints its path. A missing runner, a missing or empty guest, an empty fresh +output, a skipped or failed test, or a consumer refusal fails the task. +`STACK_CONFORMANCE_REQUIRED=1` is set throughout, so a Go test that would +skip on a missing guest fails instead. + +Without the variables, each runner still produces and opens its own +artifacts in memory, so the ordinary Rust and Go suites exercise the same +code; only the task proves the cross-language half. The Go EQL consumer +skips without its input variable, and the task treats a skip as a failure. + +CI runs the task in `tests-golang.yml` (`wasi-check`), after both +deterministic guests are built, and uploads the report as +`exchange-conformance`. The earlier scalar exchange step and the EQL rows +step remain. + +## Report + +The task prints and, under `STACK_CONFORMANCE_REPORT_DIR`, writes +`exchange.json`: the corpus, value-corpus and EQL fixture hashes; the +commit; the Go and Rust toolchains; the engine versions each path resolves +(`stack-encrypt`, `vitaminc-aead` and `recipher-frame` from the root, +guest and EQL lockfiles, and `eql-bindings`); the storage versions the EQL +rows were derived under (the `eql_v4` schema, the `@cipherstash/eql` +package and `eql-bindings` crate versions); the lockfile and guest hashes; +each producer's manifest; one row per exchanged kind and direction with +the artifact count and what the consumer compared; the languages not +enrolled; and a `released_versions` section. + +## SQL lane + +The exchanged EQL rows are opened and query-compared in the fast lane. The +PostgreSQL oracle for EQL rows is the `eql-postgres` job of +`tests-golang.yml` (`go:test:postgres`), where the Go SDK stores fresh rows +in `eql_v4` columns and the EQL encryption suite's ignored tests insert +the Go-sealed fixture rows and query them; its report records the installed +bundle and PostgreSQL version. Storing Rust-sealed rows through the Go SDK +into PostgreSQL in the same run is not wired yet. + +## Released-version combinations + +Only this checkout has exchanged with itself. The API plan +(`docs/plans/2026-10-24-stack-encrypt-api-plan.md`, "The stored format +stays compatible with Go rc.3") already fixes one combination: data that Go +`v0.1.0-rc.3` wrote (the tag `languages/golang/v0.1.0-rc.3`, with the +`eql-v4-install.sql` bundle attached to that release) must stay readable and +searchable by the current Rust and Go. The report names it as required and +not yet run. The other released-version combinations follow the EQL v4 and +Stack Encrypt compatibility policy, which is not written yet: + +```text +released_versions: { status: "rc.3 required, not yet run", + required: [ { producer: {sdk: "go", version: "languages/golang/v0.1.0-rc.3"}, + consumer: {sdk: "rust and go", version: "this checkout"}, + storage: {eql_bundle: "eql-v4-install.sql of languages/golang/v0.1.0-rc.3", + schema: "eql_v4"}, + result: "opens" } ], + row_shape: { producer: {sdk, version}, consumer: {sdk, version}, + storage: {eql_bundle, schema: "eql_v4"}, + kinds: ["values", "record", "blobs", "eql-rows"], + result: "opens | refused ()" }, + rows: [] } +``` + +`rows` holds results that a run produced. The rc.3 row joins it when a lane +runs the released Go module against this checkout; no result is written +before then. + +## Scope and remaining work + +Match terms, JSON documents, EQL types outside the `profiles` fixture, +context-field records and caller-supplied scopes are not exchanged here; +the earlier profiles cover them within one language or against frozen +vectors. Python and TypeScript runners, their backends, and a SQL lane that +stores one language's fresh rows through the other are open. No frozen +fixture or artifact changes: everything this profile writes lives in a +temporary directory for the length of one run. diff --git a/conformance/stack-encrypt/fixture-contract.md b/conformance/stack-encrypt/fixture-contract.md new file mode 100644 index 0000000000..a64ad9fbbf --- /dev/null +++ b/conformance/stack-encrypt/fixture-contract.md @@ -0,0 +1,127 @@ +# Enrolled fixture profiles + +`record-value-kinds-v1`, `record-query-operators-v1` and +`record-context-fields-v1` enroll the existing +Rust/Go fixtures in the conformance contract. They are experimental profiles +of the cases those fixtures contain, not exhaustive type/operator certification. +They use the plain record resolver (`NoTargets`), with public deterministic +keys and no database or live credentials. + +The fixtures remain at their existing paths: + +- [`value_kinds.json`](../../packages/stack-encrypt/tests/fixtures/value_kinds.json) +- [`query_operators.json`](../../packages/stack-encrypt/tests/fixtures/query_operators.json) + +Their [existing schema documentation](../../packages/stack-encrypt/tests/fixtures/README.md) +continues to own the formats. No expected frames, ciphertexts, terms, verified +pages or fetch limits are copied into this directory. + +[`v1/fixture-enrollment.json`](v1/fixture-enrollment.json) maps stable requirement IDs +to the existing Rust test functions and Go tests that provide their evidence. +It is an enrollment index, not another input corpus or a runtime capability +negotiation format. The CI wiring test checks fixture paths, source declarations, +requirement documentation and exact command selection. Rust also checks each +binary’s compiled test inventory and rejects missing or ignored enrolled tests. +The Go missing-guest regression checks each indexed test’s actual failure/skip +outcome, so a test excluded from compilation cannot silently pass enrollment. +Both language implementations are mandatory for these profiles; Python and TypeScript remain pending. + +## Value-kind requirements + +The fixture represents int8, int16, uint8, uint16, int128, uint128, date, +timestamp and decimal values. It includes the signed 128-bit minimum and +unsigned 128-bit maximum. These are representative cases, not every boundary +of every type. Values use the fixture's `type` and `text` with a frozen `frame`; +128-bit integers must never pass through a floating-point JSON number. + +| Requirement ID | Required observation | Fixture evidence | +|---|---|---| +| `values.typed-frames` | The actual host value encodes to the exact frozen typed frame, preserving integer width, decimal scale and timestamp nanoseconds. | Every `values` entry | +| `values.frozen-open` | The committed Rust record opens to those values and types, retaining decimal scale and timestamp precision. | `record` and `values` | +| `values.stored-terms` | Fresh records round-trip and store the frozen equality/order terms. Queries for their values derive the corresponding stored terms. Randomized ciphertext bytes are not compared. | Every non-`c` output in `record`, under `plan` | +| `values.normalized-queries` | Decimal queries differing only in trailing zeros and timestamp queries truncated to microseconds derive the stored equality and order terms, while the opened values retain their original precision. | Every `queries` entry and its field's order output | + +Rust additionally compares dynamic execution with typed term derivation and +retains its test of a write of another width: an exact one seals as the +field's width, and one out of range is refused. Go runs the real generated +`testusers.ValueKinds` encrypt/decrypt and field-query methods, including its +field-context substitution refusal. These assertions stay in their owning +tests. The separate Go invalid-date/decimal/timestamp tests remain in the full +Go suite; they are not claimed as shared fixture requirements here. + +## Query-operator requirements + +The fixture covers equality on text and uint32, scalar/range ordering on uint32 +and float64, and probabilistic text matching. Its operators are `eq`, `lt`, +`lte`, `gt`, `gte`, `between` and `matches`, in the combinations declared by +the fixture. It does not claim every operator for every kind or index. + +| Requirement ID | Required observation | Fixture evidence | +|---|---|---| +| `queries.term-contract` | Derive the frozen operand bytes and metadata: operator, fidelity, index, domain, and scalar versus ordered low/high range shape. | Every `queries` entry | +| `queries.match-verification` | Verify the complete page in input order, including matches, nonmatches and null; results agree with the frozen boolean vector. | `verify` | +| `queries.fetch-limits` | Given the frozen match term, requested count and statistics, return the recorded bounded row count or explicit unbounded result. | Every `target_limit` entry | + +Rust compares the dynamic path with typed queries from field references, `MatchQuery::verify` +and typed fetch sizing, and checks that the fixture contains both verification +outcomes and both bounded/unbounded limits. Go exercises the record interface +and generated query methods. Generated string-page verification omits null, +which the record-interface test covers. Its existing SQL parameter conversion, +empty-page, zero-query, inverted-range and floating-point ordering assertions +remain in those selected tests. Wider operator refusal and secret-diagnostic +tests remain in the full suites; this slice does not turn them into shared +negative cases. In Go, `TestVerifyAndTargetLimitRefuseWhatIsNotAMatchQuery` and +`TestAMatchesQueryNeverPrintsItsText` share the fixture client, so they also +fail on a missing guest in required mode. They remain outside the aggregate +selection and the shared requirements; the missing-guest regression covers them. + +## Running and maintaining the profiles + +`mise run test:conformance` selects the existing `value_kinds` and +`query_operators` Rust binaries and the Go tests listed in the enrollment index, +alongside the earlier profiles. The Go selection is generated from the index; +adding an enrolled Go test does not require editing a shell regular expression. +Fixture assertions stay in their owning tests; the separate missing-guest probes +stop at client creation. The ordinary Rust and Go +CI suites already run these tests, so enrollment adds no duplicate CI suite. + +When `STACK_CONFORMANCE_REQUIRED=1`, a missing deterministic guest fails the +enrolled Go tests instead of skipping them. The aggregate command rejects both +`STACK_CONFORMANCE_UPDATE` and `STACK_ENCRYPT_UPDATE_FIXTURES`, even when set to +an empty value. All four Rust fixture writers, including the two record-lowering +writers, +independently reject updates in required mode. A subprocess regression exercises +the guard with absent, empty and nonempty update flags without writing fixtures. +Deliberate fixture maintenance remains available outside +required mode through the existing documented regeneration commands. + +Review fixture regeneration explicitly. A requirement ID follows the +[evolution rule for case IDs](README.md#artifacts-and-evolution). It may +change in place only while every reader is in this repository. The pull +request that changes it updates every reader and lists the change. The enrollment +index's `version` is its metadata format, not a production storage version. + +This slice consolidates the coverage inventory and execution selection, not +the underlying test assertions. No test or frozen artifact is removed. These +wider fixtures prove frozen Rust-to-Go opening, local round trips and term +agreement; fresh opening of every kind in both directions is the +[exchange profile](exchange-contract.md), over the value-boundary corpus. + +Python and TypeScript should consume these same fixture paths and implement +the listed observations through their own host values and public APIs. Their +integer/decimal/time mappings and actual backends must be specified by those +implementations. EQL domains and JSON operations, all-type boundary matrices +and shared query refusals have their own profiles; supported-release matrices +wait on the compatibility policy. + +## Context-field requirements + +`record-context-fields-v1` enrolls the context-field section of the existing +`record_lowering.json` fixture. Its format and seed remain owned by that fixture. +The [context contract](context-contract.md) adds composition and boundary cases +without copying these existing vectors. + +| Requirement ID | Required observation | Fixture evidence | +|---|---|---| +| `contexts.frozen-open` | Typed and lowered Rust records open through the opposite path and generated Go methods, under their stored context. | `context_field.records` | +| `contexts.expectations` | An expectation checks the stored context; a mismatch refuses it. Generated Go queries name the base context, and tampering does not open. | Fresh records and `context_field` plan | diff --git a/conformance/stack-encrypt/lifecycle-contract.md b/conformance/stack-encrypt/lifecycle-contract.md new file mode 100644 index 0000000000..e74af5ce5c --- /dev/null +++ b/conformance/stack-encrypt/lifecycle-contract.md @@ -0,0 +1,138 @@ +# Lifecycle, cleanup and key-I/O conformance + +`lifecycle-v1` enrolls observable native Rust and Go WASI behavior. The +[index](v1/lifecycle-v1.enrollment.json) names existing compiled tests and focused +new lifetime probes. These are backend-specific observations, not another +semantic value corpus and not a promise to erase every plaintext copy in a +process. Python and TypeScript are explicitly not enrolled. + +## Required evidence + +| Requirement | Native evidence | Go evidence and limits | +|---|---|---| +| `lifecycle-ownership-v1` | Actual record operations and owned `Vec` to `Vec` conversions release fulfilment captures exactly once on success, provider failure and unpolled drop; an unpolled encrypt or decrypt makes no key request. Zipped fulfilments do not share key material. An owned `OpaqueBlob` source is wiped before its pending is returned, on success and on an encoding refusal. A decrypted `OpaqueBlob` is wiped once on drop, and the `Zeroizing` its `into_inner` returns is wiped once when it is dropped, not before. | Client keys are consumed/redacted; explicit close and unreachable-client cleanup release guest memory; calls on a closed client fail. GC cleanup is eventual, so callers should close explicitly. | +| `lifecycle-cancellation-v1` | Dropping an encrypt future paused in key generation, or a decrypt future paused in key retrieval, drops the provider future and operation captures, for a record operation or an owned collection; subsequent work on the cipher succeeds. Guest ABI abort spends the handle and drops the operation. | Cancellation before a call sends no request; cancellation between steps or during token fetch leaves unrelated operations usable. A guest step that overruns cancellation closes the client. Discarded late output is wiped. | +| `lifecycle-partial-output-v1` | A batch with a valid first row and a later authenticated type mismatch releases its decoded prefix without marked heap residue. Tests check this for the dynamic record path and for the owned `Vec` to `Vec` conversion. For owned collections, drop witnesses are test values that record whether they were wiped. They show that the prefix is wiped, not leaked, after a late failure or an element's panic. The same holds for a column that is a field of a record. For an owned record, a drop witness shows that a field opened before a later field is refused is wiped. Existing context cases reject late authentication failures without returning partial output. An `OpaqueBlob` refused before its first field is built leaves no marked residue. One refused after some fields are built leaves none either, for a derived struct serde reads in place: the blob is read into a `T::default()` that the refusal wipes. The heap observer checks this for the fields of a struct, the fields of a struct nested in it, and the elements of a sequence stored before the refusal (up to the 1 MiB of elements serde reserves before reading a sequence). A drop witness shows that a field read before a missing field is wiped once. A refusal inside a value serde builds whole is the `native-partial-decode-inside-whole-values` limit below. | Generated and raw batch APIs return no partial rows on failure; interrupted HTTP bodies fail; cancelled output is wiped. SDK conversion diagnostics contain no decrypted values. This does not assert erasure of partially populated caller-owned Go objects. | +| `lifecycle-buffer-cleanup-v1` | The existing allocator observer checks selected write/read/JSON parse paths and has a negative control. It also checks an `OpaqueBlob`'s encoded buffer (which regrows while it holds plaintext), its planned leaf and its opened buffer, and for those blob paths that no marked block allocated during the operation is still live at its end (a leak the free-time scan cannot see), with its own negative control. The partial-decode limit is pinned separately and is not enrolled here (see below). One of those paths encrypts an owned `Vec` collection through its guard. Drop witnesses show that an owned collection's source is wiped before its pending request is returned. That includes a refused context, and a context conversion that panics. It also includes the elements after an element whose declaration panics. For an owned record, drop witnesses show that the record wipes the fields it seals, also when the context is refused. When a context is refused, no copy of a sealed plaintext is dropped unwiped. Witnesses check this for a `struct` record, a nested record, a `plaintext` record, a record with a stored context, a column, a `StackCipherText`, a `Vec`, and an `Encrypted`. They also show that the record moves its passthrough fields without copying them, and that a record decrypted into a `Protected` is wiped when the `Protected` is dropped. Guest ABI tests check buffer-registry cleanup, error-buffer release and protected text drop. | Request bodies survive until their owner closes them, then wipe; refused requests wipe; heap growth wipes abandoned backing arrays; guest runtime close releases memory. Post-encryption memory scans are supplementary observations. | +| `lifecycle-diagnostics-v1` | Guest errors discard untrusted foreign cause messages; failed/successful exports do not hand over stale diagnostics. | Structured errors remain available after failures; SDK errors and redacted display/logging expose types or fields rather than plaintext values. | +| `lifecycle-validation-before-io-v1` | Existing runtime/read/context cases count provider calls. Wrong shape, independently detectable context mismatch and oversized descriptors fail before key I/O; lazy assembly stops after local failure. An `OpaqueBlob` whose `Serialize` refuses requests no key, and an oversized context is refused before the value is encoded; on decrypt the leaf authenticates (one retrieval) before any blob byte is read, and tampering is `Aead` however the bytes would decode. | Host refusals happen before entering the guest, and shared runtime/read cases exercise the uninitialised guest's preflight boundary. Go does not yet expose native provider counters. | +| `lifecycle-logical-batching-v1` | Instrumented `DataKeySource` calls establish one logical generation batch, retrieval grouping by keyset, descriptor ordering and no work for empty batches, for record operations and for an owned `Vec` collection of any length, including an empty one. | Go uses the same engine, but this profile does not claim independently instrumented Go key-request counts. | +| `lifecycle-provider-chunks-v1` | The actual KMS chunking helper preserves order, handles a final short chunk, fails the whole call on a chunk error, bounds in-flight chunks and releases their futures on cancellation. | This is a native algorithm observation, not a measurement of live HTTP request counts. | + +The drop witnesses belong to fulfilment closures and provider futures in real +record operations. They establish ownership release. They do **not** establish +that arbitrary captured values implement zeroization. The separate heap and +buffer observations provide the narrower byte-cleanup evidence. + +A validation failure detectable only after authentication necessarily retrieves +keys. The profile distinguishes that from shape and context checks that can run +without keys. An error does not imply that no provider request ever occurred. + +## Logical calls and physical requests + +A `Pending` combines requests before awaiting them. For supported assemblies, +generation dispatches one logical `generate_keys` call; retrieval dispatches one +logical `retrieve_keys` call per keyset. Existing instrumented providers observe +those calls and their ordered payloads. + +`StackKms::send_chunked` subsequently splits a logical call according to +`max_keys_per_req` and bounds concurrent chunks by `max_concurrent_reqs`. +The chunk tests observe this helper with controlled callbacks: ten inputs with +chunk size three and concurrency two start only two three-item chunks while +both are pending; dropping the aggregate releases both. This is distinct from +“one HTTP request per batch.” Live service limits, retries and transport timing +are not inferred from the logical counters. + +## Limits carried in every report + +These entries in the index are limitations, not successful requirements: + +- **`go-post-decrypt-shadow-stack` — known gap.** + `TestPlaintextDoesNotRemainInGuestMemoryAfterDecrypt` in + `languages/golang/encrypt/roundtrip_test.go` is explicitly skipped because + decrypted plaintext can remain in the WASM shadow stack in underlying cipher + temporaries. It is not enrolled as passing evidence. The post-encryption scan + cannot establish the post-decryption guarantee. +- **`native-partial-decode-inside-whole-values` — known gap.** + `opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_inside_a_sequence_element_drops_what_the_element_built` + in `packages/stack-encrypt/tests/heap_hygiene.rs` is a `should_panic` + negative control, and so is + `opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_in_a_struct_the_derive_reads_whole_drops_its_fields`. + An `OpaqueBlob` is read in place, so for most derived structs the + fields are wiped when a later field is refused. serde builds some values + whole and stores them only when they are complete: an element of a + sequence, a map, an `Option`, a `Box`, an enum, a field read with + `deserialize_with`, and a type whose own `Deserialize` impl writes no + `deserialize_in_place`. The derive writes none for a struct marked + `#[serde(transparent)]`, `from` or `try_from`, one with a + `#[serde(flatten)]` field, or one whose every field uses + `deserialize_with`, so such a struct is built whole wherever it appears, + `T` included. A refusal inside any of these drops the parts of it already + built as ordinary values, unwiped. The first control refuses a field of a + sequence's first element after the element's `String` field is built; + the second refuses a later field of a struct a `transparent` wrapper reads + whole. Separately, serde reserves room for at most 1 MiB of a sequence's + elements before reading them, and a longer sequence regrows its buffer + and frees each old one unwiped. The enrollment names each case and the + issue that tracks them (#1754). The opened buffer the parts were copied + from is wiped. The `blob` module docs state this; a part that wipes + itself on drop closes it for that part. It is enrolled as the observation + of a limit, not as passing cleanup evidence. +- **`native-heap-observer-exclusions` — limited observation.** + `packages/stack-encrypt/tests/heap_hygiene.rs` watches marked frees on the + executing thread. Its existing observer excludes a named upstream aws-lc + sealing frame by backtrace and reports excluded frees. It scrubs stack residue + before observing heap frees; it does not prove stack erasure. Its JSON query + paths use borrowed/static path text because owned path copies have separate + cleanup limitations. The observer only scans blocks that are freed, so it + misses plaintext that is leaked and never freed. For the owned `Vec` + conversion, the drop witnesses in `packages/stack-encrypt/tests/collections.rs` + record the wipe itself. For owned records, the drop witnesses in + `packages/stack-encrypt/tests/owned_records.rs` do the same. A test there fails if a source or a decrypted prefix + is leaked. The lifecycle + runner preserves the observer's output. +- **`caller-owned-host-values` — outside the guarantee.** Caller-owned strings, + bytes, objects, returned plaintext, aliases and copies remain the caller's + responsibility. Ownership transfer or protected borrowing must be stated by + each public API. Cancellation cannot retract work already accepted by a remote + service, and dropping a provider future does not prove remote cancellation. +- **`live-provider-http-chunking` — not observed.** Hermetic tests count logical + provider calls and chunk callbacks. They do not attest to actual ZeroKMS + request counts, retry behavior or remote cleanup. +- **`python-typescript-lifecycle` — not enrolled.** Their backends, cancellation + models, host mappings and extension-owned buffers need their own evidence. + +The current required lane supports Linux and macOS. Its native heap observer +requires Unix; unsupported hosts fail explicitly rather than silently skipping +that evidence. This is not Windows lifecycle certification. Memory locking under +OS resource limits, whole-process heap scans, other threads, compiler/register +residue and arbitrary caller-supplied sinks are outside the enrolled guarantees. +Existing broader platform, Miri, fuzz, live and locking tests remain in place. + +## Running and extending the profile + +From the repository root: + +```sh +mise run wasm:guest:build +mise run wasm:guest:build:deterministic +mise run test:conformance:lifecycle +``` + +No CipherStash credentials or database are required. Some Go cancellation tests +start local HTTP stubs. The runner shares inventory/execution checks with EQL +conformance: every enrolled native test must be compiled, selected and not +ignored, and every Go test must pass with no skipped subtests. Fresh Go tests +bypass the test cache. Required fixture-update variables are rejected. + +The required `wasi-check` CI job runs the task and uploads its report, failing +if the report is absent. Reports identify the engine, platform/architecture, +lockfile, guest hashes, enrollment, executed evidence and known limitations. +Set `STACK_CONFORMANCE_REPORT_DIR` locally to retain the same JSON report. + +Add evidence to the existing requirement where possible. Keep language-specific +lifetime probes and implementation regressions: a shared semantic round-trip +cannot replace them. Do not claim a stronger cleanup guarantee by removing a +limitation or accepting a skipped test; supply executable evidence on the +backend being claimed. Secure-buffer adoption and key-copy removal remain +implementation work, distinct from this inventory. diff --git a/conformance/stack-encrypt/query-refusals-contract.md b/conformance/stack-encrypt/query-refusals-contract.md new file mode 100644 index 0000000000..df6edf8836 --- /dev/null +++ b/conformance/stack-encrypt/query-refusals-contract.md @@ -0,0 +1,115 @@ +# Record query-refusal profile + +`record-query-refusals-v1` describes the cases in `v1/record-query-refusals-v1.cases.json`: +what a query is refused for before any term exists, and the few inputs +that look refusable and are not. It is an experimental test contract for +native Rust and Go WASI under `NoTargets`. Python and TypeScript runners +remain pending. + +The scalar and runtime profiles cover a handful of equality refusals. This +profile is the shared rejection corpus: every scalar operator against +every field capability of the plan, and the operand shapes and values +listed below, with the class of each refusal, its structured diagnostic, +and the observation that no key is requested. + +The runners are `packages/stack-encrypt/tests/query_refusal_conformance.rs` +and `languages/golang/encrypt/query_refusal_conformance_test.go`. + +## Plan and inputs + +`fields` declares one plan every case queries, each field under context +`["conformance", ]`: equality-only text, match-only text, order-only +text (ORE and block ORE), an integer with equality and order, an order-only +float, a 128-bit integer with equality and OPE, a ciphertext-only bool and +text, a sealed-null and a SQL-null integer, and equality-only bytes. + +A case names a `field`, an `operator` and an `input`: a scalar `{type, text}` +in the value profile's form, or `{"type": "list", "items": [...]}` for a +range. `accepted` is mandatory; a refused case carries `expected_error`. + +## Refusal classes + +| `class` | Engine error | Go sentinel | Diagnostic | +|---|---|---|---| +| `source` | `Error::Source` | `ErrEncoding` | `stack_encrypt::dynamic_source` with `reason` and `field` | +| `plan` | `Error::Plan` | `ErrEncoding` | `stack_encrypt::dynamic_plan` with `reason` and `field` | +| `term` | the index's own refusal of the value | `ErrTerm` | the term error's code (`stack_encrypt::empty_term_text`, `term_normalize`, `ore_block_too_long`, `ore_block_trailing_nul`); no reason or field | + +Source and plan refusals cover every scalar operator (`eq`, `lt`, `lte`, +`gt`, `gte`, `between`, `matches`) on every field of the plan whose +indexes do not answer it, one case per pair: the equality-only text and +integer, the match-only text, the ORE and block ORE text, the order-only +float, the ciphertext-only bool and text, and the bytes field (equality +alone: a declaration refuses an order index on bytes). The 128-bit integer (equality and +OPE) and the 32-bit integer (equality and ORE) answer every operator but +`matches`. The SQL-null integer shares the equality-only +integer's indexes and is not repeated. A JSON document operator on an +integer is refused as well. The remaining source refusals are operand +shapes and values: a range that is not a list of two +(a scalar, one bound, three bounds, text), a value of another kind (text or +a fraction for an integer, a negative for an unsigned, an integer for text, +a bool for an integer, a null bound), a null on a field that does not seal +its nulls beside an equality term (ORE and OPE order indexes included), a field the plan does not name and an +operator name the engine does not know. + +Term refusals cover match text that cuts no token (too short, empty, only +separators), text no index can normalize (a code point Unicode 16 does not +assign) under match, equality and order, and the block ORE limits (a fold +over 1023 bytes, a trailing NUL) on either bound of a range. + +Accepted cases are the positive controls: an inverted range at 32-bit, +128-bit and float widths (neither path refuses it; as SQL's `BETWEEN`, it +matches nothing), the longest block ORE +text, an interior NUL, empty order text, a null equality query on a +sealed-null field, folded match text and a losslessly widened integer. + +## Required observations + +Both runners run every case through query-term derivation: `QueryTerm` in +Go, `dynamic::query_term` in Rust, which must refuse before returning a +pending operation. For `matches`, both also run verification of an empty +page (`Verify`, `dynamic::verify`) and require the same outcome. Rust also +runs the binding's key-free check, `dynamic::check_query`, and requires the +same diagnostic, and observes that no keyset lookup, data-key generation or +retrieval happens on any path. Go's deterministic guest makes no network +request; that is not a logical key-call count. + +The operator vocabulary is closed in Rust (`dynamic::Op`), so the unknown +operator case is observed at the binding boundary alone; the Rust runner +checks that the case expects exactly that and continues. + +## The typed query + +`typed` records how a typed Rust query answers the same query, for the +queries it can spell (text on the text fields, a `uint32` range under ORE +and an `int128` range under OPE): `before_keyset`, `after_keyset` or +`none`. A typed query is a query from the field reference of a derived record. +The Rust runner has one derived record whose fields have the corpus's +labels, runs the field query for the case, and counts the keyset loads +and the key requests. The error code must equal the binding's. + +The two paths refuse the same inputs with the same codes at the same +stage: before any keyset is resolved and before any key is requested. Every +`typed` entry of a refused case is `before_keyset`, and the runner refuses +an `after_keyset` entry. Both paths call the one set of rules in the +engine's `sem::query` module: the typed query through each index's +`Supports::prepare`, and the binding through `check_query`, `query_term` +and `verify`. A rule written there is a rule on both paths, and a rule +written anywhere else is a drift this profile fails on. + +A typed query takes a keyset that is already loaded, so it cannot refuse +after a keyset load. The value `after_keyset` stays in the vocabulary for +the corpus's history: until the API plan's step 2 ("The engine's rules, and +the order of the work", `docs/plans/2026-10-24-stack-encrypt-api-plan.md`) +some rows said `after_keyset`. + +## Scope and remaining work + +The corpus covers scalar operators under `NoTargets`. Match options the +index cannot use (an n-gram length of zero) are a declaration refusal, in +`v1/record-declarations-v1.cases.json` (`match-invalid-ngram-zero`). JSON document +operators against JSON fields, EQL target refusals and `target_limit` +inputs remain with their existing tests. The match-case mismatch is gone: +`Matches` has no case parameter, and a match index's configuration is the +one place case is declared. The Go runner does not exercise generated query methods; those keep +their fixture tests. No existing test is removed. diff --git a/conformance/stack-encrypt/raw-frames-contract.md b/conformance/stack-encrypt/raw-frames-contract.md new file mode 100644 index 0000000000..d40d3fb408 --- /dev/null +++ b/conformance/stack-encrypt/raw-frames-contract.md @@ -0,0 +1,109 @@ +# Record raw-frame profile and error classes + +`record-raw-frames-v1` describes the cases in `v1/record-raw-frames-v1.cases.json`: stored +record batches supplied as transport bytes (`frame_hex`), so both runners +hand the decoder the same bytes, including what no map-based tree encoder +can write. It is an experimental test contract for native Rust and Go WASI. +Python and TypeScript runners remain pending. + +The read profile builds stored records from real ciphertext and mutates the +tree. Its Go runner encodes that tree through the host's tree codec, which +refuses a repeated key, so repeated keys and malformed leaves could not be +shared there. This profile is the explicit raw-byte path the read profile +deferred. + +The runners are `packages/stack-encrypt/tests/raw_frame_conformance.rs` +and `languages/golang/encrypt/raw_frame_conformance_test.go`. Go reaches +the guest through a test-only hook that takes the encoded batch directly +(`OpenFrameForTest`), keeping cipher validation, context, production +decoding and buffer cleanup; the uninitialised checker observes the guest's +preflight alone. + +## Error classes + +A read can fail at five points. Each class is the stage, not the message, +and a case's `class` names where its frame stops: + +| `class` | Where it stops | Native observation | Go observation | +|---|---|---|---| +| `transport` | The bytes are not a ciphertext tree in the transport codec | `decode_ciphertext` fails; the codec reports no code | `stack_guest_abi::malformed_input`, the corpus-wide `boundary_error`, as `ErrEncoding`, from the checker and the cipher | +| `leaf` | The tree decodes and a sealed leaf is not in the leaf byte format | `SealedValue::from_bytes` fails with its code and payload | The same code and payload as `ErrEncoding` | +| `shape` | Leaves are well formed and the tree does not fit the plan | `check_record` and `decrypt` refuse with `stack_encrypt::dynamic_record` before any pending operation | The same diagnostic from the checker and the cipher | +| `authenticated` | The tree fits, the leaf is opened, and what it holds is not what the plan reads | The pending opener fails after one retrieval | The checker reaches `ErrState`; the cipher reports the diagnostic | +| `success` | The record opens | Typed rows, one retrieval | Typed rows | + +Two more classes live in other profiles and are listed here so the five +are read together. An **invalid declaration** stops before any record: the +declaration grammar's cases report `stack_encrypt::dynamic_plan`, and a +malformed plan frame reports the same `malformed_input` boundary. An +**unsupported host conversion** stops before the engine: the value profile's +`host_conversions` report the host's own `ErrEncoding` with no engine +diagnostic. + +Within `authenticated`, two outcomes are distinguished. A leaf sealed as an +`int32` and read as `int64` or `string` authenticates and then fails the +declared type: `stack_encrypt::plan_field_type` naming the field and the +expected kind, as the read profile's authenticated cases do. The diagnostic +never names the kind that the leaf decrypted to. That kind was inside the +ciphertext, so the payload has no `found` field. A leaf moved +into another role (the single leaf under an empty-sequence tag) fails +authentication itself: `stack_encrypt::aead`, which Go reports as +`ErrAuthentication` carrying that code. Both runners compare the code and +fields of either outcome, as they do for every refusal. Neither is a shape refusal: a container's membership +and order are not authenticated, so a tree that fits the plan passes +preflight and is judged leaf by leaf. + +## Repeated keys + +The transport codec refuses a map with a repeated key, in the frame a +binding writes and in the frame a guest reads, so a stored record with the +same field or output twice is a `transport` refusal in both runners. It +never reaches the engine's own `field_repeated` and `repeated_key` reasons. + +Those reasons still guard a tree built in native Rust without the codec. +`native_tree` records what the engine says of the same bytes when a reader +admits the repeated key and keeps every other codec rule: the runner reads +the frame leniently, checks the tree against the plan, and compares the +diagnostic. A separate test holds that reader to the codec on every frame +the codec accepts. Go parses `native_tree` and does not execute it: a +binding cannot reach the engine with such a tree. + +## Cases + +`frame_hex` is the complete batch: one row, one field `value` with `c` and +`eq`. The well-formed leaf is the scalar profile's frozen `i32-max` +ciphertext under seed zero and context `["conformance", "value"]`, with its +frozen equality term as the passthrough. `read` names the declaration the +batch is read under. `retrievals` is `1` for `authenticated` and `success` +and `0` otherwise; a read never generates a key. The counts are a native +observation: Go checks that `retrievals` agrees with the class, and its +checker's stop at the state boundary stands in for "nothing retrieved +before preflight". + +| Case | Class | What the bytes do | +|---|---|---| +| `success-frozen-leaf` | success | The frozen leaf read as `int32` | +| `authenticated-int64`, `authenticated-string` | authenticated | The frozen leaf read as another kind | +| `authenticated-c-empty-sequence` | authenticated | The frozen leaf under the empty-sequence tag | +| `shape-c-passthrough` | shape | A plaintext passthrough where the ciphertext must be | +| `leaf-unknown-version` | leaf | The leaf's version byte is 9 | +| `leaf-truncated` | leaf | Two leaf bytes | +| `transport-repeated-field` | transport | `value` twice in the row; natively `field_repeated` | +| `transport-repeated-output` | transport | `c` twice in the field; natively `repeated_key` | +| `transport-retired-none-tag` | transport | The retired absence marker as a node | +| `transport-trailing-byte` | transport | A byte after a complete tree | +| `transport-truncated-count` | transport | A sequence count of two with one row | +| `transport-not-a-tree` | transport | One byte that is no tag | + +Both runners reject a case whose expectations contradict its class, and a +transport case whose frame the codec accepts. Go additionally shows that +its own tree codec refuses every transport frame, so none of them is a +batch the host could have written. + +## Scope and remaining work + +The frames hold one row and one field. Depth and size bounds, context +fields, other output kinds and repeated keys inside passthrough payloads +stay with the codec's own tests and the read profile. Python and +TypeScript consumers should feed the same `frame_hex` to their decoders. +No existing test is removed. diff --git a/conformance/stack-encrypt/read-contract.md b/conformance/stack-encrypt/read-contract.md new file mode 100644 index 0000000000..4123b1a0b4 --- /dev/null +++ b/conformance/stack-encrypt/read-contract.md @@ -0,0 +1,126 @@ +# Record read profile + +`record-reads-v1` adds shared cases in `v1/record-reads-v1.cases.json` for stored record +shapes, authenticated type checks and context preflight. It fixes the resolver +to `NoTargets`. It is experimental and covers native Rust and Go WASI. + +## Inputs and observations + +Each case has separate `write` and `read` declarations, each naming the `kind` +and `null` policy of `value`. Outputs are ciphertext and equality. `rows` uses +the runtime profile's typed scalar representation. Runners first encrypt these +rows successfully, then apply the named `mutation` to its zero-based `row`. +This supplies real ciphertext, including for negative reads. + +Without `context_field`, the context is `["conformance", "value"]`. With it, +`tenant` is a string passthrough supplying the row context; `value` is its +field identity. An optional `expected_context` constrains the stored context. +Omit it for an unrestricted read; when present it must be a nonempty plain +label string. Explicit JSON null is invalid, not another spelling of omission. + +`expected` describes the native opener's stage, complete diagnostic code and +payload on refusal, typed ordered rows on success, and data-key retrieval +call count. Runners must reject unknown stages, mutations, capabilities, +profiles and input types. Cases have unique, nonempty IDs. + +| Stage | Native observation | Retrieval calls | +|---|---|---| +| `shape` | `record::decrypt` refuses before returning a pending operation | 0 | +| `preflight` | The pending opener refuses before requesting keys | 0 | +| `authenticated` | Shape checking passes; opening the authenticated value finds a type mismatch | 1 | +| `success` | Opened rows match all expected values, types and ordering | 1 when ciphertext is present; 0 for the all-absent SQL-null case | + +Counters are reset after fixture encryption. Reads must never generate data +keys. These counts observe native data-key calls, not index-key initialization +or Go's logical provider calls. + +`check_error` independently describes `record::check_record`, which needs no +cipher. An absent `check_error` requires acceptance. The Go guest runs this +check before looking up its cipher state. Both an uninitialised guest and a +configured cipher execute each case (subject to the host context refusal +described below): guest preflight errors must have the specified +diagnostic in either; accepted shapes must reach `ErrState` without a cipher. +Consequently, a concealed type mismatch must pass preflight and fail only when +the active guest opens it. + +The Go runner uses a test-only entry point to the existing `se_decrypt_record` +export. This permits shapes the host's `record.Sealed` type cannot express, +including a passthrough directly under `c`. It uses the binding's existing +tree codec, Cipher validation/context/extension, production decoding and +transport-buffer cleanup. Only the uninitialised checker deliberately bypasses +host plan checks to observe the guest boundary. Cases marked `adapter` also +run the normal `Cipher.Open` path; they retain their original stored shape. +This does not certify generated SDK mappings. + +## Required behavior + +- Missing required fields, missing ciphertext outputs, non-map rows or field + outputs, and plaintext passthroughs under ciphertext are refused before keys. +- A malformed later row rejects the batch before retrieval. +- Reads project the fields and outputs the plan opens. Extra stored fields, + extra outputs and missing equality outputs do not prevent reading ciphertext. + Writes still reject unknown source fields, as the runtime profile requires. +- Reading int32 ciphertext as int64, uint64 or string fails after retrieval. + Reads do not apply the query path's lossless numeric conversion. +- A sealed null cannot open through a required declaration. It can open through + a SQL-null declaration, with retrieval because ciphertext is present. +- An absent SQL-null field opens as null without retrieval. A required or + sealed-null read declaration refuses the same missing field. +- Context-field reads work without an expected label or with a matching label. + A mismatch, including one in a later row, refuses the whole batch before keys. +- Missing context fields, missing passthrough payloads and non-string context + values fail before retrieval. +- A static-context plan cannot also take a call context. Native `check_record` + and the guest report `dynamic_record` with reason `refused`; the native pending + opener reports `plan_two_context_sources`, naming the plan and the call. + The corpus records both engine diagnostics explicitly. Go's configured + `Cipher.Context(...).Open` refuses this combination earlier in `Cipher.plan` + with `ErrEncoding`. The case also exercises that host refusal through both + `Open` and the validated tree hook; it does not require its English wording + or the absence of a diagnostic. + +Context-mismatch diagnostic payloads expose only stored descriptor length and +part count, not its value. Go diagnostic numeric metadata is compared as JSON +numbers; plaintext comparisons retain actual host types. + +## Mutation vocabulary + +| Mutation | Change to the selected row | +|---|---| +| `none` | Preserve it | +| `drop_value` / `drop_c` / `drop_eq` | Remove the named field or output | +| `field_plain` / `c_plain` / `row_plain` | Replace that node with an int32 passthrough | +| `extra_field` / `extra_output` | Add an `extra` int32 passthrough at that level | +| `drop_tenant` | Remove the context field | +| `tenant_no_payload` | Replace its output map with an empty map | +| `tenant_number` | Replace its passthrough string with an int32 | + +## Scope and consolidation + +The existing native record tests retain repeated keys, invalid leaf framing, +other tree forms, context extensions and wider type/output combinations. Go's +tree encoder accepts maps with unique keys, so repeated-key transport cases +need a separate raw-byte profile rather than being silently skipped here. + +The existing Go context-field suite retains generated SDK calls, query context +selection, extension behavior and stored-context tampering. The deterministic +provider's wrong-context refusal remains covered there and by the scalar +profile. This profile observes preflight context checks, not every context +composition or cryptographic tampering case. + +No existing tests are removed. Python and TypeScript runners, EQL/JSON read +shapes, provider failures, version compatibility and runtime artifact exchange +remain follow-up work. + +Opened row order follows the input batch. Within a row the engine emits fields +in declaration order. Both runners +construct declarations with the context field first, followed by recoverable +fields. Native expected frames use that order; Go's shared production decoder validates it +before converting objects to maps. `context_field_name` may override the default +`tenant` name when `context_field` is true; a `zone` case prevents lexical object +ordering from masquerading as declaration ordering. + +Both runners require `context_field`, `adapter`, and `mutation.row` (including +explicit false/zero values), reject empty supplied `expected_context`, and reject +contradictory stage, check-error and retrieval-count expectations. The Rust runner +collects per-case failures so later cases still execute after an earlier failure. diff --git a/conformance/stack-encrypt/runtime-contract.md b/conformance/stack-encrypt/runtime-contract.md new file mode 100644 index 0000000000..1087195d68 --- /dev/null +++ b/conformance/stack-encrypt/runtime-contract.md @@ -0,0 +1,96 @@ +# Record runtime profile + +`record-runtime-v1` describes the behavior exercised by `v1/record-runtime-v1.cases.json`. +It is an experimental test contract for native Rust and Go WASI, with no EQL +resolver. Python and TypeScript runners remain pending. + +Each case uses one field, `value`, with ciphertext (`c`) and equality (`eq`) +outputs, under context `["conformance", "value"]`. `kind` declares its type; +`null` is empty for a required value, `sql`, or `sealed`. Values use the scalar +profile's `{type, text}` representation, extended with `float64` decimal text. +Runners construct typed values before calling the engine. This profile admits +`int32`, `int64`, `uint64`, `float64`, and `string` as declared kinds; +both runners reject unknown kinds and null-policy spellings. + +## Write and read + +The `seal` operation receives an ordered `rows` array of field maps. An absent +map key is missing; `{ "type": "null", "text": "" }` is an explicit null. +These are separate inputs, including in languages that offer a nil-like value. + +Successful cases specify `expected_rows` and `expected_stored`. The former +describes opened values with their types and order. The latter states whether +each row stores the field at all. Both must have the input row count. + +- Required fields reject missing values and explicit nulls. +- SQL-null fields accept both, omit the stored field, and open as explicit null. +- Sealed-null fields require the key to exist. An explicit null stores both + ciphertext and equality, then opens as null. +- A write reads each value as the declared type, by the rules a query + reads its input by. A number of another width or kind converts when the + conversion is exact, and seals, stores its terms and opens as the same + number sent at the declared width (`required-other-width`, + `sql-other-width`, `sealed-other-width`, `required-integral-float`). A + conversion that would lose something is refused (`required-fractional-float`), + and text is never read as a number (`late-wrong-type`). +- Unknown fields are refused, including when an omitted SQL-null field makes + the input field count match the declaration; they cannot be silently dropped. +- An invalid later row rejects the whole batch before data-key generation. +- An empty batch succeeds with no data-key calls. + +Every stored equality term must match a query for its expected opened value. +`equal_lengths` additionally requires all stored ciphertexts in the case to +have equal lengths. Mixed sealed-null/value cases exercise this requirement +for int32, int64, uint64 and float64. This is not a claim about all types. +Boolean equality is not admitted; existing native null tests cover boolean +ciphertext separately. + +## Equality queries + +The `query` operation receives `input` and either `expected_value` or +`expected_error`. A successful query's term must equal the term stored by +encrypting `expected_value` through the same declaration. That value is +independent expected data, not a conversion computed by the runner. + +Cases cover signed narrowing bounds, integral and fractional float inputs, +negative-to-unsigned refusal, and exact versus rounded integer-to-float +conversion around 2^53. Text and boolean values are not parsed as numbers. +A null equality query succeeds only for sealed-null fields. + +## Refusals and observations + +`expected_error` specifies the engine diagnostic `code`, `reason`, and `field`. +Native Rust must reject before producing a pending operation. Go must expose +`ErrEncoding` and the same diagnostic when the request reaches the guest. + +Missing and unknown fields can be rejected earlier by Go's record adapter. +The adapter preserves the same structured source diagnostic (code, reason and +field); the corpus does not require a particular English message or rejection +at the host boundary. Forwarding to the guest later remains conformant. + +Each refused source row contains exactly one independent fault. The corpus does +not specify precedence between multiple faults or source-object traversal order. +Batch cases may place that single invalid row after valid rows to test preflight. + +The native runner instruments data-key generation and retrieval calls. A +successful batch makes one of each when it stores ciphertext, and zero when +every field is omitted. Refused writes and all queries make neither call. +The query oracle's separate encryption is counted separately. These assertions +exclude index-key initialization and do not establish Go provider-call counts. +Go runs the same semantic cases through its deterministic WASI guest; that +guest's lack of network requests is not proof of logical key-call counts. + +## Scope and remaining work + +The cases cover runtime writes, corresponding reads, and equality queries. +They do not cover malformed stored records, authenticated type mismatches on +read, context composition/preflight, provider failures, or other operators. +The separate [read profile](read-contract.md) adds stored-shape, authenticated +type and context-preflight cases. +Fresh cross-language artifact exchange remains the scalar profile's coverage. + +Existing `value_kinds.json` and `query_operators.json` fixtures remain the +shared evidence for their wider type/operator matrices. Existing generated +Go null tests retain pointer mapping and EQL assertions. Native null tests +retain their wider kinds and lower-level padding assertions. No tests are +deleted by this slice; consolidation requires matching those assertions first. diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md new file mode 100644 index 0000000000..0ebb0a0d0b --- /dev/null +++ b/conformance/stack-encrypt/single-value-contract.md @@ -0,0 +1,241 @@ +# Single-value profile + +`single-value-v1` is the conformance profile for one value encrypted as one +ciphertext. The profile describes the cases in +`v1/single-value-v1.cases.json`. The cases run through the run-time interface +of the engine, `stack_encrypt::dynamic::value`. The profile is an experimental +test contract. + +The run-time interface takes a value as a frame, with a declared kind. The +typed Rust interface must decrypt the result. The run-time interface must +decrypt a ciphertext that the typed Rust interface made. So every language +can decrypt a value that one language encrypted. + +## Terms + +- A frame is one value written as bytes, in the format that the engine reads. +- A kind is the name of what a value is, such as `string` or `uint64`. The + declared kind is the kind that the caller says the value has. +- A leaf is the encrypted form of one scalar. A ciphertext of one value + contains one leaf. +- To seal a value is to encrypt and authenticate it. To open a ciphertext is + to decrypt it and check it. +- A passthrough is a value that a record stores without encrypting it. +- A refusal is an error that the engine returns for a value it does not + accept. +- The typed interface is the Rust API for a value of a Rust type: + `keyset.encrypt` and `keyset.decrypt`. + +## Runners + +The Rust runner is `packages/stack-encrypt/tests/single_value_conformance.rs`. +The Go runner is pending. The Go runner will be written with the single-value +calls of the Go SDK (issue #2010). The Python and TypeScript runners are +pending too. A missing runner is not a passing result. + +## Cases + +The file has three parts: a public `seed` for the deterministic key provider, +a list of `cases`, and a list of `batches`. Each case has these keys: + +| Key | Meaning | +|---|---| +| `id` | The name of the case | +| `kind` | The name of the declared kind, or empty for no declared kind | +| `context` | The parts of the context, or an empty list for the empty context | +| `input` | The value, in the `{type, text}` form that the [value profile](values-contract.md#cases) defines | +| `stored` | The value in the ciphertext, where it differs from the input | +| `opens_as` | Kinds that the ciphertext must open as, other than the declared kind. Each entry has the `value` that the ciphertext opens to. | +| `refused_as` | Kinds that the ciphertext must not open as | +| `expected_error` | For a refused case, the `code`, the `reason`, and the `found` kind of the refusal | + +A context of two parts is a pair. For example, `["conformance", "value"]` is +the Rust context `("conformance", "value")`. For an empty list, a runner calls +the form with no context. For any other list, a runner calls the form with a +context. + +This profile adds two input types to those of the value profile: + +| `type` | `text` | +|---|---| +| `uuid` | The UUID in lowercase hex, in groups of 8, 4, 4, 4, and 12 digits | +| `shape` | The name of a value that `{type, text}` cannot spell. The next table lists the names. | + +| Shape | The value | +|---|---| +| `array` | The array of the two strings `a` and `b` | +| `empty_array` | The array with no elements | +| `object` | The object with one member, `a`, the `uint32` 1 | +| `passthrough` | A passthrough of the string `clear` | +| `typed_null` | A typed null of `int64` | + +Some host languages cannot build every shape. A runner in such a language +sends the frame that the artifact file records for the case. + +## Artifacts + +The Rust runner writes `v1/single-value-v1.expected.rust-native.json`. The +file has one entry for each case: + +- `frame`: the frame of the input, in hex. Every case has one. +- `leaf`: the plaintext that the leaf of the ciphertext is sealed with, in + hex. That plaintext is the type tag of the leaf and its payload. Only an + accepted case has one. +- `ciphertext`: a ciphertext of the value, in hex. Only an accepted case has + one. + +The typed Rust interface made each `ciphertext` where a Rust type spells the +stored value. No Rust type spells a lone `uint8`, so the run-time interface +made the ciphertext of that case. + +A runner never compares whole ciphertexts. Each sealed leaf has a random +AES-GCM nonce, so two ciphertexts of one value differ. A runner compares the +parts of a ciphertext that the nonce does not change: + +- the keyset +- the IV and tag of the data key +- the length of the ciphertext +- the plaintext of the leaf + +The deterministic provider derives a data key from the seed, the context, and +a counter. So a runner makes a new provider for each ciphertext it compares. + +Regenerate the artifacts deliberately, with `STACK_ENCRYPT_UPDATE_FIXTURES=1` +and the native runner. Review the diff of the cases and the diff of the +artifacts together. + +An update keeps the frozen ciphertext of a case whose frame and leaf have not +changed. The update checks that ciphertext as any run does. So a ciphertext +stays frozen from one update to the next, and the diff shows only the cases +that changed. + +## Required behavior + +### An accepted case + +A case with no `expected_error` is an accepted case. For each one: + +1. The frame of the input equals the frozen `frame`. +2. The run-time encrypt accepts the value with the declared kind and the + context. The plaintext of the leaf that it seals equals the frozen `leaf`. +3. The new ciphertext and the frozen `ciphertext` agree in every part that + the nonce does not change. +4. Each of the two ciphertexts opens under the same context, with no declared + kind. The result is `stored`, or the input where the case has no `stored`. +5. Each of the two ciphertexts opens under the same context, with the + declared kind, to the same value. With the kind `json`, the result is the + stored JSON text as a bytes value. +6. Each ciphertext opens as each kind in `opens_as`, to the `value` of that + entry. +7. Each ciphertext is refused when it is opened as a kind in `refused_as`. + The code of the refusal is `stack_encrypt::opened_type`. The `expected` + field of the refusal is the name of the kind. The refusal never says what + the value opened as. +8. Each ciphertext is refused under the context `["conformance", "wrong"]`. + The deterministic provider refuses the key request as forbidden, as + ZeroKMS does. Other providers can report a wrong context differently. + +Native Rust also checks two things. The typed interface seals the same parts +for the stored value. The typed decrypt opens both ciphertexts. + +### Conversions + +A case with `stored` is a conversion. The engine seals a number of another +width or kind as the value of the declared kind, when the conversion is exact. +The conversion rules are the ones that a typed field of a record uses. The +engine seals a document with the kind `json` as its compact JSON text. + +### Strings and JSON documents + +`json` is a declared kind and not a stored kind. A `string` and a document +have one stored form: text. So a check of the stored kind cannot distinguish +them. Three groups of cases pin the consequences: + +- `json-given-string`: a sealed document opens as `string`, to the JSON text + that was sealed. +- `string-json-number-text` and `string-json-spaced-text`: a sealed string + whose text is a JSON document opens as `json`. Decrypt as `json` checks that + the text parses. Decrypt then returns the document as the engine writes it, + as a bytes value. So `{ "b" : [ 1 , null ], "a" : true }` comes back as + `{"a":true,"b":[1,null]}`. +- `string-not-json-text`: a sealed string whose text is not a JSON document is + refused as `json`. + +### A refused case + +A case with `expected_error` is a refused case. The run-time encrypt refuses +the value before any key request, with the diagnostic `code`, `reason`, and +`found` of the case. The code of every such refusal is +`stack_encrypt::dynamic_value`. A single value has its own refusal, with no +record, plan, or field in it. + +`found` is the kind of the value to encrypt, as the payload field `found` +names it. Every refusal of a single value names that kind. The name is a +kind name such as `array`, `string`, or `int64`, or one of `null`, +`undefined`, `passthrough`, and `unknown`. The kind is the kind of the +input. A refusal never names the kind of a decrypted value. + +The cases cover these values: + +- An array, an object, a passthrough, a plain null, and a typed null. Each is + tested with no declared kind and with one. The reason is `not_a_scalar`. + `found` is `array`, `object`, `passthrough`, or `null`. A typed null is a + `null`. +- JavaScript's `undefined`, with a declared kind and with none. The reason is + `not_a_scalar`. `found` is `undefined`. +- A value of another kind that does not convert exactly. The reason is + `field_type`. `found` is the kind of the input. +- Text that is not a JSON document, with the kind `json`. The reason is + `json_syntax`, `json_duplicate_key`, or `json_integer_range`. `found` is + `string` or `bytes`. + +A runner checks all three of `code`, `reason`, and `found`. `reason` says +which rule the value breaks, and `found` says what the value is. + +The engine refuses `undefined` with any declared kind. An `undefined` value is +most often a misspelt property name. No typed call could read it back. + +A host language with no `undefined` has two options for those cases. The +runner can send the frame that the artifact file records. Or the runner can +check that the cases are well formed, and skip them. + +## Batches + +The run-time interface has no batch call. To encrypt many values, a binding +makes one single-value call for each value. The binding then merges the +pending calls into one key request. In Rust, `Pending::all` merges the calls. +A binding decrypts many ciphertexts the same way. + +Each call has its own declared kind, so one batch can contain values of +different kinds. Each entry of `batches` has three keys: + +- `inputs`: a list of values +- `kinds`: the declared kind for each input, or empty for none +- `context`: one context for all the inputs + +A runner seals and opens each entry as a binding does: + +- An accepted batch seals in one key request and opens in one key request. + The values come back in the order of the inputs. The expected values are + `stored` where the batch has one, and the inputs otherwise. +- An empty batch makes no key request. +- In a batch with `expected_error`, the single-value call refuses one of the + values with that `code`, `reason`, and `found`. The batch then makes no + key request. + +The counts of key requests are native observations: the Rust runner counts +them on its key source. + +## Scope and remaining work + +The profile covers every scalar kind, the exact conversions, JSON documents, +and the refusals of the run-time encrypt. The profile does not cover these: + +- A ciphertext of a null. Only the tree interface seals one. +- A scalar of a logical type that the engine does not define. The + `{type, text}` form cannot spell one. With no declared kind, the engine + seals such a scalar as it arrived. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- Decrypt limited to one keyset. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- New ciphertexts exchanged between languages. That needs a second runner. diff --git a/conformance/stack-encrypt/v1/artifact-exchange-v1.cases.json b/conformance/stack-encrypt/v1/artifact-exchange-v1.cases.json new file mode 100644 index 0000000000..acc75f08a8 --- /dev/null +++ b/conformance/stack-encrypt/v1/artifact-exchange-v1.cases.json @@ -0,0 +1,155 @@ +{ + "version": 1, + "profile": "artifact-exchange-v1", + "seed": "737461636b2d656e63727970742061727469666163742065786368616e676520", + "required_capabilities": [ + "records", + "equality", + "order", + "passthrough", + "value-kinds", + "null-policies", + "opaque-blobs" + ], + "values": { + "corpus": "record-values-v1.cases.json", + "profile": "record-values-v1", + "context": ["conformance", "exchange"], + "field": "value" + }, + "record": { + "context": ["conformance", "exchange", "people"], + "fields": [ + { + "name": "id", + "kind": "int64", + "passthrough": true + }, + { + "name": "name", + "kind": "string", + "outputs": ["c", "eq"] + }, + { + "name": "age", + "kind": "uint32", + "outputs": ["c", "eq", "ore"] + }, + { + "name": "balance", + "kind": "decimal", + "outputs": ["c", "eq", "ore"] + }, + { + "name": "born", + "kind": "date", + "outputs": ["c", "eq", "ore"] + }, + { + "name": "joined", + "kind": "timestamp", + "outputs": ["c", "eq", "ope"] + }, + { + "name": "note", + "kind": "string", + "outputs": ["c"], + "null": "sql" + }, + { + "name": "rating", + "kind": "float32", + "outputs": ["c", "eq"], + "null": "sealed" + } + ], + "rows": [ + { + "id": "ada", + "values": { + "id": { "type": "int64", "text": "1" }, + "name": { "type": "string", "text": "Ada Lovelace" }, + "age": { "type": "uint32", "text": "36" }, + "balance": { "type": "decimal", "text": "1234.5600" }, + "born": { "type": "date", "text": "1815-12-10" }, + "joined": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + }, + "note": { "type": "string", "text": "first programmer" }, + "rating": { "type": "float32", "text": "4.5" } + } + }, + { + "id": "nulls", + "values": { + "id": { "type": "int64", "text": "-9223372036854775808" }, + "name": { "type": "string", "text": "" }, + "age": { "type": "uint32", "text": "0" }, + "balance": { "type": "decimal", "text": "-0.01" }, + "born": { "type": "date", "text": "1970-01-01" }, + "joined": { "type": "timestamp", "text": "1970-01-01T00:00:00Z" }, + "note": { "type": "null", "text": "" }, + "rating": { "type": "null", "text": "" } + } + }, + { + "id": "unicode", + "values": { + "id": { "type": "int64", "text": "9223372036854775807" }, + "name": { "type": "string", "text": "Grüße, 世界 🌏" }, + "age": { "type": "uint32", "text": "4294967295" }, + "balance": { + "type": "decimal", + "text": "79228162514264337593543950335" + }, + "born": { "type": "date", "text": "9999-12-31" }, + "joined": { + "type": "timestamp", + "text": "1969-12-31T23:59:59.999999999Z" + }, + "note": { "type": "string", "text": "max" }, + "rating": { "type": "float32", "text": "-0" } + } + } + ] + }, + "blob": { + "context": ["conformance", "exchange", "blob"], + "field": "value", + "cases": [ + { + "id": "ada", + "value": { + "name": "Ada Lovelace", + "age": 36, + "tags": ["maths", "engines"], + "nickname": "ada" + } + }, + { + "id": "empty", + "value": { + "name": "", + "age": 0, + "tags": [], + "nickname": null + } + }, + { + "id": "unicode", + "value": { + "name": "Grüße, 世界 🌏", + "age": 4294967295, + "tags": ["ü", "世界", ""], + "nickname": "🌏" + } + } + ] + }, + "eql": { + "table": "profiles", + "fixture": "packages/eql/tests/encryption/fixtures/v4_rows.json", + "schema": "eql_v4" + } +} diff --git a/conformance/stack-encrypt/v1/eql-json-v1.cases.json b/conformance/stack-encrypt/v1/eql-json-v1.cases.json new file mode 100644 index 0000000000..2a5280ee80 --- /dev/null +++ b/conformance/stack-encrypt/v1/eql-json-v1.cases.json @@ -0,0 +1,214 @@ +{ + "version": 1, + "profile": "eql-json-v1", + "documents": [ + "{\"name\":\"Alice\",\"age\":34,\"visits\":[{\"at\":3},{\"at\":1}]}", + "{\"name\":\"Alice\",\"age\":34,\"visits\":[{\"at\":3,\"where\":\"x\"},{\"at\":1}],\"tags\":[\"a\",\"b\"]}", + "{\"name\":\"Bob\",\"age\":7.5,\"nested\":{\"deep\":[[1,2],{}]},\"none\":null}", + "[1,\"two\",{\"three\":3}]", + "\"a scalar root\"", + "18446744073709551615", + "-9223372036854775808", + "-926809.5051008083", + "null", + "{}", + "[]" + ], + "invalid_documents": [ + { + "text": "{\"secret\":1,\"secret\":2}", + "reason": "json_duplicate_key" + }, + { + "text": "99999999999999999999", + "reason": "json_integer_range" + }, + { + "text": "{\"secret\":", + "reason": "json_syntax" + }, + { + "text": "", + "reason": "json_syntax" + } + ], + "predicate_refusals": [ + { + "id": "text-the-grammar-does-not-read", + "predicate": "$.extra.country = $v", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_syntax", + "construct": "text the grammar does not read", + "at": 16, + "at_text": "= $v" + }, + { + "id": "like-regex", + "predicate": "$.extra.country like_regex \"secret\"", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unsupported", + "construct": "`like_regex`", + "at": 16, + "at_text": "like_regex \"secret\"" + }, + { + "id": "arithmetic", + "predicate": "$.weight + 1 == 2", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unsupported", + "construct": "arithmetic (`+`, `-`, `*`, `/`, `%`)", + "at": 9, + "at_text": "+ 1 == 2" + }, + { + "id": "a-method", + "predicate": "$.weight.size() == 1", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unsupported", + "construct": "a method (`.name()`)", + "at": 8, + "at_text": ".size() == 1" + }, + { + "id": "a-filter-outside-exists", + "predicate": "$.extra.preferred_languages[*] ? (@ == $v) == 1", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unsupported", + "construct": "a filter outside `exists`", + "at": 31, + "at_text": "? (@ == $v) == 1" + }, + { + "id": "in-a-filter", + "predicate": "exists($.extra.emergency_contacts[*] ? (@.relationship == $v || @.age > 1))", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unsupported", + "construct": "`||` in a filter", + "at": 61, + "at_text": "|| @.age > 1))" + }, + { + "id": "an-unknown-variable", + "predicate": "$.extra.country == $missing", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_unknown_variable", + "construct": "a variable", + "at": 19, + "at_text": "$missing" + }, + { + "id": "a-value-an-ordering-cannot-take", + "predicate": "$.weight < $flag", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_value_type", + "construct": "a value", + "at": 11, + "at_text": "$flag" + }, + { + "id": "an-object", + "predicate": "$.extra.country == $obj", + "vars": { + "obj": { + "secret-nz": 1 + } + }, + "reason": "json_predicate_value_type", + "construct": "a value", + "at": 19, + "at_text": "$obj" + }, + { + "id": "at-a-wildcard", + "predicate": "$.extra.preferred_languages[*] != $v", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_predicate_not_equal_at_wildcard", + "construct": "`!=` at a path with a wildcard", + "at": 31, + "at_text": "!= $v" + }, + { + "id": "a-position", + "predicate": "$.extra.preferred_languages[2] == $v", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_path_position", + "construct": "a position (`[2]`)", + "at": 27, + "at_text": "[2] == $v" + }, + { + "id": "a-filter-with-no-wildcard", + "predicate": "exists($.address ? (@.postcode == $v))", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_path_no_wildcard", + "construct": "a filter on a path with no wildcard", + "at": 7, + "at_text": "$.address ? (@.postcode == $v))" + }, + { + "id": "a-wildcard-in-a-member", + "predicate": "exists($.extra.emergency_contacts[*] ? (@.calls[*] == $v))", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_path_wildcard", + "construct": "a wildcard in a filter's member", + "at": 40, + "at_text": "@.calls[*] == $v))" + }, + { + "id": "a-number-json-cannot-hold", + "predicate": "$.weight == 1e999", + "vars": { + "v": "secret-nz", + "flag": true + }, + "reason": "json_syntax", + "construct": "a value", + "at": 12, + "at_text": "1e999" + }, + { + "id": "too-deep", + "predicate": "((((((((((((((((((((((((((((((((($.a == 1)))))))))))))))))))))))))))))))))", + "reason": "json_predicate_too_deep", + "construct": "nesting", + "at": 33, + "at_text": "$.a == 1)))))))))))))))))))))))))))))))))" + } + ] +} diff --git a/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json b/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json new file mode 100644 index 0000000000..54109d735a --- /dev/null +++ b/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json @@ -0,0 +1,296 @@ +{ + "version": 1, + "profile": "eql-json-v1", + "suites": { + "engine-queries": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "binary": "json_operators", + "features": ["--all-features"] + }, + "engine-reads": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "binary": "json_read_checks", + "features": ["--all-features"] + }, + "engine-vectors": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "binary": "json_tree_vectors", + "features": ["--all-features"] + }, + "eql-targets": { + "language": "rust", + "lane": "fast", + "workspace": "packages/eql", + "package": "eql-encryption-tests", + "binary": "targets", + "features": [] + }, + "eql-record": { + "language": "rust", + "lane": "fast", + "workspace": "packages/eql", + "package": "eql-encryption-tests", + "binary": "json_tree_data_plan", + "features": [] + }, + "eql-typed": { + "language": "rust", + "lane": "fast", + "workspace": "packages/eql", + "package": "eql-encryption-tests", + "binary": "json_tree", + "features": [] + }, + "postgres": { + "language": "rust", + "lane": "postgres", + "workspace": "packages/eql", + "package": "eql-encryption-tests", + "binary": "json_tree", + "features": [] + }, + "go": { + "language": "go", + "lane": "fast" + }, + "go-postgres": { + "language": "go", + "lane": "postgres" + } + }, + "requirements": [ + { + "id": "eql-resolver-catalog-v1", + "evidence": { + "eql-targets": [ + "the_table::names_every_stored_catalog_domain_in_order", + "the_table::every_row_is_a_compiled_domain_type_and_so_is_its_query", + "the_table::the_producible_types_are_the_ones_with_a_rust_plaintext", + "given_an_unknown_name::every_entry_point_says_no_such_type", + "given_an_unknown_name::the_name_is_refused_before_the_label_or_the_value_is_read" + ], + "eql-record": [ + "the_engine_and_the_table_agree_on_which_targets_take_json_options" + ], + "go": [ + "TestTheCatalogListsEachTypesOperators", + "TestTextEqIsRefusedByTheBuildWithoutEQLTypes", + "TestTargetWithoutEQLIsRefusedBeforeTheGuest" + ] + } + }, + { + "id": "json-write-v1", + "evidence": { + "eql-record": [ + "a_batch_of_documents_round_trips_in_one_request", + "the_data_plan_and_the_typed_layout_agree", + "text_that_is_not_a_document_is_refused_before_any_key", + "a_sql_null_stores_no_document", + "a_document_does_not_open_under_another_column" + ], + "eql-typed": ["a_document_round_trips_through_the_typed_target"], + "engine-vectors": [ + "the_derivations_are_pinned_under_the_deterministic_source" + ], + "go": [ + "TestJSONDocumentsRoundTripThroughTheGuest", + "TestJSONDocumentsDoNotOpenUnderAnotherColumn", + "TestJSONTextThatIsNotADocumentIsErrEncoding", + "TestACustomersDocumentsRoundTrip", + "TestASubscribersTypedDocumentsRoundTrip" + ], + "go-postgres": ["TestJSONTypedDocumentsInPostgres"] + } + }, + { + "id": "json-query-v1", + "evidence": { + "eql-record": [ + "a_document_field_answers_the_json_operators", + "every_operand_is_in_the_eql_wire_form_and_finds_what_it_should", + "a_json_operator_refuses_what_it_cannot_answer", + "a_document_has_no_one_plaintext_query" + ], + "engine-queries": [ + "every_operator_derives_its_tagged_operand", + "the_orderings_follow_the_resolved_options", + "malformed_inputs_are_refused_with_their_reason" + ], + "eql-typed": [ + "the_query_operands_are_the_engines_terms_in_the_sql_contract" + ], + "go": [ + "TestJSONOperatorsDeriveTaggedTerms", + "TestACustomersFieldsDeriveEachQuery", + "TestASubscribersTypedNeedlesDeriveTheRawQuery" + ], + "postgres": [ + "postgres_containment_over_the_encrypted_column_is_jsonb_containment", + "generated::given_generated_documents_in_postgres::contains_selects_the_rows_jsonb_contains_on_both_plans", + "generated::given_generated_documents_in_postgres::contained_by_selects_the_rows_jsonb_does_except_a_root_scalar_in_a_root_array" + ], + "go-postgres": ["TestJSONDocumentsQueryAndReadInPostgres"] + } + }, + { + "id": "json-request-bound-reads-v1", + "evidence": { + "eql-record": ["reads_open_against_the_request_that_prepared_them"], + "engine-queries": [ + "reads_open_against_the_request_that_prepared_them", + "rows_that_are_not_the_reads_are_refused", + "a_malformed_read_is_refused_before_any_key" + ], + "engine-reads": [ + "given_the_entry_arrow_returned::another_paths_entry_is_refused_before_any_key_is_retrieved", + "given_the_rows_of_a_read::the_honest_rows_open_to_the_nodes_value_in_any_order", + "given_the_rows_of_a_read::another_position_of_the_array_is_refused_by_its_label", + "given_the_rows_of_a_read::a_truncated_subtree_is_refused_by_the_cascade", + "given_the_rows_of_a_read::rows_of_two_documents_are_refused", + "given_answers_the_check_cannot_tell_apart::rows_withheld_whole_read_as_no_node", + "given_answers_the_check_cannot_tell_apart::another_rows_node_at_the_same_path_opens" + ], + "go": [ + "TestJSONSelectorReadsOpenAgainstTheirRequest", + "TestJSONReadTypesPrintAndLogRedacted" + ], + "postgres": [ + "postgres_every_subtree_read_answers_as_jsonb_does", + "postgres_wildcard_reads_answer_as_jsonb_path_query", + "postgres_a_position_reaches_array_elements_only", + "postgres_hostile_answers_are_refused_by_the_client", + "postgres_reads_never_answer_wrongly_under_tampering", + "generated::given_generated_documents_in_postgres::arrow_opens_a_leaf_to_the_value_jsonb_holds" + ] + } + }, + { + "id": "json-element-match-v1", + "evidence": { + "engine-queries": [ + "element_match::given_documents::one_element_must_satisfy_every_member", + "element_match::given_documents::answers_as_the_jsonpath_over_the_plaintext", + "element_match::given_the_fields_type::does_not_answer_it_when_the_type_names_no_domain", + "element_match::given_the_fields_type::does_not_list_it_without_an_ordered_path" + ], + "go": [ + "TestElementMatchIsTheReadsAndTheOrderingsOfEachMember", + "TestElementMatchRefusesBeforeTheEngine", + "TestElementMatchEngineRefusalsAreTypedErrors", + "TestAtPathMakesThePredicatesOfItsMember" + ], + "postgres": [ + "elements::postgres_an_element_predicate_holds_of_one_element", + "elements::postgres_one_element_must_satisfy_every_member", + "elements::postgres_a_probe_hit_raises", + "elements::postgres_the_elements_operand_domain_checks_each_member" + ], + "go-postgres": ["TestJSONElementMatchInPostgres"] + } + }, + { + "id": "json-predicate-match-v1", + "evidence": { + "engine-queries": [ + "compiled_match::given_an_input_it_cannot_answer::shared_predicate_refusals", + "compiled_match::given_documents::unknown_null_and_absent_answer_as_jsonpath_does", + "compiled_match::given_the_fields_type::does_not_answer_it_when_the_type_names_no_domain", + "compiled_match::given_a_predicate::each_leaf_is_its_operators_operand" + ], + "go": [ + "TestMatchCompilesToTheOperandsOfTheOtherOperators", + "TestMatchTakesItsVarsAsAnyJSONObject", + "TestMatchRefusalsNameTheConstructAndItsOffset", + "TestMatchOperandPrintsAndLogsRedacted" + ], + "postgres": [ + "predicate::postgres_a_compiled_predicate_answers_as_jsonb_path_match", + "predicate::postgres_a_compiled_predicate_answers_as_the_operators_written_out", + "predicate::postgres_a_null_leaf_is_unknown_under_and_or_and_not", + "predicate::postgres_the_predicate_domain_checks_each_node", + "predicate::postgres_the_operator_takes_a_typed_predicate_and_jsonpath_stays_blocked" + ], + "go-postgres": ["TestJSONPredicateMatchInPostgres"] + } + }, + { + "id": "json-extraction-v1", + "evidence": { + "engine-reads": [ + "given_the_entry_arrow_returned::the_entry_at_the_path_opens_to_its_scalar" + ], + "go": ["TestJSONSelectorReadsOpenAgainstTheirRequest"], + "postgres": [ + "generated::given_generated_documents_in_postgres::arrow_opens_a_leaf_to_the_value_jsonb_holds" + ] + } + }, + { + "id": "json-subtree-v1", + "evidence": { + "eql-record": ["reads_open_against_the_request_that_prepared_them"], + "engine-reads": [ + "given_the_rows_of_a_read::the_honest_rows_open_to_the_nodes_value_in_any_order" + ], + "postgres": [ + "postgres_every_subtree_read_answers_as_jsonb_does", + "postgres_wildcard_reads_answer_as_jsonb_path_query" + ], + "go-postgres": ["TestJSONDocumentsQueryAndReadInPostgres"] + } + }, + { + "id": "json-child-v1", + "evidence": { + "engine-reads": [ + "given_one_child_of_a_node::each_leaf_member_opens_to_its_key_and_value", + "given_one_child_of_a_node::each_element_opens_to_its_index_and_value_in_position_order", + "given_one_child_of_a_node::a_child_of_another_node_is_refused_by_its_selector", + "given_one_child_of_a_node::an_element_read_as_another_position_is_refused", + "given_one_child_of_a_node::a_member_under_the_element_rule_is_refused_by_its_label", + "given_one_child_of_a_node::a_row_at_another_depth_is_refused", + "given_one_child_of_a_node::a_chain_head_is_refused_before_any_key_is_retrieved", + "given_one_child_of_a_node::a_key_with_a_wildcard_is_refused_before_any_key_is_retrieved" + ], + "engine-queries": [ + "a_child_opens_against_the_parent_its_request_names", + "a_malformed_read_is_refused_before_any_key" + ], + "eql-typed": ["a_child_opens_through_the_key_of_its_parent"], + "postgres": ["postgres_each_child_opens_against_its_parent"], + "go": [ + "TestJSONChildrenOpenAgainstTheirParent", + "TestTheReadOperatorsAreTheOnesTheEngineOpens", + "TestACustomersDocumentReadsThroughACipherWithABinding", + "TestAnOlderGeneratedChildrenTokenIsAQueryOperand", + "TestJSONReadTypesPrintAndLogRedacted" + ], + "go-postgres": ["TestJSONDocumentsQueryAndReadInPostgres"] + } + }, + { + "id": "json-tamper-v1", + "evidence": { + "engine-reads": [ + "given_the_rows_of_a_read::a_truncated_subtree_is_refused_by_the_cascade", + "given_the_rows_of_a_read::rows_of_two_documents_are_refused" + ], + "postgres": [ + "postgres_hostile_answers_are_refused_by_the_client", + "postgres_reads_never_answer_wrongly_under_tampering" + ], + "go": ["TestJSONDocumentsDoNotOpenUnderAnotherColumn"] + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/fixture-enrollment.json b/conformance/stack-encrypt/v1/fixture-enrollment.json new file mode 100644 index 0000000000..6b50bd450a --- /dev/null +++ b/conformance/stack-encrypt/v1/fixture-enrollment.json @@ -0,0 +1,106 @@ +{ + "version": 1, + "profiles": [ + { + "id": "record-value-kinds-v1", + "fixture": "packages/stack-encrypt/tests/fixtures/value_kinds.json", + "rust_binary": "value_kinds", + "go_source": "languages/golang/encrypt/value_kinds_test.go", + "requirements": [ + { + "id": "values.typed-frames", + "rust_tests": [ + "the_committed_fixture_opens_and_its_terms_are_todays" + ], + "go_tests": ["TestGeneratedCodeOpensTheRustValueKindsFixture"] + }, + { + "id": "values.frozen-open", + "rust_tests": [ + "the_committed_fixture_opens_and_its_terms_are_todays" + ], + "go_tests": ["TestGeneratedCodeOpensTheRustValueKindsFixture"] + }, + { + "id": "values.stored-terms", + "rust_tests": [ + "every_new_kind_seals_opens_and_queries_as_the_typed_path", + "the_committed_fixture_opens_and_its_terms_are_todays" + ], + "go_tests": ["TestGeneratedCodeOpensTheRustValueKindsFixture"] + }, + { + "id": "values.normalized-queries", + "rust_tests": [ + "every_new_kind_seals_opens_and_queries_as_the_typed_path", + "the_committed_fixture_opens_and_its_terms_are_todays" + ], + "go_tests": ["TestGeneratedCodeOpensTheRustValueKindsFixture"] + } + ] + }, + { + "id": "record-query-operators-v1", + "fixture": "packages/stack-encrypt/tests/fixtures/query_operators.json", + "rust_binary": "query_operators", + "go_source": "languages/golang/encrypt/query_test.go", + "requirements": [ + { + "id": "queries.term-contract", + "rust_tests": [ + "the_committed_query_fixture_is_what_the_engine_derives" + ], + "go_tests": [ + "TestQueryTermsAreTheRustFixtures", + "TestGeneratedQueriesAreTheRustFixtures" + ] + }, + { + "id": "queries.match-verification", + "rust_tests": [ + "the_committed_query_fixture_is_what_the_engine_derives", + "the_fixture_pins_both_outcomes" + ], + "go_tests": [ + "TestVerifyIsTheRustFixtures", + "TestAMatchesQueryVerifiesAndSizesAsTheRustFixtures" + ] + }, + { + "id": "queries.fetch-limits", + "rust_tests": [ + "the_committed_query_fixture_is_what_the_engine_derives", + "the_fixture_pins_both_outcomes" + ], + "go_tests": [ + "TestTargetLimitIsTheRustFixtures", + "TestAMatchesQueryVerifiesAndSizesAsTheRustFixtures" + ] + } + ] + }, + { + "id": "record-context-fields-v1", + "fixture": "packages/stack-encrypt/tests/fixtures/record_lowering.json", + "rust_binary": "record_lowering", + "go_source": "languages/golang/encrypt/context_field_test.go", + "requirements": [ + { + "id": "contexts.frozen-open", + "rust_tests": ["the_committed_context_field_case_opens_both_ways"], + "go_tests": ["TestGeneratedCodeOpensTheRustContextFieldFixture"] + }, + { + "id": "contexts.expectations", + "rust_tests": [ + "the_chain_and_the_lowering_agree_on_a_context_field_today" + ], + "go_tests": [ + "TestContextFieldSealsEachRowUnderItsOwnContext", + "TestContextFieldQueriesNameTheContext" + ] + } + ] + } + ] +} diff --git a/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json b/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json new file mode 100644 index 0000000000..3abbb42c36 --- /dev/null +++ b/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json @@ -0,0 +1,370 @@ +{ + "version": 1, + "profile": "lifecycle-v1", + "suites": { + "pending": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "lib": true + }, + "lifecycle": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "lifecycle_conformance" + }, + "heap": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "heap_hygiene", + "success_output": "immediate" + }, + "collections": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "collections" + }, + "owned-records": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "owned_records" + }, + "runtime": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "runtime_conformance" + }, + "reads": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "read_conformance" + }, + "contexts": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "context_conformance" + }, + "guest-abi": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-guest-abi", + "features": ["--all-features"], + "lib": true + }, + "kms": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-kms", + "features": ["--all-features"], + "lib": true + }, + "go": { + "language": "go", + "lane": "fast", + "package": "./encrypt" + }, + "go-memory": { + "language": "go", + "lane": "fast", + "package": "./internal/guest" + }, + "go-sdk": { + "language": "go", + "lane": "fast", + "package": "./encrypt/gensupport" + }, + "opaque": { + "language": "rust", + "lane": "fast", + "workspace": ".", + "package": "stack-encrypt", + "features": ["--all-features"], + "binary": "opaque_blob" + } + }, + "requirements": [ + { + "id": "lifecycle-ownership-v1", + "evidence": { + "lifecycle": [ + "dropping_unpolled_work_releases_captures_without_key_io", + "dropping_unpolled_decrypt_releases_captures_without_key_io", + "success_and_provider_failure_release_captures_once", + "dropping_an_unpolled_owned_column_releases_captures_without_key_io", + "an_owned_column_is_one_logical_batch_and_releases_captures_once" + ], + "pending": [ + "target::pending::tests::zipped_fulfilments_never_share_key_material" + ], + "go": [ + "TestClientKeyIsConsumedAndNeverPrinted", + "TestCloseStopsTheCleanup", + "TestUnreachableClientIsReleased", + "TestClosedClientIsState" + ], + "opaque": [ + "given_an_owned_source::is_wiped_before_a_pending_is_dropped_unpolled", + "given_an_owned_source::is_wiped_before_a_pending_is_awaited", + "given_an_owned_source::is_wiped_when_encoding_fails_and_no_key_is_requested", + "given_a_decrypted_blob::is_wiped_on_drop_and_into_inner_keeps_it_guarded" + ] + } + }, + { + "id": "lifecycle-cancellation-v1", + "evidence": { + "lifecycle": [ + "cancelling_in_flight_work_drops_provider_and_captures", + "cancelling_in_flight_decrypt_drops_provider_and_captures", + "cancelling_an_owned_column_in_flight_drops_provider_and_captures" + ], + "guest-abi": [ + "step::tests::an_aborted_operation_is_dropped_and_its_handle_spent", + "step::tests::the_wrong_number_of_responses_is_refused_and_drops_the_operation" + ], + "go": [ + "TestACallerThatGivesUpBetweenStepsAbortsTheOperation", + "TestACallWhoseContextHasEndedNeverStarts", + "TestACallCancelledDuringATokenFetchFailsOnlyItself", + "TestAStepThatRunsOnAfterItsContextEndsClosesTheClient", + "TestACallThatSucceedsAfterItsContextEndsFailsWithIt", + "TestAnAbortedInitLeavesNoKeyInGuestMemory" + ] + } + }, + { + "id": "lifecycle-partial-output-v1", + "evidence": { + "heap": [ + "a_late_read_type_failure_leaves_no_plaintext_on_the_heap", + "a_late_type_failure_in_an_owned_column_leaves_no_plaintext_on_the_heap", + "opaque_blob::an_opaque_blob_of_another_shape_leaves_no_plaintext_on_the_heap", + "opaque_blob::given_a_blob_refused_after_fields_are_built::the_fields_built_before_it_are_wiped", + "opaque_blob::given_a_blob_refused_after_fields_are_built::a_nested_field_and_whole_elements_built_before_it_are_wiped", + "json_plaintext::text_that_is_not_a_document_leaves_no_plaintext_on_the_heap" + ], + "collections": [ + "a_late_element_failure_wipes_the_plaintext_recovered_before_it", + "a_panicking_element_conversion_wipes_the_plaintext_recovered_before_it", + "a_late_element_failure_in_a_column_field_wipes_the_recovered_prefix" + ], + "owned-records": [ + "a_field_opened_before_a_later_field_is_refused_is_wiped" + ], + "opaque": [ + "given_a_decrypted_blob::a_field_read_before_a_refusal_is_wiped" + ], + "contexts": ["shared_context_boundaries"], + "go": [ + "TestContextBoundaries", + "TestInterruptedResponseBodyIsTransport", + "TestACallThatSucceedsAfterItsContextEndsFailsWithIt" + ], + "go-sdk": ["TestDecryptErrorsHoldNoPlaintext"] + } + }, + { + "id": "lifecycle-buffer-cleanup-v1", + "evidence": { + "heap": [ + "a_record_encrypted_from_a_value_frame_leaves_no_plaintext_on_the_heap", + "an_owned_column_encrypted_leaves_no_plaintext_on_the_heap", + "a_record_decrypted_with_a_nested_field_leaves_no_plaintext_on_the_heap", + "a_json_document_read_from_a_frame_leaves_no_plaintext_on_the_heap", + "the_spy_sees_an_unwiped_free", + "the_spy_sees_a_leaked_block", + "opaque_blob::an_opaque_blob_encrypted_leaves_no_plaintext_on_the_heap", + "opaque_blob::an_opaque_blob_decrypted_leaves_no_plaintext_on_the_heap", + "json_plaintext::a_json_plaintext_encrypted_leaves_no_plaintext_on_the_heap", + "json_plaintext::a_json_plaintext_decrypted_leaves_no_plaintext_on_the_heap" + ], + "collections": [ + "owned_elements_are_wiped_before_the_pending_is_returned", + "owned_elements_are_wiped_when_the_context_is_refused", + "owned_elements_are_guarded_during_context_conversion", + "a_panicking_element_declaration_wipes_the_elements_after_it" + ], + "owned-records": [ + "the_owned_record_wipes_sealed_fields_and_moves_passthrough_fields", + "the_owned_record_wipes_sealed_fields_when_the_context_is_refused", + "a_panicking_field_declaration_wipes_the_sealed_fields_after_it", + "a_declaration_that_panics_while_constructed_wipes_the_plaintext", + "a_record_decrypts_straight_into_a_protected_that_wipes_it_on_drop", + "a_sealed_field_is_not_leaked_when_the_scope_is_refused", + "a_nested_sealed_field_is_not_leaked_when_the_outer_scope_is_refused", + "a_plaintext_record_is_not_leaked_when_the_caller_context_is_refused", + "a_plaintext_record_is_not_leaked_when_the_stored_context_is_refused", + "a_sealed_column_is_not_leaked_when_the_scope_is_refused", + "a_stack_ciphertext_is_not_leaked_when_the_context_is_refused", + "a_vec_of_stack_ciphertext_is_not_leaked_when_the_context_is_refused", + "a_searchable_ciphertext_is_not_leaked_when_the_context_is_refused" + ], + "guest-abi": [ + "buffers::tests::wipe_all_leaves_no_live_buffer", + "last_error::tests::clearing_wipes_and_frees_the_registered_buffer", + "step::tests::pending_requests_are_handed_over_once_and_replaced_wiped", + "value::tests::text_is_wiped_on_drop" + ], + "go": [ + "TestRequestBodyWipesOnClose", + "TestRequestBodyOutlivesTheRoundTrip", + "TestARefusedRequestIsWiped", + "TestPlaintextDoesNotRemainInGuestMemory" + ], + "go-memory": [ + "TestHeapMemoryWipesWhatItAbandons", + "TestGuestMemoryIsFreedOnRuntimeClose", + "TestClientKeyIsOpaqueAndWipes", + "TestMemoryOutlivesACallClosedDuringAHostImport" + ] + } + }, + { + "id": "lifecycle-diagnostics-v1", + "evidence": { + "guest-abi": [ + "last_error::tests::a_foreign_cause_nobody_vouches_for_gives_no_message", + "call::tests::a_failure_never_reports_an_earlier_calls_error", + "call::tests::a_failure_then_a_success_leaves_nothing_to_hand_over" + ], + "go-sdk": [ + "TestDecryptErrorsHoldNoPlaintext", + "TestRedactedHidesSealedFieldsAndSortsShown", + "TestRedactedLogHidesSealedFields" + ], + "go-memory": [ + "TestAFailureCarriesItsDiagnostic", + "TestATrapFetchingTheDetailIsATrap" + ] + } + }, + { + "id": "lifecycle-validation-before-io-v1", + "evidence": { + "runtime": ["shared_record_runtime_profile"], + "reads": ["shared_record_read_profile"], + "pending": [ + "target::pending::tests::an_over_long_descriptor_is_refused_before_any_call", + "target::pending::tests::a_lazy_column_stops_building_after_a_local_failure" + ], + "go": [ + "TestRuntimeConformance", + "TestReadConformance", + "TestMismatchedPlanIsRefusedBeforeTheGuest" + ], + "opaque": [ + "given_an_owned_source::is_wiped_when_encoding_fails_and_no_key_is_requested", + "given_an_owned_source::is_wiped_when_the_context_is_refused", + "given_an_owned_source::the_context_is_refused_before_the_value_is_encoded", + "given_a_ciphertext_that_is_not_this_blob::a_tampered_ciphertext_fails_the_aead", + "given_a_ciphertext_that_is_not_this_blob::the_wrong_context_fails_the_aead", + "given_a_ciphertext_that_is_not_this_blob::a_blob_opened_as_a_string_is_the_wrong_type", + "given_a_ciphertext_that_is_not_this_blob::a_string_opened_as_a_blob_is_the_wrong_type", + "given_a_ciphertext_that_is_not_this_blob::bytes_that_are_not_a_profile_are_refused_by_class" + ] + } + }, + { + "id": "lifecycle-logical-batching-v1", + "evidence": { + "runtime": ["shared_record_runtime_profile"], + "lifecycle": [ + "an_owned_column_is_one_logical_batch_and_releases_captures_once", + "an_empty_owned_column_makes_no_provider_call" + ], + "pending": [ + "target::pending::tests::one_pending_asking_for_many_keys_is_one_call", + "target::pending::tests::all_merges_a_column_into_one_call_preserving_order", + "target::pending::tests::generate_and_retrieve_are_one_call_each", + "target::pending::tests::retrieves_group_by_keyset_and_return_in_request_order", + "target::pending::tests::all_of_nothing_resolves_empty_without_io", + "target::pending::tests::dispatch_forwards_each_requests_descriptor_in_order" + ] + } + }, + { + "id": "lifecycle-provider-chunks-v1", + "evidence": { + "kms": [ + "futures::tests::test_keeps_the_same_order", + "futures::tests::test_a_failing_chunk_fails_the_whole_call", + "futures::tests::test_works_when_chunks_dont_divide_nicely", + "futures::tests::concurrency_limit_bounds_chunks_and_drop_releases_them" + ] + } + } + ], + "limitations": [ + { + "id": "go-post-decrypt-shadow-stack", + "status": "known-gap", + "evidence": "languages/golang/encrypt/roundtrip_test.go::TestPlaintextDoesNotRemainInGuestMemoryAfterDecrypt" + }, + { + "id": "native-heap-observer-exclusions", + "status": "limited-observation", + "evidence": "packages/stack-encrypt/tests/heap_hygiene.rs" + }, + { + "id": "native-partial-decode-inside-whole-values", + "status": "known-gap", + "tracking": "#1754", + "cases": [ + "sequence-element", + "map", + "option", + "box", + "enum", + "deserialize-with-field", + "serde-transparent-struct", + "serde-from-struct", + "serde-try-from-struct", + "serde-flatten-struct", + "all-fields-deserialize-with-struct", + "hand-written-deserialize-without-in-place", + "sequence-regrown-past-1-mib" + ], + "evidence": [ + "packages/stack-encrypt/tests/heap_hygiene.rs::opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_inside_a_sequence_element_drops_what_the_element_built", + "packages/stack-encrypt/tests/heap_hygiene.rs::opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_in_a_struct_the_derive_reads_whole_drops_its_fields" + ] + }, + { + "id": "caller-owned-host-values", + "status": "outside-guarantee" + }, + { + "id": "live-provider-http-chunking", + "status": "not-observed" + }, + { + "id": "python-typescript-lifecycle", + "status": "not-enrolled" + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-bindings-v1.cases.json b/conformance/stack-encrypt/v1/record-bindings-v1.cases.json new file mode 100644 index 0000000000..064a3387d1 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-bindings-v1.cases.json @@ -0,0 +1,79 @@ +{ + "version": 1, + "profile": "record-bindings-v1", + "required_capabilities": [ + "composition", + "typed-extensions", + "bindings", + "frozen-open" + ], + "cases": [ + { + "id": "bind-row", + "label": "users", + "scopes": [], + "bind": [ + { + "type": "uint64", + "text": "9" + } + ] + }, + { + "id": "scope-then-bind", + "label": "users", + "scopes": [ + { + "type": "uint64", + "text": "42" + } + ], + "bind": [ + { + "type": "uint64", + "text": "9" + } + ] + }, + { + "id": "two-scopes-then-bind", + "label": "users", + "scopes": [ + { + "type": "uint64", + "text": "42" + }, + { + "type": "string", + "text": "eu" + } + ], + "bind": [ + { + "type": "bytes", + "text": "0102" + } + ] + }, + { + "id": "scope-then-two-binds", + "label": "tenants/acme", + "scopes": [ + { + "type": "int64", + "text": "-3" + } + ], + "bind": [ + { + "type": "uint64", + "text": "9" + }, + { + "type": "string", + "text": "row-a" + } + ] + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-bindings-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/record-bindings-v1.expected.rust-native.json new file mode 100644 index 0000000000..34651514b9 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-bindings-v1.expected.rust-native.json @@ -0,0 +1,31 @@ +{ + "version": 1, + "profile": "record-bindings-v1", + "producer": "rust-native", + "cases": { + "bind-row": { + "descriptor": "(users/text)/9u64", + "equality": "7cc383b27a53f75bd06bf941c370a09932a18a89ca0673f9bf00fb33e69c6310", + "ciphertext": "010000000000000000000000000000000096223155634bc8c5d219bc3eb34c73c520009d802d87ef86313ecd30ef6808a4965070a3a64193df36cb51ad183c4e139f2402e53fba89758f1c90e2e82c19e4e185dd172d44e7c23026233169997981b758a73277", + "contexts": "text\n query context: users / text\n stored context: (users / text) / 9u64\n" + }, + "scope-then-bind": { + "descriptor": "((users/text)/42u64)/9u64", + "equality": "3be6f2b8c1c1b96d008101a3e1cd90a7114001fa0cd73ed9c76867b4b402f772", + "ciphertext": "0100000000000000000000000000000000f9c0da3e24b68af03533cfba6a9a507e2000076185c49aa3f46d6a2b4658ce65fd558f6ba8cc57e3cc8f35c8d86d2816678e02120f210e87ac66b1482aa3901864447ff3ab943adc19bfcfdbfbbc5f224094e0c2d3", + "contexts": "text\n query context: (users / text) / 42u64\n stored context: ((users / text) / 42u64) / 9u64\n" + }, + "scope-then-two-binds": { + "descriptor": "(((tenants/acme/text)/18446744073709551613u64)/9u64)/row-a", + "equality": "f497f570e70d0de22160b1ec71fe3397ac79d715dd338e96dbfce8cbaedb039a", + "ciphertext": "010000000000000000000000000000000071c7ceaea40be16ca3e267d2f845e2df2000100b8c046189c664ee7236eb08363302107e960d5dffe304815489a0d9961c02023fa7bc75ace10e7b201f386fe90d382cedddeaa9050a138c588de8846cabd6864962", + "contexts": "text\n query context: (tenants / acme / text) / -3i64\n stored context: (((tenants / acme / text) / -3i64) / 9u64) / row-a\n" + }, + "two-scopes-then-bind": { + "descriptor": "(((users/text)/42u64)/eu)/b64:AQI=", + "equality": "62040e9c1194a8b7de427afa05baed8fbc944da6d1ad710f97d87073233aa1ee", + "ciphertext": "01000000000000000000000000000000003208155c8b6cda75a7cc6438736eb1ad2000198dfcb486d1accb1284b01fbd4b7ee89a08c946c0a77f72b7123736b0d1e57e0211195eba17603642be4b2cb04df15b68e453c9590e9ef4413ad29fbc5b46569d1656", + "contexts": "text\n query context: ((users / text) / 42u64) / eu\n stored context: (((users / text) / 42u64) / eu) / 0x0102\n" + } + } +} diff --git a/conformance/stack-encrypt/v1/record-context-boundaries-v1.cases.json b/conformance/stack-encrypt/v1/record-context-boundaries-v1.cases.json new file mode 100644 index 0000000000..e8e50457ad --- /dev/null +++ b/conformance/stack-encrypt/v1/record-context-boundaries-v1.cases.json @@ -0,0 +1,120 @@ +{ + "version": 1, + "profile": "record-context-boundaries-v1", + "cases": [ + { + "id": "unrestricted", + "tenants": ["tenants/acme", "tenants/globex"], + "expected": "", + "mutation": "none", + "outcome": "success", + "native_retrievals": 1 + }, + { + "id": "expected", + "tenants": ["tenants/acme"], + "expected": "tenants/acme", + "mutation": "none", + "outcome": "success", + "native_retrievals": 1 + }, + { + "id": "late-mismatch", + "tenants": ["tenants/acme", "tenants/globex"], + "expected": "tenants/acme", + "mutation": "none", + "outcome": "mismatch", + "native_retrievals": 0 + }, + { + "id": "empty", + "tenants": [], + "expected": "tenants/acme", + "mutation": "none", + "outcome": "success", + "native_retrievals": 0 + }, + { + "id": "tampered", + "tenants": ["tenants/acme"], + "expected": "", + "mutation": "tamper", + "outcome": "authentication", + "native_retrievals": 1 + }, + { + "id": "tampered-matching-expectation", + "tenants": ["tenants/acme"], + "expected": "tenants/globex", + "mutation": "tamper", + "outcome": "authentication", + "native_retrievals": 1 + }, + { + "id": "tampered-mismatching-expectation", + "tenants": ["tenants/acme"], + "expected": "tenants/acme", + "mutation": "tamper", + "outcome": "mismatch", + "native_retrievals": 0 + }, + { + "id": "late-missing", + "tenants": ["tenants/acme", "tenants/globex"], + "expected": "", + "mutation": "missing", + "outcome": "shape", + "native_retrievals": 0 + }, + { + "id": "late-empty", + "tenants": ["tenants/acme", "tenants/globex"], + "expected": "", + "mutation": "empty", + "outcome": "shape", + "native_retrievals": 0 + }, + { + "id": "late-tampered-context", + "tenants": ["tenants/acme", "tenants/acme"], + "expected": "", + "mutation": "tamper", + "outcome": "authentication", + "native_retrievals": 1 + }, + { + "id": "late-tampered-ciphertext", + "tenants": ["tenants/acme", "tenants/acme"], + "expected": "", + "mutation": "ciphertext", + "outcome": "aead", + "native_retrievals": 1 + } + ], + "queries": [ + { + "id": "query-missing", + "context": "", + "outcome": "refused", + "matches": false + }, + { + "id": "query-invalid", + "context": "tenants/(acme)", + "outcome": "refused", + "matches": false + }, + { + "id": "query-matching", + "context": "tenants/acme", + "outcome": "success", + "matches": true + }, + { + "id": "query-other-tenant", + "context": "tenants/globex", + "outcome": "success", + "matches": false + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-contexts-v1.cases.json b/conformance/stack-encrypt/v1/record-contexts-v1.cases.json new file mode 100644 index 0000000000..b7935d7a11 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-contexts-v1.cases.json @@ -0,0 +1,216 @@ +{ + "version": 1, + "profile": "record-contexts-v1", + "required_capabilities": [ + "composition", + "typed-extensions", + "context-fields", + "frozen-open" + ], + "cases": [ + { + "id": "literal-base", + "base": "literal", + "label": "tenants/acme", + "parts": [] + }, + { + "id": "literal-one", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "uint64", + "text": "7" + } + ] + }, + { + "id": "literal-ordered", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "uint64", + "text": "7" + }, + { + "type": "string", + "text": "eu" + } + ] + }, + { + "id": "literal-reversed", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "eu" + }, + { + "type": "uint64", + "text": "7" + } + ] + }, + { + "id": "literal-signed", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "int64", + "text": "7" + } + ] + }, + { + "id": "literal-narrow", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "int32", + "text": "7" + } + ] + }, + { + "id": "literal-text", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "eu" + } + ] + }, + { + "id": "literal-bytes", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "bytes", + "text": "6575" + } + ] + }, + { + "id": "literal-empty-part", + "base": "literal", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "" + } + ] + }, + { + "id": "field-base", + "base": "field", + "label": "tenants/acme", + "parts": [] + }, + { + "id": "field-one", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "uint64", + "text": "7" + } + ] + }, + { + "id": "field-ordered", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "uint64", + "text": "7" + }, + { + "type": "string", + "text": "eu" + } + ] + }, + { + "id": "field-reversed", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "eu" + }, + { + "type": "uint64", + "text": "7" + } + ] + }, + { + "id": "field-signed", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "int64", + "text": "7" + } + ] + }, + { + "id": "field-narrow", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "int32", + "text": "7" + } + ] + }, + { + "id": "field-text", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "eu" + } + ] + }, + { + "id": "field-bytes", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "bytes", + "text": "6575" + } + ] + }, + { + "id": "field-empty-part", + "base": "field", + "label": "tenants/acme", + "parts": [ + { + "type": "string", + "text": "" + } + ] + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-contexts-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/record-contexts-v1.expected.rust-native.json new file mode 100644 index 0000000000..1c4e3caeaa --- /dev/null +++ b/conformance/stack-encrypt/v1/record-contexts-v1.expected.rust-native.json @@ -0,0 +1,187 @@ +{ + "version": 1, + "profile": "record-contexts-v1", + "producer": "rust-native/stack-encrypt-0.3.0", + "cases": { + "field-base": { + "context_frame": "f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874", + "plan_context_frame": "f0010000000a0400000074657874", + "descriptor": "tenants/acme/text", + "aad": "0300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874", + "prf": "0300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874", + "ciphertext": "0100000000000000000000000000000000e42a8b64607989ab5b6197de58ff5f322000175d4e4987626d968634ab7dda022fdbc41dce31bf9183e729c1f562185b1752026381a93ccb7f4ab78332ccf0a241e7cf5ab0f945ef52d3872c6f93816414ffd16e2e", + "equality": "d07ccccb55205dbb5c69c80bd88c907496a18bbed9317f39d96a83f6fd308a85", + "contexts": "text\n context: {tenant: Label, from the plaintext} / text\n" + }, + "field-bytes": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740b020000006575", + "plan_context_frame": "f002000000f0010000000a04000000746578740b020000006575", + "descriptor": "(tenants/acme/text)/eu", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f763102000000000000006575", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f763102000000000000006575", + "ciphertext": "0100000000000000000000000000000000ab137bf75fe4fa4f42a20f099ff3a77f20001a726f50cba00da93aab760c6e038be772c928d0cf8a5877dcff2e9ecbafadfe02b84b04a6b87a71fc6ba792f280b53622b736ae89e7dc0d6cde1299c95bbb89dfbaca", + "equality": "df58c27184a7707a4735ac1afd925fa3be93689eb1fa26e615cc96e78107524e", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / 0x6575\n" + }, + "field-empty-part": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a00000000", + "plan_context_frame": "f002000000f0010000000a04000000746578740a00000000", + "descriptor": "(tenants/acme/text)/b64:", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874510000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310000000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874510000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310000000000000000", + "ciphertext": "01000000000000000000000000000000001c03b0987bb51494b2f64841124a60c12000deede8eb83519fef962190d1e9c7104f75ed87d19c0f221d7c85136429b3f4b7026b8ec3a804ecb5c863042ffeb07d684ca59e86d63836c9f2efa0f7620ca9c1a341ae", + "equality": "6562228f385c28b4762ff6bcb92057ecf739847f85fc18c4c9b917e96b240ad6", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / \"\"\n" + }, + "field-narrow": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740407000000", + "plan_context_frame": "f002000000f0010000000a04000000746578740407000000", + "descriptor": "(tenants/acme/text)/7u32", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6933322d6c652f7631040000000000000007000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6933322d6c652f7631040000000000000007000000", + "ciphertext": "0100000000000000000000000000000000d8767b62020fa04a135b492d4bed93e62000023c54cc52c80ba067235a64a801d702f3f558640fa9f80508c999afe98f7cbf025a6cd4058596d9fffb4062e68802de7f7d38161fd4a94b46ca782e838551d00fe978", + "equality": "a600febf5d31afa2e8fa9dfd0d47bbed76e2a6b69b3a26f3d9ba490d953c5c43", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / 7i32\n" + }, + "field-one": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874070700000000000000", + "plan_context_frame": "f002000000f0010000000a0400000074657874070700000000000000", + "descriptor": "(tenants/acme/text)/7u64", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "ciphertext": "01000000000000000000000000000000004216f7c1c404ef65c06bf83fab7d67b720009c0baa84274beb7ccb55fb28f343ab4ad12e6d00803b3955cb5bcf9e6ed2b51202c02bd3ad80ea172246e0863772168520d4b1853a302a60324a59e59ad0ad3309ac8b", + "equality": "ef4fd47818a5ec5b472f768bed2e28e9f3e0ef1bf86b95fb85b7d23208fb215a", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / 7u64\n" + }, + "field-ordered": { + "context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740707000000000000000a020000006575", + "plan_context_frame": "f002000000f002000000f0010000000a04000000746578740707000000000000000a020000006575", + "descriptor": "((tenants/acme/text)/7u64)/eu", + "aad": "02000000000000009501000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "prf": "02000000000000009501000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "ciphertext": "0100000000000000000000000000000000d25279cf7ce2862c0e1ead193d5a7698200054b497feda700c887e38cd921614aac2016a88eb2c367e4c0b72b5c6483f5b0c025dea0c112042c3c2250848f605cc28dfcc5a4320132aa6844434285115f3d854f233", + "equality": "ad34715d40cf4bb40e35830f19c01180c08ef0492d40febc9d3267cab1464562", + "contexts": "text\n context: (({tenant: Label, from the plaintext} / text) / 7u64) / eu\n" + }, + "field-reversed": { + "context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575070700000000000000", + "plan_context_frame": "f002000000f002000000f0010000000a04000000746578740a020000006575070700000000000000", + "descriptor": "((tenants/acme/text)/eu)/7u64", + "aad": "02000000000000008d01000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631020000000000000065755b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "prf": "02000000000000008d01000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631020000000000000065755b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "ciphertext": "01000000000000000000000000000000000682e6a8c346478d0bed4f633f9f591720001d0ee4f5786d90124b1bb4a56452173e72b1dbdb1837bb1761a3dc3ba04574600231c4dcbbf7882753f5172957e1b993631f9b544c33569957b086c69dcb974d62e81a", + "equality": "ac1ae266a8574b0a164b771046e0028bc290e4018c2e48ba351515dcf95a7801", + "contexts": "text\n context: (({tenant: Label, from the plaintext} / text) / eu) / 7u64\n" + }, + "field-signed": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874050700000000000000", + "plan_context_frame": "f002000000f0010000000a0400000074657874050700000000000000", + "descriptor": "(tenants/acme/text)/7u64", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6936342d6c652f763108000000000000000700000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6936342d6c652f763108000000000000000700000000000000", + "ciphertext": "0100000000000000000000000000000000e0fa052c95f14a1b6e95adbfc952cf6e2000ee4082d049338a812d8b10673453127da1fe6dcb665dea4c96da426f52df55bf02086f0e236e482460ac2b76c40f30262b6b60e95b44e326a1b15d794265607bbfd4fe", + "equality": "1bcd9b5f12c4218bbd584dce0bad0003138408cc312c1cc8bb69bc8861a8227e", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / 7i64\n" + }, + "field-text": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575", + "plan_context_frame": "f002000000f0010000000a04000000746578740a020000006575", + "descriptor": "(tenants/acme/text)/eu", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "ciphertext": "0100000000000000000000000000000000d21a6d4e940e4329994b30afc2a81cb12000203fb57f381e7ef64dc8ebe63bd33f546a772bedc94a624e4d47b6a6c5eb45f3020f027f94da60afe229858d4d0f895bd81b1c6a98ac487d706476c235f5667993d3b5", + "equality": "76f509a979f486b783f2d4f872a1913abff9f3ef66d7007b01e3cab3a734e270", + "contexts": "text\n context: ({tenant: Label, from the plaintext} / text) / eu\n" + }, + "literal-base": { + "context_frame": "f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874", + "plan_context_frame": "f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874", + "descriptor": "tenants/acme/text", + "aad": "0300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874", + "prf": "0300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874", + "ciphertext": "0100000000000000000000000000000000233bbec00515bcc147012024a94dda1d2000421022b5ace076acb43d72b4aa3de668968552535247283db06bed86af0def7302074af5c04457e03439ad74f82b13ec326d31140d9a57b83939d8b369c632faa287ac", + "equality": "d07ccccb55205dbb5c69c80bd88c907496a18bbed9317f39d96a83f6fd308a85", + "contexts": "text\n context: tenants / acme / text\n" + }, + "literal-bytes": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740b020000006575", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740b020000006575", + "descriptor": "(tenants/acme/text)/eu", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f763102000000000000006575", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f763102000000000000006575", + "ciphertext": "0100000000000000000000000000000000f992ac91510557386b3bcfcc26e9d45d2000f9ba6397d1be9552b633ffeef89249a1a3b28a1b2a58d4c2808de639001020ae02e004e95c6a5255f649eb536e13cd276d524277498e8743b11b4d83f577c96ca5d14d", + "equality": "df58c27184a7707a4735ac1afd925fa3be93689eb1fa26e615cc96e78107524e", + "contexts": "text\n context: (tenants / acme / text) / 0x6575\n" + }, + "literal-empty-part": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a00000000", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a00000000", + "descriptor": "(tenants/acme/text)/b64:", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874510000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310000000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874510000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310000000000000000", + "ciphertext": "010000000000000000000000000000000014850b0d9658afa82000b1c214375fd42000ea552a62dd1fdd018c2279f78de9f25c5283b33cd3d51fee029fb98da7e0c35a02f2b4d67aee14a89629bad47a417d4b615d9e28fa4f962c84ca9132079fca7298d5ff", + "equality": "6562228f385c28b4762ff6bcb92057ecf739847f85fc18c4c9b917e96b240ad6", + "contexts": "text\n context: (tenants / acme / text) / \"\"\n" + }, + "literal-narrow": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740407000000", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740407000000", + "descriptor": "(tenants/acme/text)/7u32", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6933322d6c652f7631040000000000000007000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6933322d6c652f7631040000000000000007000000", + "ciphertext": "010000000000000000000000000000000006c936cf0e7c4804593649d96a530f3e20008295873720d38723e2a83007f0cc80867629e97736b65d8da267e09028679ba10299667eadfabd7c2f5724cf571ba3dedc0b09e355b5d2067472e42e9795000249b5e3", + "equality": "a600febf5d31afa2e8fa9dfd0d47bbed76e2a6b69b3a26f3d9ba490d953c5c43", + "contexts": "text\n context: (tenants / acme / text) / 7i32\n" + }, + "literal-one": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874070700000000000000", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874070700000000000000", + "descriptor": "(tenants/acme/text)/7u64", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "ciphertext": "0100000000000000000000000000000000d4e2b614715887c3b0b8b7ec13c8854820008e13eaedd78736f2531e16737e2346916e314064927acfb970d613fb11c81ba10228de0f378f2963770c8c352ec03596d26bf437c142a964810319197a5590b5ec739d", + "equality": "ef4fd47818a5ec5b472f768bed2e28e9f3e0ef1bf86b95fb85b7d23208fb215a", + "contexts": "text\n context: (tenants / acme / text) / 7u64\n" + }, + "literal-ordered": { + "context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740707000000000000000a020000006575", + "plan_context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740707000000000000000a020000006575", + "descriptor": "((tenants/acme/text)/7u64)/eu", + "aad": "02000000000000009501000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "prf": "02000000000000009501000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "ciphertext": "0100000000000000000000000000000000127e42644c439f781b72f98a90a1d0282000d1df0e854edc5616954c06efdfc883277cb48bc41b10f03e96a58d6e43e9660d02d83471396f4c04e54f7bdef59b0b71f5c50ec7973f991bb810d6a2410e31ef6bc55b", + "equality": "ad34715d40cf4bb40e35830f19c01180c08ef0492d40febc9d3267cab1464562", + "contexts": "text\n context: ((tenants / acme / text) / 7u64) / eu\n" + }, + "literal-reversed": { + "context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575070700000000000000", + "plan_context_frame": "f002000000f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575070700000000000000", + "descriptor": "((tenants/acme/text)/eu)/7u64", + "aad": "02000000000000008d01000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631020000000000000065755b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "prf": "02000000000000008d01000000000000020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631020000000000000065755b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f7536342d6c652f763108000000000000000700000000000000", + "ciphertext": "01000000000000000000000000000000008b7f54275b6c8f7b0acf5eed3c74894420006442ff82abfe7e68dffd900ec2826f1bc9ed4ae95e55118ccb6914165f4bd07602652e8049bfc026f40aec74afeab88d200f3958a836c5204684fb7e291340c4f83f25", + "equality": "ac1ae266a8574b0a164b771046e0028bc290e4018c2e48ba351515dcf95a7801", + "contexts": "text\n context: ((tenants / acme / text) / eu) / 7u64\n" + }, + "literal-signed": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874050700000000000000", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a0400000074657874050700000000000000", + "descriptor": "(tenants/acme/text)/7u64", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6936342d6c652f763108000000000000000700000000000000", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310400000000000000746578745b0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311a00000000000000766974616d696e632f636f6e746578742f6936342d6c652f763108000000000000000700000000000000", + "ciphertext": "010000000000000000000000000000000096958fa4c5718b558f2a196c4c02b901200011ff26eaa183171680c1943ed6124393bd39aa8b86e3eaadeb381dce51cb4f39024faeb3dba085150fddb07663415702398e38f5ab7b26cbc38a71c0c99415ebcf3142", + "equality": "1bcd9b5f12c4218bbd584dce0bad0003138408cc312c1cc8bb69bc8861a8227e", + "contexts": "text\n context: (tenants / acme / text) / 7i64\n" + }, + "literal-text": { + "context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575", + "plan_context_frame": "f002000000f0030000000a0700000074656e616e74730a0400000061636d650a04000000746578740a020000006575", + "descriptor": "(tenants/acme/text)/eu", + "aad": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "prf": "020000000000000022010000000000000300000000000000580000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631070000000000000074656e616e7473550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000061636d65550000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f7631040000000000000074657874530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763102000000000000006575", + "ciphertext": "01000000000000000000000000000000006379fc33f72fe6d1aa66fcdd2f394c342000e66e4d1f85d1e763c0244e39e813e1efc0af0620b0c18d2224e5183f49fc1614027448ecf67f4decec63dfe369bd0d35df1e18f3cba422855414446103bcded9097906", + "equality": "76f509a979f486b783f2d4f872a1913abff9f3ef66d7007b01e3cab3a734e270", + "contexts": "text\n context: (tenants / acme / text) / eu\n" + } + } +} diff --git a/conformance/stack-encrypt/v1/record-declarations-v1.cases.json b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json new file mode 100644 index 0000000000..4367ba4fba --- /dev/null +++ b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json @@ -0,0 +1,3536 @@ +{ + "version": 1, + "profile": "record-declarations-v1", + "resolver": "none", + "cases": [ + { + "id": "ciphertext-untyped", + "input": { + "json": { "value": { "context": ["users", "value"], "outputs": ["c"] } } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "passthrough-untyped", + "input": { + "json": { + "value": { "context": ["users", "value"], "outputs": ["passthrough"] } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["passthrough"] + } + ] + } + }, + { + "id": "index-only", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["eq"], + "type": "int64" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "int64", + "null": null, + "outputs": ["eq"] + } + ] + } + }, + { + "id": "outputs-retain-order", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["ore", "c", "eq"], + "type": "int64" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "int64", + "null": null, + "outputs": ["ore", "c", "eq"] + } + ] + } + }, + { + "id": "unit-output-null-c", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "c": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "unit-output-null-passthrough", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "passthrough": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["passthrough"] + } + ] + } + }, + { + "id": "unit-output-null-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "eq": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["eq"] + } + ] + } + }, + { + "id": "unit-output-null-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "ore": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["ore"] + } + ] + } + }, + { + "id": "unit-output-null-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "ope": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["ope"] + } + ] + } + }, + { + "id": "unit-output-null-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "ore_block": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["ore_block"] + } + ] + } + }, + { + "id": "match-default-bare", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["match"], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["match"] + } + ] + } + }, + { + "id": "match-default-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": null }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["match"] + } + ] + } + }, + { + "id": "match-default-empty", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": {} }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["match"] + } + ] + } + }, + { + "id": "match-default-explicit", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [ + { + "match": { + "tokenizer": { "ngram": 3 }, + "downcase": true, + "short_words": false, + "k": 3, + "m": 256 + } + } + ], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": ["match"] + } + ] + } + }, + { + "id": "match-custom", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [ + { + "match": { + "tokenizer": "standard", + "downcase": false, + "k": 4, + "m": 512 + } + } + ], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": [ + { + "match": { + "tokenizer": "standard", + "downcase": false, + "k": 4, + "m": 512 + } + } + ] + } + ] + } + }, + { + "id": "tokenizer-standard-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "tokenizer": { "standard": null } } }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": [ + { + "match": { + "tokenizer": "standard", + "downcase": true, + "k": 3, + "m": 256 + } + } + ] + } + ] + } + }, + { + "id": "match-short-words", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "short_words": true } }], + "type": "string" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "string", + "null": null, + "outputs": [ + { + "match": { + "tokenizer": { "ngram": 3 }, + "downcase": true, + "short_words": true, + "k": 3, + "m": 256 + } + } + ] + } + ] + } + }, + { + "id": "extended-context", + "input": { + "json": { + "value": { + "context": [[["users", "value"], 7], "eu"], + "outputs": ["c"] + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [ + { "type": "uint64", "text": "7" }, + { "type": "string", "text": "eu" } + ], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "flat-label-is-not-extension", + "input": { + "json": { + "value": { "context": ["users", "region", "value"], "outputs": ["c"] } + } + }, + "accepted": true, + "normalized": { + "label": ["users", "region"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "region", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "sealed-null-equality", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int32", + "null": "sealed" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "int32", + "null": "sealed", + "outputs": ["c", "eq"] + } + ] + } + }, + { + "id": "sealed-null-bool", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "type": "bool", + "null": "sealed" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "bool", + "null": "sealed", + "outputs": ["c"] + } + ] + } + }, + { + "id": "sealed-null-uuid", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uuid", + "null": "sealed" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": "uuid", + "null": "sealed", + "outputs": ["c", "eq"] + } + ] + } + }, + { + "id": "sql-null-untyped", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "null": "sql" + } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": "sql", + "outputs": ["c"] + } + ] + } + }, + { + "id": "context-field-infers-string", + "input": { + "json": { + "context_field": "tenant", + "tenant": { "context": ["tenant"], "outputs": ["passthrough"] }, + "value": { "context": ["value"], "outputs": ["c"] } + } + }, + "accepted": true, + "normalized": { + "label": null, + "context_field": "tenant", + "extension": [], + "fields": [ + { + "name": "tenant", + "label": ["tenant"], + "type": "string", + "null": null, + "outputs": ["passthrough"] + }, + { + "name": "value", + "label": ["value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "type-bool-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "bool" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bool-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "bool" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bool-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "bool" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bool-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "bool" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bool-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "bool" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int8-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int8" + } + } + }, + "accepted": true + }, + { + "id": "type-int8-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "int8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int8-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int8-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "int8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int8-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "int8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int16-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int16" + } + } + }, + "accepted": true + }, + { + "id": "type-int16-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "int16" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int16-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int16" + } + } + }, + "accepted": true + }, + { + "id": "type-int16-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "int16" + } + } + }, + "accepted": true + }, + { + "id": "type-int16-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "int16" + } + } + }, + "accepted": true + }, + { + "id": "type-int32-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int32" + } + } + }, + "accepted": true + }, + { + "id": "type-int32-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "int32" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int32-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int32" + } + } + }, + "accepted": true + }, + { + "id": "type-int32-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "int32" + } + } + }, + "accepted": true + }, + { + "id": "type-int32-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "int32" + } + } + }, + "accepted": true + }, + { + "id": "type-int64-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int64" + } + } + }, + "accepted": true + }, + { + "id": "type-int64-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "int64" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int64-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int64" + } + } + }, + "accepted": true + }, + { + "id": "type-int64-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "int64" + } + } + }, + "accepted": true + }, + { + "id": "type-int64-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "int64" + } + } + }, + "accepted": true + }, + { + "id": "type-int128-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "int128" + } + } + }, + "accepted": true + }, + { + "id": "type-int128-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "int128" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-int128-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int128" + } + } + }, + "accepted": true + }, + { + "id": "type-int128-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "int128" + } + } + }, + "accepted": true + }, + { + "id": "type-int128-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "int128" + } + } + }, + "accepted": true + }, + { + "id": "type-uint8-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uint8" + } + } + }, + "accepted": true + }, + { + "id": "type-uint8-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uint8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint8-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uint8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint8-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uint8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint8-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uint8" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint16-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uint16" + } + } + }, + "accepted": true + }, + { + "id": "type-uint16-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uint16" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint16-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uint16" + } + } + }, + "accepted": true + }, + { + "id": "type-uint16-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uint16" + } + } + }, + "accepted": true + }, + { + "id": "type-uint16-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uint16" + } + } + }, + "accepted": true + }, + { + "id": "type-uint32-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uint32" + } + } + }, + "accepted": true + }, + { + "id": "type-uint32-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uint32" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint32-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uint32" + } + } + }, + "accepted": true + }, + { + "id": "type-uint32-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uint32" + } + } + }, + "accepted": true + }, + { + "id": "type-uint32-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uint32" + } + } + }, + "accepted": true + }, + { + "id": "type-uint64-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uint64" + } + } + }, + "accepted": true + }, + { + "id": "type-uint64-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uint64" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint64-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uint64" + } + } + }, + "accepted": true + }, + { + "id": "type-uint64-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uint64" + } + } + }, + "accepted": true + }, + { + "id": "type-uint64-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uint64" + } + } + }, + "accepted": true + }, + { + "id": "type-uint128-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uint128" + } + } + }, + "accepted": true + }, + { + "id": "type-uint128-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uint128" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uint128-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uint128" + } + } + }, + "accepted": true + }, + { + "id": "type-uint128-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uint128" + } + } + }, + "accepted": true + }, + { + "id": "type-uint128-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uint128" + } + } + }, + "accepted": true + }, + { + "id": "type-float32-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "float32" + } + } + }, + "accepted": true + }, + { + "id": "type-float32-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "float32" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-float32-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "float32" + } + } + }, + "accepted": true + }, + { + "id": "type-float32-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "float32" + } + } + }, + "accepted": true + }, + { + "id": "type-float32-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "float32" + } + } + }, + "accepted": true + }, + { + "id": "type-float64-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "float64" + } + } + }, + "accepted": true + }, + { + "id": "type-float64-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "float64" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-float64-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "float64" + } + } + }, + "accepted": true + }, + { + "id": "type-float64-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "float64" + } + } + }, + "accepted": true + }, + { + "id": "type-float64-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "float64" + } + } + }, + "accepted": true + }, + { + "id": "type-decimal-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "decimal" + } + } + }, + "accepted": true + }, + { + "id": "type-decimal-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "decimal" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-decimal-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "decimal" + } + } + }, + "accepted": true + }, + { + "id": "type-decimal-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "decimal" + } + } + }, + "accepted": true + }, + { + "id": "type-decimal-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "decimal" + } + } + }, + "accepted": true + }, + { + "id": "type-date-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "date" + } + } + }, + "accepted": true + }, + { + "id": "type-date-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "date" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-date-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "date" + } + } + }, + "accepted": true + }, + { + "id": "type-date-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "date" + } + } + }, + "accepted": true + }, + { + "id": "type-date-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "date" + } + } + }, + "accepted": true + }, + { + "id": "type-timestamp-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "timestamp" + } + } + }, + "accepted": true + }, + { + "id": "type-timestamp-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "timestamp" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-timestamp-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "timestamp" + } + } + }, + "accepted": true + }, + { + "id": "type-timestamp-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "timestamp" + } + } + }, + "accepted": true + }, + { + "id": "type-timestamp-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "timestamp" + } + } + }, + "accepted": true + }, + { + "id": "type-string-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "string" + } + } + }, + "accepted": true + }, + { + "id": "type-string-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "string" + } + } + }, + "accepted": true + }, + { + "id": "type-string-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "string" + } + } + }, + "accepted": true + }, + { + "id": "type-string-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "string" + } + } + }, + "accepted": true + }, + { + "id": "type-string-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "string" + } + } + }, + "accepted": true + }, + { + "id": "type-bytes-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "bytes" + } + } + }, + "accepted": true + }, + { + "id": "type-bytes-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "bytes" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bytes-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "bytes" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bytes-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "bytes" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-bytes-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "bytes" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uuid-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "uuid" + } + } + }, + "accepted": true + }, + { + "id": "type-uuid-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "uuid" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uuid-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "uuid" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uuid-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "uuid" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-uuid-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "uuid" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-array-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "array" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-array-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "array" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-array-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "array" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-array-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "array" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-array-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "array" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-object-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "object" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-object-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "object" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-object-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "object" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-object-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "object" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-object-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "object" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-json-eq", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "eq"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-json-match", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "match"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-json-ore", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-json-ope", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ope"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "type-json-ore_block", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore_block"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "index_not_admitted", "field": "value" } + } + }, + { + "id": "root-null", + "input": { "json": null }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_an_object", "found": "null" } + } + }, + { + "id": "root-list", + "input": { "json": [] }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_an_object", "found": "array" } + } + }, + { + "id": "empty-plan", + "input": { "json": {} }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "no_fields" } + } + }, + { + "id": "field-not-object", + "input": { "json": { "value": "x" } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "string" + } + } + }, + { + "id": "field-null", + "input": { "json": { "value": null } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "null" + } + } + }, + { + "id": "unknown-key", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "unknown": true + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_key", "field": "value" } + } + }, + { + "id": "missing-context", + "input": { "json": { "value": { "outputs": ["c"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "missing_context", "field": "value" } + } + }, + { + "id": "missing-outputs", + "input": { "json": { "value": { "context": ["users", "value"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "missing_outputs", "field": "value" } + } + }, + { + "id": "outputs-with-target", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "target": "TextEq" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "outputs_with_target", "field": "value" } + } + }, + { + "id": "outputs-string", + "input": { + "json": { "value": { "context": ["users", "value"], "outputs": "c" } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "outputs_not_list", "field": "value" } + } + }, + { + "id": "outputs-null", + "input": { + "json": { "value": { "context": ["users", "value"], "outputs": null } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "outputs_not_list", "field": "value" } + } + }, + { + "id": "outputs-empty", + "input": { + "json": { "value": { "context": ["users", "value"], "outputs": [] } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "no_outputs", "field": "value" } + } + }, + { + "id": "output-unknown", + "input": { + "json": { + "value": { "context": ["users", "value"], "outputs": ["wat"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "output-not-string", + "input": { + "json": { + "value": { "context": ["users", "value"], "outputs": [1] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "output-options-on-equality", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "eq": {} }], + "type": "int64" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "output-duplicate", + "input": { + "json": { + "value": { "context": ["users", "value"], "outputs": ["c", "c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "duplicate_output", "field": "value" } + } + }, + { + "id": "match-options-duplicate-key", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["match", { "match": {} }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "duplicate_output", "field": "value" } + } + }, + { + "id": "passthrough-with-ciphertext", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["passthrough", "c"] + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "passthrough_with_outputs", "field": "value" } + } + }, + { + "id": "passthrough-with-index", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["eq", "passthrough"] + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "passthrough_with_outputs", "field": "value" } + } + }, + { + "id": "type-unknown", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "type": "guid" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_type", "field": "value" } + } + }, + { + "id": "type-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "type": null + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_type", "field": "value" } + } + }, + { + "id": "type-json-without-target", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "json_needs_target", "field": "value" } + } + }, + { + "id": "json-output-pending", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["json"], + "type": "json" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "json_index_pending", "field": "value" } + } + }, + { + "id": "context-bare-label", + "input": { + "json": { "value": { "context": "users/value", "outputs": ["c"] } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "value" } + } + }, + { + "id": "context-one-segment", + "input": { + "json": { "value": { "context": ["value"], "outputs": ["c"] } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "value" } + } + }, + { + "id": "context-nested-extension", + "input": { + "json": { + "value": { + "context": [["users", "value"], ["tenant"]], + "outputs": ["c"] + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "value" } + } + }, + { + "id": "context-segment-slash", + "input": { + "json": { "value": { "context": ["users", "a/b"], "outputs": ["c"] } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "value" } + } + }, + { + "id": "context-segment-digit", + "input": { + "json": { "value": { "context": ["users", "9"], "outputs": ["c"] } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "value" } + } + }, + { + "id": "mixed-prefix", + "input": { + "json": { + "a": { "context": ["users", "a"], "outputs": ["c"] }, + "b": { "context": ["orders", "b"], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "mixed_contexts", "field": "b" } + } + }, + { + "id": "mixed-extension", + "input": { + "json": { + "a": { "context": [["users", "a"], 1], "outputs": ["c"] }, + "b": { "context": [["users", "b"], 2], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "mixed_contexts", "field": "b" } + } + }, + { + "id": "shared-identity", + "input": { + "json": { + "a": { "context": ["users", "same"], "outputs": ["c"] }, + "b": { "context": ["users", "same"], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "shared_identity", "field": "b" } + } + }, + { + "id": "context-field-null", + "input": { + "json": { + "context_field": null, + "value": { "context": ["users", "value"], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_field" } + } + }, + { + "id": "context-field-not-declared", + "input": { + "json": { + "context_field": "tenant", + "value": { "context": ["value"], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "no_such_field", "field": "tenant" } + } + }, + { + "id": "context-field-encrypted", + "input": { + "json": { + "context_field": "tenant", + "tenant": { "context": ["tenant"], "outputs": ["c"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_field", "field": "tenant" } + } + }, + { + "id": "context-field-static-label", + "input": { + "json": { + "context_field": "tenant", + "tenant": { + "context": ["users", "tenant"], + "outputs": ["passthrough"] + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "context_not_label", "field": "tenant" } + } + }, + { + "id": "null-mode-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "null": null + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_null", "field": "value" } + } + }, + { + "id": "null-mode-unknown", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "null": "optional" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_null", "field": "value" } + } + }, + { + "id": "null-passthrough", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["passthrough"], + "null": "sql" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "null_passthrough", "field": "value" } + } + }, + { + "id": "sealed-null-untyped", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "null": "sealed" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "sealed_null_type", "field": "value" } + } + }, + { + "id": "sealed-null-text", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c"], + "type": "string", + "null": "sealed" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "sealed_null_type", "field": "value" } + } + }, + { + "id": "sealed-null-order", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore"], + "type": "int64", + "null": "sealed" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "sealed_null_index", "field": "value" } + } + }, + { + "id": "target-null", + "input": { + "json": { "value": { "context": ["users", "value"], "target": null } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "target-empty", + "input": { + "json": { "value": { "context": ["users", "value"], "target": "" } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "target-number", + "input": { + "json": { "value": { "context": ["users", "value"], "target": 1 } } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "target-options-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "target": { "name": "TextEq", "options": null } + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "target-options-unknown", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "target": { "name": "JsonSearch", "options": { "wat": 1 } } + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "target-options-position", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "target": { + "name": "JsonSearch", + "options": { "ordered": ["$.a[0]"] } + } + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "invalid_target", "field": "value" } + } + }, + { + "id": "context-null", + "input": { "json": { "value": { "context": null, "outputs": ["c"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_context", + "fields": { "reason": "context_kind", "field": "value" } + } + }, + { + "id": "context-bool", + "input": { "json": { "value": { "context": true, "outputs": ["c"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_context", + "fields": { "reason": "context_kind", "field": "value" } + } + }, + { + "id": "context-float", + "input": { "json": { "value": { "context": 1.25, "outputs": ["c"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_context", + "fields": { "reason": "context_kind", "field": "value" } + } + }, + { + "id": "context-empty", + "input": { "json": { "value": { "context": [], "outputs": ["c"] } } }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_context", + "fields": { "reason": "empty_context", "field": "value" } + } + }, + { + "id": "untyped-index", + "input": { + "json": { + "value": { "context": ["users", "value"], "outputs": ["eq"] } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_untyped_index", + "fields": { "field": "value" } + } + }, + { + "id": "target-unavailable-name", + "input": { + "json": { + "value": { "context": ["users", "value"], "target": "TextEq" } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::target_none", + "fields": { "target": "TextEq" } + } + }, + { + "id": "target-unavailable-configured", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "target": { "name": "TextEq" } + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::target_none", + "fields": { "target": "TextEq" } + } + }, + { + "id": "target-unavailable-json-options", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "target": { + "name": "JsonSearch", + "options": { "sealed_root": false, "ordered": ["$.age", "$.age"] } + } + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::target_none", + "fields": { "target": "JsonSearch" } + } + }, + { + "id": "match-invalid-unknown", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "wat": 1 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-k-low", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "k": 2 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-k-high", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "k": 17 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-m-power", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "m": 100 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-m-low", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "m": 16 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-m-high", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "m": 131072 } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-ngram-zero", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "tokenizer": { "ngram": 0 } } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "two-order-indexes", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": ["c", "ore", "ope"], + "type": "uint32" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { + "reason": "overlapping_outputs", + "field": "value" + } + } + }, + { + "id": "match-invalid-short-standard", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [ + { "match": { "tokenizer": "standard", "short_words": true } } + ], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-short-small", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [ + { "match": { "tokenizer": { "ngram": 2 }, "short_words": true } } + ], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "match-invalid-downcase-null", + "input": { + "json": { + "value": { + "context": ["users", "value"], + "outputs": [{ "match": { "downcase": null } }], + "type": "string" + } + } + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "unknown_output", "field": "value" } + } + }, + { + "id": "typed-extension-int32", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f002000000f0020000000a0500000075736572730a0500000076616c75650407000000070000006f757470757473f0010000000a0100000063" + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [{ "type": "int32", "text": "7" }], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "typed-extension-int64", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f002000000f0020000000a0500000075736572730a0500000076616c7565050700000000000000070000006f757470757473f0010000000a0100000063" + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [{ "type": "int64", "text": "7" }], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "typed-extension-uint32", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f002000000f0020000000a0500000075736572730a0500000076616c75650607000000070000006f757470757473f0010000000a0100000063" + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [{ "type": "uint32", "text": "7" }], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "typed-extension-uint64", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f002000000f0020000000a0500000075736572730a0500000076616c7565070700000000000000070000006f757470757473f0010000000a0100000063" + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [{ "type": "uint64", "text": "7" }], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "typed-extension-int8", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f002000000f0020000000a0500000075736572730a0500000076616c75650c07070000006f757470757473f0010000000a0100000063" + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_context", + "fields": { "field": "value", "reason": "context_kind" } + } + }, + { + "id": "frame-empty", + "input": { "frame_hex": "" }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_a_frame" } + }, + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + } + }, + { + "id": "frame-invalid", + "input": { "frame_hex": "ff" }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_a_frame" } + }, + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + } + }, + { + "id": "frame-truncated", + "input": { "frame_hex": "f101" }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_a_frame" } + }, + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + } + }, + { + "id": "frame-duplicate-key", + "input": { + "frame_hex": "f1020000000500000076616c7565f10200000007000000636f6e74657874f0020000000a0500000075736572730a0500000076616c7565070000006f757470757473f0010000000a01000000630500000076616c7565f10200000007000000636f6e74657874f0020000000a0500000075736572730a0500000076616c7565070000006f757470757473f0010000000a0100000063" + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_a_frame" } + }, + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + } + }, + { + "id": "frame-trailing", + "input": { + "frame_hex": "f1010000000500000076616c7565f10200000007000000636f6e74657874f0020000000a0500000075736572730a0500000076616c7565070000006f757470757473f0010000000a010000006300" + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { "reason": "not_a_frame" } + }, + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + } + }, + { + "id": "frame-typed-null-spec", + "input": { + "frame_hex": "f1010000000500000076616c75651506000000" + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "null" + } + } + }, + { + "id": "frame-field-order", + "input": { + "frame_hex": "f102000000010000007af10200000007000000636f6e74657874f0020000000a0500000075736572730a010000007a070000006f757470757473f0010000000a01000000630100000061f10200000007000000636f6e74657874f0020000000a0500000075736572730a0100000061070000006f757470757473f0010000000a0100000063" + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "z", + "label": ["users", "z"], + "type": null, + "null": null, + "outputs": ["c"] + }, + { + "name": "a", + "label": ["users", "a"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "json-negative-zero", + "input": { + "json": { + "value": { "context": [["users", "value"], -0], "outputs": ["c"] } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [{ "type": "int64", "text": "0" }], + "fields": [ + { + "name": "value", + "label": ["users", "value"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + }, + { + "id": "json-lexical-field-order", + "input": { + "json": { + "zeta": { "context": ["users", "zeta"], "outputs": ["c"] }, + "alpha": { "context": ["users", "alpha"], "outputs": ["c"] } + } + }, + "accepted": true, + "normalized": { + "label": ["users"], + "context_field": null, + "extension": [], + "fields": [ + { + "name": "alpha", + "label": ["users", "alpha"], + "type": null, + "null": null, + "outputs": ["c"] + }, + { + "name": "zeta", + "label": ["users", "zeta"], + "type": null, + "null": null, + "outputs": ["c"] + } + ] + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-declarations-v1.inputs.go.json b/conformance/stack-encrypt/v1/record-declarations-v1.inputs.go.json new file mode 100644 index 0000000000..33ecb59c0b --- /dev/null +++ b/conformance/stack-encrypt/v1/record-declarations-v1.inputs.go.json @@ -0,0 +1,1610 @@ +{ + "version": 1, + "profile": "record-declarations-v1", + "runner": "go", + "cases": { + "ciphertext-untyped": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "index-only": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["eq"], + "Null": "" + } + ] + }, + "outputs-retain-order": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["ore", "c", "eq"], + "Null": "" + } + ] + }, + "match-default-bare": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["match"], + "Null": "" + } + ] + }, + "flat-label-is-not-extension": { + "Context": ["users", "region"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "sealed-null-equality": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "eq"], + "Null": "sealed" + } + ] + }, + "sealed-null-bool": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c"], + "Null": "sealed" + } + ] + }, + "sealed-null-uuid": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "eq"], + "Null": "sealed" + } + ] + }, + "sql-null-untyped": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c"], + "Null": "sql" + } + ] + }, + "type-bool-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-bool-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-bool-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-bool-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-bool-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bool", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-int8-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int8", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-int8-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int8", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-int8-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int8", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-int8-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int8", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-int8-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int8", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-int16-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int16", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-int16-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int16", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-int16-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int16", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-int16-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int16", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-int16-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int16", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-int32-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-int32-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-int32-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-int32-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-int32-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int32", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-int64-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-int64-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-int64-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-int64-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-int64-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-int128-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int128", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-int128-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int128", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-int128-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int128", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-int128-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int128", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-int128-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int128", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uint8-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint8", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uint8-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint8", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uint8-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint8", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uint8-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint8", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uint8-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint8", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uint16-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint16", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uint16-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint16", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uint16-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint16", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uint16-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint16", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uint16-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint16", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uint32-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint32", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uint32-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint32", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uint32-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint32", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uint32-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint32", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uint32-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint32", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uint64-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint64", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uint64-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint64", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uint64-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint64", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uint64-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint64", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uint64-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint64", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uint128-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint128", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uint128-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint128", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uint128-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint128", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uint128-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint128", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uint128-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uint128", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-float32-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float32", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-float32-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float32", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-float32-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float32", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-float32-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float32", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-float32-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float32", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-float64-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float64", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-float64-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float64", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-float64-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float64", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-float64-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float64", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-float64-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "float64", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-decimal-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "decimal", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-decimal-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "decimal", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-decimal-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "decimal", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-decimal-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "decimal", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-decimal-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "decimal", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-date-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "date", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-date-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "date", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-date-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "date", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-date-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "date", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-date-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "date", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-timestamp-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "timestamp", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-timestamp-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "timestamp", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-timestamp-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "timestamp", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-timestamp-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "timestamp", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-timestamp-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "timestamp", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-string-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-string-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-string-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-string-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-string-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-bytes-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bytes", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-bytes-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bytes", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-bytes-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bytes", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-bytes-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bytes", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-bytes-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "bytes", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-uuid-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-uuid-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-uuid-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-uuid-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-uuid-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "uuid", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-array-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "array", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-array-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "array", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-array-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "array", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-array-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "array", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-array-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "array", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-object-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "object", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-object-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "object", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-object-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "object", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-object-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "object", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-object-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "object", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "type-json-eq": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c", "eq"], + "Null": "" + } + ] + }, + "type-json-match": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c", "match"], + "Null": "" + } + ] + }, + "type-json-ore": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c", "ore"], + "Null": "" + } + ] + }, + "type-json-ope": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c", "ope"], + "Null": "" + } + ] + }, + "type-json-ore_block": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c", "ore_block"], + "Null": "" + } + ] + }, + "outputs-empty": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": [], + "Null": "" + } + ] + }, + "output-unknown": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["wat"], + "Null": "" + } + ] + }, + "output-duplicate": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c", "c"], + "Null": "" + } + ] + }, + "type-unknown": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "guid", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "type-json-without-target": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "json-output-pending": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "json", + "Outputs": ["json"], + "Null": "" + } + ] + }, + "context-segment-slash": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "a/b", + "Kind": "", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "context-segment-digit": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "9", + "Kind": "", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "shared-identity": { + "Context": ["users"], + "Fields": [ + { + "Name": "a", + "Identity": "same", + "Kind": "", + "Outputs": ["c"], + "Null": "" + }, + { + "Name": "b", + "Identity": "same", + "Kind": "", + "Outputs": ["c"], + "Null": "" + } + ] + }, + "null-mode-unknown": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c"], + "Null": "optional" + } + ] + }, + "sealed-null-untyped": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["c"], + "Null": "sealed" + } + ] + }, + "sealed-null-text": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "string", + "Outputs": ["c"], + "Null": "sealed" + } + ] + }, + "sealed-null-order": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "int64", + "Outputs": ["c", "ore"], + "Null": "sealed" + } + ] + }, + "untyped-index": { + "Context": ["users"], + "Fields": [ + { + "Name": "value", + "Identity": "value", + "Kind": "", + "Outputs": ["eq"], + "Null": "" + } + ] + } + } +} diff --git a/conformance/stack-encrypt/v1/record-query-refusals-v1.cases.json b/conformance/stack-encrypt/v1/record-query-refusals-v1.cases.json new file mode 100644 index 0000000000..d8da2e08e4 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-query-refusals-v1.cases.json @@ -0,0 +1,1648 @@ +{ + "version": 1, + "profile": "record-query-refusals-v1", + "required_capabilities": ["records", "query-errors", "term-errors"], + "fields": { + "email": { + "kind": "string", + "outputs": ["c", "eq"] + }, + "name": { + "kind": "string", + "outputs": ["c", "match"] + }, + "nickname": { + "kind": "string", + "outputs": ["c", "ore"] + }, + "title": { + "kind": "string", + "outputs": ["c", "ore_block"] + }, + "age": { + "kind": "uint32", + "outputs": ["c", "eq", "ore"] + }, + "score": { + "kind": "float64", + "outputs": ["c", "ore"] + }, + "big": { + "kind": "int128", + "outputs": ["c", "eq", "ope"] + }, + "flag": { + "kind": "bool", + "outputs": ["c"] + }, + "note": { + "kind": "string", + "outputs": ["c"] + }, + "sealed_age": { + "kind": "int64", + "outputs": ["c", "eq"], + "null": "sealed" + }, + "sql_age": { + "kind": "int64", + "outputs": ["c", "eq"], + "null": "sql" + }, + "data": { + "kind": "bytes", + "outputs": ["c", "eq"] + } + }, + "cases": [ + { + "id": "eq-on-match-only", + "field": "name", + "operator": "eq", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "matches-on-equality-only", + "field": "email", + "operator": "matches", + "input": { + "type": "string", + "text": "ali" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "eq-on-ciphertext-only", + "field": "note", + "operator": "eq", + "input": { + "type": "string", + "text": "x" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "eq-on-bool", + "field": "flag", + "operator": "eq", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "lt-on-equality-only", + "field": "email", + "operator": "lt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "matches-on-integer", + "field": "age", + "operator": "matches", + "input": { + "type": "string", + "text": "ali" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "age" + } + }, + { + "id": "eq-on-order-only", + "field": "score", + "operator": "eq", + "input": { + "type": "float64", + "text": "1.5" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "score" + } + }, + { + "id": "lte-on-match-only", + "field": "name", + "operator": "lte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "gte-on-ciphertext-only", + "field": "note", + "operator": "gte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "contains-on-integer", + "field": "age", + "operator": "contains", + "input": { + "type": "uint32", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "age" + } + }, + { + "id": "lt-on-bytes", + "field": "data", + "operator": "lt", + "input": { + "type": "bytes", + "text": "00" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "lte-on-equality-only", + "field": "email", + "operator": "lte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "gt-on-equality-only", + "field": "email", + "operator": "gt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "gte-on-equality-only", + "field": "email", + "operator": "gte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "between-on-equality-only", + "field": "email", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "email" + } + }, + { + "id": "lt-on-match-only", + "field": "name", + "operator": "lt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "gt-on-match-only", + "field": "name", + "operator": "gt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "gte-on-match-only", + "field": "name", + "operator": "gte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "between-on-match-only", + "field": "name", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "name" + } + }, + { + "id": "eq-on-ore-only", + "field": "nickname", + "operator": "eq", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "nickname" + } + }, + { + "id": "matches-on-ore-only", + "field": "nickname", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "nickname" + } + }, + { + "id": "eq-on-ore-block-only", + "field": "title", + "operator": "eq", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "title" + } + }, + { + "id": "matches-on-ore-block-only", + "field": "title", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "title" + } + }, + { + "id": "matches-on-order-only", + "field": "score", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "score" + } + }, + { + "id": "matches-on-ope", + "field": "big", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "big" + } + }, + { + "id": "lt-on-bool", + "field": "flag", + "operator": "lt", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "lte-on-bool", + "field": "flag", + "operator": "lte", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "gt-on-bool", + "field": "flag", + "operator": "gt", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "gte-on-bool", + "field": "flag", + "operator": "gte", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "between-on-bool", + "field": "flag", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "bool", + "text": "false" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "matches-on-bool", + "field": "flag", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "flag" + } + }, + { + "id": "lt-on-ciphertext-only", + "field": "note", + "operator": "lt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "lte-on-ciphertext-only", + "field": "note", + "operator": "lte", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "gt-on-ciphertext-only", + "field": "note", + "operator": "gt", + "input": { + "type": "string", + "text": "a" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "between-on-ciphertext-only", + "field": "note", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "matches-on-ciphertext-only", + "field": "note", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "note" + } + }, + { + "id": "lt-on-equality-only-integer", + "field": "sealed_age", + "operator": "lt", + "input": { + "type": "int64", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "lte-on-equality-only-integer", + "field": "sealed_age", + "operator": "lte", + "input": { + "type": "int64", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "gt-on-equality-only-integer", + "field": "sealed_age", + "operator": "gt", + "input": { + "type": "int64", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "gte-on-equality-only-integer", + "field": "sealed_age", + "operator": "gte", + "input": { + "type": "int64", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "between-on-equality-only-integer", + "field": "sealed_age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "int64", + "text": "2" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "matches-on-equality-only-integer", + "field": "sealed_age", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "sealed_age" + } + }, + { + "id": "lte-on-bytes", + "field": "data", + "operator": "lte", + "input": { + "type": "bytes", + "text": "00" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "gt-on-bytes", + "field": "data", + "operator": "gt", + "input": { + "type": "bytes", + "text": "00" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "gte-on-bytes", + "field": "data", + "operator": "gte", + "input": { + "type": "bytes", + "text": "00" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "between-on-bytes", + "field": "data", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "bytes", + "text": "00" + }, + { + "type": "bytes", + "text": "01" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "matches-on-bytes", + "field": "data", + "operator": "matches", + "input": { + "type": "string", + "text": "alice" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "operator_not_answered", + "field": "data" + } + }, + { + "id": "between-scalar", + "field": "age", + "operator": "between", + "input": { + "type": "uint32", + "text": "40" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "not_a_range", + "field": "age" + } + }, + { + "id": "between-one-bound", + "field": "age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "uint32", + "text": "1" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "not_a_range", + "field": "age" + } + }, + { + "id": "between-three-bounds", + "field": "age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "uint32", + "text": "1" + }, + { + "type": "uint32", + "text": "2" + }, + { + "type": "uint32", + "text": "3" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "not_a_range", + "field": "age" + } + }, + { + "id": "between-text", + "field": "age", + "operator": "between", + "input": { + "type": "string", + "text": "1-2" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "not_a_range", + "field": "age" + } + }, + { + "id": "lt-text-for-integer", + "field": "age", + "operator": "lt", + "input": { + "type": "string", + "text": "40" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "age" + } + }, + { + "id": "lt-fraction-for-integer", + "field": "age", + "operator": "lt", + "input": { + "type": "float64", + "text": "40.5" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "age" + } + }, + { + "id": "between-mixed-bounds", + "field": "age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "uint32", + "text": "1" + }, + { + "type": "string", + "text": "2" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "age" + } + }, + { + "id": "between-null-bound", + "field": "age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "null", + "text": "" + }, + { + "type": "uint32", + "text": "1" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "age" + } + }, + { + "id": "eq-negative-for-unsigned", + "field": "age", + "operator": "eq", + "input": { + "type": "int32", + "text": "-1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "age" + } + }, + { + "id": "eq-integer-for-text", + "field": "email", + "operator": "eq", + "input": { + "type": "int32", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "email" + } + }, + { + "id": "matches-integer", + "field": "name", + "operator": "matches", + "input": { + "type": "int32", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "name" + } + }, + { + "id": "eq-bool-for-integer", + "field": "big", + "operator": "eq", + "input": { + "type": "bool", + "text": "true" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "big" + } + }, + { + "id": "lt-fraction-for-int128", + "field": "big", + "operator": "lt", + "input": { + "type": "float64", + "text": "1.5" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "big" + } + }, + { + "id": "gte-text-for-int128", + "field": "big", + "operator": "gte", + "input": { + "type": "string", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "big" + } + }, + { + "id": "eq-null-required", + "field": "email", + "operator": "eq", + "input": { + "type": "null", + "text": "" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "email" + } + }, + { + "id": "eq-null-sql", + "field": "sql_age", + "operator": "eq", + "input": { + "type": "null", + "text": "" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "sql_age" + } + }, + { + "id": "lt-null-ordered", + "field": "age", + "operator": "lt", + "input": { + "type": "null", + "text": "" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "age" + } + }, + { + "id": "lte-null-ope", + "field": "big", + "operator": "lte", + "input": { + "type": "null", + "text": "" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "big" + } + }, + { + "id": "no-such-field", + "field": "phone", + "operator": "eq", + "input": { + "type": "string", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "plan", + "code": "stack_encrypt::dynamic_plan", + "reason": "no_such_field", + "field": "phone" + } + }, + { + "id": "unknown-operator", + "field": "age", + "operator": "like", + "input": { + "type": "uint32", + "text": "1" + }, + "accepted": false, + "expected_error": { + "class": "source", + "code": "stack_encrypt::dynamic_source", + "reason": "unknown_operator", + "field": "age" + } + }, + { + "id": "matches-too-short", + "field": "name", + "operator": "matches", + "input": { + "type": "string", + "text": "al" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::empty_term_text" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "matches-empty", + "field": "name", + "operator": "matches", + "input": { + "type": "string", + "text": "" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::empty_term_text" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "matches-separators", + "field": "name", + "operator": "matches", + "input": { + "type": "string", + "text": " " + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::empty_term_text" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "matches-unassigned", + "field": "name", + "operator": "matches", + "input": { + "type": "string", + "text": "͸abc" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::term_normalize" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "eq-unassigned", + "field": "email", + "operator": "eq", + "input": { + "type": "string", + "text": "a͸bc" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::term_normalize" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "lt-unassigned", + "field": "nickname", + "operator": "lt", + "input": { + "type": "string", + "text": "a͸" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::term_normalize" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "between-unassigned-high", + "field": "nickname", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "b͸" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::term_normalize" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "between-unassigned-low", + "field": "nickname", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a͸" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::term_normalize" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-too-long", + "field": "title", + "operator": "lt", + "input": { + "type": "string", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_too_long" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-trailing-nul", + "field": "title", + "operator": "gt", + "input": { + "type": "string", + "text": "a\u0000" + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_trailing_nul" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-between-nul-low", + "field": "title", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a\u0000" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_trailing_nul" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-between-long-high", + "field": "title", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_too_long" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-between-long-low", + "field": "title", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + { + "type": "string", + "text": "b" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_too_long" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "ore-block-between-nul-high", + "field": "title", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "string", + "text": "a" + }, + { + "type": "string", + "text": "b\u0000" + } + ] + }, + "accepted": false, + "expected_error": { + "class": "term", + "code": "stack_encrypt::ore_block_trailing_nul" + }, + "typed": { + "refusal": "before_keyset" + } + }, + { + "id": "inverted-range", + "field": "age", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "uint32", + "text": "65" + }, + { + "type": "uint32", + "text": "18" + } + ] + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "inverted-range-int128", + "field": "big", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "int128", + "text": "170141183460469231731687303715884105727" + }, + { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + } + ] + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "inverted-range-float64", + "field": "score", + "operator": "between", + "input": { + "type": "list", + "items": [ + { + "type": "float64", + "text": "1.5" + }, + { + "type": "float64", + "text": "-1.5" + } + ] + }, + "accepted": true + }, + { + "id": "ore-block-longest", + "field": "title", + "operator": "lt", + "input": { + "type": "string", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "ore-block-interior-nul", + "field": "title", + "operator": "lt", + "input": { + "type": "string", + "text": "a\u0000b" + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "ore-block-empty", + "field": "title", + "operator": "lt", + "input": { + "type": "string", + "text": "" + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "eq-null-sealed", + "field": "sealed_age", + "operator": "eq", + "input": { + "type": "null", + "text": "" + }, + "accepted": true + }, + { + "id": "matches-folded", + "field": "name", + "operator": "matches", + "input": { + "type": "string", + "text": "ALICE" + }, + "accepted": true, + "typed": { + "refusal": "none" + } + }, + { + "id": "eq-widened-int", + "field": "big", + "operator": "eq", + "input": { + "type": "int64", + "text": "5" + }, + "accepted": true + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json new file mode 100644 index 0000000000..e98211d458 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json @@ -0,0 +1,204 @@ +{ + "version": 1, + "profile": "record-raw-frames-v1", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "required_capabilities": [ + "records", + "raw-frames", + "read-shapes", + "authenticated-types" + ], + "boundary_error": { + "code": "stack_guest_abi::malformed_input", + "fields": {} + }, + "cases": [ + { + "id": "success-frozen-leaf", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ] + }, + { + "id": "authenticated-int64", + "read": { + "kind": "int64", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "authenticated", + "retrievals": 1, + "expected": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "expected": "int64", + "field": "value" + } + } + }, + { + "id": "authenticated-string", + "read": { + "kind": "string", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "authenticated", + "retrievals": 1, + "expected": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "expected": "string", + "field": "value" + } + } + }, + { + "id": "shape-c-passthrough", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c756504020000000100000063050422000000020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "shape", + "retrievals": 0, + "expected": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "passthrough" + } + } + }, + { + "id": "authenticated-c-empty-sequence", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006306650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "authenticated", + "retrievals": 1, + "expected": { + "code": "stack_encrypt::aead", + "fields": {} + } + }, + { + "id": "leaf-unknown-version", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301650000000900000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "leaf", + "retrievals": 0, + "expected": { + "code": "stack_encrypt::leaf_version", + "fields": { + "version": 9 + } + } + }, + { + "id": "leaf-truncated", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301020000000100020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "leaf", + "retrievals": 0, + "expected": { + "code": "stack_encrypt::leaf_truncated", + "fields": {} + } + }, + { + "id": "transport-repeated-field", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004020000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c0500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "transport", + "retrievals": 0, + "native_tree": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_repeated" + } + } + }, + { + "id": "transport-repeated-output", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650403000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "transport", + "retrievals": 0, + "native_tree": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "repeated_key" + } + } + }, + { + "id": "transport-retired-none-tag", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c7565040200000001000000630200000000020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "transport", + "retrievals": 0 + }, + { + "id": "transport-trailing-byte", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030100000004010000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c00", + "class": "transport", + "retrievals": 0 + }, + { + "id": "transport-truncated-count", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "030200000004010000000500000076616c75650402000000010000006301650000000100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923020000006571050b20000000d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c", + "class": "transport", + "retrievals": 0 + }, + { + "id": "transport-not-a-tree", + "read": { + "kind": "int32", + "null": "" + }, + "frame_hex": "ff", + "class": "transport", + "retrievals": 0 + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-reads-v1.cases.json b/conformance/stack-encrypt/v1/record-reads-v1.cases.json new file mode 100644 index 0000000000..b0df0808b8 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-reads-v1.cases.json @@ -0,0 +1,1136 @@ +{ + "version": 1, + "profile": "record-reads-v1", + "required_capabilities": [ + "records", + "read-shapes", + "authenticated-types", + "context-preflight" + ], + "cases": [ + { + "id": "missing-field", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "drop_value", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + { + "id": "missing-ciphertext", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "drop_c", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "no_ciphertext_node" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "no_ciphertext_node" + } + } + }, + { + "id": "field-not-map", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "field_plain", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "outputs_not_map" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "outputs_not_map" + } + } + }, + { + "id": "plaintext-under-c", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "c_plain", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "passthrough" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "passthrough" + } + } + }, + { + "id": "row-not-map", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "row_plain", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "row": 0, + "found": "passthrough" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "row": 0, + "found": "passthrough" + } + } + }, + { + "id": "late-missing-field", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "1" + } + }, + { + "value": { + "type": "int32", + "text": "2" + } + } + ], + "mutation": { + "kind": "drop_value", + "row": 1 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + { + "id": "read-none", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ] + } + }, + { + "id": "read-drop-eq", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "drop_eq", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ] + } + }, + { + "id": "read-extra-output", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "extra_output", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ] + } + }, + { + "id": "read-extra-field", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "extra_field", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ] + } + }, + { + "id": "authenticated-int32-as-int64", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int64", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "authenticated", + "retrievals": 1, + "error": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "field": "value", + "expected": "int64" + } + } + } + }, + { + "id": "authenticated-int32-as-string", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "string", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "authenticated", + "retrievals": 1, + "error": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "field": "value", + "expected": "string" + } + } + } + }, + { + "id": "authenticated-int32-as-uint64", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "uint64", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "authenticated", + "retrievals": 1, + "error": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "field": "value", + "expected": "uint64" + } + } + } + }, + { + "id": "authenticated-null-as-required", + "write": { + "kind": "int32", + "null": "sealed" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "authenticated", + "retrievals": 1, + "error": { + "code": "stack_encrypt::plan_field_type", + "fields": { + "field": "value", + "expected": "int32" + } + } + } + }, + { + "id": "authenticated-null-as-sql", + "write": { + "kind": "int32", + "null": "sealed" + }, + "read": { + "kind": "int32", + "null": "sql" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ] + } + }, + { + "id": "sql-absent-read", + "write": { + "kind": "int32", + "null": "sql" + }, + "read": { + "kind": "int32", + "null": "sql" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 0, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ] + } + }, + { + "id": "sql-absent-as-required", + "write": { + "kind": "int32", + "null": "sql" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + { + "id": "sql-absent-as-sealed", + "write": { + "kind": "int32", + "null": "sql" + }, + "read": { + "kind": "int32", + "null": "sealed" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "value", + "reason": "field_missing" + } + } + }, + { + "id": "context-unrestricted", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ] + } + }, + { + "id": "context-expected", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ] + }, + "expected_context": "tenants/acme" + }, + { + "id": "context-mismatch", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "preflight", + "retrievals": 0, + "error": { + "code": "stack_encrypt::context_mismatch", + "fields": { + "stored_len": 12, + "stored_parts": 2 + } + } + }, + "expected_context": "tenants/other", + "check_error": { + "code": "stack_encrypt::context_mismatch", + "fields": { + "stored_len": 12, + "stored_parts": 2 + } + } + }, + { + "id": "context-late-mismatch", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "1" + } + }, + { + "tenant": { + "type": "string", + "text": "tenants/other" + }, + "value": { + "type": "int32", + "text": "2" + } + } + ], + "mutation": { + "kind": "none", + "row": 1 + }, + "adapter": true, + "expected": { + "stage": "preflight", + "retrievals": 0, + "error": { + "code": "stack_encrypt::context_mismatch", + "fields": { + "stored_len": 13, + "stored_parts": 2 + } + } + }, + "expected_context": "tenants/acme", + "check_error": { + "code": "stack_encrypt::context_mismatch", + "fields": { + "stored_len": 13, + "stored_parts": 2 + } + } + }, + { + "id": "context-drop-tenant", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "drop_tenant", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "field_missing" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "field_missing" + } + } + }, + { + "id": "context-tenant-no-payload", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "tenant_no_payload", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "no_passthrough_node" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "no_passthrough_node" + } + } + }, + { + "id": "context-tenant-number", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": true, + "rows": [ + { + "tenant": { + "type": "string", + "text": "tenants/acme" + }, + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "tenant_number", + "row": 0 + }, + "adapter": false, + "expected": { + "stage": "shape", + "retrievals": 0, + "error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "field_type" + } + } + }, + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "field": "tenant", + "reason": "field_type" + } + } + }, + { + "id": "static-context-with-expectation", + "write": { + "kind": "int32", + "null": "" + }, + "read": { + "kind": "int32", + "null": "" + }, + "context_field": false, + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "mutation": { + "kind": "none", + "row": 0 + }, + "adapter": true, + "expected": { + "stage": "preflight", + "retrievals": 0, + "error": { + "code": "stack_encrypt::plan_two_context_sources", + "fields": { + "first": "the plan", + "second": "the call" + } + } + }, + "expected_context": "tenants/acme", + "check_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "refused" + } + } + }, + { + "id": "context-field-after-value-lexically", + "write": { "kind": "int32", "null": "" }, + "read": { "kind": "int32", "null": "" }, + "context_field": true, + "rows": [ + { + "value": { "type": "int32", "text": "34" }, + "zone": { "type": "string", "text": "tenants/acme" } + } + ], + "mutation": { "kind": "none", "row": 0 }, + "adapter": true, + "expected": { + "stage": "success", + "retrievals": 1, + "rows": [ + { + "value": { "type": "int32", "text": "34" }, + "zone": { "type": "string", "text": "tenants/acme" } + } + ] + }, + "context_field_name": "zone" + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-runtime-v1.cases.json b/conformance/stack-encrypt/v1/record-runtime-v1.cases.json new file mode 100644 index 0000000000..f20d7b2d9b --- /dev/null +++ b/conformance/stack-encrypt/v1/record-runtime-v1.cases.json @@ -0,0 +1,990 @@ +{ + "version": 1, + "profile": "record-runtime-v1", + "required_capabilities": [ + "records", + "equality", + "null-policies", + "lossless-query-conversion" + ], + "cases": [ + { + "id": "required-missing", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [{}], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_missing", + "field": "value" + } + }, + { + "id": "required-null", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "required-boundaries", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "required-other-width", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "int64", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "required-integral-float", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "float64", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "required-fractional-float", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "float64", + "text": "34.5" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "sql-missing", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [{}], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [false], + "equal_lengths": false + }, + { + "id": "sql-null", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [false], + "equal_lengths": false + }, + { + "id": "sql-boundaries", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sql-other-width", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + { + "value": { + "type": "int64", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sealed-missing", + "operation": "seal", + "kind": "int32", + "null": "sealed", + "rows": [{}], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_missing", + "field": "value" + } + }, + { + "id": "sealed-null", + "operation": "seal", + "kind": "int32", + "null": "sealed", + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [true], + "equal_lengths": false + }, + { + "id": "sealed-boundaries", + "operation": "seal", + "kind": "int32", + "null": "sealed", + "rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "value": { + "type": "int32", + "text": "2147483647" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sealed-other-width", + "operation": "seal", + "kind": "int32", + "null": "sealed", + "rows": [ + { + "value": { + "type": "int64", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sql-mixed-batch", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + {}, + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [false, true, false], + "equal_lengths": false + }, + { + "id": "sealed-mixed-batch", + "operation": "seal", + "kind": "int32", + "null": "sealed", + "rows": [ + { + "value": { + "type": "null", + "text": "" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + }, + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [true, true, true], + "equal_lengths": true + }, + { + "id": "sql-all-absent", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + {}, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "null", + "text": "" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [false, false], + "equal_lengths": false + }, + { + "id": "empty-batch", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [], + "expected_rows": [], + "expected_stored": [], + "equal_lengths": false + }, + { + "id": "late-wrong-type", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "value": { + "type": "string", + "text": "private-value" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "late-missing", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + {} + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_missing", + "field": "value" + } + }, + { + "id": "unknown-field", + "operation": "seal", + "kind": "int32", + "null": "", + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + }, + "extra": { + "type": "string", + "text": "private-value" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "unknown_field", + "field": "extra" + } + }, + { + "id": "sql-missing-with-unknown-field", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + { + "extra": { + "type": "string", + "text": "private-value" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "unknown_field", + "field": "extra" + } + }, + { + "id": "sql-late-missing-with-unknown-field", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + { + "value": { + "type": "int32", + "text": "34" + } + }, + { + "extra": { + "type": "string", + "text": "private-value" + } + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "unknown_field", + "field": "extra" + } + }, + { + "id": "sealed-int64", + "operation": "seal", + "kind": "int64", + "null": "sealed", + "rows": [ + { + "value": { + "type": "int64", + "text": "9223372036854775807" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "int64", + "text": "9223372036854775807" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sealed-uint64", + "operation": "seal", + "kind": "uint64", + "null": "sealed", + "rows": [ + { + "value": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "sealed-float64", + "operation": "seal", + "kind": "float64", + "null": "sealed", + "rows": [ + { + "value": { + "type": "float64", + "text": "1.5" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_rows": [ + { + "value": { + "type": "float64", + "text": "1.5" + } + }, + { + "value": { + "type": "null", + "text": "" + } + } + ], + "expected_stored": [true, true], + "equal_lengths": true + }, + { + "id": "query-narrow-int", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "int64", + "text": "34" + }, + "expected_value": { + "type": "int32", + "text": "34" + } + }, + { + "id": "query-integral-float", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "float64", + "text": "34" + }, + "expected_value": { + "type": "int32", + "text": "34" + } + }, + { + "id": "query-int32-min", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "int64", + "text": "-2147483648" + }, + "expected_value": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "id": "query-int32-max", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "int64", + "text": "2147483647" + }, + "expected_value": { + "type": "int32", + "text": "2147483647" + } + }, + { + "id": "query-int32-underflow", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "int64", + "text": "-2147483649" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-int32-overflow", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "int64", + "text": "2147483648" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-fraction", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "float64", + "text": "34.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-negative-unsigned", + "operation": "query", + "kind": "uint64", + "null": "", + "input": { + "type": "int64", + "text": "-1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-exact-integer-float", + "operation": "query", + "kind": "float64", + "null": "", + "input": { + "type": "uint64", + "text": "9007199254740992" + }, + "expected_value": { + "type": "float64", + "text": "9007199254740992" + } + }, + { + "id": "query-lossy-integer-float", + "operation": "query", + "kind": "float64", + "null": "", + "input": { + "type": "uint64", + "text": "9007199254740993" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-text-is-not-number", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "string", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-bool-is-not-number", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "bool", + "text": "true" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "query-required-null", + "operation": "query", + "kind": "int32", + "null": "", + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "value" + } + }, + { + "id": "query-sql-null", + "operation": "query", + "kind": "int32", + "null": "sql", + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null_query", + "field": "value" + } + }, + { + "id": "query-sealed-null", + "operation": "query", + "kind": "int32", + "null": "sealed", + "input": { + "type": "null", + "text": "" + }, + "expected_value": { + "type": "null", + "text": "" + } + }, + { + "id": "sql-mixed-equal-lengths", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [ + {}, + { "value": { "type": "int32", "text": "1" } }, + { "value": { "type": "int32", "text": "2" } } + ], + "expected_rows": [ + { "value": { "type": "null", "text": "" } }, + { "value": { "type": "int32", "text": "1" } }, + { "value": { "type": "int32", "text": "2" } } + ], + "expected_stored": [false, true, true], + "equal_lengths": true + }, + { + "id": "sql-empty-equal-lengths", + "operation": "seal", + "kind": "int32", + "null": "sql", + "rows": [], + "expected_rows": [], + "expected_stored": [], + "equal_lengths": true + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-scalars-v1.cases.json b/conformance/stack-encrypt/v1/record-scalars-v1.cases.json new file mode 100644 index 0000000000..ecb01f633e --- /dev/null +++ b/conformance/stack-encrypt/v1/record-scalars-v1.cases.json @@ -0,0 +1,115 @@ +{ + "version": 1, + "profile": "record-scalars-v1", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "context": ["conformance"], + "field": "value", + "required_capabilities": [ + "records", + "equality", + "context-binding", + "query-errors" + ], + "cases": [ + { + "id": "i32-min", + "kind": "int32", + "input": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "id": "i32-max", + "kind": "int32", + "input": { + "type": "int32", + "text": "2147483647" + } + }, + { + "id": "i64-min", + "kind": "int64", + "input": { + "type": "int64", + "text": "-9223372036854775808" + } + }, + { + "id": "i64-max", + "kind": "int64", + "input": { + "type": "int64", + "text": "9223372036854775807" + } + }, + { + "id": "u64-max", + "kind": "uint64", + "input": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "id": "above-js-safe-integer", + "kind": "int64", + "input": { + "type": "int64", + "text": "9007199254740993" + } + }, + { + "id": "text-unicode", + "kind": "string", + "input": { + "type": "string", + "text": "café 東京 🔐" + } + }, + { + "id": "text-empty", + "kind": "string", + "input": { + "type": "string", + "text": "" + } + }, + { + "id": "query-text-for-integer", + "kind": "int64", + "input": { + "type": "string", + "text": "sensitive-query-value" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-bool-for-integer", + "kind": "int64", + "input": { + "type": "bool", + "text": "true" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-null", + "kind": "int64", + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null_query" + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json new file mode 100644 index 0000000000..a3d3ebdf69 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json @@ -0,0 +1,47 @@ +{ + "version": 1, + "profile": "record-scalars-v1", + "producer": "rust-native/stack-encrypt-0.3.0", + "cases": { + "above-js-safe-integer": { + "frame": "050100000000002000", + "ciphertext": "0100000000000000000000000000000000d7f53b2f05f735b1a761ae2897e32cb9200080a7c97b8885087c0530fac2a364a5259fc2177478b543e972247f3af59a3a80020fe1a86efa34927b061b60bcac42a74c0a35e21e8e84c58973e29cd30edc21b9f017bca00c", + "equality": "ac6c5f70a992a8b5d835ceb5bfb459b728a94c220e5e0ffca3f858aa66db7db4" + }, + "i32-max": { + "frame": "04ffffff7f", + "ciphertext": "0100000000000000000000000000000000df8645b1e40e43f85ac7f5e826cdc74a20000c6e5a55e60affd88eb9de36776909b2a62f0647fafd4b7e3540ef8d957793530208f96d6eb25ce8eaee6dddf6f8f78015539889051e72eddd5d96456b5487231923", + "equality": "d679831312fc2b397f9b7fa5dba2ac3918431668c9923c379eadf8fedf4a7c4c" + }, + "i32-min": { + "frame": "0400000080", + "ciphertext": "01000000000000000000000000000000003b55fcd86eac559b36435b57fb2d00d62000956e7ffef9fa6b6f0c58944a4df74aeec52dd16c166b567014a3eaab79ff63a802fefc11d37697e01980445e5adef82ec75c3840346dacca3e359e197c91ccfeeb8a", + "equality": "e9b219761c0e549e3b5540744af1ceeebe241b6ed739e0f463d1c4af6d00eb7f" + }, + "i64-max": { + "frame": "05ffffffffffffff7f", + "ciphertext": "01000000000000000000000000000000001689636dabf977a1d7fce31594bfa15420003414223db76e9c96ce9603416a47e602911f24c04522e5dcbf303b3b10c2db160296dd082dbdf1bce3876b148fcf2d28f1753c3e2c93c4ea6afc146c23fdc9434e9d770ad716", + "equality": "b3ea26e6833e7665ef374b18f7123b0a795fbeea7f1696f3e3b63971f3201bcb" + }, + "i64-min": { + "frame": "050000000000000080", + "ciphertext": "01000000000000000000000000000000005fe9f26245bf484c734b5299be73d83a200051ae2d51b5d42745b2a586e663829d635deeed00a5408cf6e427b74d6213b9de0240237777e11809dbe6f3e3b857440c2f7cba391c95284d5269daf03de849ba7563ed296ec1", + "equality": "f504a4593ee7972726e6bd6420e11d5bc30c5d36285b2029df394a1d373f76db" + }, + "text-empty": { + "frame": "0a00000000", + "ciphertext": "010000000000000000000000000000000079a06bc059ef87dec9f58a8876c0112f20005d48c836a336273250cd8150593c25f4be53b49e3ae8bfe4e0d007cb0aa720d30259e10ebabb074b442c43bd77aa42dbab6b369f7e2725e656f936480796", + "equality": "cdf6de2f0cae47435a2a3fcd8d0ec5e29670302f65567a746555507def9aad52" + }, + "text-unicode": { + "frame": "0a11000000636166c3a920e69db1e4baac20f09f9490", + "ciphertext": "0100000000000000000000000000000000aba3b145ab9dddbcf4d5424461fd45c32000ef3f0cd3daac23097d97a85e8405923e9d95d29436c6ef5d848dee41ceeca24e0298a6c8ff53f67ff24459e4db609400f9f0f2c4f5c0818fafe2aecee06aba4e9500aceb4ec3c5c13d2bfeb335d766", + "equality": "d44828c3c9a883bd802b0c3fb3728f240bbdc244095ce71f39e430a40d7e4b07" + }, + "u64-max": { + "frame": "07ffffffffffffffff", + "ciphertext": "01000000000000000000000000000000001aaf730b6c6bc77770144918b59a35932000ef235e515a8e50ff41f3a26ba62e5de76f5331373f245ced6bce3a5638acffd302e975cc6e364604b6b1c0563752772c462fc353b94531ddca1436504262400183186ff2f004", + "equality": "04c8d7f02d9555152bdd770106eab974e517a0eba6b339e3ad1b0108796359d8" + } + } +} diff --git a/conformance/stack-encrypt/v1/record-values-v1.cases.json b/conformance/stack-encrypt/v1/record-values-v1.cases.json new file mode 100644 index 0000000000..6fa5567a85 --- /dev/null +++ b/conformance/stack-encrypt/v1/record-values-v1.cases.json @@ -0,0 +1,983 @@ +{ + "version": 1, + "profile": "record-values-v1", + "required_capabilities": [ + "records", + "equality", + "value-kinds", + "null-policies" + ], + "cases": [ + { + "id": "bool-true", + "kind": "bool", + "null": "", + "outputs": ["c"], + "input": { + "type": "bool", + "text": "true" + }, + "frame": "03" + }, + { + "id": "bool-false", + "kind": "bool", + "null": "", + "outputs": ["c"], + "input": { + "type": "bool", + "text": "false" + }, + "frame": "02" + }, + { + "id": "i8-min", + "kind": "int8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int8", + "text": "-128" + }, + "frame": "0c80" + }, + { + "id": "i8-max", + "kind": "int8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int8", + "text": "127" + }, + "frame": "0c7f" + }, + { + "id": "u8-zero", + "kind": "uint8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "uint8", + "text": "0" + }, + "frame": "0d00" + }, + { + "id": "u8-max", + "kind": "uint8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "uint8", + "text": "255" + }, + "frame": "0dff" + }, + { + "id": "i16-min", + "kind": "int16", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int16", + "text": "-32768" + }, + "frame": "0e0080" + }, + { + "id": "i16-max", + "kind": "int16", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int16", + "text": "32767" + }, + "frame": "0eff7f" + }, + { + "id": "u16-zero", + "kind": "uint16", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "uint16", + "text": "0" + }, + "frame": "0f0000" + }, + { + "id": "u16-max", + "kind": "uint16", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "uint16", + "text": "65535" + }, + "frame": "0fffff" + }, + { + "id": "u32-zero", + "kind": "uint32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "uint32", + "text": "0" + }, + "frame": "0600000000" + }, + { + "id": "u32-max", + "kind": "uint32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "uint32", + "text": "4294967295" + }, + "frame": "06ffffffff" + }, + { + "id": "i128-max", + "kind": "int128", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int128", + "text": "170141183460469231731687303715884105727" + }, + "frame": "10ffffffffffffffffffffffffffffff7f" + }, + { + "id": "i128-min", + "kind": "int128", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + }, + "frame": "1000000000000000000000000000000080" + }, + { + "id": "i128-below-i64", + "kind": "int128", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int128", + "text": "-9223372036854775809" + }, + "frame": "10ffffffffffffff7fffffffffffffffff" + }, + { + "id": "i128-above-i64", + "kind": "int128", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "int128", + "text": "9223372036854775808" + }, + "frame": "1000000000000000800000000000000000" + }, + { + "id": "u128-zero", + "kind": "uint128", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "uint128", + "text": "0" + }, + "frame": "1100000000000000000000000000000000" + }, + { + "id": "u128-above-u64", + "kind": "uint128", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "uint128", + "text": "18446744073709551616" + }, + "frame": "1100000000000000000100000000000000" + }, + { + "id": "u128-max", + "kind": "uint128", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "uint128", + "text": "340282366920938463463374607431768211455" + }, + "frame": "11ffffffffffffffffffffffffffffffff" + }, + { + "id": "f32-max", + "kind": "float32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float32", + "text": "3.4028235e38" + }, + "frame": "08ffff7f7f" + }, + { + "id": "f32-min-positive", + "kind": "float32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float32", + "text": "1e-45" + }, + "frame": "0801000000" + }, + { + "id": "f32-negative-zero", + "kind": "float32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float32", + "text": "-0" + }, + "frame": "0800000080" + }, + { + "id": "f32-inf", + "kind": "float32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float32", + "text": "inf" + }, + "frame": "080000807f" + }, + { + "id": "f32-neg-inf", + "kind": "float32", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float32", + "text": "-inf" + }, + "frame": "08000080ff" + }, + { + "id": "f64-max", + "kind": "float64", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float64", + "text": "1.7976931348623157e308" + }, + "frame": "09ffffffffffffef7f" + }, + { + "id": "f64-min-positive", + "kind": "float64", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float64", + "text": "5e-324" + }, + "frame": "090100000000000000" + }, + { + "id": "f64-negative-zero", + "kind": "float64", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float64", + "text": "-0" + }, + "frame": "090000000000000080" + }, + { + "id": "f64-inf", + "kind": "float64", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float64", + "text": "inf" + }, + "frame": "09000000000000f07f" + }, + { + "id": "f64-neg-inf", + "kind": "float64", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "float64", + "text": "-inf" + }, + "frame": "09000000000000f0ff" + }, + { + "id": "bytes-empty", + "kind": "bytes", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "bytes", + "text": "" + }, + "frame": "0b00000000" + }, + { + "id": "bytes-binary", + "kind": "bytes", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "bytes", + "text": "00ff10" + }, + "frame": "0b0300000000ff10" + }, + { + "id": "string-nul", + "kind": "string", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "string", + "text": "a\u0000b" + }, + "frame": "0a03000000610062" + }, + { + "id": "decimal-scale-0", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "decimal", + "text": "42" + }, + "frame": "14000000002a0000000000000000000000" + }, + { + "id": "decimal-scale-28", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "decimal", + "text": "0.0000000000000000000000000001" + }, + "frame": "1400001c00010000000000000000000000" + }, + { + "id": "decimal-trailing-zeros", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "decimal", + "text": "-1234.5600" + }, + "frame": "14000004800061bc000000000000000000", + "equal_query": { + "type": "decimal", + "text": "-1234.56" + } + }, + { + "id": "decimal-max-mantissa", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "decimal", + "text": "79228162514264337593543950335" + }, + "frame": "1400000000ffffffffffffffffffffffff" + }, + { + "id": "date-epoch", + "kind": "date", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "date", + "text": "1970-01-01" + }, + "frame": "123bf90a00" + }, + { + "id": "date-before-epoch", + "kind": "date", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "date", + "text": "1969-12-31" + }, + "frame": "123af90a00" + }, + { + "id": "date-year-one", + "kind": "date", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "date", + "text": "0001-01-01" + }, + "frame": "1201000000" + }, + { + "id": "date-year-9999", + "kind": "date", + "null": "", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "date", + "text": "9999-12-31" + }, + "frame": "12dbb93700" + }, + { + "id": "timestamp-epoch", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "timestamp", + "text": "1970-01-01T00:00:00Z" + }, + "frame": "13000000000000000000000000" + }, + { + "id": "timestamp-nanosecond", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.000000001Z" + }, + "frame": "130bc9d26a0000000001000000" + }, + { + "id": "timestamp-before-epoch", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "timestamp", + "text": "1969-12-31T23:59:59.999999999Z" + }, + "frame": "13ffffffffffffffffffc99a3b" + }, + { + "id": "timestamp-microsecond-query", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + }, + "frame": "130bc9d26a0000000015cd5b07", + "equal_query": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456Z" + } + }, + { + "id": "timestamp-year-9999", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq", "ope"], + "input": { + "type": "timestamp", + "text": "9999-12-30T22:00:00.999999999Z" + }, + "frame": "13e0d3f2ff3a000000ffc99a3b" + }, + { + "id": "sealed-bool", + "kind": "bool", + "null": "sealed", + "outputs": ["c"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "bool", + "text": "true" + } + }, + { + "id": "sealed-int8", + "kind": "int8", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "int8", + "text": "-1" + } + }, + { + "id": "sealed-int16", + "kind": "int16", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "int16", + "text": "-32768" + } + }, + { + "id": "sealed-uint8", + "kind": "uint8", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "uint8", + "text": "255" + } + }, + { + "id": "sealed-uint16", + "kind": "uint16", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "uint16", + "text": "65535" + } + }, + { + "id": "sealed-uint32", + "kind": "uint32", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "uint32", + "text": "4294967295" + } + }, + { + "id": "sealed-int128", + "kind": "int128", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + } + }, + { + "id": "sealed-uint128", + "kind": "uint128", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "uint128", + "text": "340282366920938463463374607431768211455" + } + }, + { + "id": "sealed-float32", + "kind": "float32", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "sealed-date", + "kind": "date", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": "sealed-timestamp", + "kind": "timestamp", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + } + }, + { + "id": "sealed-decimal", + "kind": "decimal", + "null": "sealed", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "companion": { + "type": "decimal", + "text": "1.50" + } + }, + { + "id": "sql-bool", + "kind": "bool", + "null": "sql", + "outputs": ["c"], + "input": { + "type": "null", + "text": "" + } + }, + { + "id": "sql-bytes", + "kind": "bytes", + "null": "sql", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + } + }, + { + "id": "sql-string", + "kind": "string", + "null": "sql", + "outputs": ["c", "eq", "ore"], + "input": { + "type": "null", + "text": "" + } + }, + { + "id": "int8-given-int16", + "kind": "int8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int16", + "text": "1" + }, + "frame": "0e0100", + "stored": { + "type": "int8", + "text": "1" + } + }, + { + "id": "uint8-given-int8", + "kind": "uint8", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int8", + "text": "1" + }, + "frame": "0c01", + "stored": { + "type": "uint8", + "text": "1" + } + }, + { + "id": "int128-given-int64", + "kind": "int128", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int64", + "text": "1" + }, + "frame": "050100000000000000", + "stored": { + "type": "int128", + "text": "1" + } + }, + { + "id": "uint128-given-uint64", + "kind": "uint128", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "uint64", + "text": "1" + }, + "frame": "070100000000000000", + "stored": { + "type": "uint128", + "text": "1" + } + }, + { + "id": "float32-given-float64", + "kind": "float32", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "float64", + "text": "1.5" + }, + "frame": "09000000000000f83f", + "stored": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "decimal-given-float64", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "float64", + "text": "1.5" + }, + "frame": "09000000000000f83f", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "date-given-int32", + "kind": "date", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int32", + "text": "0" + }, + "frame": "0400000000", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "timestamp-given-int64", + "kind": "timestamp", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "int64", + "text": "0" + }, + "frame": "050000000000000000", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "bytes-given-string", + "kind": "bytes", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "string", + "text": "" + }, + "frame": "0a00000000", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "string-given-bytes", + "kind": "string", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "bytes", + "text": "00" + }, + "frame": "0b0100000000", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "bool-given-int32", + "kind": "bool", + "null": "", + "outputs": ["c"], + "input": { + "type": "int32", + "text": "1" + }, + "frame": "0401000000", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "int32-given-undefined", + "kind": "int32", + "null": "sql", + "outputs": ["c", "eq"], + "input": { + "type": "undefined", + "text": "" + }, + "frame": "01", + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "undefined", + "field": "value" + } + }, + { + "id": "required-bool-null", + "kind": "bool", + "null": "", + "outputs": ["c"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "required-bytes-null", + "kind": "bytes", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + }, + { + "id": "required-decimal-null", + "kind": "decimal", + "null": "", + "outputs": ["c", "eq"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type", + "field": "value" + } + } + ], + "host_conversions": [ + { + "id": "go-zero-date", + "language": "go", + "kind": "date", + "value": "zero_date" + }, + { + "id": "go-decimal-scale-29", + "language": "go", + "kind": "decimal", + "value": "decimal_scale_29" + }, + { + "id": "go-timestamp-year-300000", + "language": "go", + "kind": "timestamp", + "value": "timestamp_year_300000" + }, + { + "id": "go-complex128", + "language": "go", + "kind": "float64", + "value": "complex128" + }, + { + "id": "go-map-int-key", + "language": "go", + "kind": "string", + "value": "map_int_key" + }, + { + "id": "go-channel", + "language": "go", + "kind": "string", + "value": "channel" + } + ] +} diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json new file mode 100644 index 0000000000..26e3372d30 --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -0,0 +1,1040 @@ +{ + "version": 1, + "profile": "single-value-v1", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "required_capabilities": [ + "single-value", + "value-kinds", + "context-binding", + "refusals" + ], + "cases": [ + { + "id": "as-is-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["int64", "bytes"] + }, + { + "id": "as-is-empty-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "" + } + }, + { + "id": "as-is-int64-above-js-safe", + "kind": "", + "context": [], + "input": { + "type": "int64", + "text": "9007199254740993" + }, + "refused_as": ["int32", "uint64", "float64", "string"] + }, + { + "id": "as-is-bool", + "kind": "", + "context": [], + "input": { + "type": "bool", + "text": "true" + } + }, + { + "id": "as-is-bytes", + "kind": "", + "context": [], + "input": { + "type": "bytes", + "text": "00ff10" + }, + "refused_as": ["string", "uuid"] + }, + { + "id": "as-is-float64-negative-zero", + "kind": "", + "context": [], + "input": { + "type": "float64", + "text": "-0" + } + }, + { + "id": "as-is-uint8", + "kind": "", + "context": [], + "input": { + "type": "uint8", + "text": "200" + } + }, + { + "id": "as-is-uuid", + "kind": "", + "context": [], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "refused_as": ["bytes"] + }, + { + "id": "as-is-string-with-context", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "ada@example.com" + } + }, + { + "id": "string-json-number-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "42" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "3432" + } + }, + { + "kind": "string", + "value": { + "type": "string", + "text": "42" + } + } + ] + }, + { + "id": "string-json-spaced-text", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\" : [ 1 , null ], \"a\" : true }" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "7b2261223a747275652c2262223a5b312c6e756c6c5d7d" + } + } + ] + }, + { + "id": "string-not-json-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["json"] + }, + { + "id": "bool-false", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "bool", + "text": "false" + } + }, + { + "id": "int8-min", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int8", + "text": "-128" + } + }, + { + "id": "int16-min", + "kind": "int16", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "-32768" + } + }, + { + "id": "int32-min", + "kind": "int32", + "context": ["conformance", "value"], + "input": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "id": "int64-min", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "-9223372036854775808" + } + }, + { + "id": "int128-min", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + } + }, + { + "id": "uint8-max", + "kind": "uint8", + "context": ["conformance", "value"], + "input": { + "type": "uint8", + "text": "255" + } + }, + { + "id": "uint16-max", + "kind": "uint16", + "context": ["conformance", "value"], + "input": { + "type": "uint16", + "text": "65535" + } + }, + { + "id": "uint32-max", + "kind": "uint32", + "context": ["conformance", "value"], + "input": { + "type": "uint32", + "text": "4294967295" + } + }, + { + "id": "uint64-max", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "id": "uint128-max", + "kind": "uint128", + "context": ["conformance", "value"], + "input": { + "type": "uint128", + "text": "340282366920938463463374607431768211455" + } + }, + { + "id": "float32-fraction", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-infinity", + "kind": "float64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "inf" + } + }, + { + "id": "decimal-trailing-zeros", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "decimal", + "text": "-1234.5600" + } + }, + { + "id": "date-leap-day", + "kind": "date", + "context": ["conformance", "value"], + "input": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": "timestamp-nanoseconds", + "kind": "timestamp", + "context": ["conformance", "value"], + "input": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + } + }, + { + "id": "string-unicode", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "café ☕" + } + }, + { + "id": "bytes-empty", + "kind": "bytes", + "context": ["conformance", "value"], + "input": { + "type": "bytes", + "text": "" + } + }, + { + "id": "uuid", + "kind": "uuid", + "context": ["conformance", "value"], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + } + }, + { + "id": "uint64-given-float64", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "34" + }, + "stored": { + "type": "uint64", + "text": "34" + }, + "refused_as": ["float64", "uint32"] + }, + { + "id": "int8-given-int16", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "1" + }, + "stored": { + "type": "int8", + "text": "1" + } + }, + { + "id": "int128-given-int64", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "1" + }, + "stored": { + "type": "int128", + "text": "1" + } + }, + { + "id": "float32-given-float64", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "1.5" + }, + "stored": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-given-int32", + "kind": "float64", + "context": [], + "input": { + "type": "int32", + "text": "12" + }, + "stored": { + "type": "float64", + "text": "12" + } + }, + { + "id": "decimal-given-int64", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "5" + }, + "stored": { + "type": "decimal", + "text": "5" + } + }, + { + "id": "json-given-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\": [1, 2.5, null], \"a\": \"é\" }" + }, + "stored": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + }, + "opens_as": [ + { + "kind": "string", + "value": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + } + } + ], + "refused_as": ["int64", "bytes"] + }, + { + "id": "json-given-bytes", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "6e756c6c" + }, + "stored": { + "type": "string", + "text": "null" + } + }, + { + "id": "json-scalar-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "\"plain\"" + }, + "stored": { + "type": "string", + "text": "\"plain\"" + } + }, + { + "id": "array-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "array-array", + "kind": "array", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "array-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "empty-array-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "shape", + "text": "empty_array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "object-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "object-object", + "kind": "object", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "object-json", + "kind": "json", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "passthrough-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "passthrough" + } + }, + { + "id": "passthrough-string", + "kind": "string", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "passthrough" + } + }, + { + "id": "null-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-int64", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-string", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-bool", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "typed-null-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "typed-null-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "undefined-no-kind", + "kind": "", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "undefined-int32", + "kind": "int32", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "undefined-json", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "int64-given-string", + "kind": "int64", + "context": [], + "input": { + "type": "string", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "uint64-given-fraction", + "kind": "uint64", + "context": [], + "input": { + "type": "float64", + "text": "34.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "float64" + } + }, + { + "id": "int8-given-300", + "kind": "int8", + "context": [], + "input": { + "type": "int64", + "text": "300" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "date-given-int32", + "kind": "date", + "context": [], + "input": { + "type": "int32", + "text": "0" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int32" + } + }, + { + "id": "decimal-given-float64", + "kind": "decimal", + "context": [], + "input": { + "type": "float64", + "text": "1.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "float64" + } + }, + { + "id": "string-given-int64", + "kind": "string", + "context": [], + "input": { + "type": "int64", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "bytes-given-string", + "kind": "bytes", + "context": [], + "input": { + "type": "string", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "array-given-string", + "kind": "array", + "context": [], + "input": { + "type": "string", + "text": "a" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "object-given-int64", + "kind": "object", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "json-given-int64", + "kind": "json", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "json-syntax", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\": " + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_syntax", + "found": "string" + } + }, + { + "id": "json-duplicate-key", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\":1,\"a\":2}" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_duplicate_key", + "found": "string" + } + }, + { + "id": "json-integer-range", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "3138343436373434303733373039353531363136" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_integer_range", + "found": "bytes" + } + } + ], + "batches": [ + { + "id": "batch-strings", + "kinds": ["string", "string", "string"], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "string", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ] + }, + { + "id": "batch-converted", + "kinds": ["uint32", "uint32", "uint32"], + "context": [], + "inputs": [ + { + "type": "float64", + "text": "1" + }, + { + "type": "int64", + "text": "2" + }, + { + "type": "uint16", + "text": "3" + } + ], + "stored": [ + { + "type": "uint32", + "text": "1" + }, + { + "type": "uint32", + "text": "2" + }, + { + "type": "uint32", + "text": "3" + } + ] + }, + { + "id": "batch-mixed-no-kind", + "kinds": ["", "", ""], + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + { + "id": "batch-mixed-kinds", + "kinds": ["uint64", "string", ""], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "float64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ], + "stored": [ + { + "type": "uint64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + { + "id": "batch-empty", + "kinds": [], + "context": [], + "inputs": [] + }, + { + "id": "batch-with-null", + "kinds": ["", "", ""], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "null", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "batch-with-mismatch", + "kinds": ["int64", "int64"], + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json new file mode 100644 index 0000000000..69a7558b19 --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json @@ -0,0 +1,300 @@ +{ + "version": 1, + "profile": "single-value-v1", + "producer": "rust-native/stack-encrypt-0.3.0", + "cases": { + "array-array": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-given-string": { + "frame": "0a0100000061" + }, + "array-int64": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-no-kind": { + "frame": "f0020000000a01000000610a0100000062" + }, + "as-is-bool": { + "frame": "03", + "leaf": "03", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de029fe04f1b508676453ac04e339b2f80f53847a5ff818dcf1c532fa846fb" + }, + "as-is-bytes": { + "frame": "0b0300000000ff10", + "leaf": "0b00ff10", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02fa48756303bc32df4b8307a6f58ac8386d7f82425cccbe656ddd5e73615c571a" + }, + "as-is-empty-string": { + "frame": "0a00000000", + "leaf": "0a", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0225bef2bfdae4755442824942ed0d94a1f3ec6cb626299e50653b372e98" + }, + "as-is-float64-negative-zero": { + "frame": "090000000000000080", + "leaf": "090000000000000080", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02350d1ec5e03af0f13153705c6fb65b905d078d75d23a437399a38f864d524ed0f751b60d6b" + }, + "as-is-int64-above-js-safe": { + "frame": "050100000000002000", + "leaf": "050100000000002000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02a352279f2d7314d0814b67ade0b98d96c474f8fb7008e6071ba144db50a10e1e6634a5c5f7" + }, + "as-is-string": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02b725799857a54d0788360432755b45db393f1b7e6f2f4c153f0c54bc7e5c1938148196d75552bf87b9aeb13b" + }, + "as-is-string-with-context": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025cadd464b84b4d38682d1e50b58f59a4992f4929674814ab6ace0325ee6b5b7c65981e3d20f187a1cd3cdd8c" + }, + "as-is-uint8": { + "frame": "0dc8", + "leaf": "0dc8", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0282a2279d098f66f8776c5750e57acd502a6c3ecbbf4f77fa32e92a8aca60" + }, + "as-is-uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02de2cfad59578fbdde2113e2408c83a2e622469ff2a8561c1df6f024c6c43603ffab884daca5df9dc618361b6e4163958" + }, + "bool-false": { + "frame": "02", + "leaf": "02", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0204b52dce3c7883f4357cb091a330b4d3b6b560a28f9c9e2eeb334df765" + }, + "bytes-empty": { + "frame": "0b00000000", + "leaf": "0b", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025e243904c6b98ce10005f8b7809b03b772109d33b767c90077102e2f2a" + }, + "bytes-given-string": { + "frame": "0a00000000" + }, + "date-given-int32": { + "frame": "0400000000" + }, + "date-leap-day": { + "frame": "1281460b00", + "leaf": "1281460b00", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf360e838a4e7e80dbb78b24519ac81dc083892471b3272c8ed466ca416d28124a" + }, + "decimal-given-float64": { + "frame": "09000000000000f83f" + }, + "decimal-given-int64": { + "frame": "050500000000000000", + "leaf": "1400000000050000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028a8e782f7f1aa3a3067b3d8057ab95ede3b78d267ba118e90422a1bd0be22e700f37fbd32deaed33fc0ec5c41c" + }, + "decimal-trailing-zeros": { + "frame": "14000004800061bc000000000000000000", + "leaf": "14000004800061bc000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02eeaf9c1474e50601ee703ef75901fdcf953c9267d98b425ae42508aaeb3fa2d45adabb6470ea78059d509dae72" + }, + "empty-array-no-kind": { + "frame": "f000000000" + }, + "float32-fraction": { + "frame": "080000c03f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02693227bfd9a4e28995f12272ba296a599a9df3649e04e4ac24b7f73714618363c5" + }, + "float32-given-float64": { + "frame": "09000000000000f83f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02730a34dc8aea8436e24ede609ea29417503948651cc9232fbc9ae7dba32f867867" + }, + "float64-given-int32": { + "frame": "040c000000", + "leaf": "090000000000002840", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de021bfb53623f66f1b72532971cef2477fc61b379f9e973d3daa6f6afc05b813d85602137026c" + }, + "float64-infinity": { + "frame": "09000000000000f07f", + "leaf": "09000000000000f07f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02636c99a930f39fd9ac116bf57de36cec9477a076fcf815f7b1acca891d8d028330396f0149" + }, + "int128-given-int64": { + "frame": "050100000000000000", + "leaf": "1001000000000000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020f001346503a8a31858c52a494fa6552ad609605e0dce79835fac9ec3e33c208596ce7df6caf4b04ff7faeb954" + }, + "int128-min": { + "frame": "1000000000000000000000000000000080", + "leaf": "1000000000000000000000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0203d9fc37a766f04e6eb14ebf0c05b7d0784c17df29a5802c6d05d3c433bb0890389a848b65b37f1c1b559c5aa8" + }, + "int16-min": { + "frame": "0e0080", + "leaf": "0e0080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf38b95faaf29d4e843e72134abd32961e68d42d509a27e7d628d92983b493" + }, + "int32-min": { + "frame": "0400000080", + "leaf": "0400000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020a4033afe1a5b353a0f9661ae2981e6239d719ff4cf758c9fda3627e52f6ca8da3" + }, + "int64-given-string": { + "frame": "0a020000003334" + }, + "int64-min": { + "frame": "050000000000000080", + "leaf": "050000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0226a292092dc07c14807aaee032309eb627272f40c4fd98a795f8e24c03814b23d4b54ca92e" + }, + "int8-given-300": { + "frame": "052c01000000000000" + }, + "int8-given-int16": { + "frame": "0e0100", + "leaf": "0c01", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024c557ec1d7f0e338af7d9c88878c47c5fe066178ec92f4953df25ae9b63e" + }, + "int8-min": { + "frame": "0c80", + "leaf": "0c80", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02306ce03ce2b20cb0a7337942f156669e16eb3b639055674875b8f8b79392" + }, + "json-duplicate-key": { + "frame": "0a0d0000007b2261223a312c2261223a327d" + }, + "json-given-bytes": { + "frame": "0b040000006e756c6c", + "leaf": "0a6e756c6c", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02830450b50101f6a3b3f49caf66e78f55fe0365d5a7a308a715285840baddf67354" + }, + "json-given-int64": { + "frame": "050100000000000000" + }, + "json-given-string": { + "frame": "0a220000007b202262223a205b312c20322e352c206e756c6c5d2c202261223a2022c3a922207d", + "leaf": "0a7b2261223a22c3a9222c2262223a5b312c322e352c6e756c6c5d7d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02e591294b87dde6fa2cd3f5509ab93920b87e3d0f6999bea7e0212abd9f4dced82bd64622c68752a866af0195253a784228a6ad4547d6f986" + }, + "json-integer-range": { + "frame": "0b140000003138343436373434303733373039353531363136" + }, + "json-scalar-string": { + "frame": "0a0700000022706c61696e22", + "leaf": "0a22706c61696e22", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028e622a3d896eba4f36057db0f1dc63b1a9f93f6191c3262bea067f4a68ddb3defd74d12c" + }, + "json-syntax": { + "frame": "0a060000007b2261223a20" + }, + "null-bool": { + "frame": "00" + }, + "null-int64": { + "frame": "00" + }, + "null-no-kind": { + "frame": "00" + }, + "null-string": { + "frame": "00" + }, + "object-given-int64": { + "frame": "050100000000000000" + }, + "object-json": { + "frame": "f10100000001000000610601000000" + }, + "object-no-kind": { + "frame": "f10100000001000000610601000000" + }, + "object-object": { + "frame": "f10100000001000000610601000000" + }, + "passthrough-no-kind": { + "frame": "f20a05000000636c656172" + }, + "passthrough-string": { + "frame": "f20a05000000636c656172" + }, + "string-given-int64": { + "frame": "052200000000000000" + }, + "string-json-number-text": { + "frame": "0a020000003432", + "leaf": "0a3432", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02c5470c71a49e4a40e9cc0ecf0d2c83331b14df48b422bab48a5b6527a49c38" + }, + "string-json-spaced-text": { + "frame": "0a220000007b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "leaf": "0a7b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0230b18ebf21ce9d80030906b36df0a068478d59ed3758f82f62f37c43aa058d84932cfb94cfc506bc765c338ebe5b6033ff00f8cba133f7103ebe9b0d8d9a0b" + }, + "string-not-json-text": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02110a04698a1a246da6c8e432473b2e29e735e2c681205381dfea450121429847858582af90a83c75bbd405d8" + }, + "string-unicode": { + "frame": "0a09000000636166c3a920e29895", + "leaf": "0a636166c3a920e29895", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b06def1c5a6e1cbc44d41af64f5b733d3c2c6f22ab4d68f588725725fdeee215928cd6baa1dd" + }, + "timestamp-nanoseconds": { + "frame": "130bc9d26a0000000015cd5b07", + "leaf": "130bc9d26a0000000015cd5b07", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a66b3872cd846657a41af5155ad5c0eeb680b54de242d99ed02d32287c9aad40d738aaa09230856e76" + }, + "typed-null-int64": { + "frame": "150500000000000000" + }, + "typed-null-no-kind": { + "frame": "150500000000000000" + }, + "uint128-max": { + "frame": "11ffffffffffffffffffffffffffffffff", + "leaf": "11ffffffffffffffffffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02433597c92b736ea642fdac7b846f29b6a30616f48ef97eeda089ff30745be880cddd611075b80ecf2a94a2712c" + }, + "uint16-max": { + "frame": "0fffff", + "leaf": "0fffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02ec21438b0724ce61a47824b18fd6800703b6c14d875b41b91d11c993986d8b" + }, + "uint32-max": { + "frame": "06ffffffff", + "leaf": "06ffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b0e8441266090f216b6364619fa66c95f511fe1832467eca30f95ee24b9f93c079" + }, + "uint64-given-float64": { + "frame": "090000000000004140", + "leaf": "072200000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024d8ceabb74d6249c2115af1dcde9c55db0736dcdffc10de38b896c5594d946650b216d8423" + }, + "uint64-given-fraction": { + "frame": "090000000000404140" + }, + "uint64-max": { + "frame": "07ffffffffffffffff", + "leaf": "07ffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a9104cf6c7fc888b3be880b0ef77c8c90c39cae789b8734075fa23f57eedc832a273f3da8b" + }, + "uint8-max": { + "frame": "0dff", + "leaf": "0dff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0210713e7cf318d8bcdafc7ed5bda20a513d00948785335c60e21c2d3c0e7f" + }, + "undefined-int32": { + "frame": "01" + }, + "undefined-json": { + "frame": "01" + }, + "undefined-no-kind": { + "frame": "01" + }, + "uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02f8a12b99d4ec25ceb2e20f075c6de2577470599a6e3fb6c88fde3663da1fd5be113edfe7087a06411b67a3d1bf773fa5" + } + } +} diff --git a/conformance/stack-encrypt/values-contract.md b/conformance/stack-encrypt/values-contract.md new file mode 100644 index 0000000000..777c9ab405 --- /dev/null +++ b/conformance/stack-encrypt/values-contract.md @@ -0,0 +1,167 @@ +# Record value-kind profile + +`record-values-v1` describes the cases in `v1/record-values-v1.cases.json`: every kind the +engine names, at its boundaries, through the record path with no EQL +resolver. It is an experimental test contract for native Rust and Go WASI. +Python and TypeScript runners remain pending. + +The earlier scalar, runtime and fixture profiles are representative. This +profile is the boundary matrix they left open: the narrow and 128-bit +integer edges (the 32- and 64-bit edges are the scalar and runtime +profiles'), 32-bit floats, the float specials, bytes, decimal scale and +mantissa limits, date and timestamp precision, sealed nulls for every +fixed-width kind the runtime profile does not already seal (it has +`int32`, `int64`, `uint64` and `float64`), SQL nulls, and the write +refusals between kinds. + +The runners are `packages/stack-encrypt/tests/value_conformance.rs` and +`languages/golang/encrypt/value_conformance_test.go`. + +## Cases + +Each case declares one field, `value`, under context `["conformance", "value"]`, +with `kind`, a `null` policy (empty, `sql` or `sealed`) and an `outputs` list +that starts with `c`. Values use the scalar profile's `{type, text}` form, +extended to every kind: + +| `type` | `text` | +|---|---| +| `bool` | `true` or `false` | +| `int8` … `int128`, `uint8` … `uint128` | canonical base-10 integer at exactly that width | +| `float32`, `float64` | the canonical spelling of a representable value (below), or `inf`, `-inf`; `-0` is negative zero | +| `string` | the literal text, control characters included | +| `bytes` | the bytes in lowercase hex, possibly empty | +| `date` | `YYYY-MM-DD`, proleptic Gregorian | +| `timestamp` | RFC 3339 in UTC, `YYYY-MM-DDTHH:MM:SS[.fraction]Z`, at most nine fraction digits | +| `decimal` | fixed-point text keeping every trailing zero; the scale is the number of fraction digits | +| `null` | empty | +| `undefined` | empty: JavaScript's `undefined`, which only a refused case uses | + +A float's canonical spelling is built from the shortest decimal digits +that parse back to the value at its width. Spelled positionally (Rust's +`{}`, Go's `strconv.FormatFloat(f, 'f', -1, bits)`: `34`, `-0`, `0.5`, +`9007199254740992`) and scientifically (Rust's `{:e}`, Go's +`strconv.FormatFloat(f, 'e', -1, bits)` with the exponent's `+` and leading +zeros removed: `1e3`, `3.4028235e38`, `5e-324`), the shorter of the two is +canonical, and the positional one on a tie (`100`, not `1e2`). Both +runners refuse any other text that parses to the value as a corpus error: +`1.00`, `1.0`, `1e0`, `1000`, `1e+3`, `1E3`, `+1`, `.5`, `-0.0`, `0.001`, +`Inf`, a rounded decimal. Rust's +`the_float_reader_accepts_only_the_canonical_spelling` and Go's +`TestConformanceFloatSpelling` hold both readers to the same accepted and +refused lists. + +Runners construct real typed host values: Rust reads each integer at its +width and each logical type over its physical scalar; Go uses its own +integer types, `float32`, `[]byte`, and the SDK's `Int128`, `Uint128`, +`Date`, `Decimal` and `time.Time`. No value passes through a JSON number or +a floating-point conversion. A text the type cannot carry is a corpus +error in both runners, never a rounded value. `NaN` is excluded: hosts do +not agree on its equality, so a corpus row could not be compared. + +Every non-null input carries `frame`, its frozen typed transport frame in +hex. Both runners encode the host value and compare it byte for byte, +which pins the width, the logical type tag, the decimal scale and the +timestamp's nanoseconds. The Rust helper that parses the text forms is +held to the frames the value-kinds fixture froze for the same spellings. + +## Required behavior + +For a case with no `expected_error` whose input is not null: + +1. The typed frame equals the frozen `frame`. +2. One record of the input seals, storing ciphertext and exactly the + declared indexes, with one batched data-key generation. +3. Every stored term is the term a query of the same value derives: `eq` + for the equality index, `lt` for an order index. A query makes no key + call. With `equal_query`, that other spelling derives the stored + equality term too (a decimal without its trailing zeros; a timestamp + truncated to the microsecond). +4. The record opens to the input with its type, with one batched retrieval. + +The key-call counts (one generation, no call per query, one retrieval) and +the refusals' "no key call" are native observations: the Rust runner counts +them on its key source. The Go runner checks everything else; its +deterministic guest has no call counter to read. + +A null input carries no `frame`, so requirement 1 does not apply to it. +A sealed null (`"null": "sealed"`, input `null`) meets requirements 2 and +3: it stores ciphertext and the declared indexes with one batched +generation, and a null equality query derives the stored equality term +where one is declared. It opens as null with one batched retrieval, and its `companion` value row's ciphertext has the same +length. A SQL null (`"null": "sql"`, input `null`) meets none of +requirements 1 to 4: it stores no record, so no data key is generated, no +term exists to compare and no ciphertext is opened; its row reads back as +null. + +Every index a case declares is one a query operator answers for the kind, +because a declaration admits no other. An order index on `bytes` is the +case that shows it: bytes have no order term, because no ordering operator +compares them. A stored term would let anyone who holds two rows compare +them without a key, and no query could use it. +Both paths refuse it. The typed Rust path bounds an order index on +vitaminc-ore's `Orderable`, which does not cover `Vec`, so the +declaration does not compile. The dynamic path, which both runners +use, refuses the declaration as `index_not_admitted` +(`v1/record-declarations-v1.cases.json`, cases `type-bytes-ore`, +`type-bytes-ope` and `type-bytes-ore_block`). + +A row stored under an earlier declaration of such an index still opens +once the index is removed from the plan: opening ignores a stored term the +plan does not declare. + +A write reads each value as its field's type, by the rules a query reads +its input by. A case whose input is of another type and converts exactly +has `stored`: the input converted to the field's type, in the same +`{type, text}` form. Its runners seal `stored` as a second row and check +that the input's row stores the same terms and a ciphertext of the same +length, and that both rows open to `stored`. The cases are an `int16` for +an `int8` field, an `int8` for a `uint8`, an `int64` for an `int128`, a +`uint64` for a `uint128` and a `float64` 1.5 for a `float32`. + +`expected_error` cases are refused before any pending operation, with the +structured diagnostic `code`, `reason` and `field`, and no key call. They +cover a value of another kind that does not convert (a `float64` for a +`decimal` field, an `int32` for a `date`, an `int64` for a `timestamp`, +text for `bytes`, bytes for `string`, an integer for `bool`), a null for a +required `bool`, `bytes` or `decimal`, and JavaScript's `undefined` for an +`int32` field, which is refused with the reason `undefined` even though the +field takes a SQL null. The input type `undefined` has an empty `text` and +the frame `01`. Go has no value that writes it, so the Go runner checks the +case's shape and skips it; the native runner runs it. + +## Unsupported host conversions + +`host_conversions` lists values a binding's host refuses before the engine +sees them. Each names its `language`; today every entry is `go`. The +`value` is one of a closed vocabulary both runners check: + +| `value` | The Go value | Why the host refuses it | +|---|---|---| +| `zero_date` | `encrypt.Date{}` | The zero `Date` is not a date | +| `decimal_scale_29` | `encrypt.Decimal{Scale: 29}` | A decimal's scale is at most 28 | +| `timestamp_year_300000` | `time.Date(300000, …)` | Outside the timestamp decoder's range | +| `complex128` | `complex(1, 2)` | No transport leaf carries a complex number | +| `map_int_key` | `map[int]string` | Object keys are text | +| `channel` | `chan int` | Not a value | + +Go refuses each through `Seal` and `QueryTerm` with `ErrEncoding` and no +engine diagnostic, which shows the guest was never asked. Native Rust has +no host conversion layer: the typed API cannot spell these values, and the +dynamic API takes frames. Its runner checks the entries' shape and +vocabulary and runs none of them. Python and TypeScript will add their own +rows (bool/int, bytes/text, Number/bigint) when their runners exist. + +## Scope and remaining work + +The profile covers the record path and equality/order terms under +`NoTargets`. Match terms, EQL targets, JSON documents and context fields +remain the other profiles' coverage. Every positive case here is also +written fresh by each runner and opened by the other under the +[exchange profile](exchange-contract.md). Dates before year 1 and the ends of the timestamp range +are not in the corpus: Go's date parsing does not read them, and the +engine's bound is the decoder's. Negative-zero decimals are not in the +corpus because Go's `Decimal` drops the sign of a zero before sealing. + +No existing fixture or test is changed. The value-kinds fixture keeps its +typed Rust comparisons and generated Go methods. diff --git a/conformance/vitaminc-aead/README.md b/conformance/vitaminc-aead/README.md new file mode 100644 index 0000000000..5e6e130467 --- /dev/null +++ b/conformance/vitaminc-aead/README.md @@ -0,0 +1,99 @@ +# Value conformance corpus + +`value-conformance.json` contains the shared vectors that three codecs +check: Rust, Node, and the Go frame codec in +`languages/golang/encrypt/frame`. + +Payload bytes are frozen by +`vitaminc-aead`'s scalar tag table and leaf codec ([`vitaminc-aead`'s ADR 0001](../../packages/vitaminc-aead/docs/adr/0001-describe-plaintext-once-and-consume-it-with-sinks.md) +section 3): +fixed-width integers and float bits are little-endian, dates count days from +CE, timestamps carry seconds plus nanoseconds, decimals retain their flags and +96-bit coefficient, and a logical type with no tag of its own travels in the +`0xF3` envelope (id, one-byte parameter, physical scalar). + +## Formatting + +The file is Biome-formatted. The formatter may change its layout, never its +parsed content. Every reader parses it as JSON, so the layout fails no test. +After editing it, run `pnpm run code:fix` before committing. + +## Sections + +| Section | Rust | Node | Go | What it pins | +| ---------------------- | ---- | ---- | --- | ------------------------------------------------------------------- | +| `vectors` | yes | yes | yes | A valid value: decodes to the host value, encodes back to the bytes | +| `normalized` | yes | yes | yes | A valid value that reads back as a different canonical value | +| `malformed` | yes | yes | yes | Bytes every decoder must refuse | +| `ciphertext_malformed` | yes | no | yes | Ciphertext transport bytes the codec must refuse | +| `leaf_type_aad` | yes | no | no | The `LeafTypeAad` context bytes for a (base, kind, logical) triple | + +Node has no ciphertext transport codec, and neither binding exposes +`LeafTypeAad`, so those two sections are asserted where the code is. A new +section is consumed by every language that has the code it describes; the +table above is the record of who asserts what, so keep it current. + +## Fields + +Every row has a `name`. A row that follows an ADR 0001 rule states it in a +`rule` field, so a failing vector says which rule it pins. "ADR 0001" in a +`rule` means `vitaminc-aead`'s ADR 0001, not Stack Encrypt's. + +`vectors`: `kind`, `value` and the hexadecimal `transport` bytes. Integer and +decimal values are strings to avoid JSON number rounding. Bytes are +hexadecimal. A timestamp row may carry a `unit` (`seconds`, `millis`, +`micros`; nanoseconds is the shorthand tag); `js_date` selects a native +JavaScript Date, and other timestamps keep their nanoseconds in a wrapper, +spelled RFC 3339. Dates and timestamps cover jiff's range, years -9999 to +9999, in every binding, and a negative year is a sign and six digits +(`-000005-03-01`), as jiff and JavaScript write it. An `unknown` kind +carries `{id, param, kind, value}` for the envelope's physical scalar. + +`normalized`: as `vectors`, plus `reencode` (the canonical bytes every +language writes back) and `reencode_value` (the host value it reads as). + +`ciphertext_malformed`: `transport` bytes of a ciphertext tree. + +`leaf_type_aad`: `base`, `kind` (the physical kind), an optional `logical` +`{id, param}`, and the `context` bytes; its `rule` spells out the encoding so +another language can build the bytes from the corpus alone. + +## Host projections + +Rust re-encodes every valid vector byte for byte. A host language whose +value model cannot hold a vector as it is says so in an explicit field rather +than skipping the row: + +- `js_reencode`: Node has two projections. A Float32 becomes a Number and + re-encodes as Float64. A timestamp that is a whole number of milliseconds + is read as a `Date`, and re-encodes as the `Timestamp(Millis)` envelope. A + finer timestamp is read as an `RcTimestamp`, and re-encodes in the + nanosecond shorthand. As for Go, the timestamp projection is safe for two + reasons. `LeafTypeAad` binds the kind and the logical id, but not the + unit. The equality terms put every unit in one timestamp domain. +- `go_reencode`: Go has two projections. `undefined` becomes nil and + re-encodes as null. A timestamp in the envelope (seconds, milliseconds or + microseconds) is read as a `time.Time` and re-encodes in the nanosecond + shorthand, which is safe because `LeafTypeAad` binds the kind and the + logical id but not the unit, and the equality terms put every unit in one + timestamp domain. +- `js: "refused"`: Node has no value for this row and refuses it. Today that + is the `unknown-logical` envelope, a Node limitation tracked in #446, not a + rule of the format; Rust and Go read and re-encode it unchanged. + +New vectors state any additional projection the same way. + +## How each language checks a vector + +Rust, Go and Node each build the expected host value from `kind` and `value` +without their transport decoder, then check both directions: decoding the +bytes gives that value, and encoding that value gives the bytes. A bug that +decodes and encodes symmetrically wrong therefore still fails. Adding a kind +means teaching each language's `expected` helper to build it. The Go fuzz +targets take their seeds from `vectors`, `malformed`, `normalized`, and +`ciphertext_malformed`. Every row is therefore also a starting input for +fuzzing the Go decoders. + +These are the scalar/value-level vectors needed by #375 and #414. The wider +#332 cross-language ciphertext, guest-object and SDK corpus remains separate +work. diff --git a/conformance/vitaminc-aead/value-conformance.json b/conformance/vitaminc-aead/value-conformance.json new file mode 100644 index 0000000000..30e19d3a46 --- /dev/null +++ b/conformance/vitaminc-aead/value-conformance.json @@ -0,0 +1,810 @@ +{ + "vectors": [ + { + "name": "null", + "kind": "null", + "value": null, + "transport": "00" + }, + { + "name": "undefined", + "kind": "undefined", + "value": null, + "transport": "01", + "go_reencode": "00" + }, + { + "name": "false", + "kind": "bool", + "value": false, + "transport": "02" + }, + { + "name": "true", + "kind": "bool", + "value": true, + "transport": "03" + }, + { + "name": "int8", + "kind": "int8", + "value": "-128", + "transport": "0c80" + }, + { + "name": "uint8", + "kind": "uint8", + "value": "255", + "transport": "0dff" + }, + { + "name": "int16", + "kind": "int16", + "value": "-32768", + "transport": "0e0080" + }, + { + "name": "uint16", + "kind": "uint16", + "value": "65535", + "transport": "0fffff" + }, + { + "name": "int32", + "kind": "int32", + "value": "-2147483648", + "transport": "0400000080" + }, + { + "name": "uint32", + "kind": "uint32", + "value": "4294967295", + "transport": "06ffffffff" + }, + { + "name": "int64", + "kind": "int64", + "value": "-9223372036854775808", + "transport": "050000000000000080" + }, + { + "name": "uint64", + "kind": "uint64", + "value": "18446744073709551615", + "transport": "07ffffffffffffffff" + }, + { + "name": "int128", + "kind": "int128", + "value": "-170141183460469231731687303715884105728", + "transport": "1000000000000000000000000000000080" + }, + { + "name": "uint128", + "kind": "uint128", + "value": "340282366920938463463374607431768211455", + "transport": "11ffffffffffffffffffffffffffffffff" + }, + { + "name": "float32", + "kind": "float32", + "value": 1.5, + "transport": "080000c03f", + "js_reencode": "09000000000000f83f" + }, + { + "name": "float64", + "kind": "float64", + "value": -1.5, + "transport": "09000000000000f8bf" + }, + { + "name": "text", + "kind": "string", + "value": "é", + "transport": "0a02000000c3a9" + }, + { + "name": "text-nul", + "kind": "string", + "value": "a\u0000b", + "transport": "0a03000000610062" + }, + { + "name": "bytes", + "kind": "bytes", + "value": "00ff07", + "transport": "0b0300000000ff07" + }, + { + "name": "date", + "kind": "date", + "value": "2024-02-29", + "transport": "1281460b00" + }, + { + "name": "date-year-zero", + "kind": "date", + "value": "0000-01-01", + "transport": "1293feffff" + }, + { + "name": "date-min", + "kind": "date", + "value": "-009999-01-01", + "transport": "12b844c8ff" + }, + { + "name": "date-max", + "kind": "date", + "value": "9999-12-31", + "transport": "12dbb93700" + }, + { + "name": "timestamp", + "kind": "timestamp", + "value": "1970-01-01T00:00:00.123Z", + "transport": "130000000000000000c0d45407", + "js_date": true, + "js_reencode": "f30301057b00000000000000" + }, + { + "name": "timestamp-nanos", + "kind": "timestamp", + "value": "1969-12-31T23:59:59.999999999Z", + "transport": "13ffffffffffffffffffc99a3b", + "js_date": false + }, + { + "name": "timestamp-negative-year", + "kind": "timestamp", + "value": "-000005-03-01T12:00:00.000000001Z", + "transport": "1340a2727df1ffffff01000000", + "js_date": false + }, + { + "name": "timestamp-min", + "kind": "timestamp", + "value": "-009999-01-02T01:59:59Z", + "transport": "131fb9060fa8ffffff00000000", + "js_date": true, + "js_reencode": "f3030105182143b27aa8feff" + }, + { + "name": "timestamp-max", + "kind": "timestamp", + "value": "9999-12-30T22:00:00.999999999Z", + "transport": "13e0d3f2ff3a000000ffc99a3b", + "js_date": false + }, + { + "name": "decimal", + "kind": "decimal", + "value": "1.50", + "transport": "1400000200960000000000000000000000" + }, + { + "name": "decimal-min", + "kind": "decimal", + "value": "-79228162514264337593543950335", + "transport": "1400000080ffffffffffffffffffffffff" + }, + { + "name": "decimal-small", + "kind": "decimal", + "value": "0.0000000000000000000000000001", + "transport": "1400001c00010000000000000000000000" + }, + { + "name": "empty-array", + "kind": "array", + "value": [], + "transport": "f000000000" + }, + { + "name": "empty-object", + "kind": "object", + "value": {}, + "transport": "f100000000" + }, + { + "name": "uuid", + "kind": "uuid", + "value": "123e4567-e89b-12d3-a456-426614174000", + "transport": "f305000b10000000123e4567e89b12d3a456426614174000", + "rule": "ADR 0001 section 3: Uuid has no shorthand tag, so it travels in the 0xF3 envelope over sixteen bytes" + }, + { + "name": "timestamp-millis", + "kind": "timestamp", + "unit": "millis", + "value": "1970-01-01T00:00:00.123Z", + "transport": "f30301057b00000000000000", + "js_date": true, + "go_reencode": "130000000000000000c0d45407", + "rule": "ADR 0001 section 3: Timestamp(Millis) over an i64 count travels in the 0xF3 envelope; Go reads it as time.Time and writes nanoseconds" + }, + { + "name": "timestamp-seconds", + "kind": "timestamp", + "unit": "seconds", + "value": "1970-01-01T00:00:10Z", + "transport": "f30300050a00000000000000", + "js_date": true, + "go_reencode": "130a0000000000000000000000", + "js_reencode": "f30301051027000000000000", + "rule": "ADR 0001 section 3: Timestamp(Seconds) travels in the 0xF3 envelope; Go writes it back in nanoseconds and Node writes a Date back in milliseconds" + }, + { + "name": "timestamp-micros", + "kind": "timestamp", + "unit": "micros", + "value": "1970-01-01T00:00:00.000001000Z", + "transport": "f30302050100000000000000", + "go_reencode": "130000000000000000e8030000", + "js_reencode": "130000000000000000e8030000", + "rule": "ADR 0001 section 3: Timestamp(Micros) travels in the 0xF3 envelope; Go and Node write it back in nanoseconds" + }, + { + "name": "unknown-logical", + "kind": "unknown", + "value": { + "id": 200, + "param": 9, + "kind": "uint32", + "value": "34" + }, + "transport": "f3c8090622000000", + "js": "refused", + "rule": "ADR 0001 section 3: a logical id this build does not know is read and re-encoded unchanged (Rust, and Go through Tagged); a host builder with no value to carry it in refuses the leaf rather than dropping the annotation, which is what Node does today (#446 tracks a carrier)" + } + ], + "malformed": [ + { + "name": "unknown-tag", + "transport": "ef" + }, + { + "name": "invalid-utf8", + "transport": "0a01000000ff" + }, + { + "name": "trailing", + "transport": "0000" + }, + { + "name": "invalid-date", + "transport": "12ffffff7f" + }, + { + "name": "invalid-timestamp-nanos", + "transport": "13000000000000000000ca9a3b" + }, + { + "name": "invalid-timestamp-range", + "transport": "13ffffffffffffff7f00000000" + }, + { + "name": "date-before-min", + "transport": "12b744c8ff", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "date-past-max", + "transport": "12dcb93700", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-before-min", + "transport": "131eb9060fa8ffffffffc99a3b", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-past-max", + "transport": "13e1d3f2ff3a00000000000000", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-expanded-year", + "transport": "130001d6b14900000001000000", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused; this instant in year 12000 opened before the move from chrono" + }, + { + "name": "decimal-reserved-bits", + "transport": "1401000000000000000000000000000000" + }, + { + "name": "decimal-scale", + "transport": "1400001d00000000000000000000000000" + }, + { + "name": "tag-0c-width-0", + "transport": "0c" + }, + { + "name": "tag-0c-width-2", + "transport": "0c0000" + }, + { + "name": "tag-0d-width-0", + "transport": "0d" + }, + { + "name": "tag-0d-width-2", + "transport": "0d0000" + }, + { + "name": "tag-0e-width-1", + "transport": "0e00" + }, + { + "name": "tag-0e-width-3", + "transport": "0e000000" + }, + { + "name": "tag-0f-width-1", + "transport": "0f00" + }, + { + "name": "tag-0f-width-3", + "transport": "0f000000" + }, + { + "name": "tag-10-width-15", + "transport": "10000000000000000000000000000000" + }, + { + "name": "tag-10-width-17", + "transport": "100000000000000000000000000000000000" + }, + { + "name": "tag-11-width-15", + "transport": "11000000000000000000000000000000" + }, + { + "name": "tag-11-width-17", + "transport": "110000000000000000000000000000000000" + }, + { + "name": "tag-12-width-3", + "transport": "12000000" + }, + { + "name": "tag-12-width-5", + "transport": "120000000000" + }, + { + "name": "tag-13-width-11", + "transport": "130000000000000000000000" + }, + { + "name": "tag-13-width-13", + "transport": "1300000000000000000000000000" + }, + { + "name": "tag-14-width-15", + "transport": "14000000000000000000000000000000" + }, + { + "name": "tag-14-width-17", + "transport": "140000000000000000000000000000000000" + }, + { + "name": "timestamp-leap-second", + "transport": "133b000000000000001597f642", + "rule": "ADR 0001 section 3: a leap second has no count since the epoch in any unit and is refused" + }, + { + "name": "envelope-over-shorthand", + "transport": "f302000400000000", + "rule": "ADR 0001 section 3: there is one encoding per value, so an envelope over a type with a shorthand tag is refused" + }, + { + "name": "envelope-id-zero", + "transport": "f3000000", + "rule": "ADR 0001 section 3: id 0 means no logical type and has no envelope" + }, + { + "name": "envelope-known-id-bad-param", + "transport": "f305010b10000000123e4567e89b12d3a456426614174000", + "rule": "ADR 0001 section 3: a known id with a parameter it cannot take is refused" + }, + { + "name": "envelope-uuid-wrong-length", + "transport": "f305000b03000000010203", + "rule": "ADR 0001 section 3: a Uuid is sixteen bytes" + }, + { + "name": "envelope-nested", + "transport": "f3c800f3c80000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar, not another envelope" + }, + { + "name": "envelope-unknown-over-undefined", + "transport": "f3c80001", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar; Undefined has a shorthand tag and is refused" + }, + { + "name": "envelope-unknown-over-date", + "transport": "f3c8001200000000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar; Date has a shorthand tag and is refused" + }, + { + "name": "envelope-unknown-over-array", + "transport": "f3c800f000000000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar, not a container" + }, + { + "name": "leaf-0xf4", + "transport": "f4", + "rule": "ADR 0001 section 3: 0xF4 is reserved for a longer envelope and is refused" + }, + { + "name": "leaf-0xf4-with-payload", + "transport": "f405000b00000000", + "rule": "ADR 0001 section 3: 0xF4 is reserved for a longer envelope and is refused" + }, + { + "name": "envelope-timestamp-nanos", + "transport": "f30303050000000000000000", + "rule": "ADR 0001 section 3: a logical type with a shorthand tag is written with it, so Timestamp in nanoseconds (unit 3) inside the envelope is refused; units 0 to 2 have no shorthand and are accepted" + }, + { + "name": "envelope-undefined", + "transport": "f3010000", + "rule": "ADR 0001 section 3: Undefined (id 1) has the shorthand tag 0x01 and is refused inside the envelope" + }, + { + "name": "envelope-decimal", + "transport": "f304021000000000000000000000000000000000", + "rule": "ADR 0001 section 3: Decimal (id 4) has the shorthand tag 0x14 and is refused inside the envelope" + }, + { + "name": "envelope-timestamp-bad-unit", + "transport": "f30304050000000000000000", + "rule": "ADR 0001 section 3: Timestamp takes a unit of 0 to 3 as its parameter; 4 is refused" + }, + { + "name": "envelope-timestamp-not-int", + "transport": "f303010a00000000", + "rule": "ADR 0001 section 3: Timestamp admits only an int as its physical value; text is refused" + }, + { + "name": "envelope-timestamp-out-of-range", + "transport": "f30300100000000000000000000000000000ff7f", + "rule": "ADR 0001 section 3: a timestamp count outside the representable range (here an i128 of seconds far past year 9999) is refused" + }, + { + "name": "envelope-uuid-over-text", + "transport": "f305000a1000000030313233343536373839616263646566", + "rule": "ADR 0001 section 3: Uuid admits only sixteen bytes as its physical value; text of that length is refused" + }, + { + "name": "envelope-truncated", + "transport": "f3c8", + "rule": "ADR 0001 section 3: the envelope is id, parameter and a physical scalar; a parameter and payload cut off are refused" + }, + { + "name": "typed-null-truncated", + "transport": "15", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-no-padding", + "transport": "1506", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-short-padding", + "transport": "15060000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-nonzero-padding", + "transport": "1506000100", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-trailing", + "transport": "150600000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-null", + "transport": "1500", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-undefined", + "transport": "1501", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-bool", + "transport": "1502", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-text", + "transport": "150a", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-plain-bytes", + "transport": "150b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-nested", + "transport": "151506000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-array", + "transport": "15f000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-over-shorthand", + "transport": "15f3020004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-timestamp-nanos", + "transport": "15f3030310000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-id-zero", + "transport": "15f3000004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-undefined", + "transport": "15f3010004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-decimal", + "transport": "15f3040004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-over-int", + "transport": "15f3050004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-with-length", + "transport": "15f305000b10000000000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-with-parameter", + "transport": "15f305010b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-timestamp-over-float", + "transport": "15f303010900000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-unknown-over-bytes", + "transport": "15f3c8000b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-unknown-over-bool", + "transport": "15f3c80002", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-inside-envelope", + "transport": "f3c800150c", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-0xf4", + "transport": "15f4c80004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + } + ], + "normalized": [ + { + "name": "decimal-negative-zero", + "kind": "decimal", + "value": "-0.00", + "transport": "1400000280000000000000000000000000", + "reencode": "1400000200000000000000000000000000", + "reencode_value": "0.00", + "rule": "ADR 0001 section 3: a decimal negative zero reads back as zero with its scale kept, and zero is always written without the sign" + }, + { + "name": "typed-null-uint32", + "kind": "null", + "value": null, + "transport": "1506000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-int8", + "kind": "null", + "value": null, + "transport": "150c", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-float64", + "kind": "null", + "value": null, + "transport": "150900000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-date", + "kind": "null", + "value": null, + "transport": "1512000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-timestamp", + "kind": "null", + "value": null, + "transport": "15130000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-decimal", + "kind": "null", + "value": null, + "transport": "1514000000000000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-timestamp-millis", + "kind": "null", + "value": null, + "transport": "15f303010500000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-uuid", + "kind": "null", + "value": null, + "transport": "15f305000b000000000000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-unknown-over-float32", + "kind": "null", + "value": null, + "transport": "15f3c80908000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + } + ], + "ciphertext_malformed": [ + { + "name": "ct-none", + "transport": "0204000000deadbeef", + "rule": "ADR 0001 section 3: CT_NONE (0x02) is retired because a None is a null leaf; it is never written and refused when read" + }, + { + "name": "ct-none-in-sequence", + "transport": "03010000000204000000deadbeef", + "rule": "ADR 0001 section 3: CT_NONE is refused wherever it appears" + } + ], + "leaf_type_aad": { + "rule": "LeafTypeAad (ADR 0001 section 3): the context is PAE(domain, base, kind, id) under the vitaminc-context encoding, where PAE is a u64-le count then each element as a u64-le length and its bytes, and each element is itself a typed piece: a PAE of two parts, the u64-le-prefixed label vitaminc/context/value/v1 and the u64-le-prefixed type label then the payload. The domain is bytes/v1 over vitaminc/aead/leaf-type/v2; the base is utf8/v1 over the base string; the kind is u8-le/v1 over the physical kind byte (null 0, bool 1, int 2, float 3, text 4, bytes 5; a cross-language commitment, never renumbered); the id is u8-le/v1 over the logical id byte, 0 for no logical type. The parameter is not bound: two vectors with the same base, kind and id and different parameters have the same context.", + "vectors": [ + { + "name": "int-date", + "base": "ctx", + "kind": "int", + "logical": { + "id": 2, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002" + }, + { + "name": "text-no-logical", + "base": "ctx", + "kind": "text", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "bytes-uuid", + "base": "schema", + "kind": "bytes", + "logical": { + "id": 5, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310600000000000000736368656d61530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005" + }, + { + "name": "int-timestamp-millis", + "base": "events", + "kind": "int", + "logical": { + "id": 3, + "param": 1 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" + }, + { + "name": "int-decimal-scale-2", + "base": "price", + "kind": "int", + "logical": { + "id": 4, + "param": 2 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" + }, + { + "name": "null-undefined", + "base": "ctx", + "kind": "null", + "logical": { + "id": 1, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001" + }, + { + "name": "bool-no-logical", + "base": "ctx", + "kind": "bool", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "float-no-logical", + "base": "ctx", + "kind": "float", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "int-decimal-scale-0", + "base": "price", + "kind": "int", + "logical": { + "id": 4, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" + }, + { + "name": "int-timestamp-nanos", + "base": "events", + "kind": "int", + "logical": { + "id": 3, + "param": 3 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" + } + ] + } +} diff --git a/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md new file mode 100644 index 0000000000..f7fa7aa0fd --- /dev/null +++ b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md @@ -0,0 +1,630 @@ +--- +status: accepted +date: 2026-10-08 +revised: 2026-10-12, amended 2026-10-18 and 2026-10-19 +relates-to: ADR-0001; stack-encrypt ADR-0003, ADR-0007 +--- + +# One value model, three encodings in vitaminc, and EQL v4 separated by producer + +> **Revised 2026-10-12.** This ADR now carries the decisions from +> [`docs/plans/2026-10-11-order-and-equality-terms-layering.md`](../plans/2026-10-11-order-and-equality-terms-layering.md): +> vitaminc sits at the bottom of the stack, equality and order terms take +> per-domain transforms over a shared semantic baseline, `vitaminc-prf` no +> longer depends on order encodings, and `orderable-bytes` is frozen. The plan +> keeps the steps; this document is the decision. +> +> **Amended 2026-10-18.** vitaminc 0.6 removed the shared value type rather +> than renaming `FfiValue` to `Value` ([`vitaminc-aead`'s ADR 0001](../../packages/vitaminc-aead/docs/adr/0001-describe-plaintext-once-and-consume-it-with-sinks.md): a value describes +> itself once, and sinks consume it). Stack Encrypt follows: +> +> - A plaintext whose type is known only at run time is held as its +> transport frame (`dynamic::frame::Frame`, or `OwnedFrame` where it is kept) +> and walked into vitaminc's sinks. +> - `FfiValue` is removed. Each kind of control data a binding exchanges +> with the engine (a plan, a context, options, statistics, a configuration, +> the engine's answers) gets a type of its own, read from and written to a +> frame. Credentials in a configuration, such as the client key, are held +> in `Protected` fields. Until each message has its type, `FfiValue` carries +> only control data, never plaintext. +> - The open decision on exhaustive handling is settled by vitaminc 0.6's +> design (see "Exhaustive handling of kinds"). +> +> The bullets below that this changes say so where they stand. +> +> **Amended 2026-10-19.** A timestamp's microsecond resolution truncates +> rather than rounding half to even, as vitaminc does for both the equality +> and the order term. The reason, and the rule, are under "Lossy transforms". + +Every value Stack Encrypt handles is encoded three times: as a **ciphertext** +(reversible and self-describing), as an **equality term** (a keyed hash that +must be unambiguous) and as an **order term** (bytes whose order is the +value's order). This ADR decides where each encoding lives, which kinds of +value exist, how each kind is normalised before a term is derived from it, +and how EQL keeps columns written by Stack Encrypt apart from columns written +by cipherstash-client. + +## The problem + +In October 2026 Stack Encrypt could produce one of EQL's 51 types, `TextEq`. +The number, date, timestamp and decimal families were blocked on encoding, +not code. (`Bool` was not: it already had a kind, and EQL's only boolean +type, `eql_v3_boolean`, stores a ciphertext and nothing else.) + +- **The three encodings disagreed about which types exist.** `i16` had an + equality domain in `vitaminc-prf` and an order encoding, but no ciphertext + tag, so it could not be a kind. Date, timestamp and decimal had order + encodings only. +- **The mapping from a kind to a Rust type lived in Stack Encrypt.** + `dynamic::term::Scalar` mirrored `FfiValue`'s variants one for one to + dispatch to the term crates, and `dynamic::Value` wrapped `FfiValue` only to + add `Clone`. Both restated vitaminc's vocabulary in a downstream crate. +- **Ordering was implemented twice.** `orderable-bytes` defines a canonical, + order-preserving encoding per type. cllw-ore uses it for chrono and decimal + but hand-rolls integers and floats, and differs on `-0.0`. Block ORE was not + derivable at all, so `TextOrdOre` and `TextSearchOre` were refused. +- **Order encodings were spread over three repositories.** Encodings lived in + ore.rs, schemes in ore.rs and cipherstash-suite, and term derivation in + vitaminc and Stack Encrypt. Every change needed releases in all of them, + and the scheme crates accepted raw bytes, so a hand-encoded integer + (little-endian, sign bit not flipped) encrypted without error and sorted + wrong. +- **The existing writer's encodings are inconsistent.** cipherstash-client + hashes a timestamp's milliseconds but orders by its nanoseconds, and hashes + a decimal with its scale while ordering ignores it. Its block ORE text is + ASCII-only, lowercased, maps every digit to one symbol and truncates to six + blocks. cllw-ore's text order form (`orderize_string`) decomposes to NFD and + then drops every character that is not alphanumeric, whitespace or ASCII + punctuation, which removes symbols, emoji and non-ASCII punctuation as well + as accents, and does not fold case. +- **Two producers wrote the same EQL domains.** A Stack Encrypt query term + never matches a cipherstash-client term for the same value, and the + `eql_v3_*` domains could not tell them apart. A query from one against a + column written by the other returned no rows, silently. + +## Options considered + +**Where the value model lives.** + +1. **Move `vitaminc-aead-value` into Stack Encrypt.** It looks like FFI + plumbing. But it is the value model for vitaminc's own `Cipher` traits: + `aead-napi` and vitaminc's Go binding encrypt with `Aes256Cipher` through + it, without Stack Encrypt. Moving it makes vitaminc Rust-only, makes + vitaminc depend on Stack Encrypt (which depends on six vitaminc crates), + or forks the frozen tag table into two copies. +2. **Keep it in vitaminc, and move term derivation there too.** All three + encodings then live in one repository, next to the value type they + encode. Chosen. How "a kind exists in every layer or in none" is enforced + is under "Exhaustive handling of kinds" below, with the conformance test + described under "Which kinds get which terms" as the backstop. + +**Where order schemes sit.** + +1. **`vitaminc-ore` adapts the scheme crates.** It depends on cllw-ore and + ore-rs and wraps each in its own trait, with `orderable-bytes` underneath. + This is the spread over three repositories described above. +2. **vitaminc at the bottom.** `vitaminc-ore` owns the order encodings and an + `OrderScheme` trait and depends on no scheme crate; cllw-ore and ore-rs + implement the trait. A scheme's input is a sealed type only `vitaminc-ore` + can build, so raw bytes cannot reach a scheme. Chosen. + +**How EQL separates the two producers.** The SQL for both is identical; only +the producer of the terms differs. + +1. **Name only.** Stack Encrypt payloads go in the `eql_v3_*` domains, + distinguished by the `stack-encrypt:1:` ciphertext prefix. Nothing in the + database stops a cross-producer comparison. +2. **A producer tag in every payload and term, checked by every operator.** + A runtime check on the hottest SQL paths, across about 24k lines of + hand-written SQL. +3. **One SQL source, emitted under two names.** The build writes the same + source out as `eql_v3` (cipherstash-client terms) and `eql_v4` (Stack + Encrypt terms). A column's domain names its producer: a payload written + to the other producer's domain fails its check on insert, and a typed + client sees two different types. Names alone do not stop a cross-producer + `=` in SQL; see Consequences. Chosen. + +**How v3 and v4 ship.** Bumping `main` to v4 and patching v3 from a branch +needs a maintenance release path for five lockstep artefacts that does not +exist, and the EQL publish script puts every stable release on `latest`, so a +3.x patch would move `latest` backwards. A second package doubles the +trusted-publishing and release surface. One package carrying both bundles +avoids both, at the cost of teaching the release tooling about a second +bundle (see Consequences). Chosen. + +## Decision + +### Kinds and the ciphertext + +- vitaminc 0.6.0 adds the kinds `Int8`, `UInt8`, `Int16`, `UInt16`, `Int128`, + `UInt128`, `Date`, `Timestamp` and `Decimal`, each with a `ValueKind` name, + a `Value` variant and a ciphertext tag, in one breaking release. Rust `i128` + and `u128` get `Encrypt` and `Decrypt` impls. +- ~~`FfiValue` is renamed `Value`, with `#[deprecated] pub type FfiValue = Value` + for one release.~~ *Amended 2026-10-18:* vitaminc 0.6 has no shared value + type to rename it to. Its [ADR 0001](../../packages/vitaminc-aead/docs/adr/0001-describe-plaintext-once-and-consume-it-with-sinks.md) has a value describe itself once + (`Encrypt`) and every consumer be a sink: the encrypting sink, a term + deriver, a frame writer. A host binding walks its transport frame straight + into those sinks. So Stack Encrypt holds a dynamic plaintext as its frame, + read in place as a `dynamic::frame::Frame` or kept as an `OwnedFrame` in a + wiped buffer, from the source a binding hands + over to the sealed leaves and from the opened leaves back to the frame it + returns, with no value tree in between. `FfiValue` is removed rather than + kept for control data: each control message gets its own type, read from + and written to a frame, and holds any credential in a `Protected` field. + `ValueKind`, the vocabulary a plan field declares, stays, and is + exhaustive. +- Every variant exists in every build. `Date`, `Timestamp` and `Decimal` use + vitaminc's own representation (the payloads in the table below), with + conversions to and from chrono and rust_decimal behind those features. + *Amended 2026-11-19:* vitaminc 0.10 converts dates and timestamps to and + from jiff, behind its `jiff` feature, in place of chrono. A + variant that appeared only with a feature would break any exhaustive + handling outside `vitaminc-aead-value`, because features unify across a + build and a crate can check only its own. +- `Value` implements `Clone` as a deep copy that rebuilds every leaf into a + fresh `Protected`. A clone is under the same custody as its original. +- The sealed leaf tag table (`tags.rs`) stays frozen and contiguous. The + transport codec's framing tags move from `0x10`–`0x12` to `0xF0`–`0xF2`; + transport carries no compatibility commitment and every user of it updates + together. A leaf is `[tag] ++ payload`. The new leaves, which every binding + must produce byte for byte: + + | Tag | Kind | Payload | + |---|---|---| + | `0x0C`, `0x0D` | `Int8`, `UInt8` | 1 byte; two's complement for `Int8` | + | `0x0E`, `0x0F` | `Int16`, `UInt16` | 2 bytes, little-endian; two's complement for `Int16` | + | `0x10`, `0x11` | `Int128`, `UInt128` | 16 bytes, little-endian; two's complement for `Int128` | + | `0x12` | `Date` | `i32`, little-endian: the day number in the proleptic Gregorian calendar with **0001-01-01 as day 1** (chrono's `num_days_from_ce`). 0001-01-01 is `01 00 00 00`, not zero. *Amended 2026-11-19:* vitaminc 0.10 admits only dates from `-009999-01-01` to `9999-12-31`, jiff's range, in every binding; a stored date outside it no longer reads | + | `0x13` | `Timestamp` | `i64` Unix seconds, then `u32` nanoseconds, both little-endian, UTC. Nanoseconds are below 1,000,000,000. *Amended 2026-10-18 (#1144):* vitaminc 0.6 refuses a leap second: nanoseconds of 1,000,000,000 or more (chrono's leap-second representation, which the pre-ADR-0001 `Value` codec accepted when the seconds modulo 60 were 59) are refused, because a leap second has no count in any unit. The instant must also lie within chrono's `NaiveDateTime` range (vitaminc's `MIN_TIMESTAMP_NANOS` to `MAX_TIMESTAMP_NANOS`, years -262143 to 262142). Anything else is refused. *Amended 2026-11-19:* vitaminc 0.10 narrows the range to jiff's, `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`, in every binding; a stored instant outside it no longer reads. The bytes of an instant in range are unchanged | + | `0x14` | `Decimal` | 16 bytes: a little-endian `u32` of flags (sign in bit 31, scale in bits 16–23 and at most 28, every other bit zero), then the low, middle and high little-endian `u32` words of the 96-bit mantissa. This is rust_decimal's `serialize()` and keeps the scale. There is no NaN or infinity | + +- `transport` stays a module of `vitaminc-aead-value`. + +### Semantic baseline and per-domain transforms + +The ciphertext keeps the value exactly as given: `1.50` decrypts as `1.50`, +and a timestamp keeps its nanoseconds. Terms are derived in two steps. + +**The semantic baseline** makes values that are equal under `Value`'s own +semantics encode the same. Every term applies it; it loses nothing a user +would call a different value. + +| Kind | Baseline | +|---|---| +| `Decimal` | scale normalised: `1`, `1.0` and `1.00` are equal | +| `Float32`, `Float64` | `-0.0` folded into `+0.0`; every NaN replaced by one positive quiet NaN, which sorts above +Infinity. This is Postgres's own `float8` semantics: `'NaN' = 'NaN'`, `'-0' = '0'` and `'NaN' > 'Infinity'` are all true | +| text | NFC | +| every other kind | none | + +**Lossy transforms** sit on top of the baseline, chosen by each term's +domain: timestamp resolution, text folding and prefix truncation. Each +transform and its version is named in the domain label, for example +`…/timestamp/day/v1`. The ones defined now: + +- **Timestamp resolution**: exact, microsecond or day. ~~Microsecond rounds + to the nearest microsecond, ties to even, on the signed microsecond count + since the epoch. That is what Postgres does when it parses a timestamp with + more digits than it keeps (`.1234565` becomes `.123456` and `.1234575` + becomes `.123458`, before and after 1970; checked on Postgres 17.5).~~ + *Amended 2026-10-19:* microsecond truncates: the nanoseconds below the + microsecond are dropped, never rounded, which is floor on the signed count + since the epoch (`.1234567` becomes `.123456`, and before 1970 an instant + moves earlier). vitaminc applies this rule to the equality term and to the + order term alike (vitaminc-ore's timestamp domain is + `vitaminc/ore/value/timestamp-micros/v1`, and both terms normalise through + `vitaminc_normalize::timestamp`), so `=` and the order agree on which + instants are one. Matching PostgreSQL's parse-time rounding is not a goal: + timestamps are stored in many places besides PostgreSQL, and a term must + mean the same thing whichever store holds it. A value that already has + microsecond precision is unchanged. Day takes the UTC calendar day. +- **Text fold, v1**: NFD, then full Unicode case folding (`CaseFolding.txt` + statuses C and F, so `ß` becomes `ss`), then NFD again, then removal of + every accent, then NFC. An accent is a mark (General_Category `Mn`, `Mc` + or `Me`) with a non-zero canonical combining class: the acute in `é`, the + umlaut in `ö`, a Devanagari virama. A mark of class zero is a letter of + its own in its script, such as a Thai or Devanagari vowel sign (U+0E31, + U+0901), and is kept. The order of the steps is part of the transform, + because folding can produce text that is no longer normalised and the + steps do not commute. + *Amended 2026-10-19:* this step said "every code point with + General_Category `Mn`", which would also drop class-zero vowel signs and + so tie different words. The fold that ships, `vitaminc-ore`'s + `vitaminc/ore/value/text-folded/unicode-16/v1`, keeps them, and this + bullet now describes it. +- **Prefix truncation**: a number of code points kept after any other + transform. Alphabet packing, if ever built, is a transform of the same + kind. + +Text transforms are pinned to a Unicode version, which is part of the label +(for example `text-fold/unicode-16/v1`), and the `unicode-normalization` and +case-folding tables are pinned to it. Code points unassigned in that version +pass through unchanged (canonical combining class 0, no decomposition, no +case mapping), so the transform is a fixed function and nothing is refused on +write. The cost is that two strings using characters added after the pin, +which a later Unicode would treat as equivalent, may not match. Moving the +pin is a new label: existing columns keep the label they were written under +and stay queryable, and a column moves only by re-encryption. +*Amended 2026-10-18:* vitaminc 0.6 refuses a code point unassigned in the +pinned version instead of passing it through. `vitaminc-normalize` (equality +and match terms) and `vitaminc-ore`'s fold (order terms) both return +`UnassignedCodePoint`, so text holding one has no term, and writing it to an +indexed column or querying with it is refused. The refusal is the same on +every path and in every language, so the transform is still a fixed +function of the text it accepts, and moving the pin is still a new label. + +Order terms fold case and accents because code-point order puts `é` after +`z`; a fixed fold approximates the first level of Unicode collation without +depending on ICU, whose sort keys change between versions. Equality on text +is not folded by default: a folded order term only produces ties, while a +folded equality term produces false matches. A case-insensitive equality is +its own domain. + +**Equality and order may take different transforms**, for example an exact +timestamp for equality and the day for order, or the same one ("locked"). +Stack's index spec carries the choice per column. Two rules bound it: + +- **A non-injective order transform needs an equality term beside it.** In + the EQL SQL, the numeric, date and timestamp `_ord`, `_ord_ope` and + `_ord_ore` domains store no `hm` and answer `=` with the order term + (`timestamp_ord_functions.sql`: `eq` is `ord_term(a) = ord_term(b)`). A + day-resolution order term there would make `=` match every row from that + day. So a lossy order transform is allowed only on a domain that also + stores an equality term and answers `=` through it, the shape `text_ord` + already has (`hm` and `op`). On the other domains the order transform is + injective: exact for numbers and dates, and for timestamps whatever + resolution the equality term would have used. +- **Labels separate domains; they do not make terms incomparable.** Terms + built with different transforms are unrelated bytes, so a probe built with + one matches nothing built with the other. Nothing in a stored term records + its label. Keeping a query on the same transforms as the column is the + index spec's job, and the EQL domain is what ties a column to its spec. + +A column's leakage is the combined leakage of all its terms. Truncating the +order term to the day hides the order of events within a day, but an exact +equality term on the same column still reveals which rows share a timestamp. + +### Which kinds get which terms + +- **Every scalar kind has a ciphertext.** Containers and null have no terms. +- **Equality:** every scalar kind except `Bool`, including floats over their + baseline bits. Stack Encrypt refused float equality until now, on the + grounds that equality on IEEE-754 values is a modelling error. The baseline + removes the two cases where bitwise equality and numeric equality disagree + (signed zero and NaN payloads), and what is left is exactly Postgres's + `float8 =`, which EQL's `real_eq` and `double_eq` domains already expose. + Whether a computed float is the value the caller meant is the caller's + problem, as it is for a plaintext float column. +- **Order:** every scalar kind except `Bool`, under all three schemes, with + one exception: block ORE for text, which waits for ore-rs's variable-length + block ORE (see Deferred). *Amended 2026-10-19:* the exception is gone. + ore-rs 0.9.0 released its chained scheme, and Stack Encrypt orders text + with it (see "EQL v4"). +- **`Bool` has a ciphertext only.** A keyed hash or an order term over a + domain of two values hides nothing: it splits the rows into two groups, and + an order term also says which group is `true`. Stack Encrypt stops + producing CLLW order terms for `Bool`, and `vitaminc-ore` has no `Bool` + encoding. cllw-ore keeps its `Bool` impl, so cipherstash-client and its + stored v3 terms are unaffected. + +These exceptions are an explicit, documented list kept next to vitaminc's +conformance test. The test fails for any kind that is missing from +`vitaminc-prf` or `vitaminc-ore` without an entry, and checks that values +equal under `Value` semantics produce equal terms in both. + +### Where each encoding lives + +- **Ciphertext:** `vitaminc-aead-value`. It does no term normalisation: its + `canonical` module and its dependency on `orderable-bytes` are removed. +- **Equality:** `vitaminc-prf`, which depends only on `vitaminc-aead-value`, + gains domains for every new kind, floats and `Decimal`, and applies the + baseline and its own transforms. It has no ordering dependency. The + value-derived PRF domains landed after vitaminc 0.5.1 and are unreleased, + so their bytes are still free to choose. +- **Order:** a new `vitaminc-ore` crate, released in lockstep with the other + vitaminc crates. + - It owns the order encodings (ported from `orderable-bytes`, kept in + `Protected`, pinned by golden vectors), the baseline, the order + transforms, and derivation of order terms from `&Value`. + - Its `OrderScheme` trait takes a sealed `OrderPlaintext`, fixed-length or + variable-length, that only `vitaminc-ore` can build, and returns a + scheme-defined term, roughly `type Term: Ord + AsRef<[u8]>`. Each scheme + keeps its own comparison and stored bytes. The trait also covers the key + type, domain separation (the label goes in as the salt) and typed errors. + - It depends on no scheme crate; its tests use a mock scheme. +- **Schemes:** cllw-ore (CLLW ORE and OPE) and ore-rs (block ORE) implement + `OrderScheme` behind an optional `vitaminc` feature, so cipherstash-client + takes no vitaminc dependency. Their typed APIs are unchanged and not + feature-gated. Block ORE through the trait uses each kind's natural width; + the 8-byte padding stays a detail of the typed API cipherstash-client uses. +- **`orderable-bytes` is frozen.** It stays as it is for cipherstash-client's + stored terms and is not part of the target design. +- **Term derivation** takes a `&Value` in `vitaminc-prf` and `vitaminc-ore` + and keeps leaves inside `Protected`. A pairing a layer does not support + returns a typed error from vitaminc. + +### Stack Encrypt + +- `dynamic::Value` and `dynamic::term::Scalar` are deleted. `dynamic::term` + takes any source that describes itself to vitaminc (amended 2026-10-17, + #1232: there is no `vitaminc_aead_value::Value`; a binding's value arrives + as a transport frame and stays one, `dynamic::frame::Frame`). `admits` keeps + only the rules that belong to Stack Encrypt, such as `Match` taking text + only. +- Order terms go through `vitaminc-ore`. The index for an ORE or OPE column + picks the concrete scheme (cllw-ore or ore-rs, through `OrderScheme`) and + its transforms; Stack Encrypt no longer calls cllw-ore's typed API. A block + ORE term kind joins CLLW ORE and OPE. +- `TextEq` normalises to NFC and moves to EQL v4. The Stack Encrypt targets on + `eql_v3_*` domains are deleted. The `stack-encrypt:1:` ciphertext prefix + stays: decryption does not pass through Postgres types, and the prefix is + what lets it reject the other producer's payload. + +### Host languages + +A binding picks the kind from the field's **declared EQL target**, never +from the host type. This keeps the rule `eql-bindings` already enforces: a +target accepts exactly one kind, and nothing below the binding converts. The +binding converts a host value into the target's kind when it can do so +without loss, and refuses it otherwise. + +| Kind | EQL family | | +|---|---|---| +| `Int16` | `smallint` | | +| `Int32` | `integer` | | +| `Int64` | `bigint` | | +| `Float32` | `real` | | +| `Float64` | `double` | | +| `Decimal` | `numeric` | | +| `Date` | `date` | | +| `Timestamp` | `timestamp` | | +| `String` | `text` | | +| `Bool` | `boolean` | | +| `Int8`, `UInt8`, `UInt16`, `UInt32`, `UInt64`, `Int128`, `UInt128`, `Bytes` | none | no EQL domain and no target name yet; a kind is selectable only once a target names it | + +- **Go.** Any Go integer type whose every value fits the target's kind is + accepted (`int8` into `smallint`, `int32` into `bigint`); a wider one is + range-checked and refused if the value does not fit. `int8`, `int16`, + `uint8` and `uint16` get their own kinds when a target names them; no + target does yet, so today they reach `Int16`, `Int32` or `Int64` through + the fits-losslessly rule. + *Amended 2026-10-18 (#1144):* a field with no EQL target (`encrypt`, + `index=`) has no target to pick a kind from, so Go picks it from the Go + type: each integer type is its own kind (`int8` is `Int8`, `int16` + `Int16`, `uint8` `UInt8`, `uint16` `UInt16`, `int` and `int64` `Int64`, + `uint` and `uint64` `UInt64`), and its order terms are that width's. A + field stored as an EQL target still takes the target's kind, by the rule + above. + `Int128` and `Uint128` are SDK value types. `time.Time` means `Timestamp`, + and `encrypt.Date{Year, Month, Day}` is a date. A field whose target is a + date family also accepts `time.Time` and takes its calendar day **in the + value's own location** (`t.Date()`), which is how Go code builds a date; + taking the UTC day would store the previous day for a local midnight east + of UTC. +- **JavaScript.** A `BigInt` takes the target's kind, and is refused if it + does not fit. It decodes as a `BigInt`. `Date` means `Timestamp`; a date + has its own wrapper. +- **Decimal.** A host decimal (Go's `shopspring/decimal`, a JavaScript + string) is refused if it is NaN or infinite, has more than 28 digits after + the point, or does not fit a 96-bit mantissa at its scale. Postgres + `numeric` holds values that `Decimal` cannot, and a binding refuses them + rather than rounding. +- **Every binding** runs vitaminc's shared test vectors: a host value, the + target, the kind it must map to, and the exact `[tag] ++ payload` leaf + bytes, including normalisation and refusal cases. The leaf is + deterministic even though the AEAD is not. + +### EQL v4 + +- **v4 is the v3 SQL with Stack Encrypt terms.** One SQL source is emitted + under two names. The hand-written SQL takes the schema as a build-time + placeholder, as eql-codegen's templates already do. Consistent with + ADR-0001, the data-bearing domains (`eql_v3_*`, `eql_v4_*`) live in + `public` and survive reinstall, and the implementation schemas + (`eql_v3`, `eql_v4` and their `_internal` schemas) stay disposable. The + second name separates producers; it is not a versioned upgrade mechanism of + the kind ADR-0001 rejects. +- **A v4 payload's envelope carries `"v": 4`**, and the `eql_v4_*` domains' + check constraints test it, as the `eql_v3_*` ones test `3`. The version is + one more build-time placeholder. A payload written to the other producer's + domain then fails on insert, rather than only matching nothing when it is + queried. Queries are a different matter; see Consequences. +- **New EQL targets are v4-only.** In v3 they stay refused, with a reason + that points to v4. A domain that a lossy order transform needs, with an + `hm` beside its `op`, is one of these, and is the first point where the v4 + SQL differs from the v3 SQL. +- **`@cipherstash/eql` 4.x ships both bundles** from `main`. A SQL fix lands in + both names in one release. +- **`--eql-version` comes back, on purpose.** It was removed when v3 became + the only installable generation, and the CLI now refuses it. It returns as + `--eql-version 3|4|all` on both `stash eql install` and + `stash eql migration`, so the migration-first paths (Drizzle, and Supabase + with a local `supabase/` directory, where a direct install does not survive + `supabase db reset`) can install v4 too. The migration they write carries + the chosen bundles, and `--supabase` grants on each bundle's schemas. The + default is 3, which is today's behaviour, and changes to 4, announced in + advance, when the TypeScript stack has moved to Stack Encrypt. `2` keeps + its current message pointing at the EQL 2.3.1 release, rather than + becoming an ordinary invalid value. +- **During the overlap**, expected to last a quarter or more, cipherstash-client + takes fixes only. New kinds and domains are produced through Stack Encrypt + and v4. An exception is a decision written down in its issue. +- *Amended 2026-10-19:* **a v4 search query carries only the terms its + operator reads.** The text search query domains (`eql_v4.query_text_search` + and `eql_v4.query_text_search_ore`, whose terms include the match term + `bf` beside others) require at least one of their terms rather than all + of them. Text shorter than one 3-gram has no match term, so a query that + had to carry every term could not express `=` or `<` on short text. + Stack Encrypt emits only the term of the index that answers the query's + operator. Every extractor over such an operand raises wherever it reads + the operand when the term it reads is absent, JSON `null` or an empty + array, naming the domain, the term and the operators that compare it, and + never the operand's contents, rather than reading it as `NULL` (no row) or + as an empty filter. The raise is at evaluation: a literal operand is + folded and raises at plan time, while a bound parameter under a generic + plan whose predicate is never reached returns no row and no error. A + stored search value carries every term, and text too short for a match + term stores the empty filter (`"bf": []`), the stored side's answer in + Stack Encrypt: `=` and `<` find it, and no `@@` query does, because a + query's filter is never empty (the extractor refuses `"bf": []`). That is + a claim about queries: `@@` between two stored values (a self-join + `a.name @@ b.name`, or `matches(col, )`) keeps + the shared guard, so two stored empty filters match each other there, as + they do in v3. No producer builds that predicate. A match + query of such text is refused, as it is for `TextMatch`, whose stored + value still refuses it too. The v3 domains are cipherstash-client's format + and keep requiring every term, byte for byte, so here the v4 SQL differs + from the v3 SQL. The one source holds both forms between version-block directive lines (`-- {{#v3}}` … `-- {{/v3}}`, + `-- {{#v4}}` … `-- {{/v4}}`), which the renderer keeps for their own + version and drops from the other, so the v3 bundle renders exactly as it + did before the block was written. +- *Amended 2026-10-19:* **a v4 `ob` term is ore-rs's 6-bit block ORE.** The + key name is v3's, but the format is not. Stack Encrypt writes one term per + value, the whole ore-rs ciphertext (left and right halves) as one hex + element: the fixed-width scheme (`Bit6BlockOre`, wire header `02 02`) for + the integers and floats, and the chained scheme (`ChainedBlockOre`, `02 + 03`, then the padding policy) for text, padded with NUL bytes to a + power-of-two bucket of at least 16 bytes. v3's `ob` is cipherstash-client's + 8-bit block ORE, up to six terms per text value. The two need different + comparators, so the v4 SQL holds its own (a version block in + `sem/ore_block_256/functions.sql`), and every name built on the block ORE + type is a placeholder too: `{{ore_block}}` renders as `ore_block_256` in + v3 and `ore_block_v2` (ore-rs's wire version 2) in v4, so no v4 object + carries the 8-bit format's name. The v3 bundle renders byte for byte as + before. + + The v4 comparator checks both terms' shape before it compares (header, + block count, exact length, padding policy, every permuted symbol below 64) + and raises, naming the length and never the bytes, on a malformed term, on + terms of different schemes, on fixed-width terms of different block counts + and on chained terms padded under different policies. For terms of one + shape it runs a constant operation count: one statement per block + evaluates both of its comparisons and latches the first difference + arithmetically, and the hash runs exactly once on every path + (`packages/eql/tests/timing/ore_block_v2/` measures it). + The hash is ore-rs's σ-MMO over AES under a fixed public key, which + pgcrypto computes. A query carries the full ciphertext too, not the left + half alone, because a btree index or `between` can pass the stored value + first, and the comparator reads its second operand's right half. + + A comparison of two chained terms reveals the length of their common + prefix in 6-bit blocks, and a chained term reveals its text's length + bucket. Both are ore-rs's documented leakage for the chained scheme. + +### Review + +A domain that locks equality and order together derives both from the same +transformed bytes, and that choice is frozen once data is stored under it. +Dan Draper signs off each such domain in writing before it ships. Domains +whose equality and order transforms are independent need no such sign-off. + +## Exhaustive handling of kinds + +`vitaminc-prf`, `vitaminc-ore` and every binding must handle every kind of +value, and adding a kind should fail to build until each one does. This was +left open between dropping `#[non_exhaustive]` (A) and a visitor trait with +one required method per kind (B). + +*Settled 2026-10-18 by vitaminc 0.6's design.* There is no value enum to +match. A sink receives each scalar as a physical value and an optional +logical type. The physical enums (`Physical`, `Int`, `Float`) are exhaustive, +so a new physical kind fails to build in every sink that matches them, which +is A for the bytes a value is made of. `Logical` is `#[non_exhaustive]`, so a +new logical type (a date, a timestamp) is additive, and a sink that does not +know it refuses it at run time. Stack Encrypt's `ValueKind` is exhaustive. +The conformance test stays the backstop for the logical types a sink reaches +through a wildcard. + +## Consequences + +- **The release order is fixed.** vitaminc 0.6.0 first, then cllw-ore and + ore-rs (additive releases implementing `OrderScheme`), then the Stack + Encrypt breaking release. Stack Encrypt must reach crates.io before + `eql-bindings` uses its new API, since `cargo publish` builds + `eql-bindings` against the registry. The EQL v4 bundle and the Go SDK + changes follow. +- **Adding a kind later** takes a tag, PRF and order encodings, a codec in + every binding, test vectors and a row in the kind-to-family table, or an + entry in the exceptions list. A new physical kind is a breaking change for + every sink. A new logical type is not. +- **Stack Encrypt's terms change** for `-0.0` and negative-sign NaN floats, + for non-NFC text equality, for `Bool` order terms, which are removed, and + for every text order term: `orderize_string` drops symbols and keeps case, + while the fold keeps symbols and folds case. None is deployed, so the + breaking release carries them without migration. +- **cipherstash-client's terms do not change.** `orderable-bytes`, cllw-ore's + typed impls (`Bool` included) and its block ORE padding are all kept, so + every stored v3 payload stays queryable. +- **Separate names do not stop a cross-producer comparison in SQL.** EQL's + domains are over `jsonb`, and when no operator is defined for an exact pair + of types, Postgres treats a domain as its base type. `v3col = v4term` then + runs as the built-in `jsonb = jsonb` and returns no rows, silently, as + `eql_v3_text_eq = eql_v3.query_integer_eq` already does within v3. A join + between a v3 and a v4 column does the same, and + `eql_v3.eq_term(v3col) = eql_v4.eq_term(v4term)` compares the two terms as + text. Three things do fail loudly: an insert of the wrong version (the + domain check), the function form `eql_v3.eq(v3col, v4term)` ("not unique"), + and `OPERATOR(public.=)` between a v3 and a v4 column ("not unique"). + Verified on Postgres 17 with both bundles installed in one database. +- **Tooling that recognises encrypted columns by the `eql_v3_` prefix must + learn `eql_v4_` before any v4 column can exist.** Today that is + `stash init`'s introspection (`cli/src/commands/init/lib/introspect.ts`), + the wizard's tools (`wizard/src/tools/wizard-tools.ts`) and + `classifyEqlDomain` (`migrate/src/version.ts`), which `stash status` and + `stash encrypt status` use. Getting this wrong shows an encrypted column as + plaintext, which invites encrypting it a second time. The installer's + ADR-0001 capture, rebuild and verify logic hard-codes the disposable + schemas as `('eql_v3', 'eql_v3_internal')` + (`installer/derived-search-index-restoration.ts`, + `installer/installation-state.ts`); without `eql_v4` and + `eql_v4_internal` there, a v4 reinstall would capture and restore none of + its own indexes. Both land with the first released v4 bundle. +- **The release tooling assumes one bundle.** The lockstep stamp is read from + `COMMENT ON SCHEMA eql_v3` (`scripts/sync-lockstep-versions.mjs`, + `packages/eql/tasks/release/prepare-bindings-assets.sh`); there is one + `release-manifest.json` per artefact, which the CLI's `bundle-digest.ts` + and `eql-sql-asset-freshness.test.mjs` check; `eql_bindings::sql` embeds + only the v3 files; and `_build-eql-sql.yml` uploads only them. The v4 + bundle needs its own stamp, manifest entries, freshness check, crate + constants and release upload before it ships, or v4 drift goes unnoticed + with every digest still verifying. The `postgres-eql` image states which + bundles it installs. +- **Moving a column from v3 to v4 means re-encrypting it.** The ciphertext and + every term change. How that migration runs belongs to the decision that + moves the TypeScript stack onto Stack Encrypt. +- **The CLI surface changes** (`--eql-version` on `stash eql install` and + `stash eql migration`), so `skills/stash-cli`, `skills/stash-indexing` and + `skills/stash-postgres` change in the same PR. +- **This replaces a definition in a plan.** `docs/plans/2026-10-04-plan-builder.md` + called "EQL v4" a name for a Stack Encrypt payload in the v3 envelope and + the `eql_v3_*` domains. That plan is updated to this ADR. + +## Deferred + +- ~~**Block ORE for text** waits for ore-rs's chained, variable-length block ORE + to be reviewed and released, then arrives in a minor release of + `vitaminc-ore`. Until then it is an entry in the exceptions list.~~ + *Amended 2026-10-19:* done. ore-rs 0.9.0's `vitaminc` feature implements + `OrderScheme` for its chained scheme, and Stack Encrypt produces + `TextOrdOre` and `TextSearchOre` with it (see "EQL v4"). +- **Block ORE for `Bool`.** Block ORE stored as right ciphertexts only is + fully randomised and semantically secure, so a two-value domain leaks + nothing through it. `Bool` could support that scheme alone, enforced by a + marker trait on schemes. Not built until needed. +- **Cross-version blocker operators.** Blockers for every v3/v4 pair of the + same type family and capability would turn the silent cross-producer `=` + into an error. About 2,300 operators, generated from the catalog like the + existing blockers. Not built yet; until then, a cross-producer query is + caught only by typed clients, the function form and `OPERATOR(public.=)`; + the plain `=` returns no rows. When they are built, + **the v4 bundle owns them**: it creates them in `eql_v4_internal`, against + whichever `public.eql_v3_*` domains exist, on every install. A v4 reinstall + drops them with its schema and creates them again. A v3 reinstall leaves + them alone, because they depend only on the `public` domains, which + survive, and not on anything in `eql_v3`. Installing v3 after v4 into a + database that had no v3 domains leaves them absent until v4 is reinstalled, + so `--eql-version all` installs v3 first. +- **Locale-aware collation**, as its own domain with the collation version in + its name. +- **ASCII-packed text domains**, until a customer's column sizes make the + case. diff --git a/docs/adr/0004-same-size-swap-from-blacksmith-to-runs-on.md b/docs/adr/0004-same-size-swap-from-blacksmith-to-runs-on.md index 7971297a3e..6ac771ad4c 100644 --- a/docs/adr/0004-same-size-swap-from-blacksmith-to-runs-on.md +++ b/docs/adr/0004-same-size-swap-from-blacksmith-to-runs-on.md @@ -29,6 +29,10 @@ Each Blacksmith label becomes a RunsOn label with the same vCPU count and Ubuntu |---|---| | `blacksmith-16vcpu-ubuntu-2204` | `runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu22-full-x64/volume=80gb/extras=s3-cache` | | `blacksmith-4vcpu-ubuntu-2404` | `runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=4/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache` | +| `blacksmith-16vcpu-ubuntu-2404` | `runs-on=${{ github.run_id }}/family=c8a+m8a/cpu=16/image=ubuntu24-full-x64/volume=80gb/extras=s3-cache` | + +Only the CRAP jobs in `crap-crates.yml` use the third label. +They ran on `blacksmith-16vcpu-ubuntu-2404` on the `next` branch, because the prebuilt `cargo-crap` binary needs the glibc of Ubuntu 24.04. - **Jobs that move.** Every job that names a Blacksmith label moves, in every workflow of this repository. diff --git a/docs/fuzzing.md b/docs/fuzzing.md index e1d7ace9e8..bd68142afd 100644 --- a/docs/fuzzing.md +++ b/docs/fuzzing.md @@ -1,4 +1,4 @@ -# Fuzzing (cargo-fuzz / libFuzzer) +# Fuzzing (cargo-fuzz / libFuzzer, and Go) How the repo fuzzes its public, untrusted-input parsers, how to run a target locally, and how to add a new one. The short-form recipe lives in @@ -27,7 +27,9 @@ Current targets: | `fuzz:sealed-value` | `stack-encrypt` | `sealed_value_decode` | `SealedValue::from_bytes` (frozen v1 leaf); accepted input must re-encode to itself | | `fuzz:term-decode` | `stack-encrypt` | `term_decode` | the SEM term decoders (`EqualityTerm`, `MatchTerms`, `OreTerm`, `OpeTerm` `from_bytes`) | | `fuzz:check-record` | `stack-encrypt` | `check_record` | `dynamic::record::check_record` over an `Arbitrary`-derived plan and tree, against a model of the record rules (structure-aware) | -| `fuzz:plan-build` | `stack-encrypt` | `plan_build` | `plan::FieldsBuilder::build` over `Arbitrary`-derived untrusted names (context, fields, identities); a built field's label must render and parse back, and passthrough names are never refused (structure-aware) | +| `fuzz:json-text` | `stack-encrypt` | `json_text` | `json::parse_text`, the boundary parser for a language SDK's JSON document, against serde_json: it reads what serde_json reads to the same value, refuses beyond it only repeated members and out-of-range integers, and what it reads writes back to itself | +| `fuzz:json-wire` | `stack-encrypt` | `json_wire_decode` | the JSON index's wire decoders (`JsonDocument`, `JsonNode`, `JsonSelectorSet`, `JsonLeafQuery` from JSON text; `JsonHeader::from_bytes`), over base64 tags and base85 ciphertexts; an accepted document or node must round-trip through its wire form | +| `fuzz:label-parse` | `stack-encrypt` | `label_parse` | `Label::parse` and `Label::new`, which read a binding's names and a context field's value: a label renders back to the text it was read from, and a refusal names a segment that shows its reason | Each target is a few lines — `libfuzzer-sys` hands a `&str` (or `&[u8]` for the byte decoders) to the parser via the `arbitrary` crate: @@ -126,11 +128,94 @@ Two jobs with deliberately different roles: `restore-keys`) so coverage compounds, minimized with `cargo fuzz cmin` to stay small, and any crash reproducer is uploaded as an artifact. +- **go-fuzz-campaign** (`schedule` nightly + `workflow_dispatch`, + **non-blocking**): the same for the Go fuzz targets (see below), one job + per target. Their regression replay is plain `go test`, in + `tests-golang.yml`. + The `pull_request` trigger is path-filtered to `packages/stack-auth/**`, `packages/stack-kms/**`, `packages/stack-encrypt/**`, the root `Cargo.toml`, `Cargo.lock` and `mise.toml`, and the workflow file, with `!**.md` / `!**.example` excludes last so docs-only changes are skipped. +## Go: fuzzing the guests' ABI from the host + +The Go module in `languages/golang` runs two WASI guests (the stack-encrypt +guest and the credential guest). Every export reads its input through a +`(ptr, len)` pair, and the guests share one rule for those pairs, in +`packages/stack-guest-abi/src/abi.rs`: a pair outside linear memory is +refused with `STATUS_ENCODING` before anything reads it, and a pair inside +a buffer the host owns is read as bytes, whatever they hold. The code that +checks the pairs only compiles for wasm32, so cargo-fuzz and Miri cannot +reach it. Go's native fuzzing calls the real guests through wazero instead. + +| Go fuzz target | package | what it calls | +|---|---|---| +| `FuzzGuestExportPairs` | `encrypt` | one export of the stack-encrypt guest (the deterministic-kms test build), with one pair replaced by the fuzzed bytes, a sub-range of them, or a pair outside memory. The exports cover each way the guest reads input: borrowed (`se_plan_check`, `se_keyset`, `se_decrypt_record`), borrowed then wiped (`se_cipher_init`), and taken as plaintext (`se_term`, `se_encrypt_record`, `se_resume`). The other parameters are what the public API sent, recorded through it, so a fuzzed call gets past the checks it did not change. | +| `FuzzGuestBufferRegistry` | `encrypt` | `se_alloc` and `se_dealloc` against a model of the buffer registry: frees with the wrong length, double frees, pointers beside a live buffer, pointers outside memory, and allocations too large to make. Every live buffer must stay allocated and unchanged. | +| `FuzzAuthGuestExportPairs` | `auth` | the credential guest's one- and two-input exports (`sa_auth_validate_crn`, `sa_has_token`, `sa_workspace_dir`, `sa_lock_path`), as above. None writes to the profile. | + +Each call must not trap, must answer `STATUS_ENCODING` for a pair outside +memory and a defined status (not `STATUS_INTERNAL`) or an output inside +memory otherwise, and must leave an instance that still answers. The shared +rules live in `languages/golang/internal/guest/hostile.go`. + +Go's fuzzer is guided by coverage of Go code only. wazero compiles the +guest to native code it does not instrument, so the fuzzer cannot see which +of the guest's branches an input reached, and mutates close to blindly +there. That is why every target starts from a valid call: the seeds, and +the parameters recorded through the public API, put each input one change +away from a call the guest accepts. + +The fuzz tests never pass a pair inside memory but outside the host's own +buffers. That breaks the host's side of the contract: an export that wipes +its input would zero the guest's own memory. + +## Go: fuzzing the frame codec + +The Go frame codec, `languages/golang/encrypt/frame`, decodes bytes that +the guest wrote and blobs read from a database. The decoders treat that +input as hostile. Three fuzz targets check two rules for each decoder: + +- The decoder must not panic. +- Any input that the decoder accepts must be written back as the same + bytes. + +Some changes to the bytes are allowed, because a Go value cannot avoid +them. For example, an `undefined` comes back as null. A timestamp in +seconds, milliseconds, or microseconds comes back in nanoseconds. + +The targets need no guest. The seeds come from two files: the value corpus, +`conformance/vitaminc-aead/value-conformance.json`, and the storage corpus, +`packages/recipher-frame/testdata/storage-v1.json`. + +| Go fuzz target | package | what it decodes | +|---|---|---| +| `FuzzUnmarshal` | `encrypt/frame` | a value frame (`Unmarshal`) | +| `FuzzUnmarshalCipherText` | `encrypt/frame` | a ciphertext tree (`UnmarshalCipherText`) | +| `FuzzUnmarshalStorage` | `encrypt/frame` | a storage blob (`UnmarshalStorage`) | + +## Running the Go targets + +Run them with mise. Build the guests first for the targets that call a +guest. The targets of the frame codec need no guest. + +```bash +mise run wasm:guest:build:deterministic +mise run wasm:auth-guest:build +mise run go:fuzz # every target, 60s each +GO_FUZZ=FuzzGuestBufferRegistry GO_FUZZTIME=5m mise run go:fuzz +``` + +Plain `go test` replays each target's seeds and its committed corpus under +`testdata/fuzz//`, so `go:test` is the regression run on every pull +request. A failing input is written there; commit it once the bug is fixed. +The nightly `go-fuzz-campaign` job in `fuzz.yml` runs `go:fuzz` once per +target, with `GO_FUZZ` set from its matrix, and keeps each target's +generated corpus (`$(go env GOCACHE)/fuzz`) in the Actions cache. A new +`Fuzz*` function needs a row in that matrix; +`scripts/__tests__/crates-ci.test.mjs` fails until it has one. + ## Adding a new target 1. Pick the crate whose parser you're fuzzing and add a target file under diff --git a/docs/plans/2026-10-04-plan-builder.md b/docs/plans/2026-10-04-plan-builder.md index 88dd628fbd..8476eca528 100644 --- a/docs/plans/2026-10-04-plan-builder.md +++ b/docs/plans/2026-10-04-plan-builder.md @@ -662,9 +662,11 @@ In the `Text` family, the three `Ord` suffixes carry equality too. Each type has a query type, with `Query` after its name: `TextEqQuery`. The value of `encrypt_into` is the Go type name. -An EQL value has the EQL v3 envelope: its version field is `3`, and Postgres stores it in an `eql_v3` domain. +Once EQL v4 lands, an EQL value from the engine is an EQL v4 value: its version field is `4`, and Postgres stores it in an `eql_v4_*` domain. The ciphertext inside it is a Stack Encrypt ciphertext, which starts with `stack-encrypt:1:`. -"EQL v4" in this plan is the name of that form, and not a new envelope. +EQL v4 is the v3 SQL, emitted from the same source under a second name, so that a column written by Stack Encrypt and one written by cipherstash-client are different Postgres types ([ADR-0002](../adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md)). +This replaces this plan's first definition, under which "EQL v4" named a Stack Encrypt payload in the v3 envelope and an `eql_v3` domain; Postgres could not tell the two producers apart, and a query from one against a column written by the other matched nothing. +The `TextEq` described below is still produced into an `eql_v3` domain until that move lands. The engine produces one EQL type today: `TextEq`. Status (2026-10-06, #1062): `TextEq` is producible through the data plan's target form. @@ -1037,7 +1039,7 @@ The existing Go package has never been released, so these are removed, not depre - `EncryptRecord`, `EncryptRecords`, `DecryptRecord` and `DecryptRecords`, on `Cipher` and on `Client`. - `EncryptedRecord` and `EncryptedField`: a generated type replaces them. - `Cipher.Term`: the query methods of a field entry replace it. -- `RecordOption`, `WithPlan` and `ExtendContext`: `Cipher.Extend` replaces the last. +- `RecordOption`, `WithPlan` and `ExtendContext`: `Cipher.Extend` replaces the `ExtendContext` function. - `WithGuest`: the import of `encrypt/eql` chooses the guest build. - `TermKind`: `Index` replaces it, for generated code. - `Plan`, `FieldPlan`, `NewPlan` and `Plan.Validate`: the generator replaces them. @@ -1157,9 +1159,10 @@ model rather than a strain: it puts key material in the database. ## EQL v4 types as field targets -Naming: **EQL v4** is the EQL form of a stack-encrypt payload. **EQL v3** is -the existing SQL bundle and its `eql_v3_*` domains, which this section does -not change. Depends on #971 (`TextEq` / `TextEqQuery` through stack-encrypt +Naming: **EQL v4** is the EQL form of a stack-encrypt payload: the v3 SQL +emitted under a second name, with `eql_v4_*` domains and `"v": 4` envelopes +(ADR-0002). **EQL v3** is the same SQL holding cipherstash-client payloads in +its `eql_v3_*` domains, which this section does not change. Depends on #971 (`TextEq` / `TextEqQuery` through stack-encrypt in `eql-bindings`, and `Identifier` as a two-segment `Label`). **The engine returns an EQL type only when a plan names it as a target.** diff --git a/docs/plans/2026-10-11-order-and-equality-terms-layering.md b/docs/plans/2026-10-11-order-and-equality-terms-layering.md new file mode 100644 index 0000000000..aacd27a2d3 --- /dev/null +++ b/docs/plans/2026-10-11-order-and-equality-terms-layering.md @@ -0,0 +1,343 @@ +# Order and equality terms: vitaminc at the bottom + +> **Plan, not specification.** This document is an indicative sketch of the +> steps required, written before the work was done. It is not kept in step +> with the implementation and must not be used as a formal specification or +> as a reference for reviewing what was actually built: the code, its rustdoc +> and the tests are the source of truth. Where the two disagree, the code wins +> and this document is simply out of date. + +**Status:** planned. Decisions settled 2026-10-11, except the one listed +under "Open decision". +**Date:** 2026-10-11 +**Amends:** ADR-0002 (`docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md`). +The decisions below were folded into the ADR on 2026-10-12, and the ADR is +now the reference for them. This plan keeps the steps. +**Issues:** cipherstash/vitaminc#374 (`vitaminc-ore`), #1063 (index crates) + +## Why + +Starting on cipherstash/vitaminc#374 under ADR-0002 turned up four problems. + +- **Too many dependencies across repositories.** `vitaminc-ore` was to depend + on cllw-ore and ore-rs and adapt each to its `Scheme` trait, with + `orderable-bytes` underneath both. Order encodings, scheme traits and term + derivation ended up spread over three repositories, and every change needed + releases in all of them. +- **Raw bytes reach the schemes.** cllw-ore and ore-rs accept bytes that the + caller has already encoded. Bytes encoded by hand (little-endian integers, + an unflipped sign bit, `f64::to_bits`) encrypt without error and sort + wrong. Fixing that inside cllw-ore needed wrapper types in `orderable-bytes` + (cipherstash/ore.rs#103) and a feature split in cllw-ore + (cipherstash/cipherstash-suite#2308). Cargo features unify across a build, + so the feature split could not hold whenever anything else in the build + turned the feature on. +- **PRF depends on ordering.** `vitaminc-prf` reaches `orderable-bytes` + through `vitaminc-aead-value`'s `canonical` module, which reuses order + encodings as equality input. Equality needs a canonical form, not an order. +- **One canonical form for both term kinds is too rigid.** ADR-0002 builds + equality and order terms from the same canonical form. A leakage-tuned + domain needs them to differ, for example an exact timestamp for equality + and only the day for order. + +## Decisions + +### vitaminc is the bottom of the stack + +- `vitaminc-ore` owns: + - the order encodings; + - an `OrderScheme` trait; + - the derivation of order terms from `&Value`, generic over the scheme. + + It depends on no scheme crate. +- A scheme's input is a sealed type, `OrderPlaintext`, that only + `vitaminc-ore` can construct. It comes in fixed-length and variable-length + forms. A scheme can't be given bytes that skipped the encoding, so no + wrapper types or feature flags are needed to keep raw input out. +- `OrderScheme` returns a scheme-defined term, roughly + `type Term: Ord + AsRef<[u8]>`, whose length is only known at runtime. Each + scheme keeps its own comparison (CLLW ORE and block ORE don't compare byte + by byte) and its own stored bytes. Fixed-width types such as + `OreCllw8V1` stay as inherent APIs on the scheme crates, because stable + Rust can't name their width generically. +- The trait also covers the key type, domain separation (the term's domain + label goes in as the salt) and typed errors. +- cllw-ore and ore-rs depend on `vitaminc-ore` and implement `OrderScheme` + behind an optional `vitaminc` feature, so cipherstash-client doesn't take a + vitaminc dependency. Their existing typed APIs stay as they are, so + cipherstash-client's stored terms don't change. +- `vitaminc-ore` releases in lockstep with the other vitaminc crates. On each + vitaminc minor release, cllw-ore and ore-rs bump their optional + `vitaminc-ore` dependency before stack can upgrade. That is acceptable + while stack is the only user of the trait path. +- `vitaminc-ore`'s tests use a mock scheme defined inside the crate. A + dev-dependency on cllw-ore would form a cycle across repositories and pull + a second `vitaminc-ore` in from crates.io. + +### Equality and order are tuned per domain + +- There is no shared canonical form. Each kind has a **semantic baseline**, + which makes values that are equal under `Value`'s own semantics encode the + same: decimal scale (`1.0` = `1.00`), signed zero, NaN, NFC. +- On top of the baseline, each term's domain chooses its own **lossy + transforms**, such as timestamp resolution (exact, microsecond, day), + text folding (removing combining marks, case folding, with the Unicode + version pinned) and prefix truncation. +- Each transform is named in its term's domain label, for example + `…/timestamp/day/v1`, so terms built with different transforms are + domain-separated: a probe built with one matches nothing built with the + other. A stored term does not record its label, so they are not made + incomparable. Keeping a query on the column's transforms is the index + spec's job. +- Equality and order can be **independent** (an exact timestamp for + equality, the day for order) or **locked** (the same transform value + passed to both). Stack's index spec (#1063) carries the choice per column. +- A **lossy order transform needs an equality term beside it.** EQL's + numeric, date and timestamp `_ord` domains store no `hm` and answer `=` + with the order term, so a day-resolution order term there would make `=` + match every row from that day. A non-injective order transform is allowed + only on a domain that stores an equality term and answers `=` through it, + as `text_ord` does. Those domains are new, v4-only EQL targets. +- The semantic baseline lives in each term crate: `vitaminc-prf` and + `vitaminc-ore` each apply it. A conformance test checks that values equal + under `Value` semantics produce equal terms in both. There is no shared + canonicalisation crate. +- A column's leakage is the combined leakage of all its terms. Truncating the + order term to the day hides the order of events within a day, but an exact + equality term on the same column still reveals which rows share a + timestamp. Domain design must account for the combination. + +### PRF has no ordering dependency + +- `vitaminc-prf` depends only on `vitaminc-aead-value` and applies its own + baseline and transforms. +- `vitaminc-aead-value` does no term normalisation. Its `canonical` module and + its dependency on `orderable-bytes` are removed. +- The value-derived PRF domains (cipherstash/vitaminc#380) haven't been + released: they landed on 2026-10-08, after vitaminc 0.5.1. So `vitaminc-prf` + can choose its own canonical bytes for dates, timestamps and decimals + without affecting any stored term. + +### `orderable-bytes` is frozen + +- `orderable-bytes` stays as it is for cipherstash-client's stored terms. It + is not part of the target design. +- There is no 0.3. cipherstash/ore.rs#103 (binary wrapper types) is closed. +- 0.2.0 is not yanked: ore-rs 0.8.4 depends on it and nothing new needs it + gone. + +## Open decision: exhaustive matching over `Value` + +Once `canonical.rs` leaves `vitaminc-aead-value`, `vitaminc-prf` and +`vitaminc-ore` must each handle every kind of `Value`, and adding a kind must +fail to compile until each one does. Two approaches are on the table. + +### Prerequisite for either approach: variants that exist in every build + +`Value::Date` and `Value::Timestamp` exist only with `vitaminc-aead-value`'s +`chrono` feature, and `Value::Decimal` only with its `rust_decimal` feature. +Because features unify across a build, an exhaustive match outside +`vitaminc-aead-value` breaks: + +1. `vitaminc-prf` matches `Value` exhaustively, with its `Date` arm behind its + own `chrono` feature. +2. In a build where another crate turns on `vitaminc-aead-value/chrono` and + `vitaminc-prf`'s `chrono` is off, `Value::Date` exists and `vitaminc-prf` + has no arm for it. `vitaminc-prf` fails to compile in that build. + +A visitor fails the same way: a required `visit_date` that exists only with +`chrono` is a method an implementor can't know whether to write. A crate can +check its own features, never a dependency's. Today's design avoids this only +because the match sits inside `vitaminc-aead-value`, which checks its own +features. + +The fix is to make every variant exist in every build, using vitaminc's own +representation, with conversions to and from chrono and rust_decimal behind +the features: + +| Variant | Representation | +|---|---| +| `Date` | days from the start of the common era, `i32` | +| `Timestamp` | Unix seconds `i64`, nanoseconds `u32` | +| `Decimal` | mantissa and scale | + +The ciphertext wire format already uses these payloads (tags `0x12`–`0x14` +are independent of chrono), so stored ciphertexts don't change. The Rust +types do, which is a breaking change to `Value`. + +### The two approaches + +**A: drop `#[non_exhaustive]`.** `vitaminc-prf`, `vitaminc-ore` and the +bindings match `Value` exhaustively in their own crates. + +**B: a visitor trait, keeping `#[non_exhaustive]`.** `vitaminc-aead-value` +defines a `ValueVisitor` with one required method per kind and does the +dispatch. Crates that must handle every kind implement it. Other crates keep +matching with a `_ =>` arm. + +| | A: drop `#[non_exhaustive]` | B: visitor, keep `#[non_exhaustive]` | +|---|---|---| +| Who gets exhaustiveness | Every crate that matches `Value` | Crates that implement the visitor | +| Adding a kind | Breaking for every crate that matches | Breaking for visitor implementors, additive for others | +| Code to maintain | Nothing new | One trait, one dispatch function, a method per kind in each implementor | +| Grouping | Each match writes out every integer width | The trait can offer grouped hooks, such as one integer method that the per-width methods default to | +| Changing `Value`'s representation | Breaks every match | Hidden behind the method signatures | +| Main risk | Low | A default on a per-kind method lets a new kind compile without being handled. Per-kind methods need no defaults; only grouping hooks may have them. | + +**Evidence:** +- Outside `vitaminc-aead-value`, `Value` is matched in `vitaminc-prf` (through + `canonical`), in `aead-napi`'s `convert.rs` and `scalar.rs`, and in the hmac + tests. +- `aead-napi` already has `_ => Err("unsupported value kind")` + (`convert.rs`). That is the silent refusal `#[non_exhaustive]` invites. +- ADR-0002 requires every binding to handle every kind, so the bindings want + exhaustiveness as well. +- Under A they get it automatically. Under B each binding opts in by + implementing the visitor. + +**Leaning:** B. The decision waits on a closer look at the `Value` enum's +design, which may change the representation in ways that favour one +approach. + +## Current state + +Arrows point from a crate to what it depends on. cipherstash-client and +`vitaminc-protected` are left out. + +```mermaid +flowchart TB + subgraph stack + SE[stack-encrypt] + end + subgraph suite["cipherstash-suite"] + CLLW["cllw-ore 0.5
typed impls, own encodings"] + end + subgraph vitaminc + PRF[vitaminc-prf] + AV["vitaminc-aead-value
Value, canonical module"] + end + subgraph orers["ore.rs"] + ORERS["ore-rs 0.8"] + OB["orderable-bytes"] + end + SE --> PRF + SE --> AV + SE --> CLLW + PRF -- "canonical feature" --> AV + AV -- "git pin, pre-0.2" --> OB + CLLW -- "0.1, chrono and decimal" --> OB + ORERS -- "0.2" --> OB +``` + +- stack-encrypt calls cllw-ore directly for order terms. There is no block + ORE path. +- Equality bytes for dates, timestamps and decimals come from order + encodings, through `vitaminc-aead-value`. +- `orderable-bytes` is reached three ways, at three different versions. + +## Target state + +```mermaid +flowchart TB + subgraph stack + EQI["Equality index
picks transforms"] + ORI["Ore / Ope index
picks scheme and transforms"] + end + subgraph schemes["scheme crates"] + ORERS["ore-rs
block ORE"] + CLLW["cllw-ore
CLLW ORE and OPE"] + end + subgraph vitaminc + PRF["vitaminc-prf
equality terms, own baseline and transforms"] + VORE["vitaminc-ore
order encodings, transforms,
OrderScheme, sealed OrderPlaintext"] + AV["vitaminc-aead-value
Value"] + end + EQI --> PRF + ORI --> VORE + ORI --> ORERS + ORI --> CLLW + ORERS -- "impl OrderScheme" --> VORE + CLLW -- "impl OrderScheme" --> VORE + PRF --> AV + VORE --> AV +``` + +- vitaminc depends on nothing in the other repositories. +- The scheme crates implement `vitaminc-ore`'s trait. The index crates choose + a concrete scheme and the transforms for each column. +- `orderable-bytes` doesn't appear. It stays frozen for cipherstash-client. + +## Changes to ADR-0002 + +These have been made in the ADR itself. + +| ADR-0002 says | Now | +|---|---| +| "Equality and order terms are computed from one canonical form per kind, and both layers use the same one" | Each kind has a semantic baseline; lossy transforms are chosen per domain, independently or locked | +| Canonical forms table: timestamp truncated to microseconds, text order folded | These become per-domain transforms, named in each domain's label | +| Order: "The plaintext layer is `orderable-bytes`, which … gains a variable-length encoding" | `vitaminc-ore` owns the order encodings; `orderable-bytes` is frozen | +| "A `Scheme` trait, with block ORE (over ore-rs), CLLW ORE and CLLW OPE (over cllw-ore)" | `OrderScheme` lives in `vitaminc-ore`; ore-rs and cllw-ore implement it | +| "cllw-ore keeps its typed impls … behind a cargo feature that cipherstash-client enables, and gains a bytes-level entry point" | cllw-ore's typed API is unchanged and not feature-gated; it gains an `OrderScheme` impl behind an optional `vitaminc` feature | +| Review: "Using the canonical order bytes as the PRF input … Dan Draper signs it off" | PRF no longer uses order bytes; the review item applies only to domains that lock equality and order together | +| `Value` and `ValueKind` become `#[non_exhaustive]` | Open: see "Open decision" | +| Release order: "ore.rs (`orderable-bytes`) and cllw-ore first, then vitaminc 0.6.0" | vitaminc first, then cllw-ore and ore-rs, then stack | + +## Steps + +### Phase 1: tidy up work in flight + +1. Close cipherstash/ore.rs#103. Don't yank `orderable-bytes` 0.2.0. +2. Cut cipherstash/cipherstash-suite#2308 down to its first two commits: + known-answer tests that pin every cllw-ore encrypt path, and wiping the + plaintext bit buffer in `encrypt_ope_bits`. It becomes a cllw-ore patch + release. The known-answer tests then protect cipherstash-client's terms + through the rest of this work. + +### Phase 2: vitaminc + +3. Settle the open decision. If the `Value` changes are accepted, make every + variant exist in every build. +4. `vitaminc-aead-value` and `vitaminc-prf`: + - add the chosen exhaustiveness mechanism; + - remove `canonical.rs` and the `orderable-bytes` dependency from + `vitaminc-aead-value`; + - move the equality baseline and transforms into `vitaminc-prf`, with each + transform named in its domain label. +5. New crate `vitaminc-ore` (rewrite cipherstash/vitaminc#374 to match): + - `OrderScheme` and the sealed `OrderPlaintext`; + - order encodings ported from `orderable-bytes`, kept in `Protected`, + pinned by golden vectors, and checked against `orderable-bytes` where + they match byte for byte; + - per-domain transforms: timestamp resolution, text folding with a pinned + Unicode version, room for prefix truncation; + - order-term derivation from `&Value`, generic over the scheme; + - a mock scheme for tests; + - docs that state the combined-leakage rule. +6. A conformance test across `vitaminc-prf` and `vitaminc-ore`: every kind is + handled or listed as an exception, and values equal under `Value` + semantics produce equal terms. +7. Release vitaminc 0.6.0. + +### Phase 3: scheme crates + +8. cllw-ore: implement `OrderScheme` behind an optional `vitaminc` feature, + with known-answer tests for the trait path. This is an additive release. +9. ore-rs: the same. Block ORE uses each kind's natural width; + cipherstash-client keeps its 8-byte padding through the existing API. + Block ORE for text waits for cipherstash/ore.rs#95 and goes on the + exceptions list. +10. Release both. + +### Phase 4: stack + +11. Index crates (#1063): each index spec carries its scheme and transforms. + The Equality index calls `vitaminc-prf`; the Ore and Ope index builds the + concrete scheme and calls `vitaminc-ore`. stack-encrypt drops its direct + use of cllw-ore. +12. EQL v4 domain labels name their transforms. + +### Later + +- Block ORE for text, once cipherstash/ore.rs#95 is released. +- Retire cllw-ore's typed impls and `orderable-bytes` once cipherstash-client + is retired. diff --git a/docs/plans/2026-10-17-json-tree-index.md b/docs/plans/2026-10-17-json-tree-index.md new file mode 100644 index 0000000000..6390f7fd31 --- /dev/null +++ b/docs/plans/2026-10-17-json-tree-index.md @@ -0,0 +1,723 @@ +# The EQL v4 `json_tree` index: node-local entries, a token chain, and exact containment + +**Status:** the design and implementation record of the EQL v4 `json_tree` index, Stack Encrypt's JSON index. First written as a design with a phased plan to prove it; implementation notes are appended at the end as each phase lands +**Date:** 2026-10-17 +**Author:** Dan Draper (with Claude assistance) +**Relates to:** #1231 (containment matches across array elements), #1209 (`Contains`, `ContainedBy`, `AtPath` declared), ADR-0009 (operators select the index), system ADR-0002 (EQL v4 by producer), `packages/eql/docs/plans/stevec-envelope-key-header-rfc.md` (the v3 envelope), `docs/plans/2026-10-04-plan-builder.md` ("The JSON index" under Additions) +**Prototypes:** `2026-10-17-json-tree-index/` beside this file, three SQL files that run on a stock PostgreSQL 16 with no extension + +> **Note (2026-10-22).** The stored form this document designs has changed twice since, and the implementation notes at the end record each change. As of Phase 3b a stored entry carries only `s`, `c`, `p` and `op`. The value selectors live only in the stored projection `q`. The group tags `n` and `g`, the wrapped token `w` and the stored ordinal (`i` here, `o` in the code) are gone. A child's token is derived from its parent's token and its ordinal, not its label, and the walk probes ordinals until the first miss. The sections below are kept as written, with short dated notes where they would otherwise mislead. + +## Summary + +Stack Encrypt has no JSON index yet. The operators exist (#1209 merged `op::Contains`, `op::ContainedBy` and `op::AtPath` on `next`), the plan-builder document reserves `Json: Index` as "a new core operation", and EQL v4 has a storage-only `public.eql_v4_json` but "no SteVec bindings yet". The v4 JSON wire format is therefore unconstrained by anything shipped. This document records what to build and the phased plan that proves it, and the implementation notes at its end record what each phase built. + +Three changes to the v3 SteVec design, taken together: + +1. **One entry per JSON node, encrypting only that node.** A path entry today encrypts its whole subtree, so a document's ciphertext is O(size × depth) and the root entry alone is the size of the document. Under this proposal an entry's ciphertext holds the node's edge label, its kind and, for a scalar, its value. Total ciphertext is O(size). The separate value entry is folded into the same entry as a second selector field, halving the entry count. +2. **A token chain links a node to its children, and the server can walk it from a query key.** Each node has a secret 16-byte token. The client derives a path's token from the index key and the path alone. Each child entry stores a *parent tag* (a hash of the parent's token) and its own token *wrapped* under the parent's token. A `WITH RECURSIVE` query that is handed one start token finds that node's children by tag, unwraps their tokens, and recurses, in core SQL (`sha256`, bytea XOR). Without the token the tags and wraps are unlinkable random bytes. This is what makes node-local ciphertexts usable: `doc -> '$.a'` on an object returns the subtree's entries in one round trip, and the client reassembles the object. The prototype in `token-chain.sql` does exactly this. By default the chain starts one level down: the root entry carries the whole document, as in v3, and the top-level fields are the chain heads, so no query can ever hand the server a token for the whole column ("The sealed root", decided 2026-10-18). +3. **Exact containment, closing #1231.** Every entry under an array element carries the element's *group tag*. Containment stays a GIN-indexed `jsonb @>` over the selector sets, which is a necessary condition, and gains a recheck, run only on the rows the index returned and only when the needle has an array element that is a container, that requires each needle element's selectors to come from one stored element. The prototype in `containment-oracle.sql` agrees with PostgreSQL's `jsonb @>` on 29 of its 31 cases, including the six cross-element cases where today's selector containment is wrong; the other two are simulation artefacts the file lists. The issue's "plausible" false negative (`'["a"]' @> '"a"'`) is verified real and fixed by letting a root-scalar needle carry two selector sets. + +Everything here works on standard PostgreSQL, as a non-superuser, with no extension: the SQL uses `sha256(bytea)` (core since 11), `get_byte` / `set_byte`, recursive CTEs and the `jsonb_path_ops` GIN operator class. + +**It ships as a new domain type in EQL v4, not as the v4 SteVec (decided 2026-10-18).** The scheme gets its own column domain, query domain and entry domain beside `public.eql_v4_json` and whatever v4 port of the v3 SteVec `json_search` type may follow, and it shares no wire shape or SQL with them. Two reasons. It must not block the v4 release: a new domain is additive and can land in any 4.x. And this is what the domain-per-scheme design of EQL v3, carried into v4, was for: a new encryption scheme is a new domain type, with its own CHECK, operators and functions, and never a new EQL version. The domain names below use the placeholder `eql_v4_json_tree`; the final name is a Phase 4 decision. (Taken on 2026-10-25: the domains carry the names EQL v3 gives its searchable JSON document, `public.eql_v4_json_search`, `public.eql_v4_json_entry`, `eql_v4.query_json` and `eql_v4.query_json_leaf`, with the target `JsonSearch`; see "Where it is" under the implementation notes. Later sections keep the placeholder names they were written with.) + +## Where we are + +### The v3 SteVec, as cipherstash-client 0.42.3 produces it + +Read from the crate source (`src/encryption/json_indexer/`), not from memory: + +- `flatmap_json` walks the document. Every node emits a **path entry** `{s, c, op?}` and a **value entry** `{s, c}`. `s` is a 16-byte keyed Blake3 MAC of the canonical JSONPath (`$['a'][*]['x']`), under a per-column `prefix`. The value entry's `s` is `MAC(6-byte type tag ‖ path token ‖ canonical value)`; containers get a tag only (`MAP0{}`, `ARRY[]`). `op` is a CLLW OPE term on string and number leaves only. A value entry's `c` encrypts a fixed three-byte sentinel. +- Arrays are indexed under `ArrayIndexMode`: wildcard `[*]`, item `[@]` and positional `[n]` selectors, any combination. Under the wildcard every element of an array shares one path selector, which is the root of #1231. +- The path entry's `c` is the AEAD of the node's **whole subtree** as a `Plaintext`. The root entry (index 0) is the whole document; decryption of a document reads only the root (`into_root_record_with_nonce`). +- Since the envelope RFC: one `KeyHeader` `h` per document (iv, key tag, descriptor, keyset id), entries carry raw AEAD output, nonce `= s[..12]`, AAD `= descriptor ‖ tag ‖ s`, AES-256-GCM-SIV. SIV is what makes equal selectors (sibling array elements with equal values) safe: the cipher degrades to determinism rather than breaking. +- The SQL (`packages/eql/src/v3/json/`): `@>` is `to_ste_vec_query(a)::jsonb @> to_ste_vec_query(b)::jsonb`, where `to_ste_vec_query` projects each entry to `{s}`; a GIN `jsonb_path_ops` index on that expression serves it. `->` by selector grafts `h`, `i`, `v` onto the matched entry so it is self-contained decryptable. `jsonb_array_elements` and `jsonb_array_length` rely on a per-entry `a` flag. + +### What Stack Encrypt has + +- `op::Contains`, `op::ContainedBy`, `op::AtPath` and the arity `Pathed
` (PR #1209, on `next`). `TermFor` is implemented for every `QueryTerm`, so the containments are declared **exact**, and the issue keeps that declaration on purpose. No `Supports` impl exists; a query with these operators does not compile. +- `IndexSpec` is `Equality | Match | Ore | Ope`. The plan-builder document reserves `"json"` as the fifth key and describes the operation: "it mints one document key and seals every entry under it, a new core operation (one generate request, a fulfilment that seals N entries with selector-derived nonces)". +- The PRF: `KeysetCipher::prf()` is an `HmacSha256Prf` keyed by the keyset's index key, with PAE-framed domains per term kind (`sem/mod.rs`). Selectors and tokens derive through it. Nothing is byte-compatible with cipherstash-client, by design. +- Leaves seal with vitaminc's `Aes256Cipher`, AES-256-GCM with a random nonce. There is no GCM-SIV in the dependency tree. The JSON operation needs a deterministic nonce under one document key, so nonce uniqueness has to hold by construction (see "Keys, nonces and AAD"). +- The data plan (`dynamic`) and the Go guest spell indexes as `IndexSpec`; the match index already needed a wire form for its options, and the JSON index will too (plan-builder Additions, item 7). + +### What EQL v4 has + +ADR-0002: v4 is the v3 SQL rendered under `eql_v4` names, for values Stack Encrypt writes. `eql-bindings::v4` exists on `next` with `public.eql_v4_json` as `{v, i, c}` storage only. `v4/mod.rs` says "v4 has no SteVec bindings yet; those follow in `@cipherstash/eql` 4.0". The build renders `src/v3/**` as both bundles, so a v4-only JSON surface is a build change as well as new SQL (see "Where it lands"). + +## Goals and constraints + +- **Security.** No new leakage beyond what the selectors already announce, except where exact containment needs it, and then the minimum. Ciphertext equality must not reveal plaintext equality anywhere the selectors do not already. Nonce reuse under one key must be impossible by construction, since AES-GCM, not SIV, is what the engine has. +- **Speed.** `Contains` (`@>`) stays a GIN probe; `ContainedBy` (`<@`) has no index, as in v3 (see "`ContainedBy`" under section 3). Scalar extraction stays one entry. Encryption cost drops with depth, because no byte is encrypted twice. +- **Size.** Remove the O(size × depth) subtree duplication. Halve the entry count. Do not grow the per-entry constant by more than the duplication saves on a flat document. +- **Standard PostgreSQL.** Core functions only, no extension, no superuser. Supabase and every managed Postgres EQL supports today. +- **Fits the engine's shape.** A `Json` index implementing `Index`, one `generate_keys` request, `Supports` for the operators #1209 declared, a wire form for its options, EQL's v4 JSON type as the `EncryptFrom` that frames it (plan-builder decision 5 and "EQL v4 types as field targets"). + +## Design + +### 1. One entry per node, node-local ciphertext + +The flattening is unchanged in what it visits: every node, with arrays indexed under the wildcard path. What each node emits changes: + +| field | content | present on | +|---|---|---| +| `s` | path selector: `PRF(json/selector ‖ column, canonical wildcard path)`, 16 bytes | every entry | +| `vs` | value selector: `PRF(json/value ‖ column, kind tag ‖ s ‖ canonical(value))`, 16 bytes; containers contribute the tag only, as today | every entry | +| `p` | parent tag, `H("p" ‖ iv ‖ t(parent))[..16]` | every entry but the root | +| `w` | wrapped token, `t(node) XOR H("w" ‖ iv ‖ t(parent) ‖ c)[..16]` | every entry but the root | +| `n` | own group tag, `H("g" ‖ iv ‖ t(node))[..16]` | array elements that are containers | +| `g` | enclosing group tag: the `n` of the nearest enclosing array element | every entry inside an array element that is a container | +| `i` | the child's ordinal under its parent, in the clear, when parent tags are position-keyed (see "Position-keyed parent tags") | every entry but the root | +| `c` | `AEAD(k_doc, nonce(s, j), aad, label ‖ kind ‖ scalar)`: the edge label (object key or array index), the node kind, and for a scalar its value; nothing else | every entry | +| `op` | the leaf ordering term, as today, on string and number leaves | leaves that order | + +`t(node)` is the node's token (next section). `iv` is the document key's IV from the header `h`, already public, reused as a per-document salt. `j` is the entry's ordinal in `sv`. + +The value entry and its sentinel disappear: `vs` sits on the node's own entry. The entry count halves. `a` disappears: `n` marks an array element, and the chain enumerates an array's elements. + +> **2026-10-22:** of the fields in this table a stored entry now keeps `s`, `p`, `c` and `op` (Phase 3b). `vs` moved to the stored projection `q` (Phase 3 stored it, Phase 3b removed it from the entries), and `w`, `n`, `g` and the ordinal are not stored. + +What the client gets back for a scalar path (`doc -> 'sel'` where the leaf is a string) is unchanged in shape: one entry, decryptable with the grafted `h`, its own `s` and `c`, and its ordinal `j` (grafted by the extractor, as `h` is today). For a container path the client gets the subtree's entries and rebuilds the value from each entry's decrypted `(label, kind, scalar)` and the depth the walk reports. Whole-document decryption is one AEAD on the root entry when the sealed-root option (next section, on by default) is set, and otherwise the same walk, run by the client over the whole `sv` with the root token it can derive itself. + +### 2. The token chain + +``` +t(root) = PRF(json/token ‖ column, "$")[..16] client only +t(child) = H("t" ‖ t(parent) ‖ 0x01 ‖ key)[..16] object member +t(child) = H("t" ‖ t(parent) ‖ 0x02 ‖ LE64(index))[..16] array element +p(child) = H("p" ‖ iv ‖ t(parent))[..16] stored +w(child) = t(child) XOR H("w" ‖ iv ‖ t(parent) ‖ c(child))[..16] stored +``` + +> **2026-10-22:** superseded by Phase 3b. A child's token is `H("t" ‖ t(parent) ‖ LE32(o))`, keyed by its ordinal rather than its label, and nothing stores it: the server derives it as it walks, so there is no `w`, no unwrapping and no XOR, and the parent tag is the position-keyed one below. The client can then derive a token only for a chain head and the array positions that directly follow it, and sends gates for the rest of a path. The recursive query, the paragraph on the mask, and "Wildcard paths" below describe the original design. + +`H` is SHA-256. Only `t(root)` needs the index key; everything below it is hashing, so the server can do its half with core functions. The tokens are a function of the column and the **positional** path, so the client derives a start token for any path it can name without a wildcard: `$.nested`, `$.a[2].b`. Labels are bound with a kind byte and as the final variable-length field, so `("ab", "c")` and `("a", "bc")` cannot collide. + +Server side, the subtree under a start token is one recursive query. From `token-chain.sql`, which implements the derivations above (`chain.parent_tag(iv, t)` is `h16("p" ‖ iv ‖ t)` and `chain.mask(iv, t, c)` is `h16("w" ‖ iv ‖ t ‖ c)`) and runs as written on a stock PostgreSQL: + +```sql +WITH RECURSIVE walk(depth, t, entry) AS ( + SELECT 0, t_start, NULL::jsonb + UNION ALL + SELECT w.depth + 1, + chain.xor16(decode(e->>'w', 'hex'), chain.mask(decode(stored->>'iv', 'hex'), w.t, decode(e->>'c', 'hex'))), + e + FROM walk w + JOIN LATERAL jsonb_array_elements(stored->'sv') e + ON e->>'p' = encode(chain.parent_tag(decode(stored->>'iv', 'hex'), w.t), 'hex') +) +SELECT depth, entry FROM walk WHERE entry IS NOT NULL +``` + +Run against the fixture document with the token for `$.nested`, derived on the client from the labels alone, it returned the six entries under `$.nested` (`deep`, `list`, both elements, both `x` leaves) with their depths, nothing else; a garbage token returned zero rows; the root token returned all nine non-root entries; and the same document stored under a second IV shares no parent tag with the first. The mask for `w` includes the child's own ciphertext so that two siblings with the same `p` get different masks without the server needing to know anything about them. + +**Why plain SHA-256 is enough here, and HMAC stays an option.** Three of the derivations hash a secret token with public bytes beside it, which is the shape that invites a length-extension question. It does not apply, for two independent reasons. Every output is truncated to 16 bytes (12 for the nonce), and a length extension needs the full 32-byte digest, because the digest is the chaining state the attacker resumes from; with half of it unknown the attacker is guessing 128 bits. And an extension can only produce the hash of a message that has the original as a prefix: each derivation starts with its own domain byte, so an extended `"p"` hash is never a `"w"`, `"g"` or `"t"` value, and within a domain the extended message names nothing that exists. For `t(child)` it is the token of a sibling whose label is `key ‖ SHA-256 padding ‖ x`, and the padding begins with a lone `0x80` byte, which is not valid UTF-8 and so is not a possible JSON object key. For the mask it is the mask of a sibling whose ciphertext is `c ‖ padding ‖ x`, and a real sibling's ciphertext is independent AES-GCM output. For `p` and `g` it is a tag no entry carries. Nothing in the system accepts one of these hashes as a proof of anything: the only authenticity check is the AES-GCM tag under the ZeroKMS data key. Keying the derivations with HMAC-SHA256 (`HMAC(t(parent), "t" ‖ 0x01 ‖ key)` and so on) would make "a token is a key" literally true and remove the need for this paragraph, at the cost of one extra compression per parent for `p` and one per matched child for the mask in the recursive walk, and a 64-byte XOR in plpgsql, since core PostgreSQL has no `hmac()`. Decision (2026-10-18): SHA-256 as written; HMAC is recorded as decision 7 below and is to be re-evaluated once Phase 3 has benchmark numbers over large documents and tables, not before. + +What a token is: a capability for the **structure** of one subtree, in every row of the column, because the tokens are column-deterministic. It opens no value, which is under the ZeroKMS data key. It does expose the **key names** beneath it to guessing, as written: every child token below it is `H("t" ‖ t(parent) ‖ 0x01 ‖ key)`, a hash whose only secret is the parent's token, and the walk hands the server every descendant's token, so a server that holds a token can test a candidate name offline (`H("t" ‖ t(parent) ‖ 0x01 ‖ guess) = t(child)`) at every level of the subtree, in every row, for as long as the column lives. A selector does not allow this, because it is keyed with the index key. Key names are data whenever an object is used as a map, keyed by an email address, a user ID or a SKU. The remedy is to derive the label step under the index key, `t(child) = PRF(json/token ‖ column, t(parent) ‖ 0x01 ‖ key)[..16]` (and `0x02 ‖ LE64(index)` for an element): in this design the server never derives a child token from a label, it unwraps `w`, so keying the step costs the server nothing and the client one PRF per node in place of one hash. That is decision 11 below. Handing the server `t($.a)` in a query lets it see, for that query, which entries sit under `$.a` and how they nest. That is the same trust the client already extends when it sends a selector, and the server learns it only for the path asked. + +The per-document salt (`iv`) in `p`, `g` and the mask means that **at rest**, with no token, the tags of two rows with identical shape are unrelated bytes. Nothing links shape across rows until a query supplies a token. This is the one place the proposal leaks strictly less than the alternative of a public parent pointer, and it costs nothing: the IV is already in `h`. + +Wildcard paths. A client cannot derive `t($.a[*].b)`, because the token is positional. Extraction under a wildcard anchors at the nearest non-wildcard ancestor and gates on the selector: `subtree_at(doc, t($.a), s($.a[*].b))` walks from `$.a`, and emits an entry only once the walk has passed through an entry whose `s` matches. Scalar leaves under a wildcard need no token at all: `->` by selector returns them as today, and their nonce and AAD depend on `s` and `j`, not on `t`. + +Arrays. `jsonb_array_length(doc, t)` is the count of children of `t`; `jsonb_array_elements(doc, t)` is the children, each a subtree root. Positional access (`$.a[2]`) is a token, not a selector, so the item (`[@]`) and positional (`[n]`) `ArrayIndexMode`s have no reason to exist in v4: wildcard only, and the chain for positions. + +> **2026-10-24:** as written, a positional token names the element's children, not the element: a scalar at `$.a[2]` has no children and its selector is every sibling's, so `subtree(doc, t($.a[2]))` could neither return nor identify it (review of #1250). The implementation reaches a position from its parent: the client sends the parent's token and a position gate `#2:` (`JsonSubtreeKey::gates()`), `json_tree_subtree_at` admits the entry at ordinal 2 only if it carries the element selector, and returns that entry itself at depth 0 with its descendants below it. See the Phase 3b and 3c notes below (#1329). + +> **2026-10-24 (design change, not yet built):** an object member's token drops its ordinal, every entry gains a self tag `x`, and the client expands wildcards itself, so it derives the token of any wildcard-free path and gates go away. See "Design change (2026-10-24)" at the end. + +#### The sealed root: no root token, the document at the root (decided 2026-10-18) + +Two properties make a token worse than a selector. It is a capability over structure rather than a presence bit, and it is deterministic per column, so a server that has seen it once can re-walk every row for as long as the column lives. The chain as written above hands the server the **root** token in two legitimate queries: a wildcard extraction anchored at the root (`$[*].x`) and `jsonb_array_elements` on a root array. `t($)` unlocks the shape of every document in the column, once, forever. Any shallow token is nearly as broad. + +The fix moves the head of the chain down one level. With the option on: + +- The root entry's `c` encrypts the **whole document**, as the v3 root entry does, not the root's label and kind. It carries no token-derived fields. +- The top-level fields are the chain **heads**: `t($.a) = PRF(json/token ‖ column, "$.a")[..16]`, derived from the path alone. A head carries no `p` and no `w`, since no parent token exists to link it to. Everything below a head is the chain as written. +- There is no `t($)`. No query can send it, because nothing is derived from it. + +What a query can hand the server is then capped at one top-level field's subtree, in the rows it scans. A wildcard extraction anchored at the root, and the array functions on a root array, lose their server-side form and become a client-side decrypt of the root entry, which the client was going to fetch anyway. Whole-document decryption becomes one AEAD under the data key, with no walk and no index key, which is what cipherstash-client and the Go decrypt path do today. Everything else is unchanged: selectors, `vs`, group tags, the recheck, scalar `->`, and the walk for any path at depth 1 or below. + +This is the depth-1 case of a general threshold `d` (tokens exist only at depth `≥ d`, every node above carries its subtree as ciphertext). `d = 1` is the only setting worth exposing. Its at-rest cost is small but not nil. The only subtree whose size it reveals is the document's, which the payload length reveals regardless; but the heads carry no `p` and no `w`, so a stored row shows which of its entries are top-level fields and how many there are, which the chain from the root hides once its parent tags are position-keyed. `d = 2` would reveal every top-level field's size at rest, in every row, correlated across rows by selector, which is more than the salted sibling tags it would replace, and it doubles the storage overhead. So the option is a **boolean**, not a depth: `false` is the chain from the root (`d = 0`), `true` is the sealed root (`d = 1`), on by default. The working name is "root node obfuscation"; the final name is decision 8. The option is part of `JsonOptions`, crosses the data-plan wire with the other index options, and is recorded in the header `h`, so a reader of a stored document knows which shape the root has without consulting the column's configuration. + +Storage: one extra encrypted copy of the document's plaintext bytes, encoded on the wire like every other ciphertext. In hex characters, both sides counted alike, it is about 13% of the payload for a document of small scalars (around 15 bytes of plaintext per node, 30 characters, against about 230 characters of entry) and about 65% for one of long strings (200-byte leaves: about 410 characters of copy per leaf against an entry of about 630). Still strictly smaller than v3, which pays this copy at every level. + +The same cap can also be imposed as a client policy on the chain-from-root wire: never send a token shallower than depth 1, and fetch the whole row for anything shallower. That costs no storage, but shallow extraction then transfers the whole document and whole-document decryption keeps the walk and the index key. The option above is the one proposed; the policy is recorded as the alternative. + +#### Epochs: bounding a revealed token in time (recorded, not scheduled) + +The sealed root caps how much a token unlocks. It does nothing about how long: a token is a function of the column and the path, so the server keeps it, and every row written later is as open to it as the rows it was used on. Per-row tokens would close that entirely and are not practical, because a client cannot derive a token for a row it has not read, so multi-row extraction would need a round trip per row. Epochs sit between the two. The head derivation takes an epoch: `t_e($.a) = PRF(json/token ‖ column ‖ e, "$.a")[..16]`, with `e` a small integer recorded in the header `h`, in the clear, beside the IV. Rows written under epoch `e` have heads nobody can derive without naming `e`, and a token revealed for epoch `e` unlocks rows of that epoch only. A query reaching several epochs carries one token per epoch it wants to reach, as a small map, and the walk picks the token by the row's own `e` (`tokens ->> (doc->'h'->>'e')`), which is one more lookup per row and no change to the recursion. Selectors and value selectors are **not** epoched, because containment and `->` have to match rows from every epoch with one needle; only the chain tokens are, and `p`, `w`, `g` and `n` follow them since they derive from a token. What this buys is a bound on the forward reach of a leak: a token the server saw in epoch 3 opens nothing written in epoch 4. What it does not buy is anything backward: rows of a closed epoch stay open to the tokens that were sent for them until they are re-encrypted, and the query cost grows with the number of live epochs, so the rotation cadence has to be set against the re-encryption cadence. The wire change is one small integer in `h` and in the derivation; the SQL change is one lookup. Neither is in the phased plan. The field should be reserved in the header from the first version so that adding epochs later is a new value rather than a new shape. + +#### Position-keyed parent tags: siblings unlinkable at rest (for Phase 1) + +`p = H("p" ‖ iv ‖ t(parent))` is the same value on every child of a node, so sibling groups are visible to anyone holding the row, with no token. That is the main at-rest residue of the chain. Keying the tag by the child's position removes it: `p_i = H("p" ‖ iv ‖ t(parent) ‖ i)`, with the child's ordinal `i` stored in the clear on the entry. At rest an observer learns only "this is some node's `i`-th child". The walk changes from one hash per walked node to `F` hashes per walked node, where `F` is one more than the largest `i` in the document (public), followed by the same equality join as now; `W × F` hashes for a walk of `W` nodes, which Phase 3 measures. Array children take `i` from their index, which the client needs for reconstruction anyway. Object children take `i` from a per-document shuffled order, derived from the document key, so the ordinal does not rank key names. The storage cost is one small integer per entry. + +> **2026-10-22:** the parent tag is still position-keyed, but since Phase 3b the ordinal is not stored and there is no `F`: the ordinals under a node are dense from zero, so the walk probes them in turn and stops at the first miss, about `2N` probes for a subtree of `N` nodes. + +### 3. Exact containment (#1231) + +**The gap, verified.** `jsonb-semantics.sql` pins PostgreSQL's own answers, and `containment-oracle.sql` runs a plaintext-selector simulation of the v3 flattening (the PRF is injective in practice, so string selectors give the same containment answers as MAC'd ones) beside it: + +| case | `jsonb @>` | v3 selector containment | +|---|---|---| +| `{"a":[{"x":1,"y":5},{"x":7,"y":2}]} @> {"a":[{"x":1,"y":2}]}` (the issue's example) | false | **true** | +| `{"a":[{"b":[{"x":1},{"y":2}]}]} @> {"a":[{"b":[{"x":1,"y":2}]}]}` (nested arrays) | false | **true** | +| `{"a":[{"b":{"c":1,"d":5}},{"b":{"c":3,"d":2}}]} @> {"a":[{"b":{"c":1,"d":2}}]}` (object inside element) | false | **true** | +| `{"a":[[1,2],[3,4]]} @> {"a":[[1,4]]}` (array inside element) | false | **true** | +| `["a"] @> "a"` (the issue's "plausible" false negative) | true | **false** | +| every other case tried (empty containers, duplicates, scalar vs array at depth, `{}` against an array, nulls, type confusion) | | agrees | + +So the bug is exactly the issue's diagnosis: a needle array element that is a container with two or more constraints can be satisfied by different stored elements. Scalars in arrays are fine, single-constraint elements are fine. And the top-level scalar case is a real false negative today. + +**The fix at rest.** Every entry under an array element carries `g`, the group tag of the nearest enclosing element; an element entry carries its own tag as `n` and its enclosing element's as `g`. Tags are `H("g" ‖ iv ‖ t(element))`: per document, random-looking, deterministic given the token. + +**The fix in the needle.** The `Contains` query term serialises to `{sv: [...], grp: [...], alt?: {sv: [...]}}`: + +- `sv` is the flat selector set, as today. +- `grp` is one group per needle array element that is a container: `{at: s(element path), need: [vs...], sub: [groups...]}`. `need` holds the value selectors inside the element down to, but not into, nested elements; `sub` holds the nested elements' groups. The element's own `vs` (its `MAP` or `ARRY` tag) is in `need`. +- `alt` is present only when the needle's root is a scalar: a second `sv` with the root value selector under `$[*]` instead of `$`, so a stored root array containing the scalar matches. `'"a"' @> '"a"'` matches through `sv`, `'["a"]' @> '"a"'` through `alt`. + +**The fix in SQL.** Two stages, in one expression the planner handles well: + +```sql +to_query(doc) @> q.sv -- GIN jsonb_path_ops, necessary condition +AND groups_ok(doc->'sv', q.grp, NULL) -- recheck on the rows the index returned +OR (q.alt IS NOT NULL AND to_query(doc) @> q.alt) -- a second GIN probe, bitmap OR +``` + +`to_query` projects each entry to `{s, vs}`; a needle element `{s: X}` or `{vs: Y}` is contained by any entry carrying it, so the existing GIN strategy carries over with both selectors on one entry. `groups_ok` is the recursive recheck: for each group, some element entry with `s = at` (and, below the top level, `g` equal to the enclosing group's chosen element) has every `need` selector on itself or on an entry whose `g` is its `n`, and satisfies its `sub` groups. It is plpgsql, it runs only on rows that passed the index, and it is a no-op for a needle with no container array elements, which is every needle the Rust `AtPath` operator produces. + +**Result.** `containment-oracle.sql` agrees with `jsonb @>` on 29 of its 31 cases, the six cross-element false positives included, and its closing query counts the disagreements (8 for the v3 form, 2 for the grouped form). The two it gets wrong are simulation artefacts, not design defects: the file canonicalises numbers as `numeric::text` so `2` and `2.0` differ (the real producer canonicalises by value, as cipherstash-client's `canonical_number` does), and the root-scalar case is fixed by `alt`, which the simulation does not implement. + +**The preferred form: let native `jsonb @>` do the grouping (added 2026-10-18).** PostgreSQL's containment already has the rule `groups_ok` re-implements: a needle array element must be contained by *one* stored element, recursively. So project a stored document into a shape that nests by array element, and project the needle the same way: + +```jsonc +{ "sv": [ {"s": "…"}, {"vs": "…"}, … ], // selectors of every node outside any array element + "el": [ { "sv": [ … ], "el": [ … ] }, … ] } // one object per array element that is a container, recursively +``` + +Then `to_query(a) @> to_query(b)` is exact for arrays of containers with no plpgsql at all: the `sv` arrays check selector presence, and each needle `el` object has to fit inside one stored `el` object, which is the same-element rule. The GIN `jsonb_path_ops` index still serves it, because GIN is lossy for `@>` and the executor rechecks the real operator on the heap tuple; and the projection is computed once per row inside the expression index, so a query pays nothing for it. `alt` stays as it is. Two ways to obtain the grouping server-side, with identical leakage: build the projection from the `g` and `n` tags (a plpgsql `to_query`, immutable, run at index time), or store `sv` itself nested by element, which removes the tags from the wire and makes `->` by selector a `$.**` jsonpath lookup. Phase 2 tries the projection first, measures both, and keeps `groups_ok` only if neither engages the index. Whichever form wins, `n` and `g` are emitted only for elements that are **containers**: a scalar element carries one constraint, so grouping cannot be wrong for it, and the tags would reveal element membership for nothing. + +> **2026-10-22:** the projection won, and it is stored rather than built: the client writes it beside `sv` as `q` (Phase 3), and since Phase 3b the entries carry no `n` or `g`. Element grouping is visible at rest through the nesting of `q` instead. The `grp` needle and `groups_ok` above were never built. + +**`ContainedBy` (`<@`).** `col <@ needle` asks whether the stored document is contained by the query value, so the roles swap: the query term has to carry the whole projection of its own document, in the same element-nested shape a stored document projects to (so the same-element rule still holds), and the row's projection is the side tested for containment inside it. `jsonb_path_ops` indexes `@>`, `@?` and `@@`, not `<@`, so no GIN index serves this direction: it is a filter evaluated per row, as `<@` already is in v3, and a query that uses it at scale needs another predicate to bound the rows. The root-scalar `alt` does not carry over. It lets a scalar needle match a stored array, and for `<@` it is the stored side that would need it, which a stored document does not carry; so a stored root scalar is not found inside a needle root array, which is the one case where `<@` would disagree with `jsonb <@`. Either a stored root scalar gains the pair, or the case is documented as a known difference. + +**Portability to v3.** The group tags and the recheck do not depend on the chain. If #1231 must also be fixed for rows cipherstash-client writes, the same `g`/`n` fields and the same `groups_ok` can be added to the v3 wire and SQL, with `g` derived from the document key instead of a token. This document does not propose that; it records that the fix is separable. + +### 4. Wire format + +A document in the new domain, `public.eql_v4_json_tree` (placeholder name; a sibling of `public.eql_v4_json`, not a replacement for any SteVec domain): + +```jsonc +{ + "v": 4, + "k": "sv", + "i": { "t": "users", "c": "profile" }, + "h": "…", // key header, once: iv, key tag, descriptor, keyset id (SQL reads the iv and the flags at fixed offsets; see the note below) + "sv": [ + { "s": "…", "vs": "…", "c": "…" }, // $ sealed root: c is the whole document; no p, w + { "s": "…", "vs": "…", "c": "…", "op": "…" }, // $.hello = "world-1" a chain head: no p, w + { "s": "…", "vs": "…", "c": "…" }, // $.list (array) a chain head + { "s": "…", "vs": "…", "p": "…", "w": "…", "n": "…", "c": "…" }, // $.list[*] element 0 (object) + { "s": "…", "vs": "…", "p": "…", "w": "…", "g": "…", "c": "…", "op": "…" } // $.list[*].x = 1, inside element 0 + ], + "q": { "sv": [ {"s": "…", "vs": "…"}, … ], "el": [ { "sv": [ … ], "el": [ … ] } ] } // the containment projection, written by the client (Phase 3) +} +``` + +> **2026-10-24:** `h` is not opaque to the SQL. The walk needs the document's `iv` to derive the parent tag `p`, and the sealed-root flag to know whether to fall back, and neither is stored anywhere else (review of #1250). The header's layout is frozen, so the implementation reads both from `h` at fixed byte offsets: `eql_v4_internal.json_tree_iv(h)` is the sixteen bytes at offset 22 and `json_tree_sealed_root(h)` is bit 0 of the flags byte at offset 1 (`packages/eql/src/v3/json_tree/functions.sql`, #1329). No field was added to the domain. The key tag and descriptor stay unread by SQL. + +A `Contains` needle, `eql_v4.query_json`: + +```jsonc +{ + "sv": [ {"s": "…"}, {"vs": "…"}, … ], + "grp": [ { "at": "…", "need": ["…", "…"], "sub": [] } ], // only when an array element is a container + "alt": { "sv": [ … ] } // only when the needle root is a scalar +} +``` + +An `AtPath` needle is `{"sv": [{"vs": "…"}]}`. An `AtPath` term is the pair the ADR-0009 appendix already shows: a selector for `->` and a leaf ordering operand. A subtree request is `(t_start, s?)`. + +With the sealed-root option off, the root entry's `c` is the root's label and kind only, and the top-level entries carry `p` and `w` like every other node. The header records which shape the document has. + +> **2026-10-22:** as built, a stored document is `{"v", "i", "h", "sv": [{s, c, p?, op?}], "q"}`, with no `k`; a containment needle is a projection, `{"sv", "el", "alt"?}`, with no `grp`; and a subtree request is a token and one gate per step below it. The size estimates below predate both; the measured sizes are under Phase 3b. + +> **2026-10-24 (design change, not yet built):** an entry becomes `{s, c, x, p?, op?}`, with the eight-byte self tag `x` on every entry, and a subtree request becomes a list of tokens with no gates. See "Design change (2026-10-24)" at the end. + +**Size.** Per 16-byte field, hex costs 32 characters plus about six of framing. Measured against the envelope RFC's fixture document (`{"hello":"world-1","nested":{"deep":"constant"},"number":1}`, 5 nodes): + +| | v3 today | proposed | +|---|---|---| +| entries | 10 | 5 | +| per leaf node | ~180 chars (path entry + value entry) | ~230 chars (`p`, `w` added; one entry) | +| per container node | ~40 chars + the whole subtree's ciphertext | ~190 chars, no subtree | +| this document | ~1,060 chars | ~1,140 chars | +| 100-element array of 5-leaf objects | ~5 KB document ciphertext at the root, repeated once more across the element entries, plus the leaves | leaves only | + +On a flat five-node document the proposal is about 8% larger: the two chain fields cost more than the sentinel entry saved. The saving is the duplication, which grows with size and depth and is the term that dominates every real document. Encoding the 16-byte fields as base64url (22 characters) instead of hex (32) saves about 40 characters per entry and puts even the flat case ahead; `decode(x, 'base64')` is core SQL, so the choice is free. The phased plan should measure three shapes (flat, nested, array-heavy) before fixing the encoding. + +### 5. Keys, nonces and AAD + +- **One ZeroKMS data key per document**, requested under the column's descriptor, as today; the header `h` carries what `retrieve_keys` needs, once. +- **Nonce** `= H("nonce" ‖ s ‖ LE64(j))[..12]`, where `j` is the entry's ordinal. No two entries of a document share `j`, so the inputs are distinct, and two nonces collide only if the 96-bit truncation does: with probability about `N² / 2^97` for `N` entries, which is negligible but is not uniqueness by construction. Uniqueness by construction costs nothing more: the data key is fresh for every document, so `j` itself, as a 96-bit little-endian counter, is a nonce that cannot repeat under its key, and it meets the goal above where the hash only approximates it. Either way AES-256-GCM is safe without SIV. It is derivable for an extracted entry from public fields, so a wildcard-extracted leaf decrypts without a token. Reordering entries breaks decryption, which is tamper evidence, not a hazard: jsonb preserves array order. +- **AAD** `= PAE("stack-encrypt/json/entry/v1", keyset_id, descriptor, key_tag, s, j)`. A ciphertext moved to another entry, another document or another column fails to open. +- **PRF domains**, all PAE-framed and versioned as the existing terms are: `json/selector/v1`, `json/value/v1`, `json/token/v1`. The v3 `prefix` string is replaced by the column context, which the plan-builder document already decided. +- **Leaf ordering terms** derive as the `Ope` index derives them today, keyed by column, so the v4 scalar ordering query domains serve `AtPath` unchanged. Binding them to the selector as well would stop two paths' leaves comparing against each other and is a one-line change; the phased plan should decide it, because it changes which query operand domain `AtPath` takes. +- **Equal sibling values.** Two elements with the same value share `s` and `vs` (public, as today) but now have different ciphertexts, because `j` differs. The v3 residual case where equal siblings produce byte-identical ciphertexts is gone. + +### 6. Leakage, side by side + +| observer sees | v3 today | proposed | +|---|---|---| +| which paths a row has | yes, `s` | yes, `s` | +| which (path, value) pairs a row has | yes, value `s` | yes, `vs` | +| node count | yes (2N entries) | yes (N entries) | +| size of every subtree | yes, each path entry's ciphertext is its subtree | no, only leaf scalar lengths, as the v3 leaf entries already show | +| parent and child relation | inferable from subtree sizes and cross-row co-occurrence | hidden at rest; sibling grouping (`p`) and element grouping (`g`) visible at rest as per-document random tags; linkable only with a token the query supplies | +| shape equality across rows | selectors are column-deterministic, so yes | tags are salted by the document IV, so no, until a token is supplied | +| which leaves sit in the same array element | yes, whenever elements are indexed: document order plus the per-element `a` flag, or position selectors outright (corrected 2026-10-25; this row first said no) | yes, `g`. Required for exact containment, and bounded to array elements | +| equal values at two paths | hidden | hidden | +| equal values in sibling elements | ciphertexts equal (selectors already equal) | ciphertexts differ | +| key names | hashed into `s` | hashed into `s`; also encrypted in `c`; under a token the query supplied, testable by guessing until the label step is keyed (decision 11) | +| at query time, a subtree extraction | reveals the selector asked | reveals the selector or token asked; a token also reveals that subtree's shape for the rows scanned, for as long as the column lives, since tokens are column-deterministic, and, as written, lets the server test guesses of the key names beneath it (decision 11) | +| the broadest token a legitimate query can send | none exist | with the sealed root: one top-level field's subtree. Without it: `t($)`, the whole column's shape | +| how long a revealed token stays useful | not applicable | for as long as the column lives; epochs (recorded above, not scheduled) would bound it to rows written under the epoch it was issued for | + +> **2026-10-22:** parent tags are position-keyed (Phase 1), so siblings do not share a `p` at rest. Since Phase 3b there is no `g`: which leaves sit in the same array element is visible at rest through the nesting of the stored projection `q` instead. + +> **2026-10-23 (review of #1336):** the "proposed" column of the shape-equality and parent-and-child rows is wrong for the format as built, and was wrong for the design as written. Neither the tags nor their salt are what decides it: the entries of `sv` (and the pairs of `q`) are stored in depth-first pre-order, an object's members in sorted key order, under selectors that are the same in every row. A row's sequence of selectors therefore fixes its shape exactly, the parent of every node is inferable by comparing rows (and is exact for the top-level fields under the sealed root, whose entries are the ones with no `p`), every array's length is the count of its element selector, and the relative order of sibling key names is visible across rows. `packages/eql/docs/reference/json-tree-leakage.md` states the format as built; the decision this leaves open is recorded under Phase 4. + +> **2026-10-24 (design change, not yet built):** the "subtree extraction" and "broadest token" rows change: a read sends the tokens of exactly the nodes asked for, never a top-level field's or an array's unless that is what is read. See "Design change (2026-10-24)" at the end. + +### 7. Performance + +- **Encrypt:** per node two PRFs (`s`, `vs`), three hashes (`t`, `p`, mask), one small AEAD. v3 does two MACs and one AEAD over the subtree bytes. Fewer bytes encrypted at every depth above the leaves. +- **Containment:** the GIN probe is unchanged in cost (two keys per entry instead of two entries with one key). The recheck runs per returned row, in plpgsql, only for needles with container array elements, and scans `sv` once per group. +- **Scalar `->`:** one entry, as today. +- **Subtree `->`:** a recursive CTE, one `jsonb_array_elements` scan of `sv` per depth level. Linear in document size times depth of the subtree. Adequate for documents of hundreds of entries; `bench-eql` should measure a 1,000-entry document before this is called settled. +- **Decrypt a document:** with the sealed root, one AEAD on the root entry, as today. Without it, the client walks the chain locally: N hashes plus N small AEADs; the client has the index key, so no extra round trip either way. +- **Encrypt, with the sealed root:** one more AEAD, over the whole document, beside the N small ones. + +> **2026-10-22:** as built, encrypt is two PRFs per node (`s`, `vs`) and up to three hashes (`t`, `p`, and an object member's rank), with no mask. The walk reads the document once into a map keyed by parent tag (Phase 3) and probes it, about `2N` probes and `3N` hashes for a subtree of `N` nodes (Phase 3b); measurements are under Phase 3 and Phase 3b. + +### 8. Standard PostgreSQL + +Everything the server does: `sha256(bytea)` (core since PostgreSQL 11), `get_byte` / `set_byte` for a 16-byte XOR in plpgsql, `decode` / `encode`, `WITH RECURSIVE`, `jsonb_array_elements WITH ORDINALITY`, and `jsonb_path_ops` GIN. No pgcrypto, no superuser, no C. The same posture as the v3 surface Supabase runs today. + +> **2026-10-22:** with no XOR since Phase 3b, the walk needs no `get_byte` / `set_byte`: it is `sha256`, `decode` / `encode`, a jsonb object lookup and `WITH RECURSIVE`. + +## Further mechanisms (added 2026-10-18) + +The four above are in the phased plan: the native-`@>` projection and container-only tags under containment, the sealed root and position-keyed parent tags under the token chain. Four more are recorded here, with what each buys and costs, so that none is rediscovered as free. + +**A per-path index policy, and opaque subtrees (for the phased plan, as a wire form).** v3 emits `s`, `vs` and `op` on every node. `vs` on a low-cardinality field such as `$.country` is a frequency histogram of that field across the table, in the clear; `op` on every number is an order oracle nobody asked for. The column should declare, per path or path prefix, which nodes get equality (`vs`), which get ordering (`op`), which arrays get grouping tags, and which subtrees are **opaque**: sealed as one blob at their parent, with no entries beneath, invisible to containment and extraction below that point. Opaque subtrees are also the answer to a 10,000-node document at about 230 characters per entry. Runtime cost is nil; the cost is a wire form for the policy on the data plan, which the match index's options already needed (plan-builder Additions, item 7). The phased plan should define the wire form and implement `vs` and `op` gating and opaque subtrees; the default stays "everything indexed", which is v3's behaviour. + +**Length padding (recorded).** Pad each leaf plaintext to a bucket before sealing, the next 16 bytes or power-of-two buckets above a threshold, to blunt string-length fingerprinting. Cheap, and a per-column option. Padding the entry *count* with dummy entries, random `s`, `vs`, `p`, `w` and `c` that no selector or token ever matches, hides node counts and array lengths at about 230 characters per dummy; an option for small, sensitive documents only. + +**ORE leaf terms beside OPE (recorded).** An OPE query bound reveals roughly where the bound sits in the order; an ORE query term is the left ciphertext only and reveals nothing beyond the comparison results. The phased plan keeps OPE leaves; the leakage argument for ORE leaves is the query-time one ADR-0002 already makes for scalar columns, and the leaf term is the same `Ore` index the engine has. + +**Salted selectors for at-rest frequency hiding (recorded, with its cost).** `vs' = H(vs ‖ iv)` makes value selectors unlinkable across rows at rest, so no histogram exists until a query is made. The server then has to hash each needle selector against each row, which forfeits GIN entirely and makes every containment query a sequential scan. Defensible only for a small, rarely queried, highly sensitive column. + +**Measure bytes on disk, not characters (for Phase 3).** jsonb is TOAST-compressed. Hex at four bits per character compresses better than base64url at six, so the character-count argument for base64url may not survive compression; and 12-byte selectors are collision-safe for any realistic column (birthday bound around 2^48 distinct values). Phase 3 compares hex and base64url, 12 and 16 bytes, under pglz and lz4 before the encoding is fixed. + +## Where it lands + +**`packages/stack-encrypt`** + +- `target::Json`, `Index`, `IndexSpec::Json(JsonOptions)` with the fifth output key `"json"` the plan-builder document reserved. Options for the phased plan: the sealed-root boolean (on by default; it changes the root entry and the top-level entries, and is recorded in `h`); wildcard arrays only; case folding deferred. +- A new operation beside `ciphertext()` and the term operations: one `generate_keys` request, a fulfilment that flattens, derives selectors and tokens, and seals N entries. The plan-builder table calls this "a new core operation" under `index(name, idx)`. +- Terms: `JsonDocument` (stored; reversible with the index key and the document key), `JsonQuery` (`Contains`, `ContainedBy`, `AtPath`), `JsonLeafQuery` (selector plus leaf ordering operand, for `AtPath`), `JsonSelector` and `JsonSubtreeKey` for extraction. `Supports` impls on `Json` for each; `Input>` and `Input>` for `(JsonPath, S)` and `(JsonPath, (S, S))`, which #1209 left unimplemented until the index existed. +- PRF domain constants in `sem/mod.rs` beside the existing ones. + +**`packages/eql/crates/eql-bindings`** + +- A new module beside `v4::json` for the new domain family (placeholder `v4::json_tree`): `JsonTreeDocument`, `JsonTreeEntry`, `JsonTreeQuery` with the fields above, `v: 4`, and the `stack-encrypt` feature's `EncryptFrom` / `DecryptInto` for `public.eql_v4_json_tree` that frames the index's output with `i`, `v`, `h`. Not a change to any SteVec struct: the v3 `SteVec*` types are untouched, and a v4 SteVec port, if one happens, is separate work with its own domain. The catalog (`eql-domains`) gains the family so `inventory`, `targets` and the Go table pick it up by generation. +- `encryption/targets.rs`: `Json` becomes producible in the `se_targets` table once the type exists. + +**`packages/eql` SQL** + +- A v4-only `src/v4/json_tree/{types,functions,operators,blockers}.sql` (placeholder path) for the **new** domain family: the column domain, the entry domain and the query domain with their CHECKs, `to_query`, `@>` and `<@` as the two-stage expression, `groups_ok`, `->` with `h` and `j` grafted, `subtree(doc, token)` and `subtree_at(doc, token, selector)`, `jsonb_array_elements(doc, token)` and `jsonb_array_length(doc, token)`, the ordering extractor on an entry, and the blockers the v3 JSON surface has. The existing `src/v3/json/**` is not touched and is not excluded from anything: the two families coexist. +- **A build change, additive only.** `tasks/build.sh` renders `src/v3/**` as both bundles and `verify_installer_complete.sh` asserts every ordered v3 file is in the v4 installer. The new family needs the renderer to also order and render a v4-only source tree into the v4 bundle, and the completeness check to accept files that exist in one bundle only. Nothing is removed from either bundle, so this cannot block the v4 release: until the build change lands, the phased plan installs the new family as a separate file over the v4 bundle. +- Tests: `mise run test:encryption:postgres` in `packages/eql` installs the v4 bundle built from the tree and runs the Stack Encrypt PostgreSQL tests with fresh encryption under a fake KMS and no credentials (it reached `next` after `3a216441`, the commit the rest of this section was read from, which has only the database-free `test:encryption`). The JSON suite joins it. The SQLx fixture machinery is not needed for this and should not be used: the point of the fake key source is that the whole suite runs on a fork PR. + +> **2026-10-22:** as built, the walk functions are `eql_v4.json_tree_subtree(doc, token, budget)`, `json_tree_subtree_at(doc, token, gates, budget)`, `json_tree_children(doc, token, gates)` and `json_tree_child_count(doc, token, gates)`, and there is no `groups_ok`. + +**`languages/golang`** + +- Nothing in the phased plan. After it, `JSON` moves from "the JSON index is a new operation in the engine" to producible in `encrypt/eql`'s table, and the data plan carries the `json` index with its options (plan-builder Additions, item 7). + +**Documentation that #1231 asks for now, independent of the phased plan:** the `Contains` and `ContainedBy` docs in `stack-encrypt/src/op/mod.rs`, ADR-0009 and the EQL JSON reference should say that v3 containment over arrays of containers returns extra rows until the v4 surface ships. That is the issue's step 3 and needs no code. + +## The phased plan + +Scope: prove the three changes end to end with real encryption under the fake key source against a real PostgreSQL, measure size and query cost, and leave the wire fields decided. Not in scope: Go, TypeScript, bindings regeneration, the build-tool integration, case folding, ORE leaf terms, lock context. + +**Phase 0, the oracle, no crypto.** Port `containment-oracle.sql` into the SQLx suite as a DB test that drives the **real** `eql_v3` functions with plaintext string selectors (the v3 domain CHECKs accept any string for `s`, `c` and `h`), and reports every disagreement with `jsonb @>` over a corpus of documents and needles. This is #1231's step 1, it pins the six false positives and the false negative against the shipped SQL, and it runs on a fork PR. Acceptance: the test fails on v3 for exactly the cases this document lists, and nothing else. + +**Phase 1, the index in Rust.** `Json: Index` with the flattening, selectors, tokens, tags, nonces and AAD above, behind a `json` feature; the `JsonDocument` round trip; `JsonQuery` with `grp` and `alt`; `JsonSelector` and `JsonSubtreeKey`. Tests under `FakeDataKeySource`: round trip of nested documents and arrays; every entry's nonce distinct; unwrap of every child from its parent's token and of nothing from a wrong token; an entry moved, reordered or regrafted fails to open; the needle generator's `grp` against a hand-written expected shape for the issue's example; the selector for a path equal to the `s` of the stored entry; a property test that a document's entries decrypt and reassemble to the input for arbitrary `serde_json::Value`s. Also in Phase 1: position-keyed parent tags with `i` on the entry, tags on container elements only, the sealed-root boolean and its header field, and the reserved epoch field. Acceptance: `cargo nextest run -p stack-encrypt --features json` green, no credentials. + +**Phase 2, the SQL.** `src/v4/json_tree/*` as listed, installed over the v4 bundle in the test database. The SQLx test encrypts a corpus with the Phase 1 code, inserts it, and checks: `@>` against `jsonb @>` on the plaintexts for the Phase 0 corpus plus random documents (the real oracle, with real selectors); `->` on a scalar decrypts to the leaf; `subtree` on an object reassembles to the sub-document; `jsonb_array_elements` and `jsonb_array_length`; `AtPath` ordering against plaintext ordering; a GIN index on `to_query(col)` engages for `@>` (`EXPLAIN` shows the bitmap index scan, as `database-indexes.md` describes for v3). Containment is tried first as native `@>` over the element-nested projection, with `groups_ok` as the fallback. The per-path policy's wire form is defined here and `vs`/`op` gating and opaque subtrees are implemented against it. Acceptance: zero oracle disagreements over the corpus; every `EXPLAIN` the suite asserts shows the index; a document with an opaque subtree round-trips and is invisible to containment below it. + +**Phase 3, measure.** Three document shapes (flat 5-node, nested depth 4, 100-element array of objects), v3 size versus v4 size in hex and in base64url; encrypt time per document; `@>` latency with and without the recheck at 100k rows; `subtree` latency on a 1,000-entry document. `packages/bench` or `bench-eql.yml` as fits. Also measured: on-disk size under pglz and lz4 for hex and base64url at 12 and 16 bytes; the sealed root's copy against the three shapes; the `W × F` cost of position-keyed parent tags on the 1,000-entry document. Acceptance: a table in this document, and a decision on token encoding. + +**Phase 4, decide.** With the numbers, fix the wire (field names, encoding, whether leaf ordering terms bind the selector), write the ADR for the JSON index, and open the build-integration, Go and bindings issues. + +Each phase is a PR against `next`, where #1209 landed. + +## Implementation notes (2026-10-19, Phases 1 and 2) + +The index, the SQL and the live oracle landed in the pull request stacked on this document; what follows records where the code is and where it departs from the design above, so the two can be read against each other. Phase 0 was folded into Phase 2, and Phases 3 and 4 remain open. + +**Where it is.** The engine half is `packages/stack-encrypt/src/json/`: `Json` is the index (`Index`, term `JsonTerms`), `target::json_document` the sealing operation, `JsonDocument` the stored term and an `EncryptFrom` / `DecryptInto` target, `JsonQuery` the needle for `Contains`, `ContainedBy` and `AtPath`, `JsonLeafQuery` the operand for the orderings at a path, and `JsonSelector` / `JsonSubtreeKey` the extraction keys, derived through `KeysetCipher::json_selector` and `json_subtree_key`. `IndexSpec::Json(JsonOptions)` is the data form, with the key `"json"` and `{"json": {"sealed_root": …}}` as its wire form; a data plan refuses it as an output (`Reason::JsonIndexPending`) and reaches it through the `JsonSearch` target, whose options are the index's (`TargetOptions::Json`), on a field of the `json` kind. The SQL is `packages/eql/src/v3/json_tree/`, confined to EQL v4, where its domains take the names EQL v3 gives its searchable JSON document (decided 2026-10-25, replacing the placeholder `eql_v4_json_tree` names above): `public.eql_v4_json_search`, `public.eql_v4_json_entry`, `eql_v4.query_json` and `eql_v4.query_json_leaf`, with the target `JsonSearch`, while the v3 SteVec SQL is confined to EQL v3; the EQL types are `packages/eql/crates/eql-bindings/src/v4/json_tree.rs`; the oracle is `packages/eql/tests/encryption/tests/json_tree.rs`, which stores the design's corpus, and batches of documents proptest generates (`json_tree/generated.rs`), encrypted beside their plaintexts and checks that `@>` and `<@` over the encrypted column select the rows PostgreSQL's own `jsonb` operators select over the plaintext column, on the GIN index and on a sequential scan, each plan shown in `EXPLAIN`. The pure-Rust half of that oracle is `packages/stack-encrypt/tests/json_index.rs` (`given_the_design_corpus` and the proptest properties in `given_generated_documents`), against a model of `jsonb @>` pinned to the answers in `jsonb-semantics.sql`. + +**Decisions taken by the code.** Of the eleven listed below: 1, hex for every sixteen-byte field and base64 for `c` and `h`, pending Phase 3 (taken on 2026-10-23, Phase 3d: base64 for every field the SQL reads, base85 for `c`); 2, leaf ordering terms bound to the column only, numbers as the `f64` they round to and strings as text, under the scalar `Ope` index's derivation; 3, wildcard arrays only; 4, group tags on, and only on container array elements; 5, the child count is in every container node's ciphertext, and a truncated subtree is `OpenedType`, not a shorter array; 7, plain SHA-256; 8, the option is the boolean `sealed_root`, on by default, recorded in the header's flags; 9, the projection is built from the tags server-side (`eql_v4.json_tree_query`) and `groups_ok` was not needed; 10, position-keyed parent tags on, the ordinal stored as `o`, object members ranked under the parent's token; 11, keyed: in this first form a child's token was `PRF(json/token-step ‖ column, PAE(t(parent), 0x01, key))` (`0x02, LE64(index)` for an element) and an object member's rank `PRF(json/rank ‖ column, PAE(t(parent), key))`, each under its own PAE domain, so a token's holder could neither test key names against the child tokens the walk unwraps nor rank guessed names against the ordinals. Decision 6 is out of scope, as proposed. (Both steps were first hashed unkeyed, as the token chain section above writes them, and were corrected before any release.) + +> **2026-10-22:** 4 and 10 have since moved. The grouping lives only in the stored projection `q`, with no `n` or `g` on an entry (Phase 3 and 3b). Parent tags are still position-keyed and an object member's ordinal is still its rank under the parent's token, keyed (decision 11), but the ordinal is no longer stored (Phase 3b). The ordinal chain of Phase 3b derives a child's token from its ordinal, which carries no label, so the keyed label step of decision 11 is gone with it and only the keyed rank remains. + +**Deviations.** + +- *Nonces are random, not derived from the selector and ordinal.* Every entry seals through the engine's one AEAD path (`vitaminc-encrypt`'s AES-256-GCM with its own random 96-bit nonce, carried in `c`), so there is one leaf cipher in the crate and no second AES-GCM call site. Uniqueness under one document key is then probabilistic (`N² / 2^97` at `N` entries) rather than structural. The entry's AAD still binds its ordinal `j`, so a moved or reordered entry fails to open as the design requires; the cost is twelve bytes per entry, which Phase 3 should count. +- *The ordinal is `o`, not `i`*, because `i` is the envelope's identifier, which `->` grafts onto an extracted entry. An extracted entry also carries `j`, its ordinal in the document, which its AAD is bound to, and a walk adds `d`, its depth below the start. (2026-10-22: since Phase 3b `o` is not stored at all.) +- *The subtree walk returns a node's descendants and not the node itself.* The walk addresses nodes by their parent, and the design's wire has no field that names a node by its own token. The client reads the node's kind from its children's labels; a node with no descendants, an empty container or a scalar, yields no rows, and `->` on its selector returns the node. A self tag per node would close this at sixteen bytes an entry and is left to Phase 4. (2026-10-22: a gated walk, `json_tree_subtree_at`, now returns the node its gates reach at `d = 0`, with no self tag; the ungated `json_tree_subtree` still returns descendants only.) (2026-10-24: an eight-byte self tag on every entry is now the design; see "Design change (2026-10-24)" at the end.) +- *Containment is not `STRICT` in SQL.* PostgreSQL inlines a `STRICT` SQL function only when it can prove the body is NULL for a NULL argument, and the `OR` that adds the needle's `alt` probe is not provably NULL; un-inlined, the call was an opaque filter and the GIN index never engaged. `eql_v4.json_tree_contains` and the `@>` / `<@` wrappers over it are declared without `STRICT` and return NULL for a NULL side on their own. +- *`<@` cannot match a stored root scalar inside a needle root array*, since a stored document carries no `alt` pair. The oracle records the case; `@>` is exact. +- *Value selectors compare strings byte for byte*, with no Unicode normalization, because `jsonb @>` does, and the oracle is agreement with `jsonb @>`. The scalar equality index normalizes to NFC; a JSON value does not. Numbers canonicalize by value, so `2` and `2.0` are one value, as `jsonb` compares them. +- *`AtPath` is the containment of the needle document that holds the value at the path*, with a position in the path read as the wildcard, rather than a single `{vs}` entry: a leaf inside an array element sits in that element's group of the projection, and the needle has to say which group. Containment of that needle is equality only for a scalar, so a container value is refused (`TermError::JsonValueNotScalar`; `op::Contains` asks the containment question), and the needle carries no `alt`, so `("$", 1)` does not match a stored `[1]`. +- *The data-plan form and the catalog are not done.* The Go guest, `stashgen`, the target table and `v4::all()` do not know the family; `IndexSpec::Json` crosses the wire and is refused with a reason. The family is hand-written in `eql-bindings` as the SteVec structs are. Both are the next bindings issue. +- *A document is at most 127 levels deep*, under either root option. The sealed root's plaintext is the document as JSON, and `serde_json` parses JSON back only to 128 levels of nesting, so the 512 levels the walk first admitted sealed documents that then never opened. The bound is the reader's, so a document too deep fails when it is sealed, while the caller still holds it, and not when it is read. +- *A stored document is read as untrusted input.* Its chain fields are not authenticated, and whoever holds a token can write tags that form a cycle or a chain deeper than any sealed document. `eql_simulator::json_tree_children` checks each entry at its own ordinal instead of looping over a fan-out the document chooses; `eql_simulator::json_tree_subtree` and the SQL walks stop below 127 levels, and the Rust walk also stops once it has returned as many entries as the document holds; the rebuild of a subtree's rows refuses a repeated row and a nesting deeper than 127 levels as `OpenedType`. Each would otherwise have overflowed the stack, looped, or allocated what the document asked for. (Phase 3b replaced `children` with a probe from ordinal 0 to the first miss, bounded by the entry count, and derives a child's token from its ordinal by hash, so no stored chain can form a cycle and the SQL walks need no depth bound; the Rust walk keeps both of its bounds and the rebuild keeps its own. #1755 moved these two Rust copies of the SQL reads out of `JsonDocument` and into the `stack_encrypt::eql_simulator` module, behind the `eql-simulator` feature.) +- *Nothing wipes the plaintext copies the walk makes* (the per-node scalars it clones before sealing), where the scalar paths hold theirs in `Zeroizing`. A `serde_json::Value` does not zeroize; a follow-up should walk the caller's value without copying scalars out of it. (2026-10-23: done. The JSON plaintext is held under vitaminc's `Protected` as the scalar paths hold theirs. The walk no longer copies a scalar or a key out of the caller's value: it encodes each node's plaintext straight into a `Protected>`, sized before it is written so it never reallocates, and hands that to the cipher, which takes a `Protected` anyway; the sealed root's JSON is measured first and written once into its own. On the way back, the bytes the cipher opens stay in its `Protected>` while they are parsed, and every key, scalar and sealed-root document read out of them is wrapped as it is made (`zip_ref` over the bytes), in `Protected` for a value: `PlainJson` is a newtype over `serde_json::Value` whose `Zeroize` wipes every string, values and object keys alike, and overwrites numbers and booleans in place. A subtree is rebuilt inside a `Protected`, each member moved in from its own, and a value leaves the wrapper only where it is handed to the caller. The sealed-root fallback selects the walked path inside the document's `Protected`, so the whole document is wiped when the selection is made and only the selected nodes come out. What remains: numbers and booleans have no volatile overwrite without unsafe code, which this crate denies, so theirs is best-effort; and outside the decrypted plaintext, the query and term side still holds plaintext in places vitaminc does not reach from here: an accessor's needle document (`JsonPath::needle`), the canonical bytes of a value selector inside vitaminc's PAE `Context`, and the key names in each term node's positional path.) + +## Implementation notes (2026-10-21, Phase 3: first measurements and the fixes they forced) + +The family was measured at 10,000 rows in the `cipherstash/benches` repository (branch `feat/json-tree-benches`, report `report/JSON_TREE_COMPARISON.md`; the first run at commit 076ebfc, the re-measurement of this phase's fixes at 57abcf9, both at 10,000 and 100,000 rows) against the v3 SteVec and native `jsonb`, on a flat five-node corpus and a nested corpus of about 220 nodes per document. The figures below are that report's at 10,000 rows unless they say otherwise. The flat corpus was on par with v3 (containment 0.47 ms against 0.23 ms, equality at a path 0.70 against 0.81 ms, the containment index eleven times smaller). The nested corpus was not: containment 70 to 80 ms per query, a 244-entry subtree 10 s, the GIN index 44 s to build. Three mechanisms accounted for it, and the fixes landed in the pull request stacked on the family's: + +- **The projection is stored, not rebuilt.** Decision 9 above chose to build the element-nested projection server-side from the tags (`eql_v4_internal.json_tree_group`, recursive plpgsql). That function ran once per candidate row in the lossy GIN recheck, and again in the Filter, at about 3 ms per 220-entry document: the whole cost of containment on the nested corpus, and of the index build. The client already derives the shape for the needle, so the document now writes it to the wire as `q` beside `sv`, the domain CHECK validates it as a group, and `eql_v4.json_tree_query(doc)` is `doc -> 'q'`. It returns `jsonb` rather than `eql_v4.query_json_tree`, because a domain cast runs the needle's recursive CHECK, and the recheck would pay it per row. And it is plpgsql with `COST 1000`, not an inlinable SQL function, for a reason the first re-measurement found: inlined to `value -> 'q'` the filter is costed as one operator, and the nested table's rows are TOASTed, so its main heap is a few hundred pages and a sequential scan over it was costed below the GIN bitmap scan and chosen, at 1.5 s for a one-row match on 10,000 rows (17 s on 100,000), because every row is decompressed to read `q`. Un-inlined, the call keeps its cost, the index expression `eql_v4.json_tree_query(col)` still matches it, and the planner takes the index: 0.5 to 0.7 ms for a one-row match, 3.2 ms for ten deep-object rows (0.36 ms native), and 5 s to build the index. Nothing new is revealed: `q` is the selectors already in `sv`, grouped as `sv`'s own `n` and `g` tags already group them. It is not small: 19,100 of a nested document's 114,309 characters, about 17 per cent, though nothing measurable on disk, since its hex pairs compress against `sv`. And it is trusted as written: the CHECK validates its shape, not that it is `sv`'s, so a row written by anything but this index can answer `@>` differently from `->`, the walks and decryption, which answer from `sv`. The server-built projection could not disagree with the entries; verifying `q` against `sv` at write time would restore that at roughly the old per-row cost, paid once per write instead of once per recheck, and is left open. The deviation this replaces, "9, the projection is built from the tags server-side", is withdrawn; the `groups_ok` fallback remains unneeded. +- **The walk reads the document once, keyed by parent tag.** The shipped walk put `json_tree_parent_tag(iv, t, o)` inside a LATERAL scan of `sv`, so it was evaluated once per (node, ordinal, entry): about 670,000 SHA-256 evaluations for the 244-entry subtree. The walk now builds one jsonb object of the chained entries keyed by `p` (`eql_v4_internal.json_tree_by_parent`) and looks each computed tag up in it, so a level costs its fan-out in hashes plus one lookup each, which is the design's `W × F` as written. The `$.orders` subtree walks out in 23 ms (the six-entry `$.company` subtree in 2.8 ms); `children` and `child_count` in 1.6 ms, from 7.1. The report's prose calls `$.orders` the same 244 entries as the first run's 10.2 s, while its table counts 122 rows for the walked scenario; which count the 23 ms is for is still to be confirmed. The walk is bounded by the document as well as by depth: the fan-out it probes is at most the document's entry count, where a stored `o` could otherwise ask for two billion, and it returns at most as many rows as the document has entries, where a stored `w` that wraps a child's token to its parent's could otherwise double the rows at every level. Neither changes a sealed document's walk; the Postgres suite held both against hostile documents (`postgres_walks_end_on_hostile_documents`). The ordinal chain of Phase 3b removes both cases rather than bounding them: a child's token is a hash of its parent's, so a chain cannot loop back, and the walk probes ordinals until the first miss rather than up to a stored fan-out. Its walk carries no depth bound either, so the same test now holds it to one row per entry on a chain of 300, deeper than any sealed document. +- **A walk has a budget and falls back to the sealed root.** With the root sealed, the root's ciphertext is the whole document at about 1.3 times the plaintext, where a walk returns about 440 characters per entry and pays the fan-out in hashes per node visited. Past a dozen or so entries the document is cheaper on both sides, so `json_tree_subtree` and `json_tree_subtree_at` take a `budget` (default 64) and, once the walk passes it, return the root entry alone with `d = 0`. The client opens the root to the whole document and takes the walked path over it, over the new `JsonPath::select`, and the result is what the walked rows open to: the path is attached with `JsonSubtree::below(path)` for `json_tree_subtree`, whose rows are the descendants of the path's node, and `JsonSubtree::at(path)` for `json_tree_subtree_at`, whose rows are the nodes the path reaches (the same two on `JsonTreeSubtree` in the bindings). The two differ when the rows are opened as a list, to the node's children or to the node, which is why the rows cannot be opened without saying which walk they came from. (2026-10-23, the owner's option (c) from the #1325 review: the caller no longer says it. The path rides on the key it was derived from, `JsonSubtreeKey::path`, and the key builds the rows' wrapper, `key.open(rows)` in stack-encrypt and `JsonTreeSubtree::from_key(&key, rows)` in the bindings; a key with no gates keyed `json_tree_subtree` and opens below the path's node, a key with gates keyed `json_tree_subtree_at` and opens at the nodes the path reaches. There is no path-less constructor and no `below` or `at` to attach, so rows that cannot open past the budget cannot be built, and a caller unaware of the budget is not caught out by a document that grows past it.) A budget of 0 never falls back, a token that names no node yields no row under any budget, and an unsealed root is always walked out. `$.orders` returns the root in 9.5 ms, against 23 ms walked out; `json_tree_subtree_at` over its items in 13 ms against 23. Two costs are not in those numbers: the client's, since the benchmarks do not decrypt, which for the fallback is one AES-GCM open and a JSON parse of a document about 1.3 times the plaintext's size; and the plaintext the client then holds, which is every field of the document and not the subtree asked for. The data key is the same, so nothing is readable that was not, but the note above that a `serde_json::Value` is never zeroized now covers the whole document on every subtree read past the budget. (2026-10-23: no longer; the fallback's document is held under `Protected` and wiped once the walked path is selected from it, and only the selected nodes reach the caller. See the Phases 1 and 2 note on plaintext copies.) This is the sealed root paying for itself a second time: it is also what makes the fallback possible. +- **`json_tree_path_query_first` is costed at 1000.** `(col -> sel) > $1` extracts through it, and under a prepared statement's generic plan (what every driver reaches after five executions) the default cost chose a sequential scan with the extraction as a Filter over the functional btree: 16.9 ms against 0.11 ms with the index, at both tiers. + +Still open from the measurements, filed as a follow-up: `->` scans `sv` on every extraction (0.6 ms on a nested document, 0.2 on a flat one, against 0.1 native; an index of `sv` by `s` would make it a lookup); `json_tree_contains` plans a second GIN probe for `alt` even when the needle carries none; `ORDER BY ord_term(col -> sel)` measured 0.96 ms against v3's 0.25 ms on an index scan both ways, unexplained; and the nested document is 29 times its plaintext in characters and 34 times on disk (hex tags, a random nonce per entry, the sealed-root copy, and now `q`), which decisions 1 and 6 above and the opaque-subtree policy are the levers on. Also open, for the owner: whether the budget should be on by default (a caller who opens a walk's rows without attaching a path works until a document passes the budget, then fails), and whether to verify `q` at write time. + +## Implementation notes (2026-10-22, Phase 3b: the ordinal-chained walk) + +A review of the stored form after the Phase 3 measurements found three fields nothing read and two the walk did not need, and replaced the chain step. The wire is now `{"v", "i", "h", "sv": [{s, c, p?, op?}], "q"}`. + +- **`vs`, `n` and `g` are gone from the entries.** Once `q` was stored (Phase 3), no SQL function read an entry's value selector or group tags: containment reads `q` alone, and the engine read them only to rebuild `q` on deserialize. The engine now takes the stored `q` as the projection. That is no change in trust: `q` and the entry fields were equally unauthenticated (only `c` is, through its AAD), and a tampered `q` changes which rows a containment query returns and nothing else. On the nested benchmark document (213 entries on average) the values of those three fields were 15% of `sv`. +- **Tokens chain by ordinal.** `t(child) = H("t" ‖ t(parent) ‖ LE32(o))` replaces the label-derived step. The server derives every hit's token from its parent's as it walks, so `w` (the wrapped token) is not stored. The cost is that the client cannot derive an object member's token, because an ordinal is a rank among sibling keys it does not know. It derives a chain head's token and those of the array positions that directly follow the head, and sends one gate per further step (`JsonSubtreeKey::gates()`: the step's selector, or `#n` for a position); `json_tree_subtree_at(doc, token, gates, budget)` descends through them, and `json_tree_children` and `json_tree_child_count` take the same gates. A wildcard step's selector is every element's, which is the old `subtree_at` gate generalised to every depth. (2026-10-24: to be reversed for object members, whose tokens drop the ordinal, and with them the gates; see "Design change (2026-10-24)" at the end.) +- **The walk probes to the first miss.** The ordinals under a node are dense from zero (positions for arrays, a permutation for objects), so the walk tries `0, 1, 2, …` and stops at the first miss. `o` is not stored and `json_tree_fanout` is gone. A subtree of `N` nodes costs about `2N` probes (`N` hits, and a miss for every node visited), each a SHA-256 and a map lookup, plus a SHA-256 per hit for its token, where it cost `F` probes per visited node, `F` being the widest node in the whole document; on the nested corpus a wide `items` array taxed every object walk in the same document. +- **Depth is reported from the reached node.** A gated walk returns the node its gates reach with `d = 0` and its descendants beneath it, so the client can tell "the value at the path" (one reached node) from "the children of a node" (no `d = 0` row) without the path. A wildcard reaches several nodes and opens as a list. The ungated `json_tree_subtree(doc, token)` is now `json_tree_subtree_at` with no gates, and returns the token's node's descendants from `d = 1` as before. +- **Leakage.** At rest, the same as Phase 3 less what the stored ordinals told: their multiset gave, for every `k`, how many nodes in the chain have more than `k` children. `p` is still salted by the document `iv`. Under a token, the same: a token still unlocks the shape of that subtree in every row. The `w` mask's binding to `c` (a swapped ciphertext broke the walk on the server) is gone; the swap still fails when the client opens the entry, because `c` is bound to `s` and `j` in its AAD. +- **The chain step binds the child's selector (2026-10-23, review of #1329).** As first built, `t(child) = H("t" ‖ t(parent) ‖ LE32(o))` dropped the kind byte the label-derived step had (`0x01` for a key, `0x02` for an index), and an ordinal does not say which kind of child it numbers: an array element's is its position, an object member's its rank. Rows of one column need not agree on a node's kind, so the token the client derives for `$.a[0]` was, in a row whose `$.a` is an object, the token of the member ranked first, and a walk from it returned that member's subtree as the element's; a `#n` gate admitted the same member. `jsonb` has no node there (`jsonb_path_query_first(doc, 'strict $.a[0]')` is NULL), and the sealed-root fallback, which selects over the plaintext, agreed with `jsonb`, so one row answered differently under and over the budget. The step is now `t(child) = H("t" ‖ t(parent) ‖ s(child) ‖ LE32(o))`, the child's own selector bound in. The server holds every hit's `s`, so it derives the token as before (`eql_v4_internal.json_tree_child_token(token, s, o)`), and the client knows an element's selector from the path (the wildcard's), so it still derives positional tokens after a head. An element's selector is the wildcard path's and a member's names its key, so they never share a token. A position gate carries the element selector too, `#n:`, and the walk admits the hit at ordinal `n` only if it carries it. Nothing about leakage moves: the selector is stored beside the entry, and a token's holder already learns it with every hit. `postgres_a_position_reaches_array_elements_only` holds both forms against `jsonb`'s strict path over the plaintexts. + +### Measured (cipherstash/benches 2d9d5f2) + +Measured in `cipherstash/benches` (branch `feat/json-tree-benches`, commit 2d9d5f2, `report/JSON_TREE_COMPARISON.md`, "Third measurement") on the machine of the second Phase 3 measurement (Apple M1 Max, PostgreSQL 17.10), against the same documents: the ingest resealed the plaintext each row already held, so every scenario returned the same rows before and after. "Before" is the Phase 3 branch with its fixes, "after" this change. Query-only criterion medians over 10 samples, no decrypt, in milliseconds, on the nested corpus. + +| scenario | 10,000 rows | 100,000 rows | +|---|--:|--:| +| `subtree/orders`, default budget (falls back to the sealed root) | 9.48 → 5.71 (−40%) | 8.77 → 5.46 (−38%) | +| `subtree_at/items`, `$.orders[*].items`, default budget | 12.95 → 8.21 (−37%) | 10.92 → 7.18 (−34%) | +| `subtree/orders`, walked out (budget 0; 122 / 130 entries) | 22.97 → 10.92 (−52%) | 24.57 → 11.35 (−54%) | +| `subtree_at/items`, walked out (budget 0; 87 / 105 entries) | 23.12 → 10.93 (−53%) | 24.83 → 11.27 (−55%) | +| `subtree/company` | 2.84 → 1.99 (−30%) | 2.94 → 1.96 (−33%) | +| `subtree/user` | 3.90 → 2.38 (−39%) | 3.99 → 2.45 (−39%) | +| `children/orders` | 1.63 → 1.54 (−6%) | 1.64 → 1.49 (−9%) | +| `child_count/orders` | 1.62 → 1.53 (−6%) | 1.66 → 1.52 (−9%) | +| `path_query/wildcard` | 2.24 → 1.64 (−27%) | 1.80 → 1.41 (−22%) | +| `field_order/nested` | 4.81 → 3.81 (−21%) | 5.23 → 4.12 (−21%) | +| `extract/nested` | 0.59 → 0.47 (−19%) | 0.63 → 0.54 (−15%) | + +The walks the change was aimed at halved when walked out. Scenarios the walk does not touch improved too (`path_query`, `field_order`, `extract`): they read entries through `->` and the path functions, which scan an `sv` 30% shorter in a datum 24% smaller to decompress. `children` and `child_count` moved least; the report's explanation, not yet tested, is that both are dominated by the per-call fixed cost of detoasting the document and building the parent map over all its entries, which this change does not touch, and probing five to seven children instead of the document's widest fan-out saves only a few dozen hashes on top of it. That fixed cost is the next lever for every walk. + +Containment and field queries did not change beyond noise. The nested corpus's containment scenarios moved −12% to +7%. The flat corpus read +7% to +13% on the GIN-served containment and equality scenarios, but its operands, SQL, plans, projection and index are byte-identical before and after, and the native `jsonb` containment controls over unchanged plaintext, with freshly built indexes, drifted +5% to +19% in the same run; that points at the machine, not the format. The 100,000-row nested GIN build went from 58 s to 65 s on one sample, with the same projection and a smaller heap, which reads the same way. + +| size | before | after | +|---|--:|--:| +| nested document, characters (213 entries) | 113,458 | 85,157 (−25%) | +| nested `sv`, characters | 94,324 | 66,023 (−30%) | +| nested `q`, characters | 18,961 | 18,961 | +| nested `pg_column_size`, 10,000 rows | 81,264 B | 62,143 B (−24%) | +| nested heap with TOAST, 10,000 / 100,000 rows | 810 MB / 8,093 MB | 621 MB / 6,201 MB (−23%) | +| nested containment GIN, 10,000 / 100,000 rows | 40 MB / 358 MB | 40 MB / 358 MB | +| nested GIN build, 10,000 / 100,000 rows | 5 s / 58 s | 5 s / 65 s | +| flat document, characters (5 entries) | 2,346 | 2,136 (−9%) | +| flat `pg_column_size` | 2,452 B | 2,250 B (−8%) | + +`sv` shrank by 30% where 15% was expected from the three unread fields alone: the five removed fields carried 20,827 characters of values per nested document, and their keys and quotes about 7,500 more. The nested document is now 21 times its plaintext in characters (was 28) and 26 times in heap (was 34). The largest field is now `op`, the CLLW OPE term on the 156 number and string leaves: 24,832 characters a document. + +**Correctness.** A new benches task, `mise run check:v4:json_tree `, ran after ingest at both tiers. For 25 rows in a fixed pseudo-random order it decrypted every walk form the SQL returns and compared it with the row's plaintext: `json_tree_subtree` at `$.company`, `$.user` and `$.orders`, walked out and under the default budget (opening the sealed root at the path when the walk fell back); `json_tree_subtree_at` for `$.user.contact` (one gate) and `$.orders[*].items` (two gates); `json_tree_children` and `json_tree_child_count` at `$.orders`; every order by its position-derived token; `json_tree_path_query`; and `->`. For 10 sampled needles per predicate it compared the full id set of the encrypted containment, equality, range and ordering queries with native `jsonb` over the plaintext. 462 checks passed and none failed at each of 10,000 and 100,000 rows (350 walk checks, 112 predicate checks). + +## Implementation notes (2026-10-22, Phase 3c: the ordering term is opt-in per path) + +After the Phase 3b measurement the largest field in a stored document was `op`, the CLLW OPE term on every number and string leaf: 24,832 of the nested document's 85,157 characters, about 80 bytes of hex a leaf, on 156 leaves of which the benchmark's queries order two. An ordering term is also the one field that reveals something across rows at rest (the order of the leaf's value among every row that holds one), on fields nobody asked to order. "Further mechanisms" above proposed a per-path index policy with "everything indexed" as the default; the `op` half of it is now built, and the default is reversed: **no path is ordered unless the index says so.** + +- **`JsonOptions` gains `ordered`**, a set of `JsonPath`s, beside `sealed_root`. The walk derives a leaf's `op` only when some ordered path covers the node's positional path (`JsonPath::covers`): a key step matches the same key, a wildcard step covers any array position and the wildcard, a position covers that position alone. So `$.orders[*].total` orders the total of every order and `$.scores[0]` the first score only; literal positions and wildcards are both allowed. The set is part of the index's identity like `sealed_root`, and crosses the data-plan wire as `{"json": {"sealed_root": true, "ordered": ["$.age", "$.orders[*].total"]}}`, paths as text, written in canonical order. It is not recorded in the header: a stored leaf shows whether it carries a term. +- **An ordering query at a path the index does not order is refused** (`TermError::JsonPathNotOrdered`) when the query is awaited, before any keyset loads. Without the refusal, `ord_term` returns NULL for every stored leaf at the path and the comparison silently matches no row. A wildcard query path is covered by a wildcard only, since a position orders elements the wildcard would compare against. +- **A position in an ordered path is refused (2026-10-23, review of #1329).** As first built, `$.scores[2]` ordered the third score alone, and an ordering query at `$.scores[2]` under an index ordering `$.scores[*]` was accepted. Neither works: an ordering compares the leaf `->` extracts by the path's selector, and a selector reads every position as the wildcard, so `->` returns the first element at the path. A query at an ordered `$.scores[2]` compared the first score, which carries no term, and matched no row, which is the failure the refusal above exists to prevent; a query at `$.scores[2]` under `$.scores[*]` compared the first score and returned rows for the wrong element. `JsonOptions::ordering`, the data plan's `ordered` and an ordering query now refuse a path that names a position (`TermError::JsonOrderingAtPosition`), and sealing under options whose `ordered` field holds one, which only direct construction can produce, is refused the same way. Ordering at an array element by position would need an extractor that reaches a position, which `->` by selector is not; it is not scheduled. +- **A plan can be laid out by a value.** The typed plan had no place for options: `encrypt_into::()` reads the type's own `EncryptFrom`, which is static, so every typed plan sealed under the defaults and a query under other options was refused as `PlanError::IndexOptions`. The new `target::Layout` trait is a target's layout chosen by value, with the index it answers queries through; `Json::new(options)` implements it for `JsonDocument`, and `Plan::value().encrypt_with_layout(Json::new(options))` builds a `ValuePlan<_, Laid>` that seals under the options and resolves every query through the plan's own index, so a query does not name the options again. The EQL type has the same by value: `eql_bindings::v4::JsonTree::new(options)` lays a value out as a `JsonTreeDocument` under an identifier. +- **Nothing changes in SQL.** `ord_term` was already NULL for an entry without `op`, and the entry validator already admitted its absence; the functional btree on `eql_v4.ord_term(col -> sel)` indexes the leaves at one selector, which under the opt-in are the leaves of one ordered path. + +What remains of the per-path policy is the `vs` half (equality off for a low-cardinality field) and opaque subtrees; neither is scheduled. + +### Measured (cipherstash/benches cd9643d) + +The benches re-sealed both corpora with one ordered path each, the one their range and ordering scenarios use (`$.age` on the flat corpus, `$.company.salary` on the nested), at 10,000 and 100,000 rows, and the correctness check passed at both tiers (462 of 462). "Before" is the Phase 3b form with `op` on every number and string leaf. + +| | flat, 10,000 rows | nested, 10,000 rows | nested, 100,000 rows | +|---|--:|--:|--:| +| `pg_column_size` per row | 2,250 → 1,596 B (−29%) | 62,143 → 40,578 B (−35%) | 62,092 → 40,549 B | +| heap with TOAST | 27.1 → 17.0 MiB | 620.9 → 407.5 MiB (−34%) | 6,201 → 4,069 MiB | +| containment GIN | 0.98 → 1.03 MiB | 39.9 MiB, unchanged | 358 MiB, unchanged | +| total with indexes | 28.4 → 18.4 MiB | 662.0 → 448.6 MiB | 6,569 → 4,437 MiB | + +The nested document is now 18 times its plaintext on disk (was 26 at Phase 3b, 40 at Phase 3). Two side effects: a flat document at 1,596 bytes sits under PostgreSQL's TOAST threshold, so the flat heap moves from TOAST into the main relation (0.5 to 17 MiB at 10,000 rows) and the earlier note about a TOASTed column making a sequential scan look cheap no longer applies to that corpus; and the flat GIN grew 12% at 100,000 rows with an identical projection, because the rows now spread over many more heap pages and the index's row-address deltas are wider. Query timings were not re-run for this measurement. + +## Implementation notes (2026-10-23, Phase 3d: byte encodings and the eight-byte parent tag) + +Decision 1 below (the token encoding on the wire) is taken, and the parent tag is shortened with it. The rule is the one "Further mechanisms" set out: a field the SQL compares, derives or decodes must be in an alphabet core PostgreSQL encodes and decodes natively, and only a field the SQL never opens may take a denser one. + +- **Every field the SQL reads is padded standard base64**, as `encode(x, 'base64')` writes it and `decode(x, 'base64')` reads it: the selectors `s` and the `s`/`vs` pairs of `q` (sixteen bytes, 24 characters where hex took 32), the parent tag `p`, the ordering term `op` (54 characters where hex took 80), and the tokens and gates `json_tree_subtree_at`, `json_tree_children` and `->` take. `h` already was. The padding stays because `decode(x, 'base64')` refuses the unpadded form (`invalid base64 end sequence`, PostgreSQL 17.10): two characters on a sixteen-byte field and one on an eight-byte one, against a padding step written into every SQL site that would ever decode one. base64url was not taken for the same reason: PostgreSQL has no decoder for it. +- **The ciphertext `c` is RFC 1924 base85** (`base85-simd` 0.1.0: NEON on aarch64, AVX2 on x86_64, portable scalar code elsewhere, wasm32 included), five characters per four bytes against base64's eight per six, on the field that is most of a document. No SQL function decodes `c`. The alphabet has no `"` or `\`, so a JSON string carries it unescaped. `h` stays base64: the SQL reads the `iv` and the sealed-root flag out of it, and it is one field a document. +- **The parent tag `p` is the first eight bytes of its hash.** A parent tag is a lookup key for the server's walk and nothing else: an entry's AAD binds its selector and its ordinal, not its parent tag, so truncation authenticates nothing less. It has to be distinct among the entries of one document only, where eight bytes put a collision in a ten-thousand-node document below one in 10^11. The walk's misses are the other place a short tag could bite: a probe for an ordinal that does not exist that matches some stored tag would return an unrelated entry as a child. A walk of `N` nodes makes about `N` such probes against `N` stored tags, so the chance is the same order, about `N² / 2^64` a walk and row. The row it would add is authentic and opens; the client's rebuild checks each container's child count and each element's position, which catches it in most shapes but not all, so the bound is the probability, not a check. `eql_v4_internal.json_tree_parent_tag` is `encode(substr(h16(…), 1, 8), 'base64')`, twelve characters where hex took 32. +- **`op` needs its own extractor in SQL**, `eql_v4_internal.json_tree_ope_cllw(jsonb)`, because the `ope_cllw(jsonb)` every ordered scalar type shares reads hex and those wires are released. `eql_v4.ord_term` on an entry and on an ordering operand call it; the ordering operators and the functional btree are unchanged. + +### Measured (1,000 stored rows of each corpus, re-encoded and reloaded as jsonb, PostgreSQL 17.10) + +The rows were taken from the Phase 3c tables (one ordered path a corpus), re-encoded field by field the way the code now writes them, and both forms loaded into fresh tables; `pg_column_size` is the average over the 1,000 rows after `VACUUM FULL`. + +| | flat (5 nodes) | nested (219 nodes) | +|---|--:|--:| +| wire characters per document | 1,419 → 1,224 (−14%) | 58,111 → 47,038 (−19%) | +| `pg_column_size` per row | 1,596 → 1,398 B (−12%) | 40,808 → 31,894 B (−22%) | +| table with TOAST, 1,000 rows | 1,648 → 1,608 kB | 41 → 33 MB | + +The nested document is now about 14 times its plaintext on disk (18 at Phase 3c, 40 at Phase 3). The byte saving exceeds the character saving: pglz compressed hex better than it compresses base64 and base85, but not by enough to matter. The benchmark corpora are not re-ingested and no query is re-timed in this note; the walk, containment and ordering paths are covered by the oracle suite, which passed against the bundle built from the tree. Of the two levers left from the Phase 3 list, one is closed and one is open. **The derived nonce is rejected (2026-10-23).** It would save the twelve random bytes in every `c`, about 7% of a nested document, but it needs vitaminc to expose a caller-chosen nonce (a nonce strategy that reads the leaf's AAD, and a nonce-less leaf wire form), and a caller-chosen nonce is exactly what vitaminc's AEAD layer refuses to offer: its misuse resistance rests on never letting a caller repeat a (key, nonce) pair, and the safety argument here ("every seal mints a fresh data key") is an invariant of stack-encrypt that vitaminc could not check. Seven percent does not buy weakening that promise; the random nonce stays. Unpadded base64 (two characters a tag, about 3%) remains open and untaken. + +## Implementation notes (2026-10-23, Phase 4: the planner held to its indexes, and the leakage page) + +Two of the three items that gate a release are closed here; the third, the final re-bench, follows them. + +- **Planner fragility (gate 2).** `eql_v4.json_tree_query` is plpgsql with `COST 1000` so that a bitmap scan over the GIN index beats a sequential scan even when the documents are TOASTed and the heap looks like a few pages. That was observed in the benches, at 10,000 and 100,000 rows, on one PostgreSQL version, and nothing held it. `postgres_the_planner_picks_the_indexes_without_help` in the encryption suite now does: on a flat table (1,000 four-node documents, every row inline) and a nested table (300 documents of about 220 nodes, every row TOASTed, both regimes pinned by `pg_column_size`), with every planner setting at its default and after `ANALYZE`, containment plans as a bitmap scan over the GIN index and a range at an ordered path as a scan of the functional btree on `ord_term(doc -> selector)`. A control sets the function's cost to 1 for one transaction and shows the planner taking the sequential scan on the nested table, so the assertion is known to be able to fail. The suite runs in `test-eql.yml` in a new `rust-encryption-postgres` job, a matrix over the supported PostgreSQL versions (17 on a pull request, 14 to 17 on a push, like the SQLx jobs); it was a step of the single-version `rust-crates` job. Measured locally on 14, 15, 16 and 17 before the commit. +- **Leakage (gate 3).** `packages/eql/docs/reference/json-tree-leakage.md` is the one page: what a stored row shows at rest, field by field; what each query type hands the database; what is authenticated; the side-by-side with v3 from section 6 above, brought up to date (no `g`, position-keyed `p`, ordering opt-in) and corrected where section 6 was wrong (the entry order; see the note under its table); and the two options that change the picture. It says what a token is and that it is column-wide and does not expire, which is the sentence a customer most needs before sending one. +- **Open for the owner: the stored entry order (2026-10-23, review of #1336).** `sv` and `q` hold the nodes in the walk's order, depth-first, an object's members in the sorted order of their keys (serde_json's `Map` without `preserve_order`; a build that unifies that feature on would store insertion order instead, which leaks the application's field order). Across rows this reveals each row's shape, its parent relation, every array's length and the alphabetical order of sibling key names, which partly undoes what the keyed rank (decision 11) hides from a token holder. The leakage page says so. Closing it is a format change, not a documentation one: a stored order that does not follow the tree (a document-keyed permutation, say, with `j` the permuted position), a rebuild that does not read the tree from the order, and the same for the pairs of `q`, whose nesting would still group array elements. Not taken here. +- **Taken (2026-10-24, #1355, PR #1358): an extracted entry is checked to be the one asked for.** Until then `JsonNode` and `JsonSubtree` opened each entry under the `s` and `j` that arrived beside it, and under the data key the header that arrived with it named. The entry's AAD (`entry_aad` in `packages/stack-encrypt/src/json/derive.rs`) binds the keyset, the column's context, the data key's tag, the selector and the ordinal, and nothing that identifies a row. So a decrypted value was always one sealed in that column, but not necessarily the one at the path asked for, nor one from the row the result puts it in: `->` on `$.salary` could be answered with the row's `$.bonus`, with the sealed root (which opens to the whole document), or with another row's `$.salary` returned together with that row's header. Now a row opens only through what the client derived for the read. `JsonSelector::open(node)` refuses an entry whose `s` is not the selector (another path's entry, and the sealed root, whose selector is the root's, in place of a node) before any key is retrieved. `JsonSubtreeKey::open(rows)` refuses a row that does not fit the key's path: a node a gated walk reaches must carry the path's selector at depth `0`, and the position the path names when its last step is one; every other row must carry the selector of its parent's path extended by its own decrypted label (a key, or the wildcard for an element), which the key derives through the keyset's index-key PRF it now holds; and the rows of each subtree must be consecutive in the document, which is what a subtree is in a depth-first `sv`, so a row out of place, a dropped row and an orphan are refused. A reported depth `d` that disagrees is refused too; the rows are placed by their positions and child counts, not by `d`. The refusal is a new `Error::JsonWrongEntry`, not `Aead` (each entry is genuine) and not `OpenedType` (the entry is not of an unexpected shape; it answers another question). `eql-bindings` follows: `JsonTreeExtracted::from_selector(&selector, entry)` is how an entry `->` returned opens, and `JsonTreeEntry` no longer opens on its own. Still not covered: another row's `$.salary` with that row's header opens, by design (two values sealed under the same context are interchangeable between rows, ADR 0010 in `packages/stack-encrypt/docs/adr`, and row provenance is the database's word); and an array position before the last step of a path reads as the wildcard to every selector, so a walk's rows for `$.a[1].b` can be another element's `b` in the same row. Until the ungated walk returns the node it starts from (#1356), a walk with no gates is also not checked for which node at the path's selector it descends from, which matters only for a token chained through array positions (`$.l[3]`), whose children share every other element's selectors; nor for children left out after the last row it returns, or members left out anywhere, since the node's child count is in the node's own entry and a member's place is a keyed rank. An array's elements are checked to start at `0` (review of PR #1358: leaving out element 0 opened `[10, 20, 30]` as `[20, 30]`), and rows that stop short of a node's subtree are `JsonWrongEntry` like a gap. + +## Decisions to take before Phase 1 + +> **2026-10-22:** these are the open questions as they stood before Phase 1; the implementation notes above record how each was taken. Since then, decision 4's group tags exist only as the nesting of the stored projection `q`, decision 9 was settled by storing the projection (Phase 3), and decision 10's ordinal is not stored (Phase 3b). + +1. **Token encoding on the wire:** hex, matching v3's `s`, or base64url, saving about 40 characters per entry. Proposal: measure in Phase 3, default to base64url. Taken 2026-10-23 (Phase 3d): padded standard base64, not base64url, since PostgreSQL decodes only the former; base85 for `c`. +2. **Leaf ordering terms bound to the column only, or to the column and the selector.** Column-only reuses the v4 scalar ordering query domains unchanged and matches the ADR-0009 appendix; selector-bound stops cross-path order comparison at the cost of a JSON-specific query domain. Proposal: column-only for the phased plan, revisit in the ADR. +3. **Array index modes.** Wildcard only, with the chain serving positional access, retiring `[@]` and `[n]`. Proposal: yes. +4. **Group tags on by default**, or opt-in per column for callers who accept the v3 behaviour in exchange for not revealing element grouping. Proposal: on by default; `Contains` is declared exact and that declaration has to be true. +5. **`c` for container nodes**: label and kind only, as proposed, or label, kind and child count (lets the client pre-size and detect a truncated subtree). Proposal: add the child count; it is two bytes and it turns a missing entry into an error instead of a silently shorter array. +6. **Whether to fix v3 too** by porting the group tags and recheck to cipherstash-client and the v3 SQL. Separable; not proposed here. +7. **Plain SHA-256 or HMAC-SHA256 for the token derivations.** Plain SHA-256 is sound as argued under "The token chain": truncation and prefix domain separation each defeat length extension on their own, and no derivation is used as a MAC. HMAC would be an abundance of caution. Decided 2026-10-18: keep SHA-256 for the phased plan, and revisit only with Phase 3 benchmarks over large documents and tables in hand, since the question is whether the extra compression per walked node is measurable, not whether the construction is safe. +8. **The sealed root is a boolean option, on by default; its name is open.** Decided 2026-10-18, see "The sealed root" under the token chain. The two shapes are `d = 0` (chain from the root) and `d = 1` (document at the root, heads at the top-level fields); no other depth is exposed, because `d ≥ 2` leaks subtree sizes at rest and grows storage linearly. Working name "root node obfuscation", which says what it hides; alternatives that say what it stores are `sealed_root` or `root_document`. Phase 3 should measure the root copy against the three document shapes so the default is confirmed by numbers rather than by the estimate above. +9. **Native `@>` over the element-nested projection, built from tags or from a nested `sv`.** Both give identical leakage; the first keeps the flat `sv` every other function reads, the second drops two fields from the wire and changes `->` to a `$.**` lookup. Proposal: projection from tags first, measure both in Phase 2. +10. **Position-keyed parent tags on by default.** They remove sibling linkability at rest for one small integer per entry and `W × F` hashes per walk. Proposal: on, unless Phase 3 shows the walk cost matters on large documents. +11. **Key the label step of the token chain.** As written, a child's token is an unkeyed hash of its parent's token and its label, so whoever holds a token can test guesses of every key name beneath it (see "What a token is" under the token chain). Deriving the step under the index key, `PRF(json/token ‖ column, t(parent) ‖ 0x01 ‖ key)`, closes that at no cost to the server, which unwraps child tokens rather than deriving them. The same holds for anything else the client derives from a label under a token. Proposal: key it. **Where this stands:** the label step is keyed through the member's selector (the 2026-10-24 change below), and a member's ordinal is a random permutation per document (the 2026-10-26 notes), so no keyed rank remains in the format. + +## Design change (2026-10-24): derivable tokens, the self tag, and wildcard expansion on the client + +**Status:** agreed with the owner on 2026-10-24 and implemented in the pull request stacked on this write-up (see "Plan" below), with the open questions this section first carried settled as "Decisions (2026-10-24)" at its end, which override anything above them. The leakage page (`packages/eql/docs/reference/json-tree-leakage.md`) describes the format after the change, so neither should reach `next` without the other. Tracked in #1360. + +### Why + +Since Phase 3b a child's token is `t(child) = H16("t" ‖ t(parent) ‖ s(child) ‖ LE32(o))`, where `H16` is the first sixteen bytes of SHA-256, `s(child)` is the child's path selector and `o` is its **ordinal**, its place among its siblings. An array element's ordinal is its index. An object member's is its rank among its siblings: the members are sorted by `PRF(json/rank ‖ column, PAE(t(parent), key))` (`rank` and `shuffled_ordinals` in `packages/stack-encrypt/src/json/derive.rs`, the design's decision 11), so a member's ordinal depends on which other keys the object holds in that row. The client does not know a row's sibling keys, so it cannot derive the token of any node below a top-level field except through array positions (`subtree_key_for`). Everything else this document has had to add to the read path follows from that one fact: + +- **Gates exist only for it.** From the first key step below a head, the client stops deriving tokens and sends one gate per remaining step, which the server walks through (`json_tree_subtree_at`). A read of `$.profile.address.city` therefore sends `$.profile`'s token: a capability over that whole top-level field, in every row of the column, for as long as the column lives, to read one leaf. +- **It is why a read could not return the node it names.** A walk finds a node by its parent's token, and a chain head has none, so the ungated walk returned a node's descendants and never the node: `{}`, `[]`, a scalar and a missing field all came back as no rows (#1356). A read of `$.tags[1]` derived the element's own token and so had the same problem. +- **The patch for that widens the leak.** PR #1359 returns the node by sending a head's selector beside its token, and turns a path's last array position into a gate from the array's token (`#n:`). A read of `$.tags[1]` then sends `$.tags`'s token, which walks every element of that array in every row. + +Three changes remove all of it: a member's token stops depending on its ordinal, every entry carries a tag derived from its own token, and the client expands wildcards into concrete paths itself. + +### 1. Ordinal-free member tokens + +``` +t(member) = H16("t" ‖ t(parent) ‖ s(member)) object member: no ordinal +t(element) = H16("t" ‖ t(array) ‖ s(element) ‖ LE32(i)) array element: i is its index +p(child) = H8("p" ‖ iv ‖ t(parent) ‖ LE32(o)) unchanged; o is the stored ordinal +``` + +`H8` is the first eight bytes of SHA-256, as Phase 3d made the parent tag. Object keys are unique, so a member's selector alone separates it from its siblings, and the ordinal adds nothing to its token but the dependency on the other keys. Every element of an array shares one selector (the wildcard path's), so an element keeps its index. Since an element's ordinal already is its index, an element's token is unchanged. Chain heads and the root derive as today: under the sealed root a head's token is `PRF(json/token ‖ column, path)`, and with the root open the root's token is that PRF of `$` and a top-level field's follows the member rule from it. + +**Ordinals stay, for enumeration only.** The parent tag `p` keeps the ordinal, and an object member's ordinal is a uniformly random permutation of its object's members, drawn from the document's generator when it is sealed (`member_ordinals` in `packages/stack-encrypt/src/json/derive.rs`). Enumerating a node's children is still a probe of `o = 0, 1, 2, …` until the first miss, and the ordinals the probe reveals say nothing about the keys, in one row or across rows. Only the token stops depending on it. + +**The consequence is the point of the change: the client derives the token of any wildcard-free path from the path alone.** Head, then one hash per step, the step's selector from the path and, for a position, the index from the path. A token sent therefore always covers exactly the node asked for, and the gates have no reason to exist. + +**An element and a member still never share a token.** The Phase 3b review (#1329) bound the child's selector into the step so that the token of `$.a[0]` could not be, in a row whose `$.a` is an object, the token of whichever member ranks first. That property holds under the new rule twice over: an element's selector is the wildcard path's and a member's names its key, so the hashed inputs differ; and the inputs have different lengths (33 bytes for a member, 37 for an element), so they differ even if two selectors ever coincided. A member and an element cannot sit under the same parent in one row, and across rows a token for `$.a[0]` finds nothing in a row whose `$.a` is an object, because no entry there carries that token's self tag (next section). + +**The server cannot tell which rule a hit takes, and the self tag tells it.** As it walks, the server derives each hit's token from its parent's to go one level further. Today that is one rule for every hit. Under the new rules it needs to know whether the hit is a member or an element, and nothing stored says so: the kind is inside `c`, and a selector is a keyed hash that does not say whether its path ends in a key or a wildcard. So the walk derives the member candidate `H16("t" ‖ t ‖ s)`, keeps it if the hit's stored self tag `x` is `H8("x" ‖ iv ‖ candidate)`, and otherwise derives the element candidate with the hit's ordinal and checks that. A hit whose `x` matches neither is returned but not descended into; the client's check refuses it. That is up to four hashes per hit where the walk spends one today, on top of the two probes per node; the benchmarks below measure it. + +**Key names stay out of reach.** A member's token now hashes its selector where it hashed its ordinal. The selector is a PRF under the index key, so whoever holds a parent's token still cannot test a guessed key name: they would need the guess's selector, which takes the index key. Nothing about decision 11 moves. + +**The AAD does not change.** An entry's AAD (`entry_aad`) binds the keyset, the column's AAD, the data key's tag, the entry's selector `s` and its position `j` in `sv`. It does not bind the sibling ordinal `o`, the token, `p` or the new `x`, and it need not: the change moves only fields the server derives and compares, none of which is authenticated today. + +### 2. A self tag on every entry + +``` +x(node) = H8("x" ‖ iv ‖ t(node)) stored on every entry: the root, the heads and every node below +``` + +The self tag lets the server find an entry from its own token, where `p` finds it only from its parent's. It is salted by the document's `iv` like `p`, so at rest it is random bytes that link nothing within a row or across rows until a query supplies a token. It is on every entry, so its presence marks nothing: unlike `p`, which the heads lack, no entry is singled out by carrying it. + +**The sealed root carries one.** The root's token is derivable from `$` alone, with the root sealed or open, so the root entry gets `x = H8("x" ‖ iv ‖ PRF(json/token ‖ column, "$"))`. Today a sealed root has no token at all (the walk gives it none, and `json_subtree_key` refuses `$` as `TermError::JsonSealedRoot`). Under the sealed root nothing chains from `t($)`: the heads derive from their own paths and carry no `p`. So the root's token finds the root entry and nothing beneath it, which is the document's ciphertext the budget fallback already returns, and a read of `$` becomes an ordinary read that opens the whole document. The client still does not send `t($)` unless `$` is what is read. With the root open, `t($)` remains what it is today, the whole column's shape, and a read of `$` sends it. + +**What a read returns.** The node at depth 0, found by its `x`, then everything beneath it, enumerated under the node's own token. So `{}`, `[]`, a scalar and an absent node come back as an empty object's entry, an empty array's entry, the scalar's entry and no rows: the four distinct answers `jsonb #>` gives, which is what #1356 asks for and the semantics #1359 implements. An entry's ciphertext already carries its kind and child count, so the client tells `{}` from `[]` from the entry alone. + +**Collisions.** Eight bytes, like `p`. A probe with a token that names no node in the row matches some stored `x` with probability about `E / 2^64` for a row of `E` entries, per token. A false hit is an authentic entry of the row at the wrong place, which the client's check refuses (section 4), so a collision costs a refused read, not a wrong answer. + +**Size.** Eight bytes is twelve characters of padded base64, plus `,"x":""` framing: about 19 characters per entry, against roughly 200 per entry today, so about 10% more stored characters. Random bytes do not compress, so the on-disk share should be about the same. To be measured (section 7). + +### 3. Wildcard expansion on the client, and no gates + +A path with a wildcard (`$.items[*].price`) names no one node, so it has no token. Today the server resolves the wildcard by walking from the deepest derivable ancestor through a selector gate. After the change the client resolves it: it expands each wildcard step to the indices `0 … N−1` and sends one token per concrete path, plus one **probe** token for index `N` of each array it expands. For `$.items[*].price` that is `t($.items[0].price)` … `t($.items[N−1].price)` and the probe `t($.items[N])`. The probe is the element itself, not the element's `price`, because an element past the bound need not have one. + +- **The bound.** `N` defaults to 64, in the spirit of the walk's default budget, and is set by the caller where the read is derived. In a row where a probe hits, an array at that level is longer than `N`, and the read fails loudly with an error that names the bound (and not the path, whose key names can be customer data). It never returns a partial answer. The caller can raise `N`, or read the array itself: a read of `$.items` sends the array's own token, which is honest, because the whole array is then what was asked for. +- **Nested wildcards multiply.** Two wildcard levels send `N²` paths, `N` probes at the inner level and one at the outer: `N² + N + 1` tokens, 4,161 at the default. Each token costs the server one hash per row it scans, so a nested wildcard over many rows wants a smaller `N`. +- **A wildcard head becomes readable.** Under the sealed root, `$[*].x` on a root array was refused, because a wildcard head names no one node. Each `$[i]` is a head with its own token, so it now expands like any other wildcard. + +**The SQL.** `json_tree_subtree_at` and its gates are removed. The read is + +``` +eql_v4.json_tree_subtree(doc, tokens text[], budget integer DEFAULT 64) +``` + +For each token in turn, it looks the entry up by `x` (one map of the document's entries keyed by `x`, built once per call beside the existing map keyed by `p`), returns it at depth 0, then returns its descendants by ordinal probing under the node's own token, deriving each hit's token as section 1 describes. Rows come out in token order, and within a token in document order. A token with no entry yields no row. `json_tree_children(doc, token)` and `json_tree_child_count(doc, token)` lose their gates and take any derivable node's token: they enumerate one level below it, which needs no child token and so no rule choice. + +**The budget.** The walk counts rows across all the tokens of one call, the depth-0 rows included. With the root sealed and the count past the budget, it returns the root entry alone at depth 0, as today. The client opens the root to the whole document and evaluates the same concrete paths and the same probes over it. A probe that finds an element there is the same truncation error the walked read raises, so one row gives the same answer under the budget and over it, which is the property the Phase 3b review (#1329) held the fallback to. The client could answer a wildcard in full from the document, but then the answer would depend on the budget; decision 4 below keeps the bound. With the root open there is no fallback, as today. + +**The walk's bound needs rewording.** "The bound" in `functions.sql` argues that no two rows share a token because a hit's token is a hash of its probe, which includes the ordinal. A member's token no longer includes it: two entries forged under one parent with the same `s` and the member self tag would derive one token, and the walk would visit the subtree beneath it twice. The walk's other limit, `LIMIT` the entry count plus one, still caps the rows, and the client refuses a repeated position (`j`) as it does today. The comment has to say so. (Decision 9 below makes the read's limit the entry count times the number of tokens; `json_tree_children` and `json_tree_child_count`, which probe one level, keep the entry count plus one.) + +### 4. The client's check after the change + +PR #1358 made the client open a walk's rows only through the key it derived and refuse any row that does not fit (`Error::JsonWrongEntry`). It adapts: + +- **Each depth-0 row** must carry `x = H8("x" ‖ iv ‖ t)` for one of the tokens sent, and its authenticated selector and decrypted label must agree with that token's path: the path's selector, and the key or index its last step names. +- **Each deeper row** must sit at the next consecutive position `j` within its subtree, carry the selector of its parent's path extended by its decrypted label, and carry an `x` that matches the child token the client recomputes from its parent's token, the row's selector and its label (the key for a member; the index, from the label, for an element). `p` is not checked (decision 8). +- The child counts in each container's ciphertext still catch a dropped row, and a repeated position is still refused. + +`x` and `p` are not authenticated. The database holds every token a read sends and every row's `iv`, so it can write any `x` or `p` it likes. Matching them catches a row corrupted by someone who never saw the token, and a server that walks wrongly by mistake, but not a dishonest database. What binds a row to its place against the database is what the AAD covers: the selector, the position `j`, and the label and child count inside `c`. The check that each subtree's rows are consecutive in `sv` is on `j`, so it is one of those, and it stays beside the `x` check (decision 8). Nothing replaces it: the `x` check is a consistency check, and the bound fields with the consecutive-position rule are the security check, as the leakage page says. Decision 8 shows what the rule refuses that nothing else does. + +Still allowed by design (ADR 0010, `packages/stack-encrypt/docs/adr/0010-what-a-stored-value-authenticates.md`): an entry swapped in from another row under the same column context, returned with that row's header, opens. Row provenance is the database's word. + +### 5. Wire + +A stored entry becomes `{s, c, x, p?, op?}`: `x` on every entry, `p` below the heads as now. The domain CHECK on `public.eql_v4_json_tree_entry` and the `JsonTreeEntry` newtypes in `packages/eql/crates/eql-bindings/src/v4/json_tree.rs` gain `x` as padded base64 of eight bytes. Nothing else in `h`, `sv` or `q` changes. Counted informally, this is the format's sixth stored form, "revision 5 to 6"; that is a narrative label only, and no field records it: `JsonHeader::FORMAT_VERSION` stays `1` and the document's `v` stays `4` (decision 5). EQL v4's `json_tree` is unreleased, so nothing stored breaks: every fixture, every pinned vector and every benchmark table is regenerated. + +### 6. Leakage after the change + +`packages/eql/docs/reference/json-tree-leakage.md` carries the full statement; in short: + +- **A subtree read sends exactly the tokens of the nodes asked for.** A read of `$.profile.address.city` sends that leaf's token and nothing that covers `$.profile`. No capability over a top-level field or an array leaves the client unless that field or array is itself what is read. +- **A wildcard read sends `N + 1` tokens for each array it expands**, `N² + N + 1` in all for two levels. The database learns which of them exist in each row, so, up to `N`, which elements hold the rest of the path (each array's length, where the path ends at the element, which the stored entry order already shows, #1357), whether each array is longer than `N`, and the structure beneath each node found. It learns nothing about the elements' sibling fields. One exception: a probe that hits is a token for the element at index `N`, and the server enumerates that element's subtree in each row where it exists, although the read then fails. The exception is in the token, not in what the SQL does with it: whoever holds an element's token can derive that element's subtree in any row, now or in rows written later, so it holds for every variant of the read that sends the element's token (decision 3). +- **Unchanged:** a token is still column-wide and still does not expire; the `->` extraction path and containment send and reveal what they do today; at rest, `x` adds nothing beyond what `p` already shows; and the stored-order disclosure (#1357) is untouched by this change and stays a separate decision. + +### 7. Plan + +1. **This write-up**, as a draft pull request against PR #1358's branch. +2. **The implementation**, stacked on this branch, so the code and the revised leakage page land together. Stack Encrypt: the member rule and `x` in `derive.rs` (`child_token`, the walk, `seal`), concrete-path expansion in `path.rs`, and `JsonSubtreeKey` carrying the expanded tokens, which of them are probes, and the bound. SQL: `json_tree_subtree(doc, tokens, budget)`, the `x` map, the member-or-element choice, `json_tree_children` and `json_tree_child_count` from a token, the rewritten bound comment, and `json_tree_subtree_at` and the gates removed. `eql-bindings`: `x` on `JsonTreeEntry`, the CHECK, and `JsonTreeSubtree::from_key`. The Go guest has no `json_tree` yet and is untouched. Tests: + - pinned derivation vectors for a member token, an element token, a head token, the root token and `x`; + - a property test (proptest) that `t($.a.b)` is the same in rows whose `$.a` has different sets of sibling keys, which is the central property, and that element tokens differ by index; + - a property test, and the PostgreSQL oracle, that every wildcard-free read equals `jsonb #>` for all four answers (`{}`, `[]`, a scalar, absent), at a head, under array positions and deeper, with the root sealed and open, at budget 0 and budget 1; + - wildcard reads equal `jsonb_path_query` when every array is at most `N` long, and fail loudly with the bound when one is longer, nested wildcards included; + - the sealed-root fallback gives the same answers, the truncation error included; + - hostile PostgreSQL tests: a forged `x`, a row from another node, a moved subtree, a truncated walk, and a swapped entry from another row, which must still open (ADR 0010); + - `x` present on every entry, the root and the heads included; + - a stored-size regression test with a tolerance; + - `cargo mutants --in-diff` on both crates. +3. **Measure**, by a separate agent in `cipherstash/benches`, branch `feat/json-tree-benches` (crate `json-tree-bench/`, which builds Stack Encrypt and `eql-bindings` from the stack branch named in its `Cargo.toml`), against the local PostgreSQL on port 5400, database `jsonbench`, at 10,000 and 100,000 rows. A wire change means dropping the `json_tree` tables, reinstalling the v4 bundle built from the implementation branch, and re-ingesting. To report: the stored-size delta per corpus, in characters and `pg_column_size`; read latency of the token-list read against today's walk at `N` = 8, 64 and 256; the cost of the probes and of the member-or-element choice; and ingest time. The `check:v4:json_tree` correctness task calls the gated walk and has to move to the token list first. +4. **Close #1359 as superseded** once the implementation pull request is open. Its mechanism (a head found by selector, the last position sent as a gate from the array's token) is replaced. Its semantics carry over: the four answers, `JsonSubtree` opening as `Option` to `None` where the row has no node, and the oracle test `postgres_every_subtree_read_answers_as_jsonb_does`, rewritten for the token list. + +**Merge order.** #1345 (ready) rewrites `packages/stack-encrypt/tests/json_index.rs`, which #1358 also touches, and should merge first; #1358 then rebases, and this branch and the implementation follow it. + +### Decisions (2026-10-24) + +The owner settled the questions this section first left open, before implementation. Where a decision differs from the text above, the decision holds, and the implementation follows it. + +1. **Tokens.** `t(member) = H16("t" ‖ t(parent) ‖ s(member))`, with no ordinal; `t(element) = H16("t" ‖ t(array) ‖ s(element) ‖ LE32(i))`, `i` the index; the root's token and, under the sealed root, the heads' are PRFs of their paths, as before. The parent tag `p = H8("p" ‖ iv ‖ t(parent) ‖ LE32(o))` is unchanged, `o` the keyed rank for a member and the index for an element, and is used to enumerate children only. +2. **The self tag, and no kind bit.** `x = H8("x" ‖ iv ‖ t(self))` on every entry, the root and the heads included. Nothing stored says whether a node is a member or an element: when the server enumerates beneath a node and finds a hit at ordinal `o`, it derives the member rule's token and tests it against the hit's `x`, and on a miss tries the element rule's (`eql_v4_internal.json_tree_hit_token`). Up to four hashes per hit; the benchmarks measure what that costs. +3. **Probes are ordinary tokens.** No separate `probes` argument: for each array a wildcard expands the client sends the tokens of the positions `0 … N − 1` and the probe at `N`, the element itself (`t($.items[N])` for `$.items[*].price`). A row at a probe token has an array longer than `N`, and the client fails loudly, `Error::JsonWildcardTruncated { bound }`, never with a partial answer. `N` defaults to 64 (`JsonSubtreeKey::DEFAULT_BOUND`) and is set per read with `KeysetCipher::json_subtree_key_with_bound`; it is a read parameter, not part of the index's options, so the stored form and the data plan do not change with it. Nested wildcards multiply, and a read that would send more than 8,192 tokens is refused before any is derived (`TermError::JsonWildcardTooWide`): every one-level wildcard up to 8,191 elements, two levels up to a bound of 90, never three (the cap was 65,536 until the owner lowered it on 2026-10-25; see the implementation notes below). The exception the leakage page states stands: a probe that hits has the server enumerate that element's subtree, although the read then fails. The exception is in the token, not in what the SQL does with it: whoever holds `t($.items[N])` can find that element in any row by its self tag, probe for its children's parent tags and derive every descendant's token by the public derivations of sections 1 and 2, whatever the function returns, in rows written later too. So a separate argument answered with existence only would not remove it; it holds for every variant that sends the element's token. An existence-only probe needs a different derivation, for example a one-way value such as `H16("e" ‖ t)` sent in place of the token, with each entry storing a tag the server matches from it (beside `x`, or `x` itself derived from it): a change to the stored format and a future option, not this design. +4. **The fallback applies the same bound.** When a read falls back to the sealed root, the client evaluates the same concrete paths and the same probes over the whole document, so one row's answer never depends on the budget, the truncation error included. +5. **No version bump.** `JsonHeader::FORMAT_VERSION` stays `1` and the document's `v` stays `4`; the derivation is edited in place, as the earlier stored forms were. "Revision 5 to 6" above is a narrative label. EQL v4's `json_tree` is unreleased, so nothing stored breaks; every fixture, pinned vector and benchmark table is regenerated. +6. **`$` is a read under the sealed root.** It sends the root's token, which finds the root entry at depth 0, which opens to the whole document. `TermError::JsonSealedRoot` had no other use and is removed; `->` never used it. +7. **Children of an absent node.** `json_tree_child_count` of a token that names no node is NULL (it was 0); `json_tree_children` of one returns no rows. Both take the token of any derivable node. Under the sealed root the root's members chain from nothing, so the root's own token enumerates none: its count is NULL too, not a misleading 0. +8. **The client's check.** The depth-0 row's `s` must be the path's selector and its decrypted label the path's last step (the key, the index, or the root for `$`); each deeper row must sit at the next consecutive `j` within its subtree, with `s` the selector of its parent's path extended by its decrypted label; and every row's stored `x` must be `H8("x" ‖ iv ‖ t)` for the token the client recomputes. The `p` check is dropped. `x` is unauthenticated, so the `x` check is a consistency check that catches server bugs, not substitution; the bound fields `s`, `j` and the label are the security check. The consecutive-position rule is what refuses a node spliced in from under another element of the same array: a read of `$.items[0]` answered with the element's own entry and then `$.items[1].price` in place of `$.items[0].price`, its `x` rewritten, has the right selector, label and child count, and only its position is wrong. Still allowed by design (ADR 0010): an entry from another row, returned with its header; and a node at the same selector under another element when that node is the depth-0 row (`$.items[0].price` served for a read of `$.items[1].price`, with no row before it to fix its position), which no bound field tells apart. Also beyond any check: a database that withholds rows, so that a read opens as no node, or a wildcard read without some elements. The leakage page's "What is authenticated" says all three. +9. **No gates.** `json_tree_subtree_at` is dropped. `json_tree_subtree(e, tokens text[], budget integer DEFAULT 64)` returns, for each token in order, the entry whose `x` matches at `d = 0` and its descendants with `d` their depth below it, in document order within a token. The budget counts rows across all tokens, the depth-0 rows included; past it with the root sealed, the root entry alone at `d = 0`. The recursion is still read through a `LIMIT`, now the entry count times the number of tokens, since forged member tags can make one token's subtree be visited more than once ("The bound" in `functions.sql`). Wanting a whole array is a read of the array's path, which sends the array's own token. +10. **Stacking.** The implementation stacks on this write-up's branch and its pull request targets it. #1345 conflicts with #1358 and merges first. + +**Implemented.** The client's reads, checks and the fallback are in `packages/stack-encrypt/src/json/derive.rs`; the key and its expansion in `derive.rs` and `query.rs`; the SQL in `packages/eql/src/v3/json_tree/functions.sql`. The stored form gains `x` and is otherwise unchanged; a sealed document grows by about a tenth in characters (+9.8% on the nested benchmark shape and +9.4% on the flat one, pinned in `packages/stack-encrypt/tests/json_properties.rs`). The derivations are pinned under the deterministic key source in `packages/stack-encrypt/tests/json_tree_vectors.rs`. The PostgreSQL oracle (`packages/eql/tests/encryption/tests/json_tree.rs`) holds every read with no wildcard to `jsonb_path_query_first` in strict mode, wildcard reads to `jsonb_path_query`, the child functions to `jsonb_object_keys` and `jsonb_array_length`, and every read of a randomly tampered row to either the right answer, a refusal, or one of the allowances of decision 8. + +### Implementation notes (2026-10-25): what the walk was paying for + +The benchmarks of the implementation (cipherstash/benches `report/JSON_TREE_DERIVABLE_TOKENS.md`, summarised on #1363) found the token-specific reads faster than the gated walk and everything that enumerates slower: whole-subtree reads +38 to +46%, a full walk of a 300-element array +78%, `json_tree_child_count` on a small node +59%, with the per-hit cost inside a walk (about 36 µs per member, 80 µs per element) well above what the hashes explain. Reading the plan found four costs, none of them in the format. All four are SQL-only and fixed in #1363; the stored document is unchanged. + +1. **A pinned `search_path` disabled inlining of every chain primitive.** The post-install step (`tasks/pin_search_path_v3.sql`) sets `search_path` on every EQL function that does not carry the `eql-inline-critical` marker or take a jsonb-domain argument, and the planner does not inline a SQL function with a `SET` clause. So `json_tree_h16`, `json_tree_le32`, `json_tree_parent_tag`, `json_tree_self_tag`, `json_tree_member_token`, `json_tree_element_token` and `json_tree_hit_token` each ran as a full SQL-function call, about ten microseconds, where the hashes inside cost under one. A level of the walk makes about fourteen such calls, and `EXPLAIN ANALYZE` put the recursive step at 160 µs per level on the 300-wide corpus. The gated walk paid the same way, which is why the derivation's cost was invisible in the first comparison. The seven now carry the marker; the step is 14 µs per level. + +2. **`json_tree_hit_token` could not inline even unpinned.** Its body held a `FROM` clause, which blocks inlining; rewritten without one it was still refused, twice: as a STRICT function whose body is a `CASE`, which the planner inlines only when every argument is provably non-null, and then because its arguments, in the recursive term, were the expression that locates a hit, which the planner had flattened into the call, and a function that uses an expensive argument more than once is not inlined. It is now not STRICT, and the walk derives a hit's token where it consumes it, in the probe beneath, from the hit's stored `s` and `x` read off the working table, which are plain columns. An `OFFSET 0` fence on the lateral subqueries also inlined it, but introduced a `Memoize` node keyed on the whole document, at 64 µs per row. + +3. **The maps copied every entry, and were built twice.** `json_tree_by_parent` and `json_tree_by_self` each aggregated `elem || {"j": …}` over `sv`, 0.55 ms per map on a 215-entry document, and every read built both; `json_tree_child_count` built them, then called `json_tree_children`, which built them again. One function, `json_tree_index`, now builds both maps as tag → position in one pass (0.14 ms), set-returning with the two maps as columns so the planner inlines it as an aggregate subquery of the caller's `LATERAL`, which is computed once: a scalar function the `doc` CTE named twice (`idx -> 'p'`, `idx -> 'x'`) was evaluated twice when the planner flattened the subquery. An entry is fetched as `sv -> j` only when it is returned. + +4. **Every reference to the argument decompressed the document.** The stored value is TOAST-compressed, and the `doc` CTE referenced `e::jsonb` five times (header, `sv`, metadata, entry count, index), each a decompression of the whole document, about 40 µs for a nested one: 0.2 ms of a 0.6 ms one-token read. Each read now takes `e::jsonb #> '{}'`, the identity path, into a MATERIALIZED CTE and reads that. + +Measured on the benchmark's own pass queries (500 documents per scenario, `id = ANY(…)`, in-server time per document, three interleaved repetitions, medians), the SQL as #1363 first had it against the bundle built from the tree, on the same rows on one cluster; every scenario returned identical rows from both: + +| read | gated walk (bench) | derivable, as benched | derivable, now | change | +|---|--:|--:|--:|--:| +| `read/first_name` | 0.06 ms | 0.10 ms | 0.11 ms | +8.9% | +| `read/company.name` | 1.28 ms | 1.27 ms | 0.39 ms | -69.5% | +| `read/user.contact.emergency_contact.name` | 1.76 ms | 1.27 ms | 0.37 ms | -70.5% | +| `read/orders[2]` | 2.89 ms | 4.26 ms | 0.83 ms | -80.5% | +| `read/orders[2].status` | 1.24 ms | 1.26 ms | 0.37 ms | -70.3% | +| `read/company` | 1.36 ms | 2.06 ms | 0.49 ms | -76.2% | +| `read/user` | 1.91 ms | 2.77 ms | 0.59 ms | -78.6% | +| `read/orders (fallback)` | 5.60 ms | 8.64 ms | 0.84 ms | -90.3% | +| `read/orders (walked)` | 16.76 ms | 24.03 ms | 3.57 ms | -85.1% | +| `read/$ (sealed root)` | – | 1.26 ms | 0.39 ms | -69.1% | +| `read/$ (root open)` | 20.01 ms | 28.21 ms | 4.20 ms | -85.1% | +| `wildcard/orders[*].total N=8` | 4.62 ms | 2.41 ms | 0.60 ms | -75.0% | +| `wildcard/orders[*].total N=64` | 4.47 ms | 1.79 ms | 0.50 ms | -71.9% | +| `wildcard/orders[*].total N=256` | 4.61 ms | 2.81 ms | 0.66 ms | -76.5% | +| `wildcard/orders[*].items[*].price N=8` | 16.06 ms | 3.57 ms | 0.95 ms | -73.3% | +| `wildcard/orders[*].items[*].price N=64` | 16.30 ms | 25.03 ms | 4.08 ms | -83.7% | +| `children/orders (nested)` | – | 1.35 ms | 0.42 ms | -68.6% | +| `child_count/orders (nested)` | – | 2.39 ms | 0.31 ms | -87.1% | +| `children/attrs` | 24.13 ms | 12.33 ms | 5.12 ms | -58.4% | +| `child_count/attrs` | 24.47 ms | 14.27 ms | 1.20 ms | -91.6% | +| `read/attrs (walked)` | 29.82 ms | 40.74 ms | 7.22 ms | -82.3% | +| `children/list` | 24.45 ms | 12.59 ms | 5.08 ms | -59.7% | +| `child_count/list` | 24.28 ms | 14.23 ms | 1.21 ms | -91.5% | +| `read/list (walked)` | 30.16 ms | 55.61 ms | 8.22 ms | -85.2% | + +The gated-walk column is the benchmark's in-server figure for the same scenario, from a different run, and is there for orientation only. Every row the first comparison had as a regression against the gated walk is now faster than it. The `cipherstash/benches` harness measures `json_tree_by_parent` and `json_tree_by_self` as floors; both are gone, so its plan step must move to `json_tree_index` before the next full run. + +**For a future version of the format**, recorded here from the review of #1363 (none is in scope for this one): + +- *The sealed root's children enumerate from nothing.* The top-level entries carry no parent tag, because the format predates the root having a token, so `json_tree_children` at `$` returns no rows and `json_tree_child_count` returns NULL on the default layout, and a developer counts top-level fields by reading `$` and opening it. Chaining the heads from the root's token, `p = H("p" ‖ iv ‖ t($) ‖ LE32(o))`, would make the root enumerate like every other node. **Decided against for now (owner, 2026-10-25):** a walk from the root is a capability over the whole document's shape that the format deliberately withholds, so adding it increases leakage; SteVec offered nothing like it either, and it waits for a customer to ask. +- *Withheld rows are not detected.* Nothing in a row says how many nodes a read should find, so a database that drops rows makes a node look absent, or shortens a wildcard read. This is an integrity property against a lying database, outside the current threat model (confidentiality against an honest-but-curious one); closing it needs an authenticated count, for instance the array's child count read beside a wildcard. +- *The entries × tokens `LIMIT` and the token cap bound a lying database's own work.* Forged member tags can make a walk visit one subtree repeatedly; the client refuses the repeated positions, so only the database's work is at stake, and with the default sealed root and budget the read stops at `budget + 1` rows regardless. The `LIMIT` is the only bound when the budget is 0 or the root is open, and the token cap (`TermError::JsonWildcardTooWide`) scales it: a one-level wildcard with bound N sends N + 1 tokens and two levels send N² + N + 1, so the cap is 8,192 (owner, 2026-10-25; it was 65,536, which no measurement approached, the largest read benchmarked sending 4,161): every one-level read up to 8,191 elements, two levels up to a bound of 90, the default of 64 included, and no third level. + +### Implementation notes (2026-10-26): the cascade, and a random stored order (#1357) + +The stored order was the last disclosure of the format that no option changed: entries depth-first, members in key byte order, so a row's sequence of selectors gave its tree exactly, and comparing rows gave the parent of every node, every subtree's size and the byte order of sibling key names. It was deferred because the client's integrity check leaned on it: a read's rows had to sit at consecutive positions below the node asked for, with the position bound into each AAD. The spike in #1371 showed the way out, and the report linked from #1357 the analysis; this is the change, made the format. + +1. **The cascade is the integrity rule.** Every entry's AAD (domain `stack-encrypt/json/entry/v2`) binds, beside the keyset, the column, the key tag, the selector and the slot `j`, the digest of its children's AEAD tags, `SHA-256("k" ‖ tag(child₀) ‖ tag(child₁) ‖ …)` in ordinal order, a tag being the last sixteen bytes of a ciphertext as vitaminc lays a leaf out. Sealing runs from the leaves up. A leaf, an empty container and the sealed root (whose members chain from nothing) open under the digest of no children. A node's tag covers its AAD, so it commits to every ciphertext beneath it. Opening a read places its rows the way the server found them, by the chain (the node a token names by its self tag, a node's children by its parent tags at ordinals 0, 1, 2, …, each under the member or element rule its self tag fits), opens each node under the digest of the children placed under it, and then checks it. Nothing reads a slot as a position, so the rows may arrive, and be stored, in any order. Nothing stored changes: the AAD is not stored and the tag is already in `c`. Code: `packages/stack-encrypt/src/json/cascade.rs` and `place` in `derive.rs`. + + What it proves: the rows beneath the node a read names are exactly the ones sealed there, complete, each under its parent and in its place. What it does not: the place of that node itself, which is checked by its selector and its decrypted label alone, since nothing above it is read. The three allowances of ADR 0010 stand (another row's entry; another element's node at the same selector at the top of a read; withheld rows), and ADR 0010 now says so for `json_tree`. Upward verification was weighed in the report and not taken: it needs the ancestors' tokens, which is the capability the token-list read removed. + + Which refusal comes from where. The cipher (`Error::Aead`): a row swapped, dropped, added, reordered or moved under another parent beneath the node read; a truncated or reordered whole document; another column. An entry `->` returned that does not open alone is `Error::JsonNotALeaf`: a container with children (its AAD covers tags `->` does not return) or an altered entry, which nothing outside the ciphertext tells apart, so the error names both and claims neither. The client (`Error::JsonWrongEntry`): rows of two documents and an entry returned twice, before any key is retrieved; a row no token's subtree reaches; a reported depth the chain does not give; a child whose self tag fits neither rule, or not the one its label names; a node at the top of a read whose selector or label is not its path's; the sealed root anywhere but at `$`; a container whose plaintext child count is not the number of children it opened over. The hostile-row tests (`tests/json_read_checks.rs`, the PostgreSQL oracle) assert each of these exactly, and find rows by their paths rather than their slots. + +2. **A random stored order is the format.** Not an option, a flag or a switch. The root stays at slot 0, where the sealed-root fallback (`sv -> 0`) finds it; every other entry is placed by a uniformly random permutation of the slots 1…n, and `q`'s pair lists and element groups are shuffled the same way. The permutation is drawn per document at sealing time and thrown away: it is derived from nothing, keyed or not, because nobody needs to recompute it, and a permutation derived from anything stored (the `iv`) would be computable by the database. The generator is vitaminc's `SafeRand::from_entropy` with `next_below` (Lemire's reduction, bias at most n / 2⁶⁴) driving Fisher–Yates (`packages/stack-encrypt/src/json/order.rs`); it is not part of the format, since nothing stored depends on it. For fixtures, `StackCipherBuilder::json_order_seed` (behind `test-support`) draws every document's order from one stream started at a seed, through `SafeRand::from_controlled_seed`, and the deterministic test cipher sets it: `tests/fixtures/json_tree_vectors.json` now pins, per root option, the entries in their stored order, the path stored at each slot, the selector multiset, `q` as sets, and the tokens. The tags and tokens did not move. + + What stays visible at rest, and no order hides: the multiset of selectors (paths, node counts, array lengths, whether two rows have the same paths in the same numbers), `q`'s grouping by array element, which entries are heads under the sealed root (the head count, no longer the size of each head's subtree), each ciphertext's length, and the ordering terms at ordered paths. The leakage page drops its stored-order row and says this; the executable profile in `tests/json_leakage` models the new order, reading every world in an order an observer can rebuild without the stored one (`canonical.rs`). A containment or equality needle is shuffled the same way, with a fresh permutation per query drawn from the same `OrderSource` (`JsonQuery::of_terms` and `at_path`; the seed travels in the query's `JsonTerms`), so the query-time profile matches the at-rest one: in the walk's order a needle would show which of two sibling keys sorts first. `jsonb @>` is set containment over arrays, so the order changes no answer, and `JsonSelectorSet` (and so `JsonQuery`) compares as sets. Added at the owner's request after review, in the same PR. + +3. **First match at a wildcard path is unspecified (owner, 2026-10-26).** `json_tree_path_query_first`, and so `->`, `->>` and an ordering on `eql_v4.ord_term(col -> sel)`, returns the first entry in `sv` carrying a selector. At a wildcard path (every element under `$.a[*]`, at any depth) that is now an unspecified element, stable for a stored row but not element 0. Ordering or comparing over the elements of a wildcard path is written over all the matches (`json_tree_path_query`, `EXISTS` or `ORDER BY` over their ordering terms), and element order within a document is recovered after decryption from the labels, as it already was. No SQL changes. Two variants were considered and dropped by the owner: a fix-up after the shuffle that kept each wildcard selector's document-first entry first (it would have revealed, per wildcard selector, which entry is the document-first one), and writing the heads' digest into the sealed root's plaintext so that a client reading the root with its heads could verify them. The sealed root commits to nothing beneath it. + +4. **The keyset is loaded on a root-open decrypt.** Opening a whole document whose root is open walks the chain from the root's token, which needs the index key of the keyset it was sealed under. The open asks for it beside the data key, as a kind of request a `Pending` carries (`Request::load_keyset`), answered from the cipher's keyset cache or loaded from ZeroKMS on a miss through the path `StackCipher::keyset` uses; the loads run beside the data-key retrieval, and a load that fails fails only the documents under that keyset (`Error::KeysetLoad`). Settling a pending asks for a `DataKeySource` that is also an `IndexKeySource`, which every `StackCipher` is built over. The sealed root (the default) loads nothing. + +5. **An object's member ordinals are a random permutation.** The ordinal `o` in a member's parent tag, `H8("p" ‖ iv ‖ t(parent) ‖ LE32(o))`, which the server probes from zero to enumerate a node's children, was the member's keyed rank among its siblings (decision 11). Nothing reads a rank back: placement probes the parent tags and reads what is there, and a member's token does not depend on its ordinal. So each object's members now get a uniformly random permutation of `0..n` as their ordinals, drawn from the document's generator beside its stored order (`member_ordinals`, `shuffle::ordinals`). A token's holder, who sees the ordinals it probes, learns nothing from them about the keys, and cannot link a key to an ordinal across rows, which a rank under one token allowed. `RANK_DOMAIN` and `rank` are gone; the pinned vectors move in `order` and in each entry's `p` alone, the tags and tokens are unchanged, and the leakage profile's simulator draws per-row member orders (`member_order_shared_across_rows`). + +The SQL doc comments that promised "document order" (`json_tree_path_query`, `json_tree_children`, `json_tree_subtree`) now say what each returns: the stored order, ordinal order, and no promised order; no function changed. The benchmarks were not re-run: nothing stored and no SQL function changed. The client's added work is one SHA-256 per container over its children's tags, at sealing and at opening, and at opening the parent-tag probes the server already runs, which replace the position checks. diff --git a/docs/plans/2026-10-17-json-tree-index/containment-oracle.sql b/docs/plans/2026-10-17-json-tree-index/containment-oracle.sql new file mode 100644 index 0000000000..5355062922 --- /dev/null +++ b/docs/plans/2026-10-17-json-tree-index/containment-oracle.sql @@ -0,0 +1,163 @@ +-- ============================================================================ +-- Prototype A: plaintext-selector simulation of SteVec containment (no crypto). +-- Selectors are the canonical strings a keyed PRF would MAC; containment +-- semantics are identical because the PRF is injective in practice. +-- ============================================================================ +CREATE SCHEMA sim; + +-- Flatten a jsonb document into merged entries {s, vs, n?, g?}. +-- s = wildcard path selector ("$.a[*].x") +-- vs = value selector = s | tag | canon ("$.a[*].x|NUM|1") +-- n = this node's element tag (array elements only; positional, per column) +-- g = innermost enclosing array element's tag (descendants of an element) +CREATE FUNCTION sim.flatten(doc jsonb, path text DEFAULT '$', elem text DEFAULT NULL, pos text DEFAULT '$') +RETURNS SETOF jsonb LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE + tag text; canon text; k text; v jsonb; i int := 0; own text := NULL; e jsonb; +BEGIN + tag := CASE jsonb_typeof(doc) WHEN 'object' THEN 'MAP' WHEN 'array' THEN 'ARRY' + WHEN 'string' THEN 'STR' WHEN 'number' THEN 'NUM' WHEN 'boolean' THEN upper(doc::text) ELSE 'NULL' END; + canon := CASE jsonb_typeof(doc) WHEN 'string' THEN doc #>> '{}' WHEN 'number' THEN (doc::numeric)::text ELSE '' END; + e := jsonb_build_object('s', path, 'vs', path || '|' || tag || '|' || canon); + IF elem IS NOT NULL THEN e := e || jsonb_build_object('g', elem); END IF; + IF right(path, 3) = '[*]' THEN own := 'E:' || pos; e := e || jsonb_build_object('n', own); END IF; + RETURN NEXT e; + IF jsonb_typeof(doc) = 'object' THEN + FOR k, v IN SELECT * FROM jsonb_each(doc) ORDER BY 1 LOOP + RETURN QUERY SELECT * FROM sim.flatten(v, path || '.' || k, COALESCE(own, elem), pos || '.' || k); + END LOOP; + ELSIF jsonb_typeof(doc) = 'array' THEN + FOR v IN SELECT * FROM jsonb_array_elements(doc) LOOP + RETURN QUERY SELECT * FROM sim.flatten(v, path || '[*]', COALESCE(own, elem), pos || '[' || i || ']'); + i := i + 1; + END LOOP; + END IF; +END $$; + +CREATE FUNCTION sim.store(doc jsonb) RETURNS jsonb LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('sv', jsonb_agg(e)) FROM sim.flatten(doc) e $$; + +-- The flat needle: every selector of the needle, as today (s and vs only). +CREATE FUNCTION sim.flat_query(doc jsonb) RETURNS jsonb LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('sv', jsonb_agg(jsonb_build_object('s', e->'s') ) || jsonb_agg(jsonb_build_object('vs', e->'vs'))) + FROM sim.flatten(doc) e $$; + +-- What GIN indexes: {s, vs} per entry, nothing else. +CREATE FUNCTION sim.to_query(stored jsonb) RETURNS jsonb LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('sv', jsonb_agg(jsonb_build_object('s', e->'s', 'vs', e->'vs'))) + FROM jsonb_array_elements(stored->'sv') e $$; + +-- Flat containment = today's semantics. Both arguments are plaintext documents; +-- the stored side is flattened here, as the producer would have flattened it. +CREATE FUNCTION sim.flat_contains(stored jsonb, needle jsonb) RETURNS boolean LANGUAGE sql IMMUTABLE AS $$ + SELECT sim.to_query(sim.store(stored)) @> sim.flat_query(needle) $$; + +-- Group structure of a needle: one group per array ELEMENT that is a container, +-- {at: wildcard path of the element, need: [vs...] (constraints inside the element +-- but outside nested array elements, including the element's own vs), sub: [groups]} +CREATE FUNCTION sim.groups(doc jsonb, path text DEFAULT '$', in_elem boolean DEFAULT false) +RETURNS jsonb LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE out jsonb := '[]'; k text; v jsonb; g jsonb; +BEGIN + IF jsonb_typeof(doc) = 'object' THEN + FOR k, v IN SELECT * FROM jsonb_each(doc) LOOP out := out || sim.groups(v, path || '.' || k, in_elem); END LOOP; + ELSIF jsonb_typeof(doc) = 'array' THEN + FOR v IN SELECT * FROM jsonb_array_elements(doc) LOOP + IF jsonb_typeof(v) IN ('object','array') THEN + -- a container element: a group of everything inside it, down to nested elements + g := jsonb_build_object('at', path || '[*]', + 'need', (SELECT COALESCE(jsonb_agg(e->'vs'), '[]') FROM sim.flatten(v, path || '[*]') e WHERE NOT (e ? 'g') OR e->>'g' = 'E:$'), + 'sub', sim.groups(v, path || '[*]', true)); + out := out || jsonb_build_array(g); + END IF; + END LOOP; + END IF; + RETURN out; +END $$; + +-- Exact recheck: for every group there is a stored element whose own entries +-- carry every needed selector, and whose nested elements satisfy the sub-groups. +CREATE FUNCTION sim.groups_ok(sv jsonb, grps jsonb, parent_tag text DEFAULT NULL) +RETURNS boolean LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE grp jsonb; ok boolean; el jsonb; +BEGIN + FOR grp IN SELECT * FROM jsonb_array_elements(grps) LOOP + ok := false; + FOR el IN SELECT e FROM jsonb_array_elements(sv) e + WHERE e ? 'n' AND e->>'s' = grp->>'at' + AND (parent_tag IS NULL OR e->>'g' = parent_tag) LOOP + -- every needed selector is on an entry of this element (its own entry or a descendant outside nested elements) + IF NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements_text(grp->'need') need + WHERE NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(sv) x + WHERE x->>'vs' = need AND (x->>'n' = el->>'n' OR (x->>'g' = el->>'n' AND NOT (x ? 'n')) + OR (x ? 'n' AND x->>'g' = el->>'n' AND x->>'vs' = need)))) -- nested element's own vs (its MAP/ARRY tag) counts as inside the outer element + AND sim.groups_ok(sv, grp->'sub', el->>'n') THEN + ok := true; EXIT; + END IF; + END LOOP; + IF NOT ok THEN RETURN false; END IF; + END LOOP; + RETURN true; +END $$; + +CREATE FUNCTION sim.exact_contains(stored jsonb, needle jsonb) RETURNS boolean LANGUAGE sql IMMUTABLE AS $$ + SELECT sim.flat_contains(stored, needle) AND sim.groups_ok(sim.store(stored)->'sv', sim.groups(needle)) $$; + +-- Oracle: random-ish corpus; report every disagreement with jsonb @>. +CREATE TABLE sim.cases(stored jsonb, needle jsonb); +INSERT INTO sim.cases VALUES + ('{"a":[{"x":1,"y":5},{"x":7,"y":2}]}', '{"a":[{"x":1,"y":2}]}'), + ('{"a":[{"x":1,"y":2,"z":3}]}', '{"a":[{"x":1,"y":2}]}'), + ('{"a":[{"x":1}]}', '{"a":[{"x":1},{"x":1}]}'), + ('{"a":[{"b":[{"x":1},{"y":2}]}]}', '{"a":[{"b":[{"x":1,"y":2}]}]}'), + ('{"a":[{"b":[{"x":1,"y":2}]}]}', '{"a":[{"b":[{"x":1,"y":2}]}]}'), + ('{"a":[{"b":[{"x":1,"y":2}],"c":3},{"b":[{"x":1,"y":9}],"c":4}]}', '{"a":[{"b":[{"x":1,"y":2}],"c":4}]}'), + ('{"a":[{"b":[{"x":1,"y":2}],"c":3},{"b":[{"x":1,"y":9}],"c":4}]}', '{"a":[{"b":[{"x":1,"y":2}],"c":3}]}'), + ('{"a":[{"b":{"c":1,"d":2}},{"b":{"c":3,"d":2}}]}', '{"a":[{"b":{"c":1,"d":2}}]}'), + ('{"a":[{"b":{"c":1,"d":5}},{"b":{"c":3,"d":2}}]}', '{"a":[{"b":{"c":1,"d":2}}]}'), + ('{"a":[[1,2],[3,4]]}', '{"a":[[1,4]]}'), + ('{"a":[[1,2],[3,4]]}', '{"a":[[1,2]]}'), + ('{"a":[[1,2],[3,4]]}', '{"a":[[1],[4]]}'), + ('{"a":[1,2]}', '{"a":[]}'), + ('{"a":{"b":1}}', '{"a":{}}'), + ('{"a":{}}', '{"a":{"b":1}}'), + ('{"a":[1]}', '{"a":1}'), + ('{"a":1}', '{"a":[1]}'), + ('[1,[2]]', '[2]'), + ('[1,[2]]', '[[2]]'), + ('[1,2]', '[1,1,1]'), + ('{"a":1}', '{}'), + ('[1]', '{}'), + ('{"a":null}', '{"a":null}'), + ('{"a":"2"}', '{"a":2}'), + ('{"a":2}', '{"a":2.0}'), + ('["a"]', '"a"'), + ('"a"', '"a"'), + ('{"a":[{"x":1}]}', '{"a":[{}]}'), + ('{"a":[1]}', '{"a":[{}]}'), + ('{"a":[{"t":[{"u":1,"v":2}]},{"t":[{"u":1},{"v":2}]}]}', '{"a":[{"t":[{"u":1,"v":2}]}]}'), + ('{"a":[{"t":[{"u":1},{"v":2}]}]}', '{"a":[{"t":[{"u":1,"v":2}]}]}'); + +SELECT stored::text AS stored, needle::text AS needle, + (stored @> needle) AS jsonb, + sim.flat_contains(stored, needle) AS flat_today, + sim.exact_contains(stored, needle) AS exact_new, + CASE WHEN (stored @> needle) <> sim.exact_contains(stored, needle) THEN '<<< DISAGREES' ELSE '' END AS verdict +FROM sim.cases; + +-- The file checks itself: how many cases each form gets wrong against jsonb @>. +-- Expected: flat_today 8 (the six cross-element false positives, the root-scalar +-- false negative, and the 2 / 2.0 artefact), exact_new 2 (the two artefacts below). +SELECT count(*) AS cases, + count(*) FILTER (WHERE (stored @> needle) <> sim.flat_contains(stored, needle)) AS flat_today_disagrees, + count(*) FILTER (WHERE (stored @> needle) <> sim.exact_contains(stored, needle)) AS exact_new_disagrees +FROM sim.cases; + +-- Known simulation artefacts (not design defects): +-- * `2` vs `2.0`: this file canonicalises numbers with numeric::text, so they differ; +-- the real producer canonicalises by numeric value (cipherstash-client's +-- canonical_number does today), and the two agree. +-- * `["a"] @> '"a"'`: the top-level-scalar false negative is REAL in v3 today and +-- is fixed in the design by the needle's `alt` selector set, not here. diff --git a/docs/plans/2026-10-17-json-tree-index/jsonb-semantics.sql b/docs/plans/2026-10-17-json-tree-index/jsonb-semantics.sql new file mode 100644 index 0000000000..830b1a7213 --- /dev/null +++ b/docs/plans/2026-10-17-json-tree-index/jsonb-semantics.sql @@ -0,0 +1,25 @@ +\pset format aligned +SELECT 'root array contains scalar' AS case, '["a"]'::jsonb @> '"a"' AS result +UNION ALL SELECT 'scalar contains array', '"a"'::jsonb @> '["a"]' +UNION ALL SELECT 'nested primitive vs array', '{"a":[1]}'::jsonb @> '{"a":1}' +UNION ALL SELECT 'nested array vs primitive', '{"a":1}'::jsonb @> '{"a":[1]}' +UNION ALL SELECT 'inner array does not contain scalar', '[1,[2]]'::jsonb @> '[2]' +UNION ALL SELECT 'inner array contains array', '[1,[2]]'::jsonb @> '[[2]]' +UNION ALL SELECT 'empty object needle', '{"a":{"b":1}}'::jsonb @> '{"a":{}}' +UNION ALL SELECT 'empty object target', '{"a":{}}'::jsonb @> '{"a":{"b":1}}' +UNION ALL SELECT 'empty array needle', '{"a":[1,2]}'::jsonb @> '{"a":[]}' +UNION ALL SELECT 'root {} in object', '{"a":1}'::jsonb @> '{}' +UNION ALL SELECT 'root {} in array', '[1]'::jsonb @> '{}' +UNION ALL SELECT 'root [] in array', '[1]'::jsonb @> '[]' +UNION ALL SELECT 'duplicates', '[1,2]'::jsonb @> '[1,1,1]' +UNION ALL SELECT 'issue 1231 cross-element', '{"a":[{"x":1,"y":5},{"x":7,"y":2}]}'::jsonb @> '{"a":[{"x":1,"y":2}]}' +UNION ALL SELECT 'issue 1231 same element', '{"a":[{"x":1,"y":2,"z":3}]}'::jsonb @> '{"a":[{"x":1,"y":2}]}' +UNION ALL SELECT 'two needle elements one stored', '{"a":[{"x":1}]}'::jsonb @> '{"a":[{"x":1},{"x":1}]}' +UNION ALL SELECT 'nested arrays of objects', '{"a":[{"b":[{"x":1},{"y":2}]}]}'::jsonb @> '{"a":[{"b":[{"x":1,"y":2}]}]}' +UNION ALL SELECT 'nested arrays same inner', '{"a":[{"b":[{"x":1,"y":2}]}]}'::jsonb @> '{"a":[{"b":[{"x":1,"y":2}]}]}' +UNION ALL SELECT 'scalar inside nested array at depth', '{"a":[["x"]]}'::jsonb @> '{"a":["x"]}' +UNION ALL SELECT 'root scalar equal', '"a"'::jsonb @> '"a"' +UNION ALL SELECT 'root number 2 vs 2.0', '2'::jsonb @> '2.0' +UNION ALL SELECT 'null leaf', '{"a":null}'::jsonb @> '{"a":null}' +UNION ALL SELECT 'root array of arrays contains scalar?', '[["a"]]'::jsonb @> '"a"'; +SELECT sha256('abc'::bytea) IS NOT NULL AS core_sha256, set_byte('\x00'::bytea,0,1) AS set_byte_ok; diff --git a/docs/plans/2026-10-17-json-tree-index/token-chain.sql b/docs/plans/2026-10-17-json-tree-index/token-chain.sql new file mode 100644 index 0000000000..efb1639d2a --- /dev/null +++ b/docs/plans/2026-10-17-json-tree-index/token-chain.sql @@ -0,0 +1,110 @@ +-- ============================================================================ +-- Prototype B: the token chain, server side, in core PostgreSQL only (sha256, bytea). +-- The derivations are the plan's ("The token chain"), with H = SHA-256 truncated to +-- 16 bytes and the domain byte first: +-- t(root) = PRF(json/token ‖ column, "$")[..16] client only (simulated: a hash) +-- t(child) = H("t" ‖ t(parent) ‖ 0x01 ‖ key) object member (client only) +-- t(child) = H("t" ‖ t(parent) ‖ 0x02 ‖ LE64(index)) array element (client only) +-- p(child) = H("p" ‖ iv ‖ t(parent)) stored: unlinkable without t(parent) +-- w(child) = t(child) XOR H("w" ‖ iv ‖ t(parent) ‖ c) stored: the wrapped token +-- c = node-local ciphertext (simulated here as random-looking bytes) +-- iv is the document key's IV from the header `h`, simulated as the stored `iv` field. +-- This is the chain from the root (the sealed-root option off), so that the root +-- token can be shown to reach every non-root entry. +-- The server, given t(start), finds children by p, unwraps each child's token with +-- its own c as the mask input, and recurses. Nothing else in the row is linkable. +-- ============================================================================ +CREATE SCHEMA chain; + +CREATE FUNCTION chain.h16(x bytea) RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ SELECT substr(sha256(x), 1, 16) $$; +CREATE FUNCTION chain.xor16(a bytea, b bytea) RETURNS bytea LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE r bytea := a; i int; +BEGIN + FOR i IN 0..15 LOOP r := set_byte(r, i, get_byte(a, i) # get_byte(b, i)); END LOOP; + RETURN r; +END $$; +CREATE FUNCTION chain.le64(n bigint) RETURNS bytea LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE r bytea := '\x0000000000000000'; i int; +BEGIN + FOR i IN 0..7 LOOP r := set_byte(r, i, ((n >> (8 * i)) & 255)::int); END LOOP; + RETURN r; +END $$; + +-- Client side: a child's token from its parent's and its label (a key or an index). +CREATE FUNCTION chain.child_token(t bytea, label jsonb) RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ + SELECT CASE jsonb_typeof(label) + WHEN 'string' THEN chain.h16('t'::bytea || t || '\x01'::bytea || convert_to(label #>> '{}', 'UTF8')) + ELSE chain.h16('t'::bytea || t || '\x02'::bytea || chain.le64((label #>> '{}')::bigint)) + END $$; +CREATE FUNCTION chain.parent_tag(iv bytea, t bytea) RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ + SELECT chain.h16('p'::bytea || iv || t) $$; +CREATE FUNCTION chain.mask(iv bytea, t bytea, c bytea) RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ + SELECT chain.h16('w'::bytea || iv || t || c) $$; + +-- Client-side simulation: flatten a doc into chained entries {s, p, w, c, lbl(debug only)}. +CREATE FUNCTION chain.flatten(doc jsonb, iv bytea, t bytea, path text, parent_t bytea, label text) +RETURNS SETOF jsonb LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE k text; v jsonb; i int := 0; e jsonb; ct bytea; +BEGIN + -- simulated node-local ciphertext: Enc(label, kind, scalar) -> here just a hash so it is unique and public + ct := sha256(convert_to('ct' || path || label || doc::text, 'UTF8')); + e := jsonb_build_object('s', path, 'c', encode(ct, 'hex'), 'lbl', label || '=' || CASE WHEN jsonb_typeof(doc) IN ('object','array') THEN jsonb_typeof(doc) ELSE doc::text END); + IF parent_t IS NOT NULL THEN + e := e || jsonb_build_object('p', encode(chain.parent_tag(iv, parent_t), 'hex'), + 'w', encode(chain.xor16(t, chain.mask(iv, parent_t, ct)), 'hex')); + END IF; + RETURN NEXT e; + IF jsonb_typeof(doc) = 'object' THEN + FOR k, v IN SELECT * FROM jsonb_each(doc) ORDER BY 1 LOOP + RETURN QUERY SELECT * FROM chain.flatten(v, iv, chain.child_token(t, to_jsonb(k)), path || '.' || k, t, k); + END LOOP; + ELSIF jsonb_typeof(doc) = 'array' THEN + FOR v IN SELECT * FROM jsonb_array_elements(doc) LOOP + RETURN QUERY SELECT * FROM chain.flatten(v, iv, chain.child_token(t, to_jsonb(i)), path || '[*]', t, i::text); + i := i + 1; + END LOOP; + END IF; +END $$; + +CREATE FUNCTION chain.t_root() RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ SELECT chain.h16('idxkey:json/token:$'::bytea) $$; +-- the client derives a start token from a positional path: keys as strings, indexes as numbers +CREATE FUNCTION chain.t_for(steps jsonb) RETURNS bytea LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE t bytea := chain.t_root(); step jsonb; +BEGIN FOR step IN SELECT * FROM jsonb_array_elements(steps) LOOP t := chain.child_token(t, step); END LOOP; RETURN t; END $$; + +CREATE FUNCTION chain.store(doc jsonb, iv bytea) RETURNS jsonb LANGUAGE sql IMMUTABLE AS $$ + SELECT jsonb_build_object('iv', encode(iv, 'hex'), 'sv', jsonb_agg(e)) + FROM chain.flatten(doc, iv, chain.t_root(), '$', NULL, '$') e $$; + +-- SERVER SIDE: subtree of the node whose token is t_start. Plain recursive CTE. +CREATE FUNCTION chain.subtree(stored jsonb, t_start bytea) +RETURNS TABLE(depth int, entry jsonb) LANGUAGE sql STABLE AS $$ + WITH RECURSIVE walk(depth, t, entry) AS ( + SELECT 0, t_start, NULL::jsonb + UNION ALL + SELECT w.depth + 1, + chain.xor16(decode(e->>'w', 'hex'), chain.mask(decode(stored->>'iv', 'hex'), w.t, decode(e->>'c', 'hex'))), + e + FROM walk w + JOIN LATERAL jsonb_array_elements(stored->'sv') e + ON e->>'p' = encode(chain.parent_tag(decode(stored->>'iv', 'hex'), w.t), 'hex') + ) + SELECT depth, entry FROM walk WHERE entry IS NOT NULL +$$; + +\set doc '{"hello":"world-1","nested":{"deep":"constant","list":[{"x":1},{"x":2}]},"number":1}' +\set iv '\'\\x000102030405060708090a0b0c0d0e0f\'::bytea' +SELECT jsonb_pretty(chain.store(:'doc'::jsonb, :iv)); +-- subtree under $.nested (what `doc -> '$.nested'` must return), via the client-derived token +SELECT depth, entry->>'s' AS s, entry->>'lbl' AS decrypted_label_kind_value +FROM chain.subtree(chain.store(:'doc'::jsonb, :iv), chain.t_for('["nested"]')) ORDER BY depth, s; +-- a wrong token unlocks nothing +SELECT count(*) AS entries_with_wrong_token FROM chain.subtree(chain.store(:'doc'::jsonb, :iv), chain.h16('garbage'::bytea)); +-- whole document from the root token +SELECT count(*) AS entries_under_root, (SELECT jsonb_array_length(chain.store(:'doc'::jsonb, :iv)->'sv')) - 1 AS expected +FROM chain.subtree(chain.store(:'doc'::jsonb, :iv), chain.t_root()); +-- the same document under another IV: no parent tag in common, so shape does not link across rows at rest +SELECT count(*) AS parent_tags_shared_across_ivs +FROM jsonb_array_elements(chain.store(:'doc'::jsonb, :iv)->'sv') a +JOIN jsonb_array_elements(chain.store(:'doc'::jsonb, '\xff0102030405060708090a0b0c0d0e0f'::bytea)->'sv') b + ON a->>'p' = b->>'p'; diff --git a/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md new file mode 100644 index 0000000000..3999401962 --- /dev/null +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -0,0 +1,2515 @@ +# Stack Encrypt API plan + +Date: 8 November 2026. Checked against `next` at commit `e4990e49b`. +Revised 9 November 2026: the derive emits the combinators, not the plan +builder, and `Planned` is a target (ADR-0007, amended). Tracking lines +refreshed on 15 November 2026, against `next` at `360530276` and the open +stack of pull requests #1613, #1659, #1664 and #1666. + +Stack Encrypt encrypts each value under its own data key from ZeroKMS, +CipherStash's key service. It also makes the search terms that let +PostgreSQL query the encrypted value. The Rust crate `stack-encrypt` is the +engine. The Go SDK runs the same engine through the dynamic interface. + +This plan is for the engineers who build Stack Encrypt, and for the lead +who approves its design. It has three parts: + +1. [Target state](#target-state): the API we are building, shown as code. +2. [Remaining work](#remaining-work): what is left to build to reach it. +3. [Open questions and decisions to be + made](#open-questions-and-decisions-to-be-made). + +Three documents go with it: + +- the [context scenarios](2026-10-24-stack-encrypt-context-examples.md), + the acceptance matrix for how a record gets its context; +- [binds, claims, and labels](2026-11-08-stack-encrypt-key-policy.md), + the design of key policy: what ties a value to a fact, and what only + records one; +- [packaging and names](2026-10-25-stack-encrypt-packaging.md), the + proposal the naming review judged on 8 November 2026. + +The naming review of 8 November 2026 decided every public name this plan +uses. [Names decided in the naming +review](#names-decided-in-the-naming-review), at the end, records each +decision. + +## Contents + +- [Terms](#terms) +- [Target state](#target-state) + - [Rust with static types](#rust-with-static-types) + - [The dynamic interface](#the-dynamic-interface) + - [Rules in the target state](#rules-in-the-target-state) +- [Remaining work](#remaining-work) + - [1. The Go module](#1-the-go-module) + - [2. The stored format](#2-the-stored-format) + - [3. The Rust API](#3-the-rust-api) + - [4. The query engine](#4-the-query-engine) + - [5. Packaging, and two key provider features](#5-packaging-and-two-key-provider-features) +- [Open questions and decisions to be made](#open-questions-and-decisions-to-be-made) + - [Names decided in the naming review](#names-decided-in-the-naming-review) + +## Terms + +| Term | Meaning | +| --- | --- | +| AAD (additional authenticated data) | Data that encryption checks for one ciphertext, but does not encrypt. Stack Encrypt builds it from the context. See [Context and AAD](#context-and-aad) | +| ADR | An architecture decision record, in `packages/stack-encrypt/docs/adr/`. ADR-0007 says every binding runs the engine's one executor | +| Access intelligence | The record of who retrieved which key, and for which value, built from ZeroKMS's log of key retrievals. Labels are what make the record useful | +| Analyzer | The pipeline that turns match text into tokens: a source, such as `Words`, then stages. A match index is configured by one analyzer | +| Binding | A part of the context that ties a ciphertext to its row, such as a row ID. It is in the stored context and not in the query context. Passed as `Bind::new(..)` | +| Claim | A binding whose value the key provider resolves from the caller's verified token, such as `sub`. The client names it and never sees the value. See [Claims the key provider resolves](#claims-the-key-provider-resolves) | +| Cipher | The Rust connection to ZeroKMS, with credentials and the key provider: `Cipher::new()`. `cipher.keyset(..)` resolves a `Keyset`, and `cipher.decrypt(..)` opens values from any keyset it holds. Today `StackCipher` | +| Ciphertext | One encrypted value, as the Rust `Ciphertext` type. It is stored as bytes, or as Base64 text | +| Conformance profile | A named, versioned set of test cases for one area, such as `record-contexts-v1`. Rust and Go run the same cases. The files are in `conformance/stack-encrypt/v1/` | +| Context | Data that a ciphertext is tied to, such as a column name or a row ID. Decryption needs the same context. See [Context and AAD](#context-and-aad) | +| Descriptor | The string a key request names its key under. ZeroKMS derives the data key from it. Today the whole context is rendered into it, such as `users/age`. Under envelope version 2 it is the name scopes only: the record name and the field name | +| Dynamic interface | The engine's interface for languages other than Rust. It takes a declaration and values as data, not as Rust types | +| EQL (Encrypt Query Language) | The PostgreSQL types and functions in `packages/eql` that store encrypted values and answer queries on them | +| Executor | The combinators in `target/`: the one engine path that runs every declaration. The derive's generated code and `Planned` both compose them. The executor derives each field's context, requests the keys in one batch, and seals or opens every value | +| Field reference | A constant the derive emits for each field of a record, such as `EncryptedMember::EMAIL`. It names the field, its plaintext type, its accessor, and its indexes. A typed query starts from it | +| Guest | The Rust engine compiled to WebAssembly. The Go SDK runs it inside the Go process | +| Key tag | The HMAC ZeroKMS returns with a data key. A reader must present it to get the key again. Stack Encrypt binds it into every leaf's AAD | +| Keyset | A set of keys in ZeroKMS. Every data key belongs to one keyset. A tenant can have its own keyset. In Rust, `Keyset` is also the handle bound to one keyset, which encrypt and query calls take. Today `KeysetCipher` | +| Leaf | One sealed value inside a stored record or document: the unit the AEAD encrypts, with its own data key and AAD | +| Label | A named, typed fact added to a stored value's key tag after encryption, such as `row_id` or `written_by`. ZeroKMS verifies it and logs it. It restricts no reader. See [Labels](#labels) | +| Key header | The Base64 field `h` of an EQL payload: the header version, the keyset ID, the IV, and the key tag, as the v4 JSON document stores them today. `label_tag` rewrites it. A bare `Ciphertext` keeps the same facts inside its envelope | +| Key request item | One part of the stored context as a key request sends it to ZeroKMS beside the descriptor: a name and value, or a claim. The ZeroKMS protocol calls the list `context` | +| Name scope | A declared scope that names the record or a field. A field's name scope is its last declared scope, pinned when the Rust field is renamed (ADR-0006). Two fields of one record never share one | +| n-gram | A run of `n` characters of a token, such as the trigrams of a word. The match index stores a Bloom filter of n-grams | +| Opaque blob | A whole value, such as a struct, encoded and sealed as one ciphertext. Nothing inside it can be searched | +| PAE | Pre-authentication encoding: a length-prefixed encoding of several values, so that two values cannot run into each other. The leaf AAD and a label use it | +| Passthrough field | A field stored unencrypted next to the encrypted fields. It is not authenticated | +| Plan | The dynamic interface's declaration of a record, as data: each field, its context, and its indexes. A binding sends one, and the engine reads it at run time. No Rust program builds one by hand, and the derive does not emit one. See [A value under a plan: `Planned`](#a-value-under-a-plan-planned) | +| Planned | A value paired with a plan that is data, `Planned::new(&plan, value)`, with the context parts a call supplies. It is a target, so the owned entry points encrypt, query, and decrypt it, with the keyset as the argument. Its serialisation is what a binding sends for an operation. See [A value under a plan: `Planned`](#a-value-under-a-plan-planned) | +| Query artifact, context artifact | Two design documents Dan wrote as Claude artifacts, one on queries and one on context. This plan compared them with itself on 8 November 2026 and records every decision. Dan deletes the artifacts after this plan merges | +| Query context | All the scopes of a context, declared and caller-supplied. Search terms derive under it. See [Query context and stored context](#query-context-and-stored-context) | +| Query plan | A record plan narrowed to one field and one operator, `plan.query(field, op)`. A query value is encrypted under it. See [A query plan](#a-query-plan) | +| QueryTerm | The result of a query on the dynamic path: the operand bytes and the EQL type they bind as, known at run time | +| Serialised `Planned` | A `Planned` as a binding sends it: the plan, the caller's context parts, and the value. A transport form, never stored. For a check, a binding sends a serialised `Plan` alone. See [A value under a plan: `Planned`](#a-value-under-a-plan-planned) | +| Scope | A part of the context that narrows the data and the queries over it. The declaration supplies the first scopes, such as `users` and `email`; the caller adds more, such as a tenant ID, with `Scope::new(..)` | +| Search term | A value stored next to a ciphertext, so that a query can find it without decrypting it. Equality, order, and match each use their own term | +| Stage | One step of an analyzer that maps, drops, or expands tokens, such as `Downcase`, `Stop`, `Stem`, or `Ngrams`. A serialised plan may name only the closed set of stages | +| Stored context | Every part of a value's context. The data key and the AAD derive under it | +| Stored format | Everything Stack Encrypt writes to the database. See [The stored format stays compatible with Go rc.3](#the-stored-format-stays-compatible-with-go-rc3) | +| Target | The encrypted type that a value is stored as, such as `Ciphertext`, an EQL type like `TextEq`, or a record type | +| Vitamin C | CipherStash's Rust cryptography library, the `vitaminc-*` crates. It seals and opens leaves and derives the AAD; Stack Encrypt plans, batches, and stores | + +## Target state + +This section shows what a developer writes when every item in this plan is +built. A comment marks each piece of code that does not compile on `next` +today. [Remaining work](#remaining-work) says what each of those needs. + +### Rust with static types + +These examples use the `stack-encrypt` crate directly, with a Rust type for +each encrypted value. + +#### Connect and choose a keyset + +A client reads its credentials from the environment, or from the profile +that `npx stash auth login` writes. Every encryption uses one keyset. A +program can use the client's default keyset, or select another by name or +ID. + +The connection is a `Cipher`. A keyset resolved on it is a `Keyset`, +and every encrypt and query call takes a `&Keyset`. Decrypt takes a +`&Cipher` or a `&Keyset`, because a stored value names its own keyset. + +```rust +use stack_encrypt::{kms::IdentifiedBy, Cipher, Keyset}; + +// Not on `next` yet: the names. Today `Cipher` is `StackCipher` and +// `Keyset` is `KeysetCipher`. +let cipher = Cipher::new().await?; +let keyset: Keyset = cipher.default_keyset(); +// Not on `next` yet: the `IdentifiedBy::name` and `IdentifiedBy::uuid` +// constructors. `name` checks the name, so it returns a `Result`. +let tenant = cipher.keyset(IdentifiedBy::name("acme")?).await?; +let by_id = cipher.keyset(IdentifiedBy::uuid(keyset_id)).await?; +``` + +#### Encrypt and decrypt one value + +`encrypt` returns one `Ciphertext`. A context ties the ciphertext to where +it belongs, so it cannot be decrypted anywhere else. + +`encrypt` accepts an owned value or a borrowed one. It wipes an owned +value, such as a `String`. It only reads a borrowed value, such as a +`&str`, so the caller is responsible for wiping the original. + +```rust +use stack_encrypt::Ciphertext; + +// Not on `next` yet: borrowed values such as `&str`. +let secret: Ciphertext = keyset.encrypt("secret").await?; +let plaintext: String = keyset.decrypt(secret).await?; + +let number: String = read_card_number()?; +let card: Ciphertext = keyset .encrypt_with_context(number, "card-number") // wipes `number` + .await?; + +// Store the ciphertext as bytes, or as Base64 text through Serde. +let bytes: Vec = card.to_bytes(); +let card = Ciphertext::from_bytes(&bytes)?; +let number: String = keyset.decrypt_with_context(card, "card-number").await?; +``` + +A plain string is a context. `Scope::new("card-number")` would mean the +same thing. It is not needed here. The kind of a part matters only +where there are search terms. A `Ciphertext` has none. + +A value encrypted with no context is bound to nothing but its keyset. +Its ciphertext can be moved to any column or any row, and it still opens +there. Use the plain `encrypt` only for a value whose location does not +matter. `contexts()` shows such a value's context as empty. + +`encrypt` accepts only single values: text, numbers, booleans, dates, +times, and decimals. A struct or a `Vec` does not compile. Use a record, a +collection, or an opaque blob instead. + +#### Encrypt a record + +A record type says how each field of a plaintext struct is stored. The +derive seals each encrypted field under its own context, such as +`("users", "name")`. All the fields in a record share one batch of key +requests. + +```rust +use stack_encrypt::sem::EqualityTerm; +use stack_encrypt::target::{DecryptSource, EncryptTarget}; +use stack_encrypt::{Ciphertext, DecryptFrom, EncryptInto}; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct User { + id: u64, + name: String, + email: String, + created_at: i64, +} + +// A searchable email: its ciphertext and an equality term. +#[derive(EncryptTarget, DecryptSource)] +#[stash(plaintext = String)] +struct SearchableEmail { + ciphertext: Ciphertext, + equality: EqualityTerm, +} + +// Not on `next` yet: the record derive, `passthrough`, and `scope =`, +// which is `context =` today. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users")] +struct EncryptedUser { + #[stash(passthrough)] + id: u64, + name: Ciphertext, + email: SearchableEmail, + #[stash(passthrough)] + created_at: i64, +} + +let encrypted: EncryptedUser = user.encrypt_into(&keyset).await?; +let user = User::decrypt_from(encrypted, &keyset).await?; +``` + +`scope = "users"` is the record's name and its first scope. The derive +adds each field's name as the next scope, so `users` then `email` are the +declared scopes of the `email` field. `scope(..)` and `bind(..)` add the +parts that come from the caller or the row. The attribute, the data +plan's context, and Go's `scope=` tag use one word for it. +Decided by Dan on 8 November 2026. + +The derives need no Serde. A program that stores an encrypted value as +JSON adds `Serialize` and `Deserialize` to the encrypted type. That is +the same as for any other type. + +To tie every field to one row, the caller supplies the row ID as a part of +the context, and supplies it again to decrypt. The row ID is a binding +part. It is in the stored context, so the key and the AAD depend on it. It +is not in the query context, so a query still finds the row across the +column. + +[Query context and stored context](#query-context-and-stored-context) +gives the rule. The [context +scenarios](2026-10-24-stack-encrypt-context-examples.md) show how a +declaration marks a binding. The naming review confirmed the attribute +spelling `bind(..)` on 8 November 2026. + +```rust +// Not on `next` yet: `Bind`. Today the row ID is passed bare. +let encrypted: EncryptedUser = user + .encrypt_into_with_context(&keyset, Bind::new(user_id)) + .await?; +let user = User::decrypt_from_with_context(encrypted, &keyset, Bind::new(user_id)).await?; +``` + +#### Store a field as an EQL type + +A field can use an EQL type from the `eql-bindings` crate as its target. +The field is then stored as one EQL column, such as +`public.eql_v4_text_eq`. + +Go records already do this through the dynamic interface. A field there +names its EQL type, such as `"target": "TextEq"`, and the engine runs that +type for the field. The Rust record derive does the same (#1658). The +field's column is the record's scope and the field's name. + +```rust +use eql_bindings::v4::{integer::IntegerOrd, text::TextEq}; + +#[derive(Zeroize)] +struct Member { + id: u64, + email: String, + age: i32, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Member, scope = "members")] +struct EncryptedMember { + #[stash(passthrough)] + id: u64, + email: TextEq, + age: IntegerOrd, +} +``` + +#### Query a field + +A query encrypts the search value into the query type of the field. It uses +the same keyset and the same context as the stored value. Each EQL type has +a query type, such as `TextEqQuery` for `TextEq` and `IntegerOrdQuery` for +`IntegerOrd`. The query value binds to SQL as a parameter, and the SQL +operator chooses the comparison. + +```rust +use eql_bindings::v4::{integer::IntegerOrdQuery, text::TextEqQuery}; +use eql_bindings::Identifier; + +let email = Identifier::for_column("members", "email")?; +let age = Identifier::for_column("members", "age")?; + +// Not on `next` yet: a borrowed value, and a context built with +// `Scope::new`. Today this needs an owned value and an owned context: +// `"alice@example.com".to_owned().encrypt_into_with_context(&keyset, email.clone())`. +let by_email: TextEqQuery = "alice@example.com" + .encrypt_into_with_context(&keyset, Scope::new(&email)) + .await?; +let older: IntegerOrdQuery = 30_i32 + .encrypt_into_with_context(&keyset, Scope::new(&age)) + .await?; +``` + +```sql +SELECT id, email, age FROM members WHERE email = $1::eql_v4.query_text_eq; +SELECT id, email, age FROM members WHERE age > $1::eql_v4.query_integer_ord; +``` + +The context `Identifier::for_column("members", "email")` is the same as the +context that the record derive gives the `email` field of +`EncryptedMember`. So the query matches the stored values. A field of a +record is queried through its field reference instead, so that the operator is +checked at compile time. See [Query a record field](#query-a-record-field). + +A match query works in the same way, on a field with a match index. Its +answer can include rows that do not match. So the caller decrypts the rows, +and checks each one. + +#### Query a record field + +The derive emits one field reference for each field of a record, such as +`EncryptedMember::EMAIL`. A field reference names the field, the context the +derive sealed it under (the record's scope, then the field's identity), +and the field's target type, whose `Answers` impls are the field's index +list. It is the value a query starts from. The derive emits no plan: the +field reference is enough for a query, and a binding sends a plan of its own. +Built on 10 November 2026 (pull request #1595): the field reference has no +plaintext type and no accessor, because the derive sees the record's +field types and not the plaintext struct's, and a query value converts +from the borrowed form a caller has (`&str` to `String`) through +`ToOwned`. So an equality field reference takes a value of any type its index +accepts, unless the field states its query type with +`#[stash(query = String)]`. A field whose type is several indexes, a +nullable field, and a record field (through `.field(..)`) have operator +methods too (#1596). + +A typed query starts from the field reference, and has one method for each +operator the field's indexes answer. A missing operator is a compile +error: "no method named `gt`", with a message that names the field's +indexes. A record that lists a caller scope gives its field references the +scope's type, and the query has no `encrypt` until `.scope(..)` is given +once, with a value of that type; a record with no caller scope gives a +query that is ready at once. A binding cannot be given, because the +query type has no `bind` method, so a query accepts its scope only, by +type. The query ends with `encrypt(&keyset)`, and its output type is the +EQL query type the field reference fixes. Decided on 7 November 2026. + +```rust +// On `next` since pull request #1595, with the index's query term as +// the output type (`EqualityTerm`, `RangeQuery>`, +// `MatchQuery`); the EQL query types follow with the EQL owned +// implementations. A value is passed by value; a string literal as it is. +let by_email: TextEqQuery = EncryptedMember::EMAIL + .eq("alice@example.com") + .scope(tenant) + .encrypt(&keyset) + .await?; +let adults: IntegerOrdQuery = EncryptedMember::AGE + .between(18, 65) + .scope(tenant) + .encrypt(&keyset) + .await?; + +// error: `TextEq` has no order index, so the field reference has no `gt` +EncryptedMember::EMAIL.gt("alice@example.com") +// error: the query builder has no `bind` +EncryptedMember::EMAIL.eq("alice@example.com").bind(row_id) +``` + +```sql +SELECT id, email, age FROM members WHERE email = $1::eql_v4.query_text_eq; +``` + +A chained scope is allowed on a query because a query has one field and +one value, so a scope cannot mean anything else. The rule that no chain state offers context, in [One context argument, and paired entry points](#one-context-argument-and-paired-entry-points), was about `.extend(..)` after `.fields()` on a record. There, a part added late looked per-field +and was not. + +A typed query lowers from its field reference to the term combinator, under the +field reference's context. A dynamic query lowers a [query plan](#a-query-plan) +to the same combinator through `Planned`. The equivalence suite checks +that the two agree (ADR-0007, amended 9 November 2026). + +#### Encrypt a JSON document + +A JSON field is stored as one encrypted document in a +`public.eql_v4_json_search` column. That column type, the Rust type +`JsonTreeDocument`, and the dynamic target `JsonSearch` are three names +for the one stored type. + +The simplest form encrypts straight into `JsonTreeDocument`, with the +default options. The context is the column. The default options order no +paths. They also store the whole document in its root entry, so it +decrypts in one step. + +```rust +use eql_bindings::{v4::json_tree::JsonTreeDocument, Identifier}; +use serde_json::json; +use stack_encrypt::json::JsonPlaintext; + +let column = Identifier::for_column("customers", "profile")?; + +// Not on `next` yet: a context built with `Scope::new`. Today this +// passes the column itself: `.encrypt_into_with_context(&keyset, column.clone())`. +let profile: JsonPlaintext = json!({ "name": "Ada", "age": 35 }).into(); +let encrypted: JsonTreeDocument = profile + .encrypt_into_with_context(&keyset, Scope::new(&column)) + .await?; + +// On decrypt the column is checked against the one stored in the document. +let opened = JsonPlaintext::decrypt_from_with_context(encrypted, &keyset, Scope::new(&column)).await?; +let name = &opened.value()["name"]; // `opened` wipes the document when it is dropped +``` + +`JsonPlaintext` contains a `serde_json::Value`. It wipes the value when it +is dropped. It converts from a `serde_json::Value`, or parses JSON text with +the strict checks on JSON input. A program can also encrypt a borrowed +`&serde_json::Value`. Then the program is responsible for wiping it, as for +any [borrowed value](#encrypt-borrowed-values). + +With the default options, no path has an ordering term. So a query cannot +compare the order of the values at a path. To order some paths, a record +field names them with `#[stash(json(..))]`, as Go's struct tag does +(`encrypt_into=JsonSearch(ordered=$.age)`). Decided by Dan on 16 November +2026, in place of a named type with options in a `target(..)` attribute: + +```rust +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32, "$.visits[*].at": u64, "$.visits[*].place": String }))] + profile: JsonTreeDocument, +} + +let customer = Customer { profile: JsonPlaintext::parse(r#"{"name":"Ada","age":35}"#)? }; +let encrypted: EncryptedCustomer = customer.encrypt_into(&keyset).await?; +let opened = Customer::decrypt_from(encrypted, &keyset).await?; +``` + +The field is sealed under the options, and its field queries under them. +`ordered` maps each ordered path to the type of the values at it. +`sealed_root = false` in the same list turns off the sealed root. + +#### Query a JSON document + +A JSON query is a query on the document's field reference. The field reference has +one method for each kind of query. A scalar field's reference has one method +for each operator in the same way (see [Query a record +field](#query-a-record-field)). A query needs two things from the field's +declaration: + +- **The column context.** Each path's selector is derived under it, so the + query must use the same context as the stored documents. +- **The options.** They say which paths have ordering terms, and how far a + wildcard such as `[*]` expands. An order query on a path without order + terms would find no rows, so Stack Encrypt refuses it. + +The field reference carries both, so the query names only its kind and its +values. The output type is the EQL query type, fixed by the field reference. +Decided on 7 November 2026. Built in #1459; this example runs as +`packages/eql/tests/encryption/tests/json_tree_field_references.rs`. + +```rust +use eql_bindings::v4::json_tree::{JsonTreeElementsQuery, JsonTreeLeafQuery, JsonTreeQuery}; + +let ada: JsonTreeQuery = EncryptedCustomer::PROFILE + .contains(json!({ "name": "Ada" })) + .encrypt(&keyset) + .await?; +let older: JsonTreeLeafQuery = EncryptedCustomer::PROFILE + .at() + .age() + .gt(30) + .encrypt(&keyset) + .await?; +let (low, high): (JsonTreeLeafQuery, JsonTreeLeafQuery) = EncryptedCustomer::PROFILE + .at() + .age() + .between(18, 65) + .encrypt(&keyset) + .await?; +let home: JsonTreeElementsQuery = EncryptedCustomer::PROFILE + .elements() + .visits() + .place().eq("home") + .and().at().gt(15) + .encrypt(&keyset) + .await?; +``` + +```sql +SELECT id FROM customers WHERE profile @> $1::eql_v4.query_json; + +-- $1 is the selector of `$.age`. $2 and $3 are the bounds. +SELECT id FROM customers +WHERE (profile -> $1::text) >= $2::eql_v4.query_json_leaf + AND (profile -> $1::text) <= $3::eql_v4.query_json_leaf +ORDER BY eql_v4.ord_term(profile -> $1::text); + +SELECT id FROM customers +WHERE eql_v4.json_tree_element_match(profile, $1::eql_v4.query_json_elements); +``` + +The kinds of JSON query, the field reference method for each, and what each finds: + +| Query | Field reference method | What it finds | EQL query type | +| --- | --- | --- | --- | +| Containment | `contains(doc)`, `contained_by(doc)`, and `at().age().eq(v)` | Rows whose document contains the given document, or is contained by it. Equality of a scalar at a path is containment of a one-entry document, so a path's `eq(v)` lowers to it | `JsonTreeQuery` | +| Comparison at a path | `at().age().gt(v)`, `.lt(v)`, `.between(a, b)`, and the rest | Rows where the value at an ordered path orders against, or lies between, the given values | `JsonTreeLeafQuery`; two for `between`, low then high | +| A path's selector | `at().age().selector()` | The selector `->` and `ORDER BY eql_v4.ord_term(col -> $1)` take | `JsonTreeSelector` | +| Element match | `elements().visits().place().eq(v).and().at().gt(v)` | Rows where one element of an array meets several conditions together | `JsonTreeElementsQuery` | +| Jsonpath predicate | `predicate!(FIELD, "text", name = v, ..)`, checked when the program compiles, and `predicate(text)`, with `.var(name, v)` for each variable, for text built at run time | Rows where a SQL/JSON path predicate is true | `JsonTreePredicateQuery` | +| Children and child count | `children(path)` | The entries directly below one node, or how many there are | `JsonTreeToken` | + +Paths are typed, from the attribute. Decided by Dan on 21 November 2026: + +- `ordered = { "$.age": u32, .. }` names each ordered path and the type of + the values at it. The derive parses every path at compile time with the + engine's grammar, from the `stack-encrypt-jsonpath` crate that + `stack-encrypt` and its derive share. A path that does not parse, names + an array position, or is given twice does not compile. +- `paths = { "$.name": String, .. }` names a path compared with equality + alone, and its type: a number, a string or a boolean. It adds nothing to + the field's options, so the field stores no ordering term for it, and + an ordering of it does not compile. A path given under both keys does + not compile. Decided by Dan on 22 November 2026. +- The derive gives each path a method under `at()`, and each array whose + elements have an ordered member a method under `elements()`, whose + methods are the members. The names come from the path's keys + (`$.visits[*].at` is `at().visits_at()`), and `names = { "key": word }` + names a key that gives no Rust name. Each method takes the path's + type. So a path or a member the field does not declare, a value of + another type, a member of another array, and an element match on a path + that is not an array do not compile. These are the Go SDK's generated + `At`, `Elements` and `Paths`. +- A filter a program builds at run time names its paths as text: + `at_text_path(path)` and `elements_text_path(path)`, whose members are + text. A text path is checked when the query is encrypted, before any key + is fetched, and derives the operand the typed method derives for the same + path and value. A field that declares no paths has only these. +- A predicate's variables are given one at a time: `.var(name, v)`, with + `v` a scalar, and `.var_null(name)`. A repeated name, a NaN and an + infinity are refused before any key is fetched. The text of + `predicate(text)` is checked when the query is encrypted. +- `predicate!(FIELD, "text", name = v, ..)` checks a predicate written in + the program when the program compiles: that the text parses, that the + index can answer it, that each variable is given once and used, that the + field declares each path and member, and that each value, a variable's or + a literal's, is of the path's type. It sends the same text, so its + operand is the one `predicate(text)` derives. + +Two limits of the SQL stay, from the reference page's sections on +comparing a value at a path and on what the SQL cannot do. Sorting rows by a path through an array +needs a rule the application chooses, such as `MIN` or `MAX` over the +matches. The supported way to the plaintext of every match at such a +path is a subtree read with a wildcard bound. The [EQL v4 reference +page](../../packages/eql/docs/reference/json-tree.md) gives the SQL for +each query. A scope chains on a JSON +query as on a scalar one: `.contains(doc).scope(tenant)`. + +The field reference methods build the same inputs the dynamic interface reads a +binding's frames into (`json::inputs`, compiled without the `dynamic` +feature), so the typed form and the dynamic form share one set of input +rules and derive the same operands. The operand types `Contains`, `AtPath`, +`ElementMatch`, `Predicate`, and `Children` that the plan proposed earlier +were retired as operands a caller builds, on 7 November 2026: a caller +writes the methods above. The query a method returns, +`field_reference::json::JsonFieldQuery`, names its kind as a type with no +values, `Op`: `op::Contains`, `op::ContainedBy`, or `op::AtPath` of a +comparison, which the dynamic `Op` enum is generated from, and, for the +kinds that have no operator type, `field_reference::json::Selector`, +`ElementMatch`, `Predicate` and `Children`. That kind decides what +`encrypt` returns. Recorded on 16 November 2026, in #1459's pull +request. + +A document encrypted straight into `JsonTreeDocument`, with no record, +has no field reference. It is queried through a [query plan](#a-query-plan), as any +value under a plan that is data. + +#### Encrypt a whole value as one ciphertext + +`OpaqueBlob` encodes any Serde value and seals it as one ciphertext. Go +writes the same format for its opaque structs. So each language can read +the blobs that the other one writes. + +```rust +use stack_encrypt::blob::OpaqueBlob; + +// Not on `next` yet: `OpaqueBlob`. +let sealed = keyset + .encrypt_with_context(OpaqueBlob::new(settings), ("users", "settings")) + .await?; +let settings: OpaqueBlob = keyset + .decrypt_with_context(sealed, ("users", "settings")) + .await?; +``` + +#### Encrypt a collection + +A `Vec` of values encrypts into a `Vec` of targets, with one batch of key +requests for the whole collection. Each element has its own data key, so +each one decrypts on its own. The order and the length of the `Vec` are +not authenticated, because a database can return rows in any order. + +```rust +let column: Vec = vec![1_i32, 3, 5].encrypt_into(&keyset).await?; +let values = Vec::::decrypt_from(column, &keyset).await?; + +let rows: Vec = users.encrypt_into(&keyset).await?; +``` + +That is the default, because it is the common case. A caller who needs +the order and the length authenticated asks for it by type. This is the +same way that `OpaqueBlob` changes how a value is sealed. The wrapper seals each +element under its position and the length of the `Vec`, as part of the +context. An element that is swapped, dropped, or added then fails to open. + +```rust +use stack_encrypt::Positioned; + +// Not on `next` yet: `Positioned`. The name is a proposal. +let steps: Positioned> = Positioned(vec![1_i32, 3, 5]) + .encrypt_into(&keyset) + .await?; +let values = Positioned::>::decrypt_from(steps, &keyset).await?; +``` + +`Positioned` is a new stored form, so it does not change the data that +Go rc.3 writes. ADR-0010 records that stricter authentication of a +container is opt-in, by type. + +#### Encrypt a byte string + +A `Vec` is the exception to the collection rule. It encrypts as one +value, into one `Ciphertext`, because a byte string is almost always one +thing: a file, a key, or an image. A fixed-size array `[u8; N]` is a byte +string too. `u8` on its own is not a value that encrypts, so a `Vec` +cannot encrypt byte by byte. + +A Go `[]byte` field takes the same path. The Go SDK sends the bytes to +the engine as one bytes value. The engine seals them with the same +Vitamin C code that seals a Rust `Vec`. The dynamic interface and the +Rust API share one engine, so they write the same bytes for the same +declaration (ADR-0007). + +The byte string is not a special case of either language. It is a rule of +the engine. + +A `Vec` of byte strings follows the collection rule. It encrypts into a +`Vec`, one for each byte string, with no wrapper type. The +byte-string rule was decided on 7 November 2026 by Dan. It is what pull +request #1501 built. + +```rust +let file: Ciphertext = std::fs::read("photo.jpg")?.encrypt_into(&keyset).await?; +let photo = Vec::::decrypt_from(file, &keyset).await?; + +let key: Ciphertext = [7u8; 16].encrypt_into(&keyset).await?; + +let files: Vec = vec![vec![1u8, 2, 3], vec![], vec![9]] + .encrypt_into(&keyset) + .await?; +let opened = Vec::>::decrypt_from(files, &keyset).await?; +``` + +To encrypt each byte of a `Vec` as its own ciphertext, name a type +for one byte. A `Vec` of that type is an ordinary collection, so it +encrypts into one `Ciphertext` for each element. The named type is a +single value because its borrow implements Vitamin C's `Scalar`. That is +the same rule every built-in single value follows. + +```rust +use stack_encrypt::Scalar; +use zeroize::Zeroize; + +/// One byte, sealed on its own. +// Not on `next` yet: `#[derive(Scalar)]`. Today `Byte` needs `Encrypt` +// and `Scalar` on `&Byte`, and `FromScalar` on `Byte`, by hand. +#[derive(Zeroize, Scalar)] +struct Byte(u8); + +let bytes: Vec = vec![0u8, 1, 255].into_iter().map(Byte).collect(); +let each: Vec = bytes.encrypt_into(&keyset).await?; +let opened = Vec::::decrypt_from(each, &keyset).await?; +``` + +`#[derive(Scalar)]` works on a struct with one field, whose type is a +built-in single value. The derive encrypts the struct as that field, and +decrypts the field back into the struct. So `Byte` is sealed exactly as +the `u8` inside it would be, if `u8` were a single value on its own. + +### The dynamic interface + +The dynamic interface takes a declaration and values as data, not as Rust +types. A program uses it in two cases: + +- when it learns the declaration only at run time, such as a query that + chooses its operator and path from user input; +- when it is written in another language, such as Go. + +The engine turns a declaration into the same plan that the Rust derive +builds. So the dynamic interface writes the same bytes as the static API +for the same declaration. + +#### A declaration as data + +A declaration names each field and its context. It also says how the field +is stored: as a passthrough field, with the indexes it lists, or as an EQL +type. + +```json +{ + "id": { "context": ["users", "id"], "outputs": ["passthrough"], "type": "int64" }, + "email": { "context": ["users", "email"], "target": "TextEq" }, + "age": { "context": ["users", "age"], "outputs": ["c", "eq", "ore"], "type": "int32" }, + "profile": { "context": ["users", "profile"], + "target": { "name": "JsonSearch", + "options": { "sealed_root": true, "ordered": ["$.age"] } } } +} +``` + +Each row crosses the boundary as one transport frame. A query names a +field and an operator, such as `eq` or `contains`, and gives a value. In +the target state that is a [query plan](#a-query-plan) and a +[serialised `Planned`](#a-value-under-a-plan-planned). The engine returns the query value, with +its EQL type. + +The output keys and the type names are part of the stored format, so they +cannot change. The output keys are `c`, `eq`, `match`, `ore`, `ope`, and +`passthrough`. The type names include `int64` and `string`. + +#### A value under a plan: `Planned` + +Anything encrypted under a plan that is data is a `Planned` value. That +is a record under a record plan, or a query value under a [query +plan](#a-query-plan). + +`Planned` is a plain struct, like `OpaqueBlob` and `Positioned`. It adds +no method to any other type. Decided on 7 November 2026. + +`Planned` is a target in the owned API's sense. The stored row type +implements `EncryptTarget>`, and `Planned` +implements `DecryptSource`. Both compose the combinators from the plan +when they run. So `encrypt_into` and `decrypt_from` run it, with the +keyset as the argument. Made a target after the combinator spike of +9 November 2026 (ADR-0007, amended). + +```rust +// On `next` since pull request #1595. The value under a data plan is +// the dynamic interface's value, a `ValueFrame` of the record's fields, +// and the stored row is a `StackCipherText`. A typed struct uses the +// derive, not a plan. +let row: StackCipherText = Planned::new(&plan, values).encrypt_into(&keyset).await?; +let values = ValueFrame::decrypt_from(Planned::new(&plan, row), &keyset).await?; + +let row: StackCipherText = Planned::new(&plan, values) + .encrypt_into_with_context(&keyset, Scope::new(tenant).bind(row_id)) + .await?; +``` + +A serialised `Planned` is what a binding sends for an operation. A +serialised `Plan` alone is what it sends for a check, an operator list, +or a query plan. There is no separate request type. A `Planned` has +three parts: + +- the plan, by reference to one the engine holds, or inline; +- the caller's context parts, in declared order, with their types; +- the value. + +The keyset stays outside, as the receiver, so a `Planned` never names a +key. + +```json +{ + "plan": "e3b0c442…", + "context": { "scope": [42], "bind": ["7f3c2a9e-…"] }, + "value": { "email": "alice@example.com", "age": 35 } +} +``` + +The engine answers with the stored row, the query term, or the plaintext. +The same shape is a conformance case, with the engine's expected answer +beside it. `contexts()` works on a `Plan` before any value exists, with +a placeholder for each part the caller supplies. `context()` on a +prepared call, a `Planned` with its context parts attached, shows the +exact context that call will use. See [Show the +context](#show-the-context). + +A serialised `Planned` is a transport form, never a storage form. The +value in it is plaintext. So it lives only in a wiped buffer, as the +engine already reads it (`ProtectedRef<[u8]>`), and is never logged or +written to disk. A binding that keeps one, for a retry say, keeps it +wiped. + +The serialised `Planned`'s shape is not part of the stored format. It can change +with the dynamic grammar, and a change to it moves no stored byte. + +Beside `Planned`, `stack_encrypt::dynamic::record` has the functions that +take a declaration as a frame: `plan_with`, `encrypt_with`, `query`, and +`decrypt_with`. `encrypt_with` and `decrypt_with` build a `Planned` and run +it. Each takes a `TargetResolver`. The resolver runs the EQL type that a +field names. + +`eql-bindings` provides the resolver: `eql_bindings::encryption::EqlTargets`. +See [A ready-made EQL resolver](#a-ready-made-eql-resolver). + +#### A query plan + +A query plan is derived from a record plan. It names one field and one +operator, and so the index and the options the query runs under. It is refused where it is made if the field has no index for the +operator. + +The record plan does not change. A field's indexes stay the only thing +it declares about queries, so no declaration lists the queries a program +might run. + +```rust +// On `next` since pull request #1595. A query value is a `ValueFrame`. +let by_email = plan.query("email", Op::Eq)?; // refused here if no index answers Eq + +let q: QueryTerm = Planned::new(&by_email, ValueFrame::of("alice@example.com")?) + .encrypt_into_with_context(&keyset, Scope::new(tenant)) + .await?; +``` + +A query plan can be serialised beside its record plan, as +`{"field": "email", "op": "eq"}`. The bytes a query sends to the engine do +not change: the engine already receives the plan, the field, the +operator, and the value. They are grouped differently. + +The result on the dynamic path is a `QueryTerm`: the operand bytes, and +the EQL type they bind as, known at run time. A typed query returns the +EQL query type instead, because its field reference fixes it. + +A typed query from a field reference lowers to the term combinator +directly, with no plan. The dynamic form lowers its query plan to the +same combinator through `Planned`. [Query a record +field](#query-a-record-field) shows the typed form. + +#### The dynamic field handle + +A program whose plan is data uses the same builder through a field +handle. The handle has one method per scalar operator, and `op(..)` for +any operator, the JSON ones included. Each one is checked at run time +against the plan, and returns `operator_not_answered` when no index +answers it. A field that names an EQL type takes its resolver at the +handle, `plan.field_with(name, &resolver)`. The handle has no `bind` +method either. + +```rust +// On `next` since pull request #1595. A query value is a `ValueFrame`. +let email = plan.field("email")?; +let q: QueryTerm = email + .eq(ValueFrame::of("alice@example.com")?)? // refused here if no index answers Eq + .scope(tenant) + .encrypt(&keyset) + .await?; +``` + +Rust is the superset. The serialised plan is checked at run time, and a +language generates its own type-checked builder over it where it can. Go +has that today: `stashgen` generates one method per field for each +operator the field's indexes answer, and asks the engine which operators +those are. + +A TypeScript binding could get a generated `.d.ts`, and a Python +binding generated `.pyi` stubs. Then an editor and a type checker show +only the operators each field supports. A binding through NAPI or +PyO3 exposes the dynamic path method for method: + +```ts +const q = await plan.field("email").eq("alice@example.com").scope(tenant).encrypt(keyset); +q.sqlType; // "eql_v4.query_text_eq", from the plan, at run time +``` + +#### Call it from Go + +A Go program declares its records with struct tags. The `stashgen` +generator reads the tags, and writes the encrypted type, its functions, and +the declaration it sends to the engine. The examples show how a customer +uses the Go SDK today, on Go `v0.1.0-rc.3`. + +The `scope=` tag gives the record's name, its first scope. The tag on each field says +how the field is stored: as a passthrough field, as an EQL type, or with +the indexes it names. + +```go +//go:generate go tool stashgen -type User +type User struct { + _ struct{} `stash:"scope=users"` + ID int64 `stash:"id,passthrough"` + Email string `stash:"email,encrypt_into=TextEq"` + Name string `stash:"name,encrypt_into=TextMatch"` + Age int32 `stash:"age,encrypt_into=Integer"` +} + +//go:generate go tool stashgen -type Customer +type Customer struct { + _ struct{} `stash:"scope=customers"` + ID int64 `stash:"id,passthrough"` + Profile Profile `stash:"profile,encrypt_into=JsonSearch(ordered=$.age;$.visits[*].at)"` +} + +//go:generate go tool stashgen -type Settings +type Settings struct { + _ struct{} `stash:"scope=settings,opaque"` // sealed as one blob + Theme string `json:"theme"` +} +``` + +As in Rust, a `Cipher` is the connection. A `Keyset` is the cipher bound +to one keyset. The naming review of 8 November 2026 chose one vocabulary +for both languages; on rc.3 the two are `Client` and `Cipher`. + +`Scope` adds a scope to the context of every field, such as a +tenant ID. `Bind` adds a binding, such +as a row ID. The generated `Encrypt` and +`Decrypt` functions take a slice. They send one ZeroKMS request for each +500 values. + +```go +cipher, err := encrypt.NewCipher(ctx) +defer cipher.Close() +// Not on rc.3 yet: `Scope`, `Bind`, and the names. On rc.3 the +// connection is `Client` and the keyset-bound handle is `Cipher`. +// Today `Scope` is `Extend`. +keyset := cipher.DefaultKeyset().Scope("tenant-42") + +encrypted, err := Encrypt(ctx, keyset, people) // []EncryptedUser +opened, err := Decrypt(ctx, keyset, encrypted) // []User + +term, err := Fields.Email.Eq(ctx, keyset, "bob@example.com") +// SELECT id, email, name, age FROM users WHERE email = $1::eql_v4.query_text_eq + +needle, err := Fields.Profile.Contains(ctx, keyset, map[string]any{"name": "Ada"}) +older, err := Fields.Profile.At.Age.Gt(ctx, keyset, 30) +visit, err := Fields.Profile.Elements.Visits.Match(ctx, keyset, encrypt.JSONReadOptions{}, + encrypt.AtPath(Paths.Profile.Visits.Place).Eq("home"), + encrypt.AtPath(Paths.Profile.Visits.At).Gt(15), +) +``` + +A field has a query method only for the operators it supports, so an +unsupported query does not compile. The generator asks the engine which +operators each field supports. It does not keep its own copy of the +rules. These generated methods are Go's typed form over the dynamic plan. The +engine checks the plan at run time, and the Go compiler checks the +operators. + +Code that `stashgen` wrote for rc.3 compiles and runs against the next +module without being generated again, with one exception. The generated file names the keyset-bound handle's type. So the handle +rename from the naming review needs one regeneration. The program +renames its own call sites with it. + +The generated file builds its +declaration through `gensupport` calls, and the module builds the frames +it sends to the engine. So a change to the serialised `Planned`'s shape is a change inside the +module. A program generates again only to adopt a new +declaration, such as a scope or binding on a field, or a new generated +method. The generator keeps its output identical for unchanged input. So +an upgrade alone does not change a committed `*_stash.go` file. + +A regeneration picks up two changes to the generated code. The handle +rename is the one a program needs. The other is the new `Children`. The +new `Children` returns `encrypt.JSONChildren`, and that type opens each +child. + +A file generated before this change still compiles and runs. That file's +`Children` returns the token alone. + +One part of the target state is not in Go yet: + +- A Go program cannot set match options. + +[Remaining work](#remaining-work) lists it. + +### Rules in the target state + +#### The stored format stays compatible with Go rc.3 + +Decided on 7 November 2026 by Dan: "The stored data must not break as of +now. The Go customer has already started implementation with rc.3. We can +make breaking changes to the code/API but not the stored format." + +The Go customer already uses Go `v0.1.0-rc.3`. So the data that rc.3 +writes must stay readable and searchable. The stored format is everything +that Stack Encrypt writes to the database: + +- ciphertexts, with their envelopes and headers; +- search terms; +- the entries of JSON documents; +- the declaration names that a stored row depends on. + +The baseline is the tag `languages/golang/v0.1.0-rc.3`, at commit +`114e08448`. It includes the `eql-v4-install.sql` bundle attached to that +release. + +The code and the APIs can still change in ways that break callers. A change +to the stored format must keep rc.3 data readable and searchable, or add a +new format version beside it. See [Changes that would alter the stored +format](#changes-that-would-alter-the-stored-format). + +#### Context and AAD + +The context is the data that a ciphertext is tied to, such as a column +name or a row ID. The field's declaration supplies part of the context, +such as `users/age`. The caller can supply the rest, such as a row ID. + +Stack Encrypt uses the context in three ways: + +1. **To derive the data key.** Stack Encrypt sends the context to ZeroKMS + with each key request. Today the whole context is rendered into a text + descriptor, such as `users/age`. Under the planned envelope version 2, the name scopes are the + descriptor. Each part is a key request item. ZeroKMS needs the same request to derive the key again. +2. **To build the AAD of each ciphertext.** The AAD is data that + encryption checks without encrypting it. Stack Encrypt builds it from + the context and the place of the value in its record. The AAD also + includes the format version, the keyset ID, and the key tag. +3. **To derive the search terms** for the field. + +A different context gives a different key and a different AAD, so +decryption fails. + +A parameter that takes the caller's context is named `context`. The name +`aad` is used only for a value that is an AAD. Some public methods do not +follow this rule yet. See [Name context parameters +`context`](#name-context-parameters-context). + +Sources: the module documentation of `packages/stack-encrypt/src/cipher.rs` +describes the descriptor and the AAD. The module documentation of +`packages/stack-encrypt/src/target/context.rs` describes the search terms. + +#### Query context and stored context + +Decided on 7 November 2026. Every part of a context is a scope or a +binding. The declaration supplies the first scopes: the record name, then +the field's name scope. The caller supplies the rest. + +- **The query context** is all the scopes: the declared ones, then the + caller's. Search terms derive under it. A query supplies the caller's + scopes, and matches every row stored under the same query context. +- **The stored context** is the query context followed by the bindings. + The data key and the AAD derive under it. + +The kind of a part is not in the derivation. Two contexts with the same +parts in the same order give the same key, the same AAD, and the same +descriptor, whatever their kinds. The kind decides only which parts are +in the query context. rc.3 data has no kinds. This rule is what keeps it +deriving the same way. Decided by Dan on 8 November 2026. + +A field's **name scope** is its last declared scope: the field's name by +default. It can be pinned when the Rust field is renamed, so that +stored data keeps opening. + +The name scope is always the last declared scope, so two fields of one +record never share a context. If they did, they would share a key and an +AAD, and a ciphertext copied between the two columns would open. ADR-0006 +records this. + +A part of the context is one of two kinds. The declaration says which, +and fixes the order: the scopes first, then the bindings. + +| Kind of part | Verb | Example | In the query context | Sent to ZeroKMS | In the AAD | Verified by | +| --- | --- | --- | --- | --- | --- | --- | +| Scope | `scope` | A record name, a field's name scope, or a tenant ID | Yes | Yes | Yes | ZeroKMS and the AEAD | +| Binding | `bind` | A row's UUID | No | Yes | Yes | ZeroKMS and the AEAD | + +The words were decided on 7 November 2026. A caller scopes a value with a +scope. A scope narrows the data and the queries over it. A caller binds a +value with a binding. A binding ties the ciphertext to its row and leaves +the queries as they are. + +"Extend" and "extension" are no longer used. Go `Extend` becomes `Scope`, with +`Extend` kept as a deprecated alias until Go 0.1.0. `Bind` is added to +Go. + +A part is a scope unless the declaration marks it as a binding, because +that is what Go rc.3 writes. A binding can be stored in the row as a context field, +so the reader takes it from the row. + +Every scope and binding is sent to ZeroKMS, so each part leaves the +customer's system, and ZeroKMS logs it at every key retrieval. Today the parts travel in the descriptor. The descriptor has a length +limit. Under envelope +version 2 they travel as [key request +items](#context-parts-as-key-request-items), with no limit. ZeroKMS +version 2 is planned to encrypt the access log. + +A [label](2026-11-08-stack-encrypt-key-policy.md#labels) is not a part +of the context. ZeroKMS verifies it. It is in neither the query context +nor the AAD. + +The use case is access control: a value that must stay in its row. Each +value is bound to its row by a client-generated UUID, and a query by +column or by tenant still finds it. +The facts of a row's writing, such as the address it came from, are +labels, not bindings. + +#### A developer can see the context + +Decided on 7 November 2026. A wrong context is silent: a query matches +nothing, or a row opens somewhere it should not. So every declaration +and every call can show the context it uses, before any key is fetched. + +```rust +// Not on `next` yet: `contexts()` and `context()`. + +// For a declaration: each field, its query context, and its stored +// context, with a placeholder for every part the caller supplies. +println!("{}", EncryptedUser::contexts()); +// email +// query context: users / email / {tenant: u64} +// stored context: users / email / {tenant: u64} / {row: Uuid} +// search terms: under the query context + +// For a call: the exact context, with the caller's values filled in. +let call = EncryptedUser::EMAIL.eq("alice@example.com").scope(42_u64); +println!("{}", call.context()); +// query context: users / email / 42u64 +``` + +The output shows each part's type, because `7u64`, `7i64`, the text `7`, +and the bytes `37` are four different contexts. The descriptor that +ZeroKMS logs is coarser, so it is not enough on its own. A call's context +can include the caller's values, such as a tenant ID or an IP address. +The plan form shows placeholders instead, so it is the one to put in +logs. + +The same output serves a unit test. A testing feature of the crate gives assertions over it. A developer can +pin the context of a field or a call, and the build fails when it +changes. The Go module has the same +assertions, in a testing package. + +```rust +// Not on `next` yet: the `testing` feature and `assert_context!`. +#[cfg(test)] +mod tests { + use stack_encrypt::testing::assert_context; + + #[test] + fn email_is_scoped_to_the_tenant_and_bound_to_the_row() { + assert_context!( + EncryptedUser::EMAIL, + query = ["users", "email", scope::()], + stored = ["users", "email", scope::(), bind::()], + ); + } +} +``` + +#### Labels + +A label adds a named fact to the ZeroKMS key tag of a stored value, +after encryption. The row and the facts of its writing are then recorded on the value. +ZeroKMS can verify the record. + +Its context, its AAD, and its queries do not change. +ZeroKMS verifies the labels when it returns the key, and logs them. +That log is where access intelligence comes from. + +A label restricts no +reader. A bind does. [Binds, claims, and +labels](2026-11-08-stack-encrypt-key-policy.md) has the design and the +rules that keep the two apart. + +```rust +// Not on `next` yet: `label` and `labels`. +let sealed: TextEq = sealed + .label("written_from", request.ip())? + .label("created_at", now())?; +let body: String = String::decrypt_from(sealed, &keyset).await?; +``` + +```sql +-- In a trigger, once the primary key is known. +NEW.body := eql_v4.label_tag(NEW.body, 'row_id', NEW.id::text); +``` + +#### Other rules + +- **One context argument.** The caller's parts arrive in one chain, + `Scope::new(..)`, `Bind::new(..)`, or `Scope::new(..).bind(..)`, through + the `_with_context` entry point. No chain state offers context. The + entry points accept the chain through a trait bound, `impl ContextParts`. + +- **Rust and Go behave the same.** Every built-in capability has the same + meaning and the same stored bytes in Rust and in Go. The conformance + profiles test this. A custom Rust query stage can be Rust-only. It is + then marked as not portable. +- **Checks run before keys are used.** Every check that needs no key runs + before Stack Encrypt asks ZeroKMS for a key, or loads an index key. +- **Encryption wipes an owned plaintext.** `encrypt` and `encrypt_into` wipe an + owned plaintext, including when they fail. They only read a borrowed + plaintext, so the caller is responsible for wiping it. Stack Encrypt + wipes every copy it makes. A decrypted value is an ordinary owned value. + The caller is responsible for wiping it. +- **Context is passed by reference.** A method that takes a context + borrows it while the request runs. So a program can use one context for + a write, a query, and a read without cloning it. An owned context also + works. +- **Context is explicit.** A declaration lists the parts the caller must + supply, each with its kind and type. A part that is not declared is + refused. A declaration can mark a part as optional. That is the rare + case, because a query that omits an optional part matches nothing and + gives no error. Stack Encrypt does not use a type's `Default` + implementation to decide. Decided on 7 November 2026. +- **The dynamic grammar can declare required parts too,** with their kind + and type, so the Go generator can require them when it generates the + code. Its default stays "any part or none", because Go rc.3 callers use + that, and the stored bytes are the same either way. +- **`encrypt` or `encrypt_into`.** `encrypt_into` is for the case where + the caller names the output type. `encrypt` is for the case where a + field reference or a plan fixes it: a query from a field reference, or a `Planned` value. + `keyset.encrypt(value)` and `value.encrypt_into::` follow this rule + on `next` today. +- **Rust is the superset.** The plain serialised plan is checked at run + time by the engine. A language generates its own type-checked builder + over it where it can, as `stashgen` does for Go. A capability lands in + Rust first, and the dynamic grammar adopts it by an explicit change. +- **Each element of a collection stands alone.** Each element has its own + data key. Each element is authenticated on its own. +- **Match text is analysed by one pipeline.** A typed configuration can + use any stage, including a customer's own. A serialised plan can name + only the closed dynamic subset, and every reader runs exactly the + stages it names. +- **Ordering terms do not answer equality.** An order-revealing encryption + (ORE) term does not answer an equality query. A field that needs both + declares both indexes. + +## Remaining work + +Everything in this section is work to implement. Each item ends with the +issues and pull requests that track it, checked on 15 November 2026, +against `next` at `360530276`. Every issue named in this section is in +the milestone "Stable Stack Encrypt Rust release". An item marked +**Done** is kept so that its decisions stay on record. + +An issue that a merged pull request says it closes can stay open, +because GitHub closes issues only on the default branch. So an open +issue here may be done. It is in five groups: +the Go module, the stored format, the Rust API, the query engine, and +packaging with two key provider features. The Go customer's +release happened in late October 2026, so the groups are no longer +ordered around it. The [stored-format +rule](#the-stored-format-stays-compatible-with-go-rc3) is what that +release leaves behind. + +### 1. The Go module + +#### Finish the specification around the conformance profiles + +- **What to build.** JSON Schema files for declarations, requests, and + responses. Protocol version identifiers. A compatibility matrix of releases. + Tests that exchange new JSON values between languages. +- **Why.** The specification lets another language implement the dynamic + interface and get the same results. +- **Done already.** Conformance profiles exist for these areas (#1460, + #1461, #1462, #1469, #1491, #1492, #1493): + - the declaration grammar; + - runtime values and value kinds; + - stored reads and context; + - queries; + - EQL and JSON; + - the lifecycle of values and keys. The profiles are experimental. They do not certify a whole SDK. Pull request #1505 added value, + refusal, and raw-frame corpora. Pull request #1506 added a fresh Rust + and Go artifact exchange, with `conformance/stack-encrypt/exchange-contract.md` + and a placeholder for the released-version matrix. Pull request #1507 + consolidated the tests. All three are merged. +- **Tracked in.** Issue #1678 is open for the JSON Schemas and the protocol version identifiers. Issue #1490 is open for the stable gates and the version matrix. Issue #1314 is open for the compatibility policy, #1479 for a TypeScript runner, and #1512 for cross-language queries through PostgreSQL. Issues #1471 to #1478, #1480 and #1481 are closed. +- **Finished when** these are all true: + - the profiles are no longer experimental; + - the schemas exist; + - the version identifiers exist; + - the compatibility matrix lists rc.3. + +#### Open one child of a JSON node, bound to its parent + +- **What to build.** An operation that opens one child value of a JSON + node, and checks that the child belongs to that parent. Today `eql_v4.json_tree_children` returns the child entries. Go's + `JSONSelection.Open` opens one entry for each document, and refuses a + group with more than one entry for a selector. The contract for every + JSON operation is `conformance/stack-encrypt/eql-json-contract.md` on + `next`; the SQL is the [EQL v4 reference + page](../../packages/eql/docs/reference/json-tree.md). +- **Why.** Today a program must read and open the parent's whole subtree to + see one child. That transfers more data and reveals a different set of + tokens. +- **Done already.** + - The engine opens one entry that `json_tree_children` returned. The + engine checks the entry against the key of the parent's path, with + the same parent-link checks as a subtree read + (`JsonSubtreeKey::open_child`, a `JsonChild`). + - A child opens to its value (`JsonPlaintext`). A child also opens to + its value with its authenticated key or index (`JsonChildPlaintext`; + Go's `JSONChildValue`). + - `eql-bindings` has `JsonTreeChild`. `children(path).encrypt_keyed` + returns the token with the key that opens what the query returns. + - The dynamic interface's `json_open` takes the `children` operation. + - Go's generated `Children` returns an `encrypt.JSONChildren`. + `JSONChildren.Open` opens each entry. + - The `eql-json-v1` profile enrolls the read as `json-child-v1`, with + Rust, Go, and PostgreSQL evidence. +- **Tracked in.** Issue #1677. Pull request #1353, the Go JSON plan document, lists it as remaining. +- **Finished when** Go can open one child, and the `eql-json-v1` + conformance profile covers it. + +#### Configurable match options in Go + +- **What to build.** Match options that a Go program can set, as the + stages of the analyzer's dynamic subset: the tokeniser, the filters, + and the n-gram length. Issue #1112 tracks the part in the generator. + [Match configuration: one analyzer](#match-configuration-one-analyzer) + has the design. +- **Why.** Today Go uses only the default match options. +- **Done already.** Words of two letters can be searched (#1397). +- **Tracked in.** Issue #1112 is open for the generator. Issue #1673 is open for the analyzer that defines the options. Issues #1398 and #1399 are open for match-index follow-ups. Issue #1299 is an open question on short substrings. Issue #1396 is closed. Pull request #1397 is merged. +- **Finished when** a Go field can declare match options, and its queries + use the same options as its stored terms. + +#### Freeze the rc.3 stored format in test vectors + +- **What to build.** Fixed test vectors for the JSON storage format and the + matching EQL bundle, recorded as the rc.3 baseline. +- **Why.** The vectors make sure that later work keeps rc.3 data readable + and searchable. +- **Done already.** The conformance jobs run in CI. Two fixtures are + frozen: `stored_rows_v1.json` since 18 October 2026, and the Go rows + that `eql_v4_test.go` never regenerates. Both predate the rc.3 tag of + 2 November 2026, so neither is labelled rc.3. +- **Tracked in.** Issue #1490 is open, and lists this item as a task. Issue #1119 is closed. It froze `stored_rows_v1.json` on 18 October 2026. +- **Finished when** CI fails on any change to the stored bytes of rc.3 + data. + +#### Replace the temporary Vitamin C pins in Go + +- **What to build.** Replace the Go module's pseudo-versions of Vitamin C + with released module tags. +- **Why.** A final Go release cannot depend on unreleased commits. +- **Done already.** Prereleases can keep the pins, so rc.3 uses them. +- **Tracked in.** Issue #1679 is open. Pull request #1369, merged, introduced the pin. Issue #1253 is open. It would bring the frame codec into the Go module and remove the dependency instead. +- **Finished when** the release workflow accepts a final version. + +### 2. The stored format + +#### Changes that would alter the stored format + +Each change below would alter the stored format if it were built as first +planned. Each one must keep rc.3 data readable and searchable, or add a new +format version beside it. + +| Planned change | What it would alter | +| --- | --- | +| Search terms under the query context | A new form of search term, beside the rc.3 form, where terms derive under every part | +| A key header `h` beside a Base85 `c`, in EQL payloads | The shape of every scalar EQL payload. Payload version 2, beside rc.3's version 1 | +| The `SealedValue` envelope and the JSON header version | The offsets of the key tag, and header version 1, which rc.3 writes | +| Configurable match options | The terms of columns written with the rc.3 defaults | +| Context parts as key request items | The descriptor a key is derived under, and so the data key itself. A new envelope version marks the new form | + +- **Tracked in.** Each change has its own item below. Draft pull request #1524, which defined a version 2 leaf header of its own, was closed on 12 November 2026. + +#### Context parts as key request items + +Decided on 8 November 2026. [Binds move from the descriptor to key request items](2026-11-08-stack-encrypt-key-policy.md#binds-move-from-the-descriptor-to-key-request-items) +has the design. + +- **What to build.** New values send each scope and binding to ZeroKMS as a key request item. Each item is a name with a value, never the + part's kind, because [the kind is not in the + derivation](#query-context-and-stored-context). The descriptor shrinks to the name scopes: the record name and the field + name. + The `SealedValue` format version becomes `0x02` for + these values. On decrypt, the engine reads the version byte and sends + the request in the form the value was written with. +- **Why.** The descriptor is one string of at most 512 bytes. ZeroKMS + logs it and cannot parse it. Items are structured. They have no size + limit. Claims use the same channel, so a scope, a binding, and a + claim travel the same way. +- **No conflict over `0x02` now.** Draft pull request #1524, from the + key-vendor work, defined its own version 2 leaf. It was closed on + 12 November 2026, when the key-vendor work dropped the version 2 leaf: + every leaf stays version 1, and the key router sends a leaf to its + backend by its keyset ID. So this item can take `0x02`. +- **Stored format.** Version 1 values keep the rc.3 descriptor rendering. That rendering stays in the engine until the last such + value is gone. The change is additive: nothing written by rc.3 is re-encrypted. +- **Done already.** `SealedValue` has the version byte, bound into the + leaf AAD, and the rendering of a context into a descriptor is frozen + and documented in `packages/stack-encrypt/src/descriptor.rs`. +- **Tracked in.** Issue #1566 is open. Related: issue #1067, open, says Stack Encrypt never sends key request items to ZeroKMS. Issue #1487 is closed. +- **Finished when** these are all true: + - a version 2 value round-trips, and a version 1 value from the rc.3 + vectors still decrypts; + - a context longer than 512 bytes encrypts; + - a conformance case covers both versions. + +#### Opaque blobs + +- **What to build.** `OpaqueBlob` in Rust, using Vitamin C's storage + profile. The storage profile is Vitamin C's versioned byte format for an + opaque value that is stored. +- **Why.** Go rc.3 already writes opaque structs in this format, so Rust + must read them. +- **What the blob guarantees.** + - The stored bytes are one sealed leaf under one data key. + - The envelope contains what is needed to fetch the key again. The + caller never saves an initialisation vector or a key tag separately. + - A different context fails to open the blob. + - Stack Encrypt owns the matching encode and decode pair. + - The format's identifier and version are inside the encrypted payload, + so decoding never guesses a codec from unauthenticated metadata. + - The blob reuses the outer ciphertext envelope. Its payload is a new, + explicit format, and never reinterprets bytes sealed earlier. + - A change to the application's own type still needs explicit handling. + A codec version does not migrate it. +- **Constant time is a requirement to investigate, not a property.** + Strings, lengths, enum variants, errors, allocations, and the Serde code + a user writes all add work that depends on the values. So arbitrary + `Serialize` and `Deserialize` cannot be constant time as a whole. Before any such claim, define three things. Which types are supported. + Which shape and length information is public. Which limits apply to + custom implementations. + Authentication finishes before the blob is decoded. Check: `serdect`, + already a dependency, for its exact guarantees and whether any of them + apply to the blob codec. Its guarantees for encoding bytes do not extend + to arbitrary objects. +- **Done.** Go writes and reads the format (#1369, #1370). `OpaqueBlob` + is merged (#1503), and the Rust and Go exchange of sealed blobs is + merged (#1506). +- **Tracked in.** Issues #1484, #1367 and #1113 are closed. Pull requests #1369, #1370, #1503 and #1506 are merged. +- **Finished when** Rust and Go each open blobs that the other wrote, and + the conformance profiles cover it. + +#### Labels: the work + +Decided on 7 and 8 November 2026. [Binds, claims, and +labels](2026-11-08-stack-encrypt-key-policy.md#labels) has the design. + +- **What to build.** + - `label(name, value)` on every EQL type and on a JSON document. It + computes `HMAC(tag, PAE(name, value))`, stores the result as the tag, + and appends the label to the payload's list. + - `eql_v4.label_tag(payload, name, value)`, the same in SQL, for a + trigger that labels with the generated primary key. The tag is in the payload's key header `h`, so `label_tag` reads and + writes one Base64 field. [A key header beside a Base85 + ciphertext](#a-key-header-beside-a-base85-ciphertext) defines it. + - `label` and `labels` as operations of the dynamic interface, so Go + can label a value before it writes the row, and read the labels. + - `labels()` on a stored value, to read the list without decrypting. + - The optional `labels` list in every EQL payload type. + - On decrypt, send the stored tag and the labels to ZeroKMS, and + rebuild the leaf AAD from the original tag it returns. +- **Why.** Access intelligence needs each value tied to its row and to + the facts of its writing. A label does that without touching the + context, the AAD, or the queries, and without restricting any reader. +- **Stored format.** The list is present only once a label is added, so + a payload without one is the rc.3 form. The change is additive. +- **Depends on ZeroKMS.** The read path needs the retrieve-key request to + carry the labels, and the response to return the original tag. That + work is outside this repository. Labels written by ZeroKMS itself, and + policy over labels, are deferred to the ZeroKMS version 2 work. The + key policy document's [Still to + explore](2026-11-08-stack-encrypt-key-policy.md#still-to-explore) + section records the thinking. +- **Done already.** `Ciphertext::key_tag` reads the tag in Rust (#1404). + The leaf AAD already binds the original tag. +- **Tracked in.** Issue #1567 is open. Related: issue #1067, open, and issue #1485, the key header. +- **Finished when** these are all true: + - the example in the key policy document round-trips through a + trigger, in Rust and in Go; + - a changed label, or a changed tag, is refused by ZeroKMS; + - the conformance profile for EQL covers the `labels` list. + +#### A key header beside a Base85 ciphertext + +Decided by Dan on 8 November 2026. An EQL payload separates what +retrieving the key needs from the ciphertext itself, as the v4 JSON +document already does. A bare `Ciphertext` does not change: its envelope +keeps the keyset ID, the IV, and the tag inside, and Serde writes it as +Base64. + +- **What to build.** + - A key header field `h` in every scalar EQL payload, in Base64. Its + layout is the JSON tree header's: the header version, the keyset + ID, the IV, and the key tag. + - The `c` field contains the ciphertext without that header, in Base85. + No SQL function decodes it. The JSON tree's node ciphertext is + the same type. + - This is payload version 2. Version 1, the rc.3 form, keeps Base64 + `c` with the header inside, and stays readable. + - `eql_v4.label_tag` reads the tag from `h` with PostgreSQL's own + Base64 decoder, and writes the labelled tag back into `h`. It never + parses `c`. The same function serves a JSON document, whose tag is + already in `h`. + - A `to_base64` method on the bare `Ciphertext`, returning the existing + `Base64Text` type. One field target that stores a bare ciphertext as + text, with the working name `Base64Ciphertext`. +- **Why.** Labelling must be a one-field update in SQL. With the tag in + `h`, PL/pgSQL never needs the envelope's layout, in either encoding. + The header also gives SQL the keyset ID without decoding anything + else, and Base85 saves about a quarter of Base64's overhead on `c`. +- **Rule.** The tag moves into `h`. It is not copied. After labelling, + the base tag must be gone from the row. The chain is one-way only if + no one can read the base tag back. +- **Done already.** The v4 JSON document has `h` with this layout and a + Base85 `c` (`eql-bindings`, `v4/json_tree.rs`). `Ciphertext::key_tag` + reads the tag of a bare ciphertext in Rust (#1404). `Base64Text` and + `Base85Text` exist in `eql_bindings::encoding`. +- **Tracked in.** Issue #1485 is open. It asked for key tag extraction + from the envelope. This item replaces that with the header field. +- **Finished when** these are all true: + - a version 2 scalar payload round-trips in Rust and Go, and a version + 1 payload from the rc.3 vectors still decrypts; + - `eql_v4.label_tag` labels a scalar and a JSON document through `h` + alone, and Rust reads the tag it wrote; + - the conformance corpus has both versions. + +### 3. The Rust API + +#### Record derives + +- **What to build.** The `EncryptTarget` and `DecryptSource` derives for + records, with passthrough fields, nested records, and stored context. + The existing `from` attribute renames a source field. It is extended to + passthrough fields. +- **Where the derive lives.** On the encrypted struct. That struct is + the declaration. Each field's type says how the field is stored, and a + field's indexes come from its target type, such as `SearchableEmail` or + `IntegerOrd`. The plaintext struct carries no attributes, so it can + come from another crate. Decided on 7 November 2026, as area four of + the query design review. The query artifact's derive on the plaintext + struct generates the encrypted struct. It is not planned. It could + return later as a convenience that produces this form. +- **Two safety rules.** A plaintext field with no counterpart in the + encrypted struct is a compile error, so no field is dropped silently. + A field is stored in the clear only where `passthrough` is written on + it. Together they give what the artifact's "encrypted unless marked + plaintext" default gives, stated on the struct a developer reads. +- **Why.** The derives give the [record example](#encrypt-a-record). The + encrypted struct is what goes in the row, so a developer reads the + stored shape, and adds `Serialize` or `sqlx` derives, in one place. +- **Done.** One value (#1404), collections (#1501), and the record + derives (#1504), which emit the combinators (ADR-0007, amended + 9 November 2026) and land `scope = ".."` and `DeclaredScopes`. + `#[stash(from = "..")]` renames the source field of an encrypted field + (`stack-encrypt-derive/src/attrs.rs`). +- **Tracked in.** Issues #1482 and #1483 are closed. Pull requests #1404, #1501 and #1504 are merged. +- **Finished when** these are both true: + - a mixed record, with passthrough and encrypted fields, and a searchable + record round-trip as tests; + - a `tests/ui` case shows that a plaintext field with no counterpart + fails to compile. + +#### EQL types as fields + +- **What to build.** EQL types such as `TextEq` and `JsonTreeDocument` as + field types of the Rust record derive. +- **How it works.** The record derive gives each field a context of its + own: the record's scope, then the field's name. A field type that stores + its context stores that own context, as the type it stores. The stored + type implements `target::ContextFromField`. `Identifier` takes an own + context of two parts, the table first and the column second, and gives + the same context as that pair, so the stored bytes do not change. +- **What `i` stores.** The declared names only: the table and the column. + A record can also list a scope or a binding, supplied by the caller or + stored in the row. The terms of an EQL field derive under the query + context: the column, then the scope. The ciphertext is sealed under the + stored context: the column, then the scope, then the binding. A field + of any other type works the same way. `i` does not store the scope or + the binding, so the reader supplies them again, and a query supplies + the scope. An EQL field of a record nested in another stores its own + column in the same way. +- **Why.** This gives the [EQL field example](#store-a-field-as-an-eql-type) + and the [JSON example](#encrypt-a-json-document). +- **Done already.** In #1658: + - A Rust record with EQL fields encrypts and decrypts through the new + API, with or without a scope and a binding, and when it is nested in + another record. + - For a field of each kind (equality, storage only, order, and a JSON + document), a record with no scope writes the terms that a data plan + writes for the same declaration. A data plan is the path Go takes. + Each path opens the other's values + (`packages/eql/tests/encryption/tests/record_fields.rs`). + - `JsonTreeDocument` implements `EncryptTarget` and + `DecryptSource`. + - A query from a field reference works for the equality and match + types, with the record's scope. A data plan's query for an EQL type + takes a scope too. + - In #1668, a field reference queries the order types too: `lt`, `lte`, + `gt` and `gte` on every ordered type, `eq` as well on `TextOrd`, and + the orderings and `matches` on text search. A twin that requires + several terms (`TextOrdQuery`'s `hm` and `op`) gets all of them for the + one value; a twin whose terms are optional gets the answering index's + term alone, as the data plan's does. No SQL or stored form changes. + Each query is the data plan's for the same value, and each finds the + rows the other finds + (`packages/eql/tests/encryption/tests/typed_queries.rs`, + `typed_order_queries.rs`). A `TextOrd*` query is refused, before any + key is requested, for text either of its indexes refuses, by both + paths. `between` is not answered from a field reference, as the data + plan answers it on no EQL type; #1286 answers it on both. + - A data plan that names an EQL type takes a scope and a binding too. + `TargetResolver` receives them after the field's label, and + `TargetError::Extended` is removed. Under the same scope and binding, + a data plan and a derived record write the same terms, and each + opens the other's values. A Go struct with an `encrypt_into` field + seals through `cipher.Scope(..).Bind(..)`. +- **Tracked in.** Issue #1658 is closed: pull request #1659 closed it and merged on 2026-11-21. Issue #1668 is for order queries from a field reference, and pull request #1752 closes it. Issue #1286 is for `between` from a field reference and from a data plan. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. +- **Finished when** these are all true: + - a Rust record with EQL fields encrypts, decrypts, and queries through + the new API, including the order queries `lt`, `lte`, `gt` and `gte`, + and `between` (#1286); + - it writes the same terms as a Go record with the same declaration, + with and without a scope. + +#### A ready-made EQL resolver + +- **What to build.** A `TargetResolver` in `eql-bindings`, behind its + `targets` feature. It runs the EQL type that a field of a dynamic + declaration names, for encryption, decryption, and queries. +- **Why.** On `next`, every Rust program that uses + `stack_encrypt::dynamic::record` with EQL types writes its own resolver. + The EQL tests and the Go guest each have a copy. +- **Done already.** The functions it calls exist in `eql-bindings`: + `encrypt_with`, `decrypt`, and `query` in `v4::targets` and + `encryption::targets`. +- **Done.** The resolver is `eql_bindings::encryption::EqlTargets`, on + `next`. The EQL tests and the Go guest use it, and no other + `TargetResolver` impl remains. +- **Tracked in.** Issue #1571 is still open, and can be closed. +- **Finished when** the tests and the Go guest use the resolver from + `eql-bindings`, and their own copies are deleted. + +#### Static JSON queries + +- **What to build.** One method for each kind of JSON query on a JSON + document's field reference. The methods are `contains` and `contained_by`; + `at()` with a method per declared path and the comparison operators; + `elements()` with a method per declared array and its member conditions; + `predicate` with its variables; and `children`. Paths are typed from the + attribute, and `at_text_path` and `elements_text_path` take paths built + at run time (decided on 21 November 2026, see [Query a JSON + document](#query-a-json-document)). Each method builds the input type the + dynamic interface already has for that operator, and `encrypt(&keyset)` + returns the EQL query type. The field reference supplies the column and the + options. The dynamic parser keeps reading into the same input types, so + there is one definition of each input. +- **Names.** The method names above were confirmed in the naming review + of 8 November 2026. The operand types `Contains`, `AtPath`, + `ElementMatch`, `Predicate`, and `Children` that this plan proposed + earlier were retired as operands a caller builds, on 7 November 2026; + the query a method returns names its kind with value-free type tags of + those names (see [Query a JSON document](#query-a-json-document)). +- **Why.** On `next`, a Rust program needs a plan for any JSON query, and + needs the dynamic interface for element match, predicates, and children. + Go already has typed methods for these. +- **Done** in the pull request for #1459. Each method builds the input + the dynamic parser reads into (`json::inputs`, out of the `dynamic` + feature), and returns the field type's query type (`JsonQueries`): + the EQL types for `JsonTreeDocument`. A field's options are its + `#[stash(json(..))]`, decided on 16 November 2026. Pull request #1687 + types the paths: `ordered = { "$.age": u32, .. }`, parsed at compile time + through `stack-encrypt-jsonpath`, with a typed method per path, array + and member (21 November 2026), and `paths = { "$.name": String, .. }` + for a path compared with equality alone (22 November 2026). Tests hold every typed query to the text + form's operand and to the data plan's, the compile-fail cases under + `packages/stack-encrypt/tests/ui` hold the refusals, and the [JSON query + example](#query-a-json-document) runs. +- **Done** too: `predicate!(FIELD, "text", name = value, ..)` checks a + predicate's text at compile time, in the pull request stacked on #1687 + (22 November 2026). It reads the text with the engine's parser, which + moved into `stack-encrypt-jsonpath`; refuses what the parser and the + index refuse whatever the variables hold; matches the variables with + the text's `$name`s; and checks each path, member and value through the + accessors the derive generated, found by the path's text. When the + program runs it is `predicate(text).var(..)`, so the operand is the text + form's and the data plan's `match` operand. +- **Tracked in.** Issue #1459 closes with the `predicate!` pull request. + Issue #1677, for opening one child, closes with its pull request: a + `JsonDocument` field's `children(path)` key opens each child + (`open_child`). Issue #1486 is closed. +- **Finished when** these are all true: + - the [JSON query example](#query-a-json-document) compiles; + - a path, a member or a value type the field does not declare does not + compile; + - a text path the options do not order is refused before any key is + fetched; + - a predicate's text is checked at compile time. + +#### Field references and the encryption plan + +Decided on 7 November 2026, as difference six of the context artifact +review. + +- **What to build.** The derive emits one field reference for each field, as an + associated constant such as `EncryptedMember::EMAIL`. The field reference has + the field's name, its plaintext type, its accessor, and its index + list. It is the value a query starts from. The index list is what lets + the field reference offer one method per operator, resolved at compile time. A + query from a field reference lowers to the term combinator under the field reference's + context. Typed Rust option factories, and the same options read from + data in the dynamic interface. +- **Why.** A query must use the same declaration as the stored values. + The caller must not write a second plan by hand. The field reference holds the + declaration the derive wrote, so the query term and the stored term + come from one source. +- **Done already.** `Answers` on a target type is the compile-time + lookup of the index for an operator; a field reference's methods are bound by + it, so the field reference's index list is its target type's `Answers` impls. + Pull request #1595 lands the field references, their query methods and + `assert_context!` over a field reference (`src/field_reference.rs`, `tests/field_references.rs`, + `tests/ui/field_reference_*.rs` and `tests/ui/field_query_*.rs`). Pull request #1599 gives a field of several + indexes, a nullable field and a record field their operator methods, + and a field its query type (`#[stash(query = ..)]`). The chain query + `cipher.query(op, value).on(&plan)` is removed (#1662). It was the only + typed JSON query; a document field's reference methods replace it (#1459). +- **No hand-built plan.** The review of 7 November 2026 gave a + hand-built plan the same field references, through `Plan::::scope(..)` + with `pick!`. That is withdrawn. No Rust program builds a plan by hand. + A program whose declaration is data uses `Planned`. The builder is + removed with the structural API (ADR-0007, amended 9 November 2026). +- **Cannot fail.** The derive sees every field, so it refuses a repeated + field name or a shared name scope at compile time. A typed index set + that repeats an index, `(Equality, Equality)`, is refused at compile + time too. The builder refused it at run time. With the builder gone + (#1662), `Encrypted` and a derived `plaintext` record refuse it + at run time, before any key is requested. The compile-time check is + not built (#1670). The dynamic grammar keeps its run-time checks. +- **Tracked in.** Issues #1486 and #1596 are closed: pull requests #1595 + and #1599 are merged. Issue #1670 is open for the compile-time check. +- **Finished when** these are all true: + - the [field reference example](#query-a-record-field) compiles, with the + index's query term as the output type; the EQL query types come + with the EQL owned implementations; + - the compile-fail cases in `tests/ui` cover an operator the field's + indexes do not answer (`field_reference_operator_not_answered`), a binding + on a query (`field_query_has_no_bind`), and a missing, mistyped or + repeated scope (`field_query_needs_its_scope`); + - tests show that a query cannot run without its plan or its required + context (`tests/field_references.rs`, `tests/planned.rs`). + +#### `Planned` and its serialised form + +Decided on 7 November 2026, as area one of the query design review. + +- **What to build.** + - `Planned::new(&plan, value)`, a target. It implements `EncryptTarget` + and `DecryptSource` by composing the combinators from the plan, so + `encrypt_into`, `decrypt_from`, and their `_with_context` forms run + it. It serves a record under a record plan and a query value under a + query plan. + - Two wire shapes. A serialised `Plan` alone serves a check, an + operator list, or a query plan. A serialised `Planned` serves + encrypt, query, and decrypt. It contains the plan by reference or + inline, the context parts in declared order with their types, and + the value. The engine reads it from a wiped buffer. It answers with + the row, the query term, or the plaintext. The keyset is never in it. + - Query plans: `plan.query(field, op)`, refused where it is made if no + index answers the operator, and serialisable beside the record plan. + - The dynamic field handle, `plan.field(name)`, with every operator + method checked at run time. + - `QueryTerm` as the dynamic path's query result. It contains the operand + bytes and the EQL type they bind as. + - `contexts()` on a `Plan` and on a `Planned`, before either runs. +- **Why.** One shape for every binding. A binding then has no logic of + its own, so it cannot drift. The same shape is a conformance case. A plan + that is data is checked at run time, and a language adds its own typed + builder over it where it can. +- **Rules.** A serialised `Planned` is a transport form, never a storage + form, because its value is plaintext. It is never logged or written to disk. Its shape + is not part of the stored format. +- **Done already.** `Planned`, the query plan, the field handle, + `QueryTerm` and `contexts()` on a `Plan` and a `Planned` (#1595, + merged: `src/dynamic/planned.rs`, `tests/planned.rs`). The chain and + the builder are removed (#1666). `Planned` runs the lowering under the + plan extended by the caller's parts, and calls `query_term` in + `dynamic::query`; `encrypt_with` and `decrypt_with` in + `dynamic::record` build a `Planned` and run it (#1669). + The guest still sends the engine a plan frame, then a value frame for + each call. The serialised `Planned` names and groups what those + functions already receive, and is not built yet. +- **Tracked in.** Issue #1594 is open: the serialised `Planned`, the Go module sending it, and the corpus rewrite. Issue #1669 is open. Issue #1486 is closed. On the Go side, issue #1116 is open to hide or rename `record.Plan`. Issue #1307 is open for a Go plan-building API, for types `stashgen` cannot tag. It builds a data plan, so the Rust builder's removal does not affect it. +- **Finished when** these are all true: + - every case in the conformance corpus is a serialised `Plan` or + `Planned` with the engine's expected answer beside it; + - a Go program generated for rc.3 runs against the module that sends + serialised `Planned` values, apart from the one regeneration the + handle rename needs. That regeneration also changes `Children` to + return `encrypt.JSONChildren`. That type still binds as the token; + - the chain in `plan/chain.rs` and the builder in `plan/build.rs` + are gone. + +#### Context from fields and from the caller + +- **What to build.** One set of combinators for where a field's context + comes from. The derive emits them. The dynamic grammar lowers to them + through `Planned`. A field's context comes from one of three sources: + - the declaration: `scope = ".."` on a record, or the plan's context + in the data grammar, with each field's name scope after it; + - a row field stored unsealed in the record, so the reader takes it + from the row. A reader may pass it on decrypt to check it; + - the caller, on every write, query, and read, as a scope or a + binding. + + Parts are separate and ordered: the declared scopes, the caller's + scopes, then the bindings. Grouping is available inside one part. Nothing + is read from the plaintext on one side and from the caller on the + other. Decided on 7 November 2026, with the context artifact. +- **Why.** A program must never need to open a ciphertext to learn the + context that opens it. One mechanism keeps Rust and Go writing the same + bytes. +- **Scenarios.** The [context + examples](2026-10-24-stack-encrypt-context-examples.md) are the + acceptance matrix: eight scenarios, from a static context alone to an + EQL type with its column as the context. Two earlier scenarios were removed, because + each sealed a value that was also another field's context, so nothing + could open without the plaintext. +- **Done already.** The order in which parts are joined is fixed and + tested in Rust and Go (#1491). The context inputs `RequiredContext`, + `NoCallerContext`, and `OptionalContext` exist (#1404). #1504 added + `DeclaredScopes` and made `ExpectedContext` a context input, and #1612 + hid `ExpectedContext` from the API. Scopes and bindings are separate + kinds of part (#1487). + The naming review of 8 November 2026 decided that `ContextExtension` + goes: the `Scope::new(..).bind(..)` chain is the input. The plan builder's + `.context(..)` and `.context_field(..)` and the derive's + `#[stash(context_field)]` are the forms this replaces. +- **Required parts.** A Rust declaration lists the parts the caller must + supply, with kind and type. The context artifact proposed that for its + one kind of part; this extends it to bindings. An undeclared part is refused. Optional is + the marked case. The dynamic grammar can declare required parts; its + default stays "any", and the Go generator requires a declared part at + compile time. `RequiredContext`, `OptionalContext`, and `NoCallerContext` + (#1404) are the three states this keeps. +- **Tracked in.** Issue #1308 is open for Go identity independent of the column. Issues #1120, #1475 and #1487 are closed. Pull requests #1491 and #1504 are merged. +- **Finished when** these are both true: + - all eight scenarios run as tests in Rust and Go, on both paths: the + derive, and `Planned`; + - a Rust call with an undeclared part fails to compile. + +#### Query context and stored context + +- **What to build.** The binding kind of part, in the declaration and in + the dynamic grammar. Search terms derive under the query context, and the + key and the AAD under the stored context. A binding can be a context + field stored in the row. The order is fixed: the scopes, then the + bindings. +- **Why.** Access control needs each value bound to its row, and still + found by a column or tenant query. The facts of a row's writing are + [labels](2026-11-08-stack-encrypt-key-policy.md#labels), not bindings. [Query context and stored + context](#query-context-and-stored-context) has the rule. +- **Vocabulary.** The Rust chain's `.extend(..)` is removed; the context + argument carries the scopes and bindings instead. Go `Extend` becomes + `Scope`, with `Extend` as a deprecated alias until 0.1.0. `Bind` is added + to Go. The context contract and the conformance README say "scope" + instead of "extension". The frozen vectors do not change, because no key + on the wire names the operation. +- **Done.** Issue #1487 added the binding kind to the derive, the + dynamic grammar, and Go, and the `record-bindings-v1` conformance + profile. +- **Tracked in.** Issue #1487 is closed. Issue #1067 is open and related. +- **Finished when** these are all true, in Rust and in Go: + - a record with a binding row ID encrypts; + - a column query finds it; + - it fails to open under another row ID; + - the stored bytes of a record with no binding are unchanged. + +#### One context argument, and paired entry points + +Decided on 7 November 2026, as differences two and five of the context +artifact review. The rules are in the target state. See [the context +argument](#other-rules) and [`Planned`](#a-value-under-a-plan-planned). This item +records only the work. + +- **What to build.** The `Scope` and `Bind` value types, with the order + fixed by type. The paired entry points on the typed API. They run + `Planned` too, because it is a target. `Planned` replaces the chain in + `plan/chain.rs`, + and with it every chain state and its `.context(..)`, `.extend(..)`, + and `.keyset(..)`. A stored part passed on decrypt is checked against + the row before any key is fetched. That check is what `ExpectedContext` + does today. It stops being a public type. That last step is done + (#1612): the type is hidden from the documentation and from compile + errors, and is public only so that code the derives emit can name it. + A caller passes a `NonEmpty` or nothing. The chain is removed + (#1662): a data plan runs as `Planned`, and a typed record runs through + the derives and its field references. +- **Why.** The typed API already pairs its entry points (#1404). A value + for the context reads the same on both layers. A builder state for the + context, and a part added later in a chain, are the mistakes the context + artifact describes. +- **Done already.** The scalar pairs (#1404). The record pairs, in #1504. + The chain's `encrypt`, `query`, and `open`, with `.extend(..)` and + `.context(..)` on several states. `Planned` replaces them. +- **Order of calls.** The keyset is chosen first. It is the receiver of + the scalar entry points, `keyset.encrypt(..)`, and the argument of every + other verb, `encrypt(&keyset)`. There is no `using` method. +- **One handle reference.** `Scope<'a, K>` in `dynamic::record` and + `CipherScope` in the owned API both reduce to a connection and an + optional keyset ID. The naming review of 8 November 2026 replaced both + with one borrowed value, `CipherRef<'c, K>`, built by `From<&Cipher>` + and `From<&Keyset>`. The entry points take `impl Into`, and + the Go guest builds one from its keyset selector. A `Keyset` reference + refuses a foreign leaf with `ForeignKeyset`. A `Cipher` reference opens leaves from any keyset the client has. + Done, in the second pull request for #1488. +- **Tracked in.** Issue #1488 is open. Its sub-issue #1662 is the chain removal, done in pull request #1666. Issue #1120 is closed. Pull request #1504 is merged and added the record pairs. +- **Finished when** these are all true: + - the examples in [Target state](#target-state) compile; + - the compile-fail cases in `tests/ui` cover a binding in a query, and + a scope after a bind; + - `plan/chain.rs` is gone, and `Planned` runs every test it ran. + +#### Show the context + +Decided on 7 November 2026. + +- **What to build.** Two ways to see a context before any key is fetched: + - `contexts()` on a `Plan`, listing each field's query context and + stored context, with a typed placeholder for every caller-supplied + part. The derive emits `contexts()` on every record directly, and a + data plan has it too. + - `context()` on a prepared call. It gives the exact query context and + stored context the call will use, with the caller's values filled in. + Each part shows its type. A call with no context shows an empty + context, as such. + + Both render through the same code that derives the key descriptor and + the AAD, so what a developer sees is what the engine uses. The dynamic + interface has the same two forms. So `stashgen` can print a Go record's + contexts. A Go call can show its context. +- **Assertions for tests.** A `testing` feature of `stack-encrypt`, with + `assert_context!` over a field reference, a plan, or a prepared call. It + compares the query context and the stored context, with types, against + what the test states, and names the first part that differs. The Go + module has the same in a testing package, such as `encrypttest`, so a + Go test can pin a record's contexts the same way. Both read the same + output as `contexts()` and `context()`, so a test and a log never + disagree. +- **Why.** A wrong context loses data silently. A query under the wrong + context matches nothing and gives no error. A developer who cannot see + the context cannot find the mistake. A test that cannot state the + context cannot catch a change to it. +- **Done.** `contexts()`, `context()`, `assert_context!`, and the Go + `encrypttest` package (#1568), the scenarios that need `scope(..)` and + `bind(..)` (#1487), and the field-reference form (#1486). +- **Tracked in.** Issues #1568, #1487 and #1486 are closed. +- **Finished when** these are all true: + - a test pins the output of `contexts()` for each of the [context + scenarios](2026-10-24-stack-encrypt-context-examples.md); + - a conformance case shows that Rust and Go print the same context for + the same declaration; + - the [context scenarios](2026-10-24-stack-encrypt-context-examples.md) + each carry an `assert_context!` test, in Rust and in Go. + +#### Name context parameters `context` + +These public methods on today's types in +`packages/stack-encrypt/src/cipher.rs` take a context through a parameter +named `aad`: + +- `KeysetCipher::encrypt_tree`; +- `KeysetCipher::decrypt_tree`; +- `StackCipher::decrypt`; +- `PendingStackCipherText::plan`, whose bound is Vitamin C's `IntoAad`; +- `PendingStackCipherText::seal`; +- `PendingStackCipherText::into_pending`. + +Rename each parameter to `context`. This breaks the Rust API only. It does +not change the stored format. Renaming Vitamin C's `IntoAad` trait is a +follow-up in Vitamin C. The Go SDK and the dynamic interface have no public +parameter named `aad`. + +- **Done** (#1568, closed). + +#### Pass context by reference + +- **What to build.** Let every method that takes a context accept a + borrowed context, such as `&Identifier`. The request borrows the context + for as long as it runs. `eql-bindings` needs `IntoContext` for + `&Identifier`. +- **Why.** On `next`, every context is taken by value. A program that uses + one column context for a write and a query must clone it for each call. +- **Done already.** Stack Encrypt implements `IntoContext` for `&Label`, + the old context path type that [Apply the naming + review](#apply-the-naming-review) removes. + The context inputs, such as `RequiredContext`, still need an owned value. +- **Tracked in.** Issue #1568 is closed. A stored EQL type still takes + its `NonEmpty` by value: Rust's orphan rule keeps + `From<&NonEmpty>` for `NonEmpty` out of this repository, so that + impl is a follow-up in Vitamin C, tracked in issue #1684. +- **Finished when** the examples in this plan pass a context by reference, + without moving it, and compile. The parts are cloned into the call. + +#### Encrypt borrowed values + +- **What to build.** Let `encrypt` and `encrypt_with_context` accept a + borrowed single value, such as `&str`, `&[u8]`, or `&i64`. Keep the + current behaviour for an owned value. +- **Why.** A program that encrypts a string literal must write + `"secret".to_owned()` on `next`. The copy adds nothing, because a literal + cannot be wiped. +- **How.** The engine already reads an owned value through a borrow + (`ScalarRef` in `scalar.rs`). But `OpaqueEncode` requires `Zeroize` and + `'static`, so `&str` does not meet it. A borrowed value needs its own + bound, and the request borrows the value for as long as it runs. +- **Done already.** Owned single values (#1404). +- **Tracked in.** Issue #1569 is open. It also covers the newtype derive below. Issue #1468, a Vitamin C buffer type, is closed. +- **Finished when** `keyset.encrypt("secret")` compiles, and a test shows + that Stack Encrypt wipes its own copies of a borrowed value. + +#### A public `JsonPlaintext` + +- **What to build.** A public `stack_encrypt::json::JsonPlaintext`, with: + - `From`; + - `parse(&str)`, with the strict checks on JSON input; + - `value()`, to read the document by reference. + + Encryption into a JSON target accepts a `JsonPlaintext`, or a borrowed + `&serde_json::Value`. Decryption returns a `JsonPlaintext`. +- **Why.** The new traits need a plaintext that can be wiped. + `serde_json::Value` does not implement `Zeroize`. Rust's orphan rule + stops this repository adding that, so a wrapper is needed. A program + that already has a `serde_json::Value` must not have to print it and + parse it again. +- **Done already.** `stack_encrypt::json::JsonPlaintext` is public on + `next` (#1636), with `From`, `parse(&str)` and + `value()`, and wipes the value when it is dropped. Every JSON target + encrypts from a `JsonPlaintext` or decrypts to one through the new + traits: the document, one entry of it, and the rows of a read (#1658, + #1660). Encrypting from a borrowed `&serde_json::Value` is not built. +- **Tracked in.** Issue #1636 is closed. Issue #1569 is open for borrowed values, including `&serde_json::Value`. +- **Finished when** the JSON examples in this plan compile, and a test + shows that a dropped `JsonPlaintext` leaves no plaintext behind. + +#### Constructors for `IdentifiedBy` + +- **What to build.** Two constructors that select a keyset: + - `IdentifiedBy::name(&str)`. It checks the name, so it returns a + `Result`; + - `IdentifiedBy::uuid(Uuid)`. +- **Why.** On `next`, selecting a keyset by name needs + `IdentifiedBy::Name("acme".to_string().into())`. The `.into()` converts + the `String` into the `Name` type. That conversion does not check the + name. Only `Name::try_from(&str)` checks it: at most 64 characters, not + empty, and only `A-Z a-z 0-9 _ - /`. +- **Where.** `IdentifiedBy` and `Name` are in the `zerokms-protocol` crate. + The `cipherstash-suite` repository publishes that crate. Rust allows inherent methods only in + the crate that defines the type. So the constructors go in + `zerokms-protocol`. Stack Encrypt re-exports `IdentifiedBy` from + `stack_encrypt::kms`, so callers get them through that path. +- **Done already.** Today's `StackCipher::keyset` takes + `impl Into`, + and `IdentifiedBy` implements `From` and `From`. +- **Tracked in.** Issue #1675 is open. The `cipherstash-suite` repository, where `zerokms-protocol` lives, has issues disabled, so the issue is here. +- **Finished when** a released `zerokms-protocol` has both constructors, + and the examples in this plan compile. + +#### Authenticate the order and length of a collection + +- **What to build.** A wrapper type, `Positioned>`, that seals each + element under its position and the length of the collection. Opening + checks both, so a swapped, dropped, or added element fails. The dynamic + interface needs the same form, so that Go can declare it. +- **Why.** The default collection does not authenticate order or length, + because a database returns rows in any order. Some callers store a + sequence whose order matters, such as the steps of a workflow. ADR-0010 + says this is opt-in, by type. It does not exist yet. +- **Done already.** Nothing. The default collection (#1501). +- **Tracked in.** Issue #1570 is open. +- **Finished when** a test shows that each of swapping, dropping, and + adding an element fails to open, in Rust and in Go. + +#### A derive for a single-value type + +- **What to build.** `#[derive(Scalar)]`, for a struct with one field + whose type is a built-in single value, such as `struct Byte(u8)` or + `struct Token(String)`. It gives the type what `OpaqueEncode` and + `OpaqueDecode` need: `Encrypt` and `Scalar` on its borrow, and + `FromScalar` on the type. Each one forwards to the field. +- **Why.** A newtype is how a caller changes the rule for a value, such as + encrypting a `Vec` byte by byte. On `next`, the three + implementations are written by hand. `FromScalar` is not documented for + that use. +- **Done already.** `OpaqueEncode` and `OpaqueDecode` already accept any + type that meets those bounds. Vitamin C documents a hand-written + `Blob(Vec)` newtype. +- **Tracked in.** Issue #1569 is open. It covers the newtype case. +- **Finished when** the [byte example](#encrypt-a-byte-string) compiles + with the derive and no hand-written implementation. + +#### Apply the naming review + +Decided by Dan on 8 November 2026, one name at a time. [Names decided in +the naming review](#names-decided-in-the-naming-review) has the full +table. + +- **What to build.** The renames. Each is a breaking change to the Rust + API and none changes the stored format. + - `StackCipher` becomes `Cipher`, and `KeysetCipher` becomes `Keyset`. + - In Go, `Client` becomes `Cipher`, with `NewCipher`, and the + keyset-bound `Cipher` becomes `Keyset`. Generated files are + regenerated, and the generator's output changes for every input. + - `CipherScope` and `dynamic::Scope` are replaced by one `CipherRef`. Done. + - The old context path type `Label` is removed, with `IntoLabel` and + Go's `ContextLabel()`. A plan's context is its declared `Scope` + parts, so `Label` is free for the key tag fact. + - The ZeroKMS unit of work `Request` is made crate-private with + `Pending::request`, built on stack-kms's `GenerateKeyPayload` and + `RetrieveKeyPayload`. There is no public request type. A binding + sends a serialised `Plan` or `Planned`. + - `OpSpec` becomes `Op`. + - `context = ".."` becomes `scope = ".."`, and Go's `context=` tag becomes `scope=`. The builder's + `Plan::context(..)` goes with the builder. + - The marker trait `op::QueryTerm` becomes `Query`, and + `LabelledTarget` becomes `Stored`. `dynamic::QueryTerm` stays. + - `ContextExtension` is removed. `EncryptionPlan` is never added. +- **Why.** The plan used placeholders so that the review could change a + name without changing a design. The review is done, so the code can + follow. +- **Done already.** `OpSpec` is `Op`. `CipherScope` and `dynamic::Scope` + are `CipherRef`. `scope = ".."` replaced `context = ".."` (#1504). + `ContextExtension` is gone. The rest are still the old names: + `StackCipher`, `KeysetCipher`, the Go `Client` and `Cipher`, `Label`, + a public `Request`, `op::QueryTerm` and `LabelledTarget`. +- **Tracked in.** Issue #1489 is open for naming and packaging. Issue #1663 is open for `Label`, and on hold: the context naming work may give the declared path, which `Label` holds today, a new name and mode, so it is not renamed or removed until that settles. Issues #1116 and #1307 are open for the Go names. Pull request #1504 is merged. +- **Finished when** no old name remains in the public API, the examples + in [Target state](#target-state) compile under the new names, and the + packaging glossary matches. + +#### Remove the structural API + +- **What to build.** Remove `EncryptFrom`, `DecryptInto`, `encrypt_as` and + `decrypt_as`. Remove the plan builder: + `plan/build.rs`, `plan/chain.rs`, `plan/value.rs`, and + `plan/field_ref.rs`, with `pick!`, `FieldRef`, `Runs`, and `Opens`. + `Plan::encryption` moves into `Planned` (ADR-0007, amended 9 November + 2026). Remove the context path type `Label` and `IntoLabel`: a plan's + context is its declared `Scope` parts, and the guest sends parts, not + a path. Move EQL, Go, and the guest to the new API in the same change. + Keep an entry point for a standalone borrowed value. `encrypt_as(&value, + ..)` goes with the structural API, and the owned entry points take the + value by value. + The removal of `Label` is also listed in [Apply the naming + review](#apply-the-naming-review); it happens once, here. +- **Why.** Two APIs for the same job make the right one hard to find. +- **Done already.** The first + pull request for #1488 makes `Planned` the one lowering of a data plan: + `dynamic::planned::compose` and `opening` build each field's combinator + from the parsed plan, and `encrypt_with`, `decrypt_with`, `contexts()` + and the checks read them. The dynamic path no longer uses the plan + builder. `encrypt_with` and `decrypt_with` build a `Planned` and run + it, so a record is encrypted and opened only through `Planned`; + `contexts()` still composes the plan, to read the contexts (#1669). + `Label` is still to be removed. The helpers in `target::legacy` are + removed, in the fourth pull request for #1488. The builder, the chain, + `EncryptFrom`, `DecryptInto`, their derives, `encrypt_as` and + `decrypt_as` are removed (#1661, #1662). + EQL, the Go guest, the examples and every test use the owned API, field + references or `Planned`. + Every JSON target has the new traits over `JsonPlaintext` (#1658 for + `JsonTreeDocument`, #1660 for the other five), so no target needs the + old traits any more. +- **Tracked in.** Issue #1488 is open. Its first pull request is the + lowering. Its second replaces `CipherScope` and `dynamic::Scope` with + `CipherRef`. Its third hides `ExpectedContext` (#1612, merged). Its + fourth removes `target::legacy` (#1613, open). The other removals are + its sub-issues, in this order: #1660 gives the remaining JSON targets + the new traits (#1664, open); #1662 removes the chain and the builder, + and #1661 removes `EncryptFrom`, `DecryptInto`, `encrypt_as` and + `decrypt_as` (both in #1666, open); #1663 removes `Label` and + `IntoLabel`, on hold until the context naming work settles what the + declared path is called; and #1669 makes `encrypt_with` and `decrypt_with` build a + `Planned`. +- **Finished when** the old API is gone, and every consumer uses the new + API. + +#### Wipe plaintext in the remaining cases + +- **What to build.** Wipe the parts of a Serde value that were decoded + before a later part failed. Add an adapter that wipes a decrypted value + when it is dropped. +- **Why.** Plaintext must not stay in freed memory. +- **Done already.** Collections wipe the values decoded before a failure. + Cancellation and drop are tested (#1493, #1501). A decrypted + `OpaqueBlob` is read in place into a `T::default()`, so a refusal + wipes the fields of most derived structs that were read before it + (#1676, pull request #1750). Decrypting needs `T: Default`. +- **Tracked in.** Issue #1754 is open for what #1676 left: the + `native-partial-decode-inside-whole-values` known gap. serde still builds + some values whole (an element of a sequence, a map, an `Option`, a `Box`, + an enum, a field read with `deserialize_with`, and a struct marked + `transparent`, `from` or `try_from`, with a `flatten` field, or whose + every field uses `deserialize_with`), and a refusal inside one drops what + it built unwiped; a sequence longer than the 1 MiB serde reserves frees + each regrown buffer unwiped. Issue #1684 is open for the drop-wiping adapter for a single value, such as `Zeroizing`, which needs Vitamin C to implement `FromScalar` for `Zeroizing`. Issue #1458 is open: data keys by reference. Issues #1468 and #1480 are closed. Pull requests #1493, #1501 and #1503 are merged; a decrypted `OpaqueBlob` wipes its value when it is dropped, and its `into_inner` returns a `Zeroizing`. +- **Finished when** the conformance profile for the lifecycle covers both cases. + +### 4. The query engine + +#### One definition of each operator + +Decided on 7 November 2026, as area two of the query design review. + +- **What to build.** Each operator exists once, as its `op` type, such as + `op::Eq` and `op::Between`. One macro generates the dynamic enum and + its wire names from those types. A field query method, the dynamic + handle's method, and a query plan's operator all resolve to the same + type. So `eq`, `"eq"`, and `op::Eq` are three faces of one operator. +- **The dynamic enum's name.** It is public, because a program building a + query plan writes it: `plan.query("email", Op::Eq)`. The engine's enum + is `OpSpec` today. The plan writes `Op`. The naming review confirmed it on 8 November 2026. +- **`Matches` loses its case parameter.** On `next`, `op::Matches` + has a case parameter. The match index's configuration has a case too. + The two can disagree. A disagreement is refused at query time. The field's configuration + is now the only one, so case belongs to the index alone. `Matches` + becomes a plain operator, as the dynamic `"matches"` already is. +- **An inverted range is let through.** `between(65, 18)` derives both + bounds and matches nothing, as commit `8b5fc57b6` decided. The engine + does not know which bound the caller meant. The `InvertedRange` error + asked for in #1279 predates that commit and is dropped. +- **Stored format and wire.** Unchanged. A query sends the operator's wire name. That name does not change. +- **Tracked in.** Issues #1279, #1318, #1317 and #1233 are closed: their pull request made `Op` and removed `Matches`'s case parameter. Issue #1321 is still open and may already be fixed by it. Issue #1319 is open. Issue #1320, the inverted-range rule, is closed: this plan's decision superseded it. +- **Finished when** these are all true: + - the dynamic enum is generated from the `op` types; + - `Matches` has no type parameter; + - a test shows that each operator's three faces name the same operator. + +#### Match configuration: one analyzer + +Decided on 7 November 2026, as area five of the query design review. The +design is the query artifact's; the adjustments below are the plan's. + +- **What to build.** + - An analyzer pipeline, typed first: `Words.downcase().stop(..).stem(..).ngrams(3)`, + built like an iterator chain. The order is checked by type, so a + stemmer after n-grams does not compile. Any type that implements + `Stage` can join, so a customer's own filter needs no change to the + crate. + - A closed dynamic subset, `StageSpec`: `Words`, `Whole`, `Downcase`, + `Stop`, `Stem`, `Ngrams`, `EdgeNgrams`, `Shingles`. A plan names its + stages, and every reader of the plan runs exactly those: Rust, the Go + verify path, and EQL. A typed stage joins the subset by an explicit + change. Until then a configuration that uses it is typed-only, and a + serialised plan that names it is refused with `NotPortable`. + - Case stated once, as whether `downcase()` is in the analyzer. + - Two types: `Match`, with the options in the type, and + `Match`, with the options in the value. Both derive terms + through one `sem::match_terms`. A stored field and its query agree by + type on the typed path, and by reading one plan entry on the dynamic + path. + - Versioned stop lists and stemmers, such as `english@1`. Changing a + list is a new id, never a silent change to stored terms. + - Refusals written once, in the `sem` functions, for both paths: empty + text, text that cannot be normalised, and invalid options. +- **Stored format.** A declaration is data that a stored row depends on. + A rc.3 declaration, `{tokenizer, downcase, short_words}`, keeps loading, + mapped to the equivalent stage list. A conformance case shows that the + mapped list produces the same terms as rc.3, for both tokenisers. New + declarations may write `analyzer` instead. +- **Short words.** The short-word channel (#1397) is a stage in the + analyzer, not a sibling index. A second filter is a second index only + if it answers a different operator. The privacy question about short + words stays open as it is. +- **Go.** A struct tag's match options are the stages of the dynamic + subset. `stashgen` asks the engine which stages exist, and keeps no + list of its own. This is what [configurable match options in + Go](#configurable-match-options-in-go) builds. +- **EQL.** EQL's match configuration has a tokeniser and token filters. + `EqlMatch` uses only stages that map onto them. Edge n-grams and + shingles stay Stack-only until EQL supports them. +- **`expected_tokens` is dropped.** It is an optional prior for the + false-positive estimate in `op::Stats`, `None` by default, and a data + plan never declares one. `Stats::measured(rows, ..)` stays. Decided on + 7 November 2026. +- **Breaking.** Every hand-written `MatchConfig` changes shape. This lands + as a `!` commit with a changelog entry. +- **Tracked in.** Issue #1673 is open for the analyzer. Issues #1319, #1112, #1398, #1399, and #1299 are open. Issue #1309 is closed. Pull request #1397 is merged. +- **Finished when** these are all true: + - the conformance case for the rc.3 mapping passes in Rust and Go; + - a `tests/ui` case shows a stemmer after n-grams fails to compile; + - a serialised plan naming a typed-only stage is refused with + `NotPortable`; + - EQL, Go, and Rust produce the same terms for the same stage list. + +#### The engine's rules, and the order of the work + +Decided on 8 November 2026, as areas six and seven of the query design +review. The rules are the query artifact's. + +- **Six rules.** + 1. A query runs on the field's own index, with that index's + configuration. There is no default index and no `.via`. A query starts from the + field's reference, so the rule is true by construction. + 2. A field declares at most one index per operator. `(Equality, Ore)` + is allowed, because they answer different operators. `(Ore, Ope)`, + `(Ore, OreBlock)`, and two match indexes are refused when the plan is + built. So the lookup returns zero or one index, on both paths. + 3. An index declares its operators once. The typed lookup, the dynamic + lookup, and the plan validation all derive from that one + declaration. There is no second table in the dynamic path, and no + third in `eql-bindings`. + 4. Refusals are part of deriving the term. They are written once, in + the `sem` functions, for both paths. + 5. The typed path is strict at compile time. The dynamic path checks + the same rules at run time. Both lower to the same functions. + 6. Rust is the superset. The dynamic path is a named subset. +- **The dynamic plan's shape.** A field's indexes become a closed + `FieldIndexes` enum of the valid shapes, generated from the index + declarations: equality optional, at most one match index, at most one + of `Ore`, `Ope`, and `OreBlock`. Deserialising is validation. A plan + with two match indexes has no variant, so the boundary refuses it. + Order is canonicalised, so the two spellings `[ore, equality]` and + `[equality, ore]` name one shape. + + `index_for(op)` is one match with no priority order. The wire keys + `c`, `eq`, `match`, `ore`, and `ope` do not change, so the stored + format is untouched. Until the enum lands, the dynamic plan keeps + `Vec`, with a one-table lookup over each index's declared + operators. +- **`check_query` stays, for Go.** The Go SDK promises to refuse a bad + query before it resolves a keyset, and calls `dynamic::check_query` for + that. It becomes a thin call into the `sem` functions, with no cipher. + The typed path has no separate check step: a saving on the error path + alone does not justify a trait method. +- **The order of the work.** Four steps, each shippable on its own, each + removing one copy of something: + 1. One declaration per index and operator. `Op`, `OpSpec` today, is + generated from the `op` types. Each index declares its operators and admitted + plaintexts once, and `index_for` reads them. Overlap is refused on + both paths. A test shows the typed and dynamic faces agree. + An index admits exactly the plaintexts one of its operators + answers. The typed path enforces this with a trait bound, not a + test: each order index, order term and ordering operator is bounded + by vitaminc-ore's `Orderable`, which does not cover bytes. So an + order index on bytes does not compile. The dynamic path refuses the + declaration, in `dynamic::admits`, as `index_not_admitted`. A row + stored under such a declaration still opens once the index is removed + from the plan, because opening ignores a stored term the plan does + not declare. + 2. Derivation once, refusals once. The `sem` query functions, the + analyzer in place of `MatchCase`, and `Match` arrive. + `check`, `verifier`, `admit`, `QueryToken`, `check_input`, and the + second tokenisation go. This is the `!` commit. It closes #1318 and + #1279, with #1279's `InvertedRange` item dropped. + 3. Typed field references with their index lists, the per-operator query + methods, `Planned`, and the removal of `DefaultIndex`, `.via`, + `PlanError::IndexOptions`, and `PlanError::MatchCase`. + 4. `FieldIndexes` on the dynamic plan. The dynamic path then shares + the typed derivation itself, through `Index` + implementations per index kind. Both paths run the one executor + that ADR-0007 asks for. Dan closed this question on 8 November + 2026. +- **Issues.** #1318 and #1279 are closed by steps 1 and 2. #1309, short + tokens, is a stage in the analyzer. The searchable-encryption investigation is + independent: a future SSE index is one more index declaration. +- **ADRs.** ADR-0009 describes `Supports`, `Answers`, `DefaultIndex`, and + `.via`. The `MatchConfig` documentation says a field and its query agree "by + construction". That is true only for one-value plans today. Both + are amended, not contradicted in silence. +- **Tracked in.** Steps 1 and 2 are done: #1279, #1318, #1317 and #1233 are closed. They brought `prepare`, the `sem::query` rules and `Op`, and dropped `Matches`'s case parameter. The analyzer of "Match configuration: one analyzer" is its own work (#1673). Step 3 is done apart from its clean-up: the field references and `Planned` (#1486, closed), and the removal of `DefaultIndex` and `.via` (#1666). #1671 removes `PlanError::IndexOptions` and the six other variants nothing raised, and amends ADR-0009 and the `MatchConfig` documentation. Step 4 is issue #1672, open. +- **Finished when** these are all true: + - every index's operators appear in one declaration, and a test shows + the typed and dynamic lookups agree on every index; + - a plan with two match indexes, or with `Ore` and `Ope`, is refused on + both paths; + - `DefaultIndex`, `.via`, `MatchCase`, and `PlanError::IndexOptions` + are gone; + - ADR-0009 and the `MatchConfig` documentation are amended. + +### 5. Packaging, and two key provider features + +- **Packaging and names.** Crate moves, the shared format crate, and the + final names. The [packaging + document](2026-10-25-stack-encrypt-packaging.md) has the proposal. +- **Split the leaf cipher.** One small clean-up inside the crate, below. +- **Keyset selection and claims.** Two optional features of the ZeroKMS + key provider, below. Nothing else in this plan depends on them, and no + merged pull request implements either. + +#### Split the leaf cipher into sealing and opening + +Vitamin C's `Cipher` trait has a `seal` method and an `open` method. +Stack implements it twice, in `packages/stack-encrypt/src/cipher.rs`: +`MintedKeys` only seals, and `BoundKeys` only opens. Each type still has +to provide the other method, and that method only returns an error. + +Fix this in the packaging pass. One option splits the trait into a +sealing capability and an opening capability. Another changes the +internal adapter in some other way. Decide this separately from the +[retirement of `AsyncCipher`](2026-10-25-stack-encrypt-packaging.md#retire-asynccipher) +in the packaging document. + +- **Tracked in.** Issue #1489 is open, and asks how to split it. Draft pull request #1522, which reworked the stack-kms key source traits, was closed. + +#### Choose the keyset from the data + +Today the caller resolves a keyset by hand and passes it to every call, +as [Connect and choose a keyset](#connect-and-choose-a-keyset) shows. +The proposal lets a declaration name the plaintext field that contains +the keyset, so a record selects its own keyset: + +```rust +// Proposed. `tenant_id` holds the keyset's name. `id(field = "..")` +// selects by UUID instead. +#[stash(struct = User, scope = "users", keyset(name(field = "tenant_id")))] +struct EncryptedUser { /* .. */ } + +// The call takes the client, and the record selects the keyset. +let encrypted: EncryptedUser = user.encrypt_into(&cipher).await?; +let encrypted: Vec = users.encrypt_into(&cipher).await?; +``` + +Rules for the proposal: + +- A missing, unknown, unauthorised, or disabled keyset is an error. There + is no fallback to the default keyset. +- The selector resolves before any key is fetched. A batch is split by + resolved keyset. The results keep the order of the input. +- A keyset selector selects a keyset. It does not add its field to the + context. A scope does not select a keyset. +- Where the business tenant ID is not the keyset's name, the application + supplies an explicit mapping. The declaration never carries code. +- A query has no record to read, so the caller supplies the keyset, or a + typed input that the declaration maps to one. No query term compares + across keysets: a search over several keysets is one term per keyset. +- Decryption uses the keyset ID stored with the ciphertext, as today. It + never resolves a name again. +- If the caller passes a keyset and the record selects one, the two must + match, or the call is refused. Neither wins silently. + +- **Tracked in.** Issue #1572 is open. Related open issues: #1048, the Go eager keyset; #735, a keyset mismatch is silently unsearchable; #561, a per-operation keyset in TypeScript; #1312, Go control-plane keysets. Issue #832 is closed. Pull request #1407, open, is the Go control SDK. + +#### Claims the key provider resolves + +A claim is a binding whose value the key provider resolves from the +caller's verified token. The `sub` of a JSON Web Token (JWT) is one. +The client names it and never sees the value, so a claim is in the +stored context and never in the query context. Only a reader whose +token resolves to the same value gets the key. + +[Binds, claims, and +labels](2026-11-08-stack-encrypt-key-policy.md#claims) has the design. +The plan's rules: + +- A claim is declared on the type, `bind(claim = sub)`, and never added + on one call. A per-call claim could make a row unreadable to everyone + else without anyone noticing. +- The claim type belongs to the provider: `zerokms::Claim::Sub` and + `zerokms::Claim::Custom(name)`. A `ResolvesClaims` trait gates it. + A declaration with a claim fails to compile against a keyset whose + provider does not implement the trait. A dynamic declaration with a + claim part is refused at load on such a provider, before any key I/O. +- A claim is strict by construction. Lose the claim, lose the data. + Where a fact only needs recording, the plan recommends a + [label](#labels) instead. +- The claim resolves from the bearer token on the request. The + `@cipherstash/stack` native entry does not yet send the caller's + own token on each call (#1565). A claim on that path waits for that fix. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Note, scope = "notes", bind(claim = sub))] +struct EncryptedNote { + body: Ciphertext, +} + +let encrypted: EncryptedNote = note.encrypt_into(&keyset).await?; +let note = Note::decrypt_from(encrypted, &keyset).await?; +``` + +- **Tracked in.** Issue #1683 is open. Issue #1566, context parts as key request items, is the prerequisite, with issue #1067. Issue #1565 is open for the TypeScript entry. Issue #1045 is closed. + +## Open questions and decisions to be made + +The lead who approves this plan decides each question. + +| Question | Options | Recommendation | +| --- | --- | --- | +| For each change that would alter the stored format, should it keep the rc.3 format or add a new version? | Keep rc.3 data readable and searchable. Or add a version beside it | Decide for each change when it is designed | +| Should a record choose its keyset from a plaintext field? | The declaration in [Choose the keyset from the data](#choose-the-keyset-from-the-data). Or the caller keeps resolving the keyset by hand | The declaration | +| Should this plan ask ZeroKMS version 2 to derive the data key over the key request items, not only the descriptor? | Yes, so a bind or a claim is enforced by derivation. Or keep the tag check as the only enforcement. The version 2 work decides | Yes. The [key policy document](2026-11-08-stack-encrypt-key-policy.md#what-zerokms-must-do) asks for it | +| Which change owns envelope version `0x02`: this plan's key request items, or #1524's key backend header? | One version 2 header that carries both, shared with the EQL key header `h`. Or separate bytes | Settled: #1524 was closed on 12 November 2026 and the key-vendor work keeps every leaf at version 1, so key request items (#1566) take `0x02` | +| What privacy claim can be made for match terms of short words? | Accept what they reveal, and document it. Or change how short words are stored | No recommendation yet. Merging #1397 did not show that they reveal nothing new | +| Which Vitamin C crate should own `Base64Text` and `Base85Text`? | A new Vitamin C types crate that also holds key types. Or a small encoding crate | Vitamin C owns them, decided by Dan on 8 November 2026. The crate is to be confirmed, probably the types crate | +| What crate layout should the final API use? | The proposal in the packaging document | Review the layout proposal when the crate moves begin. The names are decided | + +### Names decided in the naming review + +Dan decided each name on 8 November 2026, one at a time, against the +packaging document's proposal and the names already on `next`. The +[Apply the naming review](#apply-the-naming-review) item carries the +renames. + +| Name | Decision | +| --- | --- | +| `Cipher`, `Keyset` | The connection, today `StackCipher`, and the handle bound to one keyset, today `KeysetCipher`. Decrypt through a `Cipher` opens values from any keyset it holds. The clash with Vitamin C's `Cipher` trait is accepted. Go renames to match: `encrypt.Client` becomes `Cipher`, with `NewCipher`, and the keyset-bound `encrypt.Cipher` becomes `Keyset`. A Go program regenerates once | +| `CipherRef<'c, K>` | One borrowed value for both paths, a connection and an optional keyset ID, built by `From<&Cipher>` and `From<&Keyset>`. Replaces the `CipherScope` trait and the `dynamic::Scope` enum. A design decision, not only a name | +| `Plan` | A record's declaration as data. `TargetDefinition` is dropped | +| `Plan::scope(..).fields(..)`, `encrypt_index`, `passthrough`, `query`, `pick!` | Removed. The hand-built plan builder, settled on 4 October 2026, goes with the structural API. The derive emits the combinators, and `Planned` lowers a data plan to them (ADR-0007, amended 9 November 2026). `EncryptionPlan::record(..).field(..)` is dropped | +| `Label`, `label`, `labels`, `label_tag` | The key tag fact and its operations. The old context path type of that name, a field's declared scopes as `users/email`, is removed: those are `Scope` parts. Go's `ContextLabel()` goes with it | +| No `Request` type | A binding sends a serialised `Plan` alone for a check, an operator list, or a query plan, and a serialised `Planned` for encrypt, query, and decrypt. The ZeroKMS unit of work that is `Request` today becomes crate-private, built on stack-kms's payload types | +| `Query`, `Stored` | Two marker traits on the term types. `Query` marks a value a query sends, today `op::QueryTerm`. `Stored` marks a stored index term, today `LabelledTarget`. `EqualityTerm` and the order terms implement both; `MatchTerms` only `Stored`; `MatchQuery` only `Query`. `QueryToken` stays the run-time guard | +| `QueryTerm` | The dynamic field handle's result, unchanged | +| `Op` | The public dynamic operator enum, today `OpSpec` | +| The chain `Scope::new(..)`, `Bind::new(..)`, `Scope::new(..).bind(..)` | The caller-supplied context input. No separate type; `ContextExtension` from #1504 goes. A trait bound, `impl ContextParts`, names what an entry point accepts | +| `JsonTreeDocument`, `JsonTreeQuery`, `JsonTreeLeafQuery`, `JsonTreeElementsQuery`, `JsonTreePredicateQuery` | Kept. The SQL domain `eql_v4_json_search` and the dynamic target `JsonSearch` are the other two names of the one stored type | +| `Planned`, `Positioned>`, `Claim`, `ResolvesClaims`, `#[derive(Scalar)]`, `Base64Ciphertext` | Confirmed. `Base64Ciphertext` is the text form of a bare `Ciphertext`, which keeps its header inside. EQL payloads instead carry a Base64 key header `h` beside a Base85 `c`, as the JSON tree does. There is no `Base85Ciphertext` target | +| `contains`, `at`, `elements`, `predicate`, `children` | The JSON query methods on a document's field reference. Confirmed | +| `contexts()`, `context()`, `assert_context!`, the `testing` feature, `encrypttest` | Showing and asserting a context, in Rust and Go. Confirmed | +| `scope(..)`, `bind(..)`, `bind(claim = ..)`, `keyset(name(field = ..))` | The declaration attributes. Confirmed | +| `stack-kms` to `stack-zerokms` | Not decided. The crate rename is part of the crate layout question, which stays open | +| `scope = ".."`, Go `scope=` | The record's name is its first scope, so the attribute and the Go tag both say `scope`. Today they say `context = ".."` and `context=`. The builder's `Plan::scope(..)` was part of this decision and goes with the builder. Decided by Dan on 8 November 2026 | +| `plan.query(field, op)`, `plan.field(name)`, `FieldIndexes`, `StageSpec`, `Match`, `NotPortable` | The dynamic interface names. Confirmed. `IndexNotDeclared` was on this list and is removed (#1671): no query takes an index from the caller | diff --git a/docs/plans/2026-10-24-stack-encrypt-context-examples.md b/docs/plans/2026-10-24-stack-encrypt-context-examples.md new file mode 100644 index 0000000000..1739a8aac9 --- /dev/null +++ b/docs/plans/2026-10-24-stack-encrypt-context-examples.md @@ -0,0 +1,273 @@ +# Context scenarios for the Stack Encrypt API + +Date: 8 November 2026. + +This document lists eight ways a record can get its context, each as a +code example with its use case. Together they are the acceptance matrix +for the work item [Context from fields and from the +caller](2026-10-24-stack-encrypt-api-plan.md#context-from-fields-and-from-the-caller) +in the API plan. The plan's section [Query context and stored +context](2026-10-24-stack-encrypt-api-plan.md#query-context-and-stored-context) +gives the rules, and its terms table defines every term used here. + +In short: every part of a context is a scope or a binding. The query +context is all the scopes. The stored context is the scopes followed by +the bindings. Search terms derive under the query context, and the data +key and the AAD derive under the stored context. + +The code below is proposed. None of it compiles on `next` today. The +rules are decided. The attribute verbs `scope(..)` and `bind(..)` are +confirmed. The form inside them, such as `tenant: u64`, is illustrative. + +## Contents + +- [How to read the examples](#how-to-read-the-examples) +- [1. A static context only](#1-a-static-context-only) +- [2. A scope the caller supplies and does not store](#2-a-scope-the-caller-supplies-and-does-not-store) +- [3. A scope taken from the plaintext and stored in the row](#3-a-scope-taken-from-the-plaintext-and-stored-in-the-row) +- [4. A binding stored in the row](#4-a-binding-stored-in-the-row) +- [5. A stored scope and a stored binding](#5-a-stored-scope-and-a-stored-binding) +- [6. A stored part and a caller-supplied part together](#6-a-stored-part-and-a-caller-supplied-part-together) +- [7. A scope the caller supplies on every call and never stores](#7-a-scope-the-caller-supplies-on-every-call-and-never-stores) +- [8. An EQL type, with its column as the context](#8-an-eql-type-with-its-column-as-the-context) + +## How to read the examples + +- `scope = "users"` is the record's name and its first scope. The derive + adds each field's name as the next, so the declared scopes of `email` + are `users` then `email`. +- `scope(tenant: u64)` declares a scope the caller supplies on every call. + `bind(row: Uuid)` declares a binding the caller supplies. +- `scope(field = "tenant")` declares a scope stored in the row, in the + passthrough field `tenant`. `bind(field = "id")` declares a stored + binding in the same way. +- A caller passes its parts as `Scope::new(..)`, `Bind::new(..)`, or + `Scope::new(..).bind(..)`. A query accepts a `Scope` only. +- `SearchableEmail` is the target type from the plan's [record + example](2026-10-24-stack-encrypt-api-plan.md#encrypt-a-record): a + ciphertext and an equality term. +- A stored part is read from the plaintext on encrypt. On decrypt, the + reader takes it from the row. If the reader passes it as well, Stack + Encrypt checks it against the row before it fetches any key. + +## 1. A static context only + +The record's own name and each field's name make up the whole context. +Nothing comes from the caller or the row. This is the default for a +record that has no tenant and no row binding, such as a settings table. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Settings, scope = "settings")] +struct EncryptedSettings { + theme: Ciphertext, +} + +let encrypted: EncryptedSettings = settings.encrypt_into(&keyset).await?; +let settings = Settings::decrypt_from(encrypted, &keyset).await?; +``` + +## 2. A scope the caller supplies and does not store + +The caller knows the tenant from the request, and passes it on every +write, query, and read. Nothing about the tenant is stored with the row. +A query for one tenant matches only that tenant's rows. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(tenant: u64))] +struct EncryptedUser { + email: SearchableEmail, +} + +let encrypted: EncryptedUser = user + .encrypt_into_with_context(&keyset, Scope::new(tenant)) + .await?; +let user = User::decrypt_from_with_context(encrypted, &keyset, Scope::new(tenant)).await?; + +let by_email = EncryptedUser::EMAIL + .eq("alice@example.com") + .scope(tenant) + .encrypt(&keyset) + .await?; +``` + +## 3. A scope taken from the plaintext and stored in the row + +The tenant is a field of the plaintext, and the record stores it in the +clear. The declaration marks that field as the stored copy, so encrypt +reads it from the plaintext. A reader takes the tenant from the row, so a +batch job can decrypt rows from many tenants without knowing each one +first. A reader that serves one +tenant passes it as well, to check that the row belongs to that tenant. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(field = "tenant"))] +struct EncryptedUser { + #[stash(passthrough)] + tenant: u64, + email: SearchableEmail, +} + +let encrypted: EncryptedUser = user.encrypt_into(&keyset).await?; // tenant comes from `user.tenant` + +let user = User::decrypt_from(encrypted, &keyset).await?; // tenant comes from the row +let user = User::decrypt_from_with_context(encrypted, &keyset, Scope::new(session.tenant)).await?; +``` + +The second decrypt is refused with `ContextMismatch` if the row's tenant +is not `session.tenant`, before any key is fetched. + +## 4. A binding stored in the row + +The row's own ID is part of the context, so each ciphertext opens only +in its row. A ciphertext copied into another row fails to open. The ID is +stored in the clear, as any primary key is. A query is not affected, +because a binding is not in the query context. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", bind(field = "id"))] +struct EncryptedUser { + #[stash(passthrough)] + id: Uuid, + email: SearchableEmail, +} + +let encrypted: EncryptedUser = user.encrypt_into(&keyset).await?; +let user = User::decrypt_from(encrypted, &keyset).await?; + +// A query covers the whole column. It does not take the row ID. +let by_email = EncryptedUser::EMAIL.eq("alice@example.com").encrypt(&keyset).await?; +``` + +## 5. A stored scope and a stored binding + +The tenant and the row ID are both stored in the row. A query for one +tenant matches that tenant's rows, and each ciphertext opens only in its +own row. This ties each decrypted value to the row it came from. The facts of a +row's writing, such as the address it came from, are +[labels](2026-11-08-stack-encrypt-key-policy.md#labels), not parts of +the context. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(field = "tenant"), bind(field = "id"))] +struct EncryptedUser { + #[stash(passthrough)] + tenant: u64, + #[stash(passthrough)] + id: Uuid, + email: SearchableEmail, +} + +let encrypted: EncryptedUser = user.encrypt_into(&keyset).await?; +let user = User::decrypt_from(encrypted, &keyset).await?; + +// Check both stored parts on decrypt. +let user = User::decrypt_from_with_context( + encrypted, + &keyset, + Scope::new(session.tenant).bind(requested_id), +) +.await?; + +let by_email = EncryptedUser::EMAIL + .eq("alice@example.com") + .scope(session.tenant) + .encrypt(&keyset) + .await?; +``` + +## 6. A stored part and a caller-supplied part together + +The tenant is stored in the row. The row ID comes from the caller on +every call, and is never stored. The row ID is known from elsewhere, such +as the request path. A reader passes the row ID, and may pass the tenant +as well to check it. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(field = "tenant"), bind(row: Uuid))] +struct EncryptedUser { + #[stash(passthrough)] + tenant: u64, + email: SearchableEmail, +} + +let encrypted: EncryptedUser = user + .encrypt_into_with_context(&keyset, Bind::new(row_id)) + .await?; + +// The tenant comes from the row. The row ID must be passed. +let user = User::decrypt_from_with_context(encrypted, &keyset, Bind::new(row_id)).await?; + +// Passing the tenant as well checks it against the row. +let user = User::decrypt_from_with_context( + encrypted, + &keyset, + Scope::new(session.tenant).bind(row_id), +) +.await?; +``` + +## 7. A scope the caller supplies on every call and never stores + +The scope is a value that exists only where the data may be used, such as +a host or application ID. The record is fully stored, but part of its +context is not. So the data opens only on a host that has the value. A +row copied to another host fails to open, and a query from another host +matches nothing. + +```rust +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Secret, scope = "secrets", scope(host: String))] +struct EncryptedSecret { + value: Ciphertext, +} + +let host = host_id()?; +let encrypted: EncryptedSecret = secret + .encrypt_into_with_context(&keyset, Scope::new(&host)) + .await?; +let secret = Secret::decrypt_from_with_context(encrypted, &keyset, Scope::new(&host)).await?; +``` + +## 8. An EQL type, with its column as the context + +An EQL type such as `TextEq` is one column's value, stored in a +PostgreSQL column of type `public.eql_v4_text_eq`. Its context is the +table and column, as an `Identifier`. The type stores the identifier in +its `i` field, so a reader takes it from the stored value. A reader that +knows which column it is reading passes the identifier as well. If the +stored identifier differs, the value is refused before any key is +fetched. + +Inside a record, the derive supplies the identifier from the record's +name scope and the field's name scope. None of this is written by hand. + +```rust +use eql_bindings::{v4::text::{TextEq, TextEqQuery}, Identifier}; + +let column = Identifier::for_column("users", "email")?; + +// Encrypt one value for the column. The identifier is the context, and +// `TextEq` stores it in `i`. +let stored: TextEq = "alice@example.com" + .encrypt_into_with_context(&keyset, Scope::new(&column)) + .await?; + +// Decrypt, taking the column from the stored value. +let email = String::decrypt_from(stored, &keyset).await?; + +// Decrypt, checking that the stored column is the one expected. A value +// from `users.name` is refused with `ContextMismatch` before any key +// is fetched. +let email = String::decrypt_from_with_context(stored, &keyset, Scope::new(&column)).await?; + +// A query for the column uses the same context, so its term matches. +let query: TextEqQuery = "alice@example.com" + .encrypt_into_with_context(&keyset, Scope::new(&column)) + .await?; +``` diff --git a/docs/plans/2026-10-25-json-tree-leakage-before-and-after.md b/docs/plans/2026-10-25-json-tree-leakage-before-and-after.md new file mode 100644 index 0000000000..dd54eb2c06 --- /dev/null +++ b/docs/plans/2026-10-25-json-tree-leakage-before-and-after.md @@ -0,0 +1,224 @@ +# The json_tree leakage profile, before and after #1363 + +**Date:** 2026-10-25. **Pull request:** #1362 (branch `test/json-tree-leakage-profile`), now based on #1363 (`feat/json-tree-derivable-tokens`). + +This note compares two versions of one test, and through them two versions of EQL v4's encrypted JSON column, `json_tree`. It is written for someone new to both. + +## What the test is + +A `json_tree` column stores each JSON document as a list of encrypted entries, one per node of the document, so PostgreSQL can answer queries over it without the key. The database cannot read a value, but it can see a great deal of structure, and `packages/eql/docs/reference/json-tree-leakage.md` (the **leakage page**) says in prose exactly what it learns. + +PR #1362 turns that page into a test, in `packages/stack-encrypt/tests/json_leakage/`: + +- The **profile**, `L` (`profile.rs`), is the page written as code: a function of the plaintext documents and queries alone that outputs what the page says the database learns. Every secret-derived value (a selector, a token, an ordering term) is replaced by an opaque integer that is equal exactly where the real bytes are equal. Each field of its output is one **clause** of the page. +- The **simulator** (`simulator.rs`) builds a fake column and a fake query log from `L`'s output and random bytes, with no plaintext and no key. +- The **distinguishers** (`distinguishers.rs`) are computations a curious database administrator could run on what the database holds and is sent: which entries share a selector, how long each ciphertext is, what a token finds when it walks the parent tags, and so on. Each returns an exact value, so a real world and a simulated one are compared for equality. +- The **positive control** runs every distinguisher on the real scheme (documents sealed by Stack Encrypt) and on the simulation. If any distinguisher tells them apart, the real scheme reveals something the profile, and so the page, does not state. +- The **calibration** checks the test can see anything at all. Each **mutant** (`mutants.rs`) is the profile with one clause dropped or coarsened; some distinguisher must tell each mutant's simulation from the real scheme. A clause no mutant tests is a clause nobody checked. + +#1362 was written against the format as it stood before #1363. #1363 changed the format. This note records what the port of the test found, and how the leakage changed. + +## The net, first + +The tables below grow from the old profile to the new one: more clauses, more distinguishers, more mutants. That measures the test, not the scheme. A longer profile means more of what the database sees is written down and held by a test. Measured as leakage, the format after #1363 discloses less, and less where it matters: + +- A read no longer sends any token above the node it asks for. Before, a read of `$.profile.address.city` sent `$.profile`'s token, a capability over that whole field in every row of the column, for the life of the column. Now it sends the leaf's token and nothing that covers a node above it. The `ancestor_links` distinguisher exists to hold this. +- The gates are gone. Each key step and array position below the head used to reach the server in the clear, as a selector or `#n:selector`. + +What is new is small. The self tag `x` is a fresh unlinkable name per entry that at rest says only that entries are distinct, which the entry count already said; a token the client sends links it, as a token always linked the parent tag. At the nodes a walk reaches, the element index was already disclosed by the gated walk's ordinals. Whether a node is a member or an element was disclosed only where selectors showed it, in an array that has two elements in some row. It is new for a node that is an only child in every row: before #1363 every child's token took one rule, and an only child's ordinal is 0 either way. The page now says so. That walk also covers fewer nodes than the old one, because no read sends a token above the node it names. A wildcard read's token count, bound and probes are a smaller form of what the plaintext gates showed. The last two sections set each item out. + +## The two formats, briefly + +Terms used below: a **selector** `s` is a keyed hash of a node's path, the same in every row. A **token** is a 16-byte secret for one node that lets the database find that node and walk the nodes beneath it. A **parent tag** `p` on an entry is `H8("p" ‖ iv ‖ t(parent) ‖ LE32(o))`: eight bytes derived from the parent's token, the child's **ordinal** `o` (its index if it is an array element, a keyed rank if it is an object member) and the row's random `iv`. The database enumerates a node's children by computing the parent tag of ordinals 0, 1, 2, … until one is missing. + +**Before #1363** (the format #1362 was written for, at `9a7ca372c`): + +- Each entry was `{s, c, p?, op?}`: selector, ciphertext, parent tag (absent on the root and, under the sealed root, on the top-level fields), ordering term (only at ordered paths). +- Every child's token was `H16("t" ‖ t(parent) ‖ s(child) ‖ LE32(o))`. A member's ordinal is a rank among its siblings' keys, which the client does not know for a row it has not read, so the client could not derive the token of anything below a top-level field except through array positions. +- A subtree read therefore sent one **head token** (the top-level field's, or the root's with the root open), and one plaintext **gate** per remaining step: the step's selector, or `#n:` with the array position `n` in the clear. The database walked from the head token through the gates (`json_tree_subtree_at`). Reading `$.profile.address.city` handed the database `$.profile`'s token: a capability over that whole top-level field, in every row, for the life of the column (#1360). + +**After #1363** (the format now, at `997c64b1e`): + +- Each entry is `{s, c, x, p?, op?}`. The new **self tag** is `x = H8("x" ‖ iv ‖ t(self))`, on every entry, the root and the top-level fields included. +- A member's token is `H16("t" ‖ t(parent) ‖ s)`, with no ordinal. An element's is `H16("t" ‖ t(array) ‖ s ‖ LE32(i))`, `i` its index: this is the old rule, unchanged, since an element's ordinal always was its index. The parent tag is unchanged. So the client derives any node's token from its path alone. +- A read sends `json_tree_subtree(doc, tokens text[], budget)` with the tokens of exactly the nodes it names: one for a path with no wildcard. A wildcard is expanded by the client to positions `0 … N − 1` plus a **probe** for position `N` of every array it expands; the **bound** `N` defaults to 64, so one wildcard level sends 65 tokens and two send `N² + N + 1` = 4,161, and a read past 8,192 tokens is refused. A probe that finds an element means the array is longer than `N`, and the client fails the read rather than return part of it. Gates and `json_tree_subtree_at` are gone. +- The database finds a token's node by its self tag, probes the ordinals under it by parent tag, and for each child it finds derives the child's token by testing the child's `x` against the member rule first and then the element rule. +- Past the **budget** (default 64 rows) with the root sealed, the database returns the root entry alone, whose ciphertext is the whole document, and the client evaluates the read over it. + +## Step 1: what failed when the old test met the new format + +The test was run unchanged on the merge of #1363 into #1362 (`848940081`). The failures, in the order they appeared, were the first evidence of what changed. + +1. **It did not compile.** Two `E0308` errors in `calibration.rs`, at lines 324 and 329: `JsonSubtreeKey::token_bytes()` now returns `Vec<[u8; 16]>`, and `JsonDocument::subtree` takes `&[Tag]`. *What it taught:* a read is no longer one token; it is a list. + +2. **With a throwaway two-character fix to compile it, 1 test passed and 6 failed.** Five panicked in the parser (`observe.rs:126`, "a base64 field is a string") before any distinguisher ran: the read's wire form changed from `{"t": "", "g": [gates]}` to `{"t": ["", …]}`. The sixth, `chain_is_the_crates_chain`, compares the harness's own walk with the crate's. For `$.a` under the sealed root, the old harness found `[(6, 1), (2, 1)]` and the crate `[(1, 0), (6, 1), (2, 1), (3, 2), (4, 2), (5, 3)]` (pairs are entry position and depth). *What it taught:* the crate now returns the named node itself at depth 0, found by its self tag, which the old walk could not identify. The old harness still found `$.a`'s two children, because the parent tag and the head token are unchanged; it stopped there because both children are members and a member's token lost its ordinal. In the column-wide run below, the old harness did reach depth 2 under array elements, whose rule did not change. The one test that passed, `the_order_reveals_the_shape`, uses no query: the attack that reads each row's shape off the stored order works exactly as before. + +3. **With the parser also patched to read the first token of the list, the positive control failed on exactly five distinguishers**, on the handcrafted "shapes, sealed root" column: `wire_fields`, `token_reach`, `token_derivability`, `gated_walk_results` and `transcripts`. The random-column run failed on `wire_fields` and `transcripts`, shrunk by proptest to two empty objects under an open root and four reads of `$.a`. *What it taught:* at rest, the only thing that changed is the new `x` field (`wire_fields`). Every other stored-form feature (ciphertext lengths, selector patterns, parent-tag presence, the stored order, projections, ordering terms, headers) still agreed with the old profile. Everything else that changed is in what a query sends and what a token reaches. + +4. **The page-as-written test fired six distinguishers instead of one**: `gated_walk_results`, `ordering_term_lengths`, `token_derivability`, `token_reach`, `transcripts`, `wire_fields`, where it expected exactly `ordering_term_lengths`. The jsonb key-order test still passed. + +5. **The calibration passed: all 34 mutants "caught".** *What it taught:* this is the most important lesson of the run. A calibration only means something once the positive control passes. If the profile is already told apart from the real scheme, every mutant of it is too, and "all caught" says nothing. `mod.rs` now says so under "Reading a failure". + +## The clauses, before and after + +The "before" column is the profile at `9a7ca372c`; the "after" column is the port at `839c0f6fd` (with `fa26cb540`, which only speeds one distinguisher up). A clause is a field of the profile's output, or a switch in `Clauses`. + +"Not measured" in the before column means the old profile had no such clause, for one of two reasons, and the row says which: the old format had no such thing to state (`x`, the hit rule as a rule, probes), or the old format disclosed it and the old test did not model it, so no distinguisher could see it (string folding, whose corpus was lower-case ASCII, and the budget, which the old `json_tree_subtree` also had). The second kind is the method's limit: the calibration proves the page accounts for everything the distinguishers measure, not everything the database sees, and a clause both omit is invisible to it. Each new distinguisher is a way of finding one. + +| clause | before (`9a7ca372c`) | after (port) | what changed and why | +|---|---|---|---| +| `EntryLeakage::selector` | which paths, how many nodes at each, equal across rows, elements share their array's | same | unchanged | +| `EntryLeakage::parent` | each node's parent, used to place the chain | same | unchanged | +| `EntryLeakage::step` | `Root`, `Member`, `Element(i)`: decides the ordinal, and in the old chain the token too | `Root`, `Member`, `Element(i)`: decides the ordinal (the `o` of the parent tag) only | the token rule moved to `rule` | +| `EntryLeakage::rule` | not measured (the old format had no such thing) | `Member` or `Element` for every entry that chains, `None` for the root and sealed-root top-level entries | new: the database tests each reached node against the member rule then the element rule, and learns which. Beyond the page as #1363 published it; this branch adds it | +| `EntryLeakage::head` | the head token an entry is (top-level fields under the sealed root, the root otherwise) | removed | a head is now named only inside a token name (`TokenName::head`); nothing at rest refers to it | +| `EntryLeakage::has_parent_tag` | absent on the root and, under the sealed root, the top-level fields | same | unchanged | +| `EntryLeakage::self_tag` | not measured (the old format had no such thing) | a fresh opaque name per entry | new: `x` on every entry. A fresh name per entry states that it is distinct within a row and unlinkable across rows; where a sent token links an entry the simulator writes its real self tag instead | +| `EntryLeakage::ciphertext_len` | AEAD overhead (29 bytes) + kind, child count, label, scalar | same | unchanged: `x` sits beside the ciphertext. It adds a fixed 12 base64 characters per entry, 19 with its key in compact JSON (`,"x":"…"`), 21 in PostgreSQL's `jsonb` text (`, "x": "…"`); #1363 measured +9.8% on a nested document and +9.4% on a flat one | +| `EntryLeakage::ordering` / `OrderingLeak::class` | equal values share a class, ordered by `ordering_ranks`; strings ordered by their bytes | equal values share a class; strings ordered by their folded encoding (Unicode 16 NFC, case and accents folded) | the code always folded; the old corpus held only lower-case ASCII, where the two agree. The page now says "folded", and the corpus holds `"Carol"`/`"carol"` and `"ál"`/`"al"` | +| `OrderingLeak::len` | **beyond the page**: 65 bytes for a number, `8 × (len + 1) + 1` for a string | on the page: 65 for a number, `8 × (n + 1) + 1` for a string of folded length `n` | #1363's page states it; it now counts the folded length | +| `Clauses::ordering_term_length` | on/off switch for the beyond-the-page length | removed | on the page now; its mutant (`ordering_term_length_constant`) still checks it | +| `Clauses::key_order` | a reading: UTF-8 byte order vs jsonb's length-first order | same | the page now says "byte order of their key names' UTF-8 encodings"; the reading test stays to keep that sentence load-bearing | +| `Clauses::string_order` | not measured (the old format had it; the old profile did not model it) | a reading: folded vs raw bytes | new, with a test that the raw-bytes reading is told apart | +| `Clauses::hit_rule` | not measured (the old format had no such thing) | on/off switch for the member-or-element rule | new, the one clause beyond the page as #1363 published it | +| `RowLeakage::{sealed_root, keyset, data_key, entries, projection}` | header flag, keyset, data key unique to the row, entries in depth-first order with members in UTF-8 key order, projection `q` | same | unchanged. `data_key` also names the `iv` that salts every `p` and `x` in the row | +| `GroupLeakage::{pairs, elements}` | `{s, vs}` pairs in walk order, nested by array element | same | unchanged | +| `QueryLeakage::Extract` | the selector of the path asked | same | unchanged | +| `QueryLeakage::Subtree` | `token: TokenName{head, positions}` (one head token, chained through leading array positions), `gates` (`Selector(s)` or `Slot(n, s)`, positions in the clear), `reach` (every descendant of the token's node, in every row), `named` | `reads: Vec` and `budget` | rewritten. See the next three rows | +| `ReadLeak::token` | (one per read, see above) | `TokenName{head, steps}`, each step `Member(s)` or `Element(s, i)`: one per concrete path, in the order the client sends them | the list is what the database receives; its length gives the bound away, its order places each token | +| `ReadLeak::probe` | not measured (the old format had no such thing) | whether the token is a probe | new; the database is not told, and can tell (see findings) | +| `ReadLeak::hits` / `ReadLeak::reach` | `reach`: descendants of the head's node; `named`: what the gates reached | `hits`: the entry the token names in each row, if any; `reach`: every descendant of it that chains from it, in each row | a token now names exactly its node; nothing above it. Under the sealed root the root's token reaches nothing below the root | +| `QueryLeakage::Subtree::budget` | not measured (the old read had a budget too; the old profile did not model it) | the `budget` argument | new; the fallback to the root entry is computed from it and the walk, so the database learns nothing new from it | +| `QueryLeakage::{Contains, Equals, Order}` | needle projection with `alt`; equality needle; selector and the bound's ordering term | same | unchanged | +| `Leakage::{key_tag_len, ordering_ranks}` | the key tag's length, the order of every ordering class | same | unchanged | + +## The distinguishers, before and after + +27 before, 35 after: 26 kept unchanged in meaning, 1 renamed, 1 removed (by the rename), 8 added. The walk-based ones were rewritten for the new chain, but what each measures is the same. + +| distinguisher | status | what it measures | +|---|---|---| +| `wire_fields` | kept | the wire keys of every row and entry (now `{c, op?, p?, s, x}`) | +| `entry_counts` | kept | entries per row | +| `parent_tag_presence` | kept | which entries carry `p` | +| `ordering_term_presence` | kept | which entries carry `op` | +| `ciphertext_lengths` | kept | every ciphertext's length, by position | +| `ciphertext_length_multisets` | kept | the same, order removed | +| `ciphertext_framing` | kept | the ciphertexts' version bytes, and how many pairs are equal (a deterministic cipher) | +| `selector_pattern_within_rows` | kept | which entries of a row share a selector | +| `selector_pattern_across_rows` | kept | which entries of the column share a selector | +| `parent_tag_equalities` | kept | pairs of entries sharing a `p` (expected none) | +| `headers` | kept | header fields, and equality of keyset, `iv` and key tag across rows | +| `projections` | kept | each row's `q`: grouping, pair order, selector and value-selector equality | +| `value_selector_partitions` | kept | per path, the rows grouped by value | +| `chain_head_runs` | kept | the runs after each entry with no `p`: each top-level field's subtree size | +| `selector_precedence` | kept | which of two selectors comes first across rows: sibling key order | +| `depth_recovery` | kept | an attack that reconstructs every row's depth sequence from the stored order alone | +| `token_reach` | kept | per read, row and token: the node it finds and everything its walk links, with parents and depths | +| `ordinal_patterns` | replaced by `member_order_shared_across_rows` | whether one token's objects give their members one order of ordinals across rows, reported only below a `2⁻⁴⁰` chance bound: members' ordinals are now a random permutation per row | +| `member_ordinals_follow_key_order` | kept | whether members' ordinals follow key order, reported only below a `2⁻⁴⁰` chance bound | +| `token_derivability` | kept | which reads' tokens the database can derive from which others' (now by the member rule and by the element rule at an index below 4, from the tokens that find a node in some row) | +| `transcripts` | kept | every query term with its tags named: determinism, shared selectors, needles; a read is now its token list and budget instead of a token and gates | +| `extraction_matches` | kept | which entries each `->` selector matches | +| `containment_matches` | kept | which rows each needle matches | +| `ordering_term_order` | kept | every ordering term's rank, stored and sent | +| `ordering_term_lengths` | kept | every ordering term's length | +| `ordering_matches` | kept | which entries each ordering bound holds for | +| `gated_walk_results` → `subtree_results` | renamed | what a read returns from each row: before, the walk through the gates; after, every token's node and subtree, or the root entry alone past the budget under the sealed root | +| `stored_lengths` | added | each row's and each entry's length in characters: sees `x`'s fixed 19 characters | +| `self_tag_equalities` | added | pairs of entries whose `x` equals another `x` or a `p` anywhere (expected none) | +| `token_counts` | added | how many tokens each read sends | +| `bound_recovery` | added | the `(levels, N)` an observer recovers from the count: 65 is one level at 64 and nothing else; 4,161 is two levels at 64 or one at 4,160 | +| `token_hits` | added | per read and row, which tokens (by place in the list) find a node, and where | +| `wildcard_positions` | added | for a one-level wildcard read: per row, which positions below `N` hold the rest of the path, whether the probe found an element, and whether the probe's find carries a selector the others do not | +| `hit_rules` | added | for every node a walk reaches, which rule its `x` matched: member, element, or neither | +| `ancestor_links` | added | whether the database can link each node a read names to its parent with any token it holds: the "no ancestor capability" check | + +## The mutants, before and after + +34 before, 44 after: 28 kept unchanged, 4 redefined for token lists, 2 removed, 12 added. + +| mutant | status | clause it drops | +|---|---|---| +| `selectors_all_distinct`, `selectors_per_row_only`, `positions_in_selectors` | kept | selector equality; column-wide; array positions folded | +| `entry_count_padded` | kept | the number of entries | +| `order_random_permutation`, `members_unsorted` | kept | the stored order; members in key order | +| `parent_tag_on_every_entry`, `parent_tag_on_no_entry` | kept | which entries lack `p` | +| `ciphertext_length_bucketed`, `sealed_root_length_hidden` | kept | ciphertext length | +| `value_selectors_all_distinct`, `value_selectors_path_only` | kept | value-selector equality | +| `projection_flat`, `projection_shuffled` | kept | element grouping and pair order in `q` | +| `ordering_terms_absent`, `ordering_terms_unordered`, `ordering_terms_all_distinct`, `ordering_term_length_constant`, `ordering_terms_per_path` | kept | `op` presence, order, equality, length, equality across paths | +| `member_ranks_follow_key_order` | kept | a member's ordinal is a keyed rank | +| `sealed_flag_flipped`, `data_key_shared`, `keyset_per_row` | kept | the header | +| `extraction_selector_fresh`, `queries_nondeterministic` | kept | `->` sends the stored selector; queries are deterministic | +| `needle_flat`, `needle_alt_dropped`, `bound_rank_random` | kept | needle grouping, `alt`, the ordering bound's rank | +| `tokens_per_row` | redefined | before: head tokens per row; after: a token finds its node in one row only | +| `parent_tags_unchained` → `tokens_find_nothing` | redefined | a token finds and links nothing | +| `token_reaches_named_nodes_only` → `token_reaches_its_node_only` | redefined | before: the head token reaches only the path asked (the narrower reach #1360 wanted); after: a token finds its node and links nothing below it | +| `position_tokens_unchained` → `tokens_not_chained` | redefined | a token with a step below its head is unrelated to its head's | +| `slot_positions_hidden`, `gates_dropped` | removed | gates no longer exist | +| `self_tags_absent`, `self_tags_linkable_across_rows`, `self_tags_per_selector` | added | `x` on every entry; salted by the row; distinct per entry | +| `hit_rule_uniform` | added | the member-or-element rule (the page fix) | +| `probe_reaches_nothing` | added | a probe that finds an element links its subtree (the page's exception) | +| `ancestor_token_sent` | added | no ancestor's token: the pre-#1363 read, which also sent the top-level field's token | +| `member_tokens_carry_ordinal` | added | a member's token has no ordinal: the pre-#1363 member rule, under which reads through a key step find nothing | +| `element_tokens_without_index` | added | an element's token carries its index | +| `probes_dropped`, `token_list_shuffled`, `token_list_padded` | added | a probe per expanded array; the list's order; the list's length | +| `budget_not_sent` | added | the budget, in the clear | + +## Calibration, before and after + +| | before (the profile at `9a7ca372c`, on the old format) | first run on the new format (step 1) | after the port (`839c0f6fd`, `fa26cb540`) | +|---|---|---|---| +| tests | 7, all passing, about 3 s (the PR measured 6.3 s for the binary) | did not compile; with throwaway patches 1 of 7 passing | 9, all passing, 11.3 s for the binary: the calibration 9.6 s, every other test under 0.5 s | +| positive control, handcrafted columns | 4 columns, no distinguisher separates | fails: 5 distinguishers separate | 4 columns, no distinguisher separates | +| positive control, random columns | 48 cases pass | fails on the first case (`wire_fields`, `transcripts`) | 48 cases pass | +| mutants caught | 34 of 34 | 34 of 34, meaningless (the control failed) | 44 of 44 | +| page-as-written test | exactly `ordering_term_lengths` separates | 6 separate | renamed `the_hit_rule_separates_it_from_the_real_scheme`: exactly `hit_rules`, `subtree_results`, `token_derivability`, `token_reach` | +| `member_ordinals_follow_key_order` | decided on the wide-objects column, `2⁻⁴⁰` bound | not reached | decided on the wide-objects column (`Some(false)`: members' ordinals do not follow key order), same bound | + +The ported handcrafted columns exercise every new mechanism: one-level reads at the default bound (65 tokens) and at bounds the rows overflow, a two-level read (7 tokens at a bound of 2), probes that find elements in every column (3, 3, 1 and 1 probe hits), a probe whose element no other read names (so `probe_reaches_nothing` is load-bearing), `$` under both root options, a read below a key step (`$.nested.deep`, which before #1363 needed a gate), and a read past its budget under the sealed root (3 rows answered with the root alone). The random columns draw bounds from {1, 2, 3, 64} and budgets from {0, 2, 64}. + +Two tests are new. `given_strings_ordered_by_their_bytes` holds the page's folding sentence: read as raw bytes, the profile is told apart by `ordering_term_lengths` and `ordering_term_order`. `a_read_gives_away_its_bound_and_its_probes` runs `$.items[*].price` and `$.items[*].tags[*]` on the real scheme over rows with 0, 3 and 70 items: the counts are 65 and 4,161, the bound is recovered, and in the 70-item row the database sees positions 0 and 2 … 63 holding a price, the probe finding an element, and the probe's find carrying a different selector from the others. + +## What the port found + +**One finding against the page as #1363 published it, fixed on this branch.** Nothing stored says whether a node is an object member or an array element (the design's decision 2, "no kind bit"). But to derive the token of each node it reaches, the database tests the node's self tag against the member rule and then the element rule, and the one that matches says which. So below any token it is sent, the database learns whether each node is a member or an element, and therefore whether each parent is an object or an array; for an element it also learns the index, which is the ordinal it was found at. Where selectors already show it (an array that has two elements in some row) this adds nothing; for a node that is an only child in every row, it does. The page said a token's holder can "see how the nodes beneath it nest, link each one to its parent, and derive the tokens of the nodes beneath". This branch adds: "It also learns whether each node beneath is an object member or an array element, and each element's index". `the_hit_rule_separates_it_from_the_real_scheme` shows the sentence is needed: without it, `hit_rules` separates the worlds, and so do the three features that break when a world tries to hide the rule while still matching the tokens a client sends (a read through a key step always sends a member-rule token). + +**One inaccuracy in a SQL comment, reported, and corrected by #1363.** `json_tree_subtree`'s comment in `packages/eql/src/v3/json_tree/functions.sql` said "the server cannot tell a probe from any other token". It cannot from a token's bytes. But the probe is always the last token at its level, the count gives the bound away, and a probe that finds something finds the element, whose selector differs from that of the leaf the path's other tokens find. The leakage page does not repeat the claim. #1363 corrected the comment in `b2a20abb9`: it now says the server "can pick it out". + +**One error in the old profile, which its corpus could not show.** It ordered strings by their raw bytes. The code folds case and accents before ordering, so `"Carol"` and `"carol"` share a term, and the term's length counts the folded form. The old corpus held only lower-case ASCII, where the two agree. The port models folding, the corpus now holds names that fold, and a test holds the page's sentence. + +**The old page's three findings are closed.** The ordering term's length, equal values at two ordered paths sharing a term, and UTF-8 byte order of keys are all on the page now. Each keeps a mutant or a reading that the calibration catches. + +**The tension stands.** #1358's read check, kept by #1363 (decision 8), refuses a subtree's rows unless they sit at consecutive positions `j`. That consecutiveness is what #1357 wants gone from the stored order. Both cannot hold as written; it is the owner's decision. + +## What the database learns now that it did not before + +- **The self tag, at rest: nothing.** Every entry carries 8 more bytes (12 base64 characters; 19 more characters per entry in compact JSON, 21 in `jsonb` text; about a tenth of a document's size). The tag is salted by the row's random `iv`, so no two are equal in a column (`self_tag_equalities` is empty in both worlds), and since every entry has one, its presence marks none. +- **The self tag, under a token: the named node itself.** Before, a head token let the database find the head's children, not the head; it never identified the node a token belonged to (the old walk recorded its children's parent as unknown). Now a token finds its node directly, by `x`, in every row that has it. +- **The token count, and with it the bound.** A read with no wildcard sends 1 token. One wildcard level sends `N + 1` (65 at the default), two send `N² + N + 1` (4,161), and 8,192 is the cap. 65 identifies `N = 64` uniquely; 4,161 is either two levels at 64 or one at 4,160, and which tokens find nodes settles it. +- **The probes.** Per row, whether each expanded array is longer than `N`, and, where a probe finds an element, that element's whole subtree, including the siblings of the path asked for, although the read then fails. The probe is identifiable by its place in the list and by what it finds. +- **Which elements hold the rest of the path.** For `$.items[*].price`, per row, which positions below `N` have a `price`. Before, the gated walk returned the same rows, so the result was visible; now each position also has its own token, column-wide. +- **Member or element, for every reached node** (the finding above). +- **The budget**, in the clear. The fallback to the root entry is computed by the database from the walk it already sees, so it learns nothing more from it; someone who sees only the results learns, from a row answered with its root alone, that the read found more than `budget` rows there. + +## What the database no longer learns + +- **An ancestor's capability in every row.** Before, any read below a top-level field sent that field's token, a capability over the whole field's structure in every row for the life of the column, and under an open root every read sent the root's token, the whole column's shape. Now no token over any node above the one read leaves the client unless that node is itself read. `ancestor_links` is the check: in the ported worlds a named node's parent is linked only where another read named one of its ancestors, and the mutant that sends the pre-#1363 head token is caught by it, by `token_reach` and by the token counts. +- **The gates.** Before, a read sent the selector of every step below the head, and every array position in plaintext (`#n:`), whether or not a row had the path. Now no selector is sent with a read: the database learns the selector of the node read only from the entries the token finds. Array positions travel only inside tokens; the database still infers a found node's position from the stored order (#1357), and, for a wildcard, from the token's place in the list. +- **The head token.** Reading `$.profile.address.city` sends the city leaf's token and nothing that covers `$.profile`. Under the sealed root the root's token, sent only for a read of `$`, finds the root entry and nothing beneath it, since the top-level fields carry no parent tag. + +Everything at rest other than `x` is unchanged: shape through the stored order, parent structure, sibling key order, selector equality across rows, value-selector equality, ciphertext lengths, ordering terms with their lengths, their equality across ordered paths and their shared prefixes, and the header. + +## After review + +A review of the port (2026-10-25) found one disclosure that both profiles missed, and a set of gaps in the method. None of them changes the comparison above, since the missed disclosure is the same before and after #1363. + +- **The ordering terms' shared prefixes.** A CLLW OPE term is a carry byte, then one byte per plaintext bit (the PRF of the bits before it, plus the bit at weight 128, plus a carry). So two terms agree to within one up to the first bit their values' encodings differ in, and differ by about 128 there. The database reads that bit off the stored terms exactly. For numbers it is their signs and binary exponents. The page stated the disclosure in bytes, and the profile had listed it as out of reach ("not an exact function of the plaintexts", which is true of the byte prefix and not of the bit). Its simulator drew terms with no prefix structure, so nothing could see the omission. It is now a clause (`Leakage::ordering_prefixes`), with a distinguisher (`ordering_term_prefixes`) and a mutant (`ordering_prefixes_hidden`), and the simulator builds CLLW-shaped terms. The page's sentence now says bits, and what they mean for a number and a string. +- **New checks on the method.** `cross_kind_equalities` compares values across kinds (a token equal to a selector, say), which every other feature names apart. `term_fields` checks the field names inside `q` and every query term, which the parser would otherwise drop unread. `token_derivability` tries the element rule up to index 64 or the longest token list, not only below 4. +- **Four clauses with no mutant** now have one: `key_tag_shortened`, `order_selector_fresh`, `element_ordinals_reversed`, `parents_lifted`. +- **The corpus.** The random columns hold big integers, floats, strings that fold, and non-scalars at ordered paths. They order numbers or strings, and run 256 cases instead of 48. A fifth handcrafted column orders numbers of both signs and many magnitudes, and holds two integers past 2⁵³ that share a term. +- **Decided by the owner, and now on the page and in the profile.** At a path ordered over numbers and strings both, the order between a number and a string depends on the column key and is not jsonb's; within each kind the order is the values'. The two kinds' terms are under different keys (the order space's salt names its domain), so they show which leaves are numbers and which are strings, and the strings sort as one block that the key places below the numbers, between the negative and non-negative ones, or above them. The profile states the kinds and the within-kind order and leaves the placement to the key; the calibration simulates each placement, and the mutant fixing jsonb's numbers-first order (`mixed_kinds_jsonb_order`) is caught. A number's equality under its term is as a 64-bit float, held by the reading `NumberOrder::Exact`. The shared prefix is CLLW's known profile, and a scheme that hides it is planned for a later version. + +After the review and the owner's decisions: 38 distinguishers, 50 mutants, 12 tests. diff --git a/docs/plans/2026-10-25-stack-encrypt-packaging.md b/docs/plans/2026-10-25-stack-encrypt-packaging.md new file mode 100644 index 0000000000..94aab09994 --- /dev/null +++ b/docs/plans/2026-10-25-stack-encrypt-packaging.md @@ -0,0 +1,435 @@ +# Stack Encrypt packaging and public names + +Dated 25 October 2026, with updates on 27 October, 7 November, and 8 +November 2026. The last check was against `next` at commit `e4990e49b`. +This recommendation for review accompanies the +[implementation plan](2026-10-24-stack-encrypt-api-plan.md). + +## Contents + +- [Status](#status) +- [Summary of recommendations](#summary-of-recommendations) +- [Terms used in this document](#terms-used-in-this-document) +- [Facts this proposal relies on](#facts-this-proposal-relies-on) +- [Ownership rule](#ownership-rule) +- [Proposed packages](#proposed-packages) + - [Crates that stay as they are](#crates-that-stay-as-they-are) + - [Modules, not more crates](#modules-not-more-crates) + - [Why the format crate is needed](#why-the-format-crate-is-needed) +- [Dependency direction](#dependency-direction) + - [Providers as optional features](#providers-as-optional-features) +- [What moves out of Vitamin C](#what-moves-out-of-vitamin-c) + - [Frames and codecs](#frames-and-codecs) + - [Normalisation and index adapters](#normalisation-and-index-adapters) + - [Context encoding](#context-encoding) +- [Retire AsyncCipher](#retire-asynccipher) +- [Recommended public glossary](#recommended-public-glossary) + - [Spellings already agreed](#spellings-already-agreed) + - [Definition, layout, seal, and open](#definition-layout-seal-and-open) + - [Ciphertext types in the format crate](#ciphertext-types-in-the-format-crate) +- [JSON names by role](#json-names-by-role) + - [Notes on the JSON names](#notes-on-the-json-names) +- [Implementation order and acceptance](#implementation-order-and-acceptance) + +## Status + +This document proposes boundaries and names. The proposals are not +implemented APIs or accepted renames. The naming review of 8 November +2026 judged them. The plan's [Names decided in the naming +review](2026-10-24-stack-encrypt-api-plan.md#names-decided-in-the-naming-review) +records the outcome, and the glossary below matches it. The JSON +operation contract is live, in use as the release candidate Go +`v0.1.0-rc.3`. + +## Summary of recommendations + +- Stack Encrypt owns the application value model and its execution. + Vitamin C keeps the reusable cryptographic primitives. +- Add one new crate, `stack-encrypt-format`, and rename `stack-kms` to + `stack-zerokms`. Use modules, not crates, for the other boundaries. +- Retire Vitamin C's `AsyncCipher` trait. +- Adopt the public glossary for Rust. Keep the merged Go and SQL names for + JSON. + +## Terms used in this document + +| Term | Meaning | +| --- | --- | +| Context | Data that a ciphertext is tied to, such as a column name or a row ID. Decryption needs the same context. See [Context and AAD](2026-10-24-stack-encrypt-api-plan.md#context-and-aad) | +| AAD | Additional authenticated data: data that encryption checks for one ciphertext, but does not encrypt. Stack Encrypt builds it from the context. See [Context and AAD](2026-10-24-stack-encrypt-api-plan.md#context-and-aad) | +| Stored format | What is written to the database, as Go `v0.1.0-rc.3` writes it. See [the stored-format decision](2026-10-24-stack-encrypt-api-plan.md#the-stored-format-stays-compatible-with-go-rc3) | + +## Facts this proposal relies on + +- `encrypt_as` is public on `next`. The structural `decrypt_into` is + public in `target::legacy`. `StackCipherText` remains for the tree API, + whose methods are `encrypt_tree` and `decrypt_tree`. +- #1404 implements `Ciphertext`, `EncryptInto`, `DecryptFrom`, + `OpaqueEncode`, `OpaqueDecode`, `target::EncryptTarget`, and + `target::DecryptSource`. #1504 adds the derives with those names. #1503 adds `OpaqueBlob`. Both +are open for review. No crate has moved. No rename below is implemented. +- #1501 moves the Rust crates to Vitamin C 0.9, and re-exports `Buffer`, + `ProtectedRef`, and `AsProtectedRef` from the crate root. +- #1403 bumps `stack-kms` to 0.2.0 on crates.io. So the proposed rename to + `stack-zerokms` renames a published crate. The rename also touches the + crate's release-plz version group (`release-plz.toml`, + `release-plz.yml`), the Go guest, the EQL encryption test crate, and the + `stack_encrypt::kms` re-export in `lib.rs`. The naming review of 8 November 2026 did not decide it. It belongs to the crate layout question. The plan keeps that question + open. +- From 7 November 2026, the stored format must not break. Moving codecs + and adapters between crates must keep the bytes that Go rc.3 writes. + +## Ownership rule + +Stack Encrypt owns the application value model and its execution. That +means turning owned Rust values and dynamic values into ciphertext, +structured targets, and search operands, and reconstructing plaintext. +Vitamin C owns reusable primitives for cryptography and protected memory. +An ordinary Stack Encrypt user should not have to import Vitamin C +encryption traits to implement an application type. + +Moving code should remove duplicate abstractions. Moving code should not +keep both public surfaces under new names. + +Dan's rule of 7 November 2026 applies. Code and APIs may change in ways +that break callers, because this is a prototype. The stored format may +not. Before deleting +dependencies upstream, review the other consumers of Vitamin C that use +them. + +## Proposed packages + +| Package | Responsibility | +| --- | --- | +| `stack-encrypt` | The public Rust API; traversing and reconstructing values; target declarations and plans; context and scope roles; normalisation and adapters for searchable targets; plans; batching; JSON tree execution; and validating and executing dynamic definitions | +| `stack-encrypt-derive` | Derive macros that generate the same declarations and plans a user can write by hand. `stack-encrypt` re-exports the derives | +| `stack-encrypt-format` (new) | Pure data representations and codecs shared by the engine and the bindings: frame primitives and the required scalar representations, the stable format of stored blobs, parsing and encoding of the ciphertext envelope, and validated Base64 and Base85 text. No key requests and no execution runtime | +| `stack-zerokms` (the current `stack-kms`, renamed) | The ZeroKMS protocol client, authentication integration, native keysets, request types for the key request items, and responses. Not the neutral abstraction over several providers | +| `eql-bindings` | EQL storage and query types by version, JSON serialisation compatible with SQL, the catalog, and Stack target adapters. Stays downstream of the engine | +| Vitamin C crates | Protected memory; randomness; AEAD and key operations on bytes; HMAC, PRF, and ORE algorithm primitives; and reusable canonical encoding of context | + +The abbreviations in the last row are: + +- AEAD: authenticated encryption with associated data; +- HMAC: hash-based message authentication code; +- PRF: pseudorandom function; +- ORE: order-revealing encryption. + +### Crates that stay as they are + +Keep `stack-auth` and `stack-profile` separate, because they have +consumers outside encryption. Keep `stack-guest-abi` for the calling +convention between the host and the guest. Neither the application binary +interface (ABI) nor the Go host should own a second model of target +policy. + +Put the formal dynamic contract, its schemas, and its conformance fixtures +beside Stack Encrypt. The implementation of the dynamic contract uses the +same plan types and validation as static Rust. + +### Modules, not more crates + +At first, use modules for the remaining boundaries. In particular, do not +create separate crates for execution, JSON policy, queries, context, or +provider traits only so that each concept has its own crate. + +### Why the format crate is needed + +The format crate has a concrete consumer. EQL's wire types now work +without EQL's optional `stack-encrypt` integration. Those wire types need +shared encoding types without depending on an encryption client or +runtime. + +- Put Serde, schema, and TypeScript support behind features, where + practical. +- Define the trait implementations beside the types the crate owns. + Otherwise Rust's orphan rule forces downstream crates to duplicate + wrappers. The orphan rule says an implementation must be in the crate + of the trait or of the type. +- Re-export the ordinary format types through Stack Encrypt, so users + normally need only that one dependency. + +The format crate is one implementation with separate formats. Each of +these has its own contract and versioning requirements: blob storage, the +transport to and from the guest, and ciphertext envelopes. Sharing code must not +silently turn the Serde mapping for short-lived transport into the stored +blob format. + +The format crate does not add a way to store arbitrary internal `Node` +trees. Structured outputs still use their explicit target layout and +ordinary Serde composition. + +## Dependency direction + +In the diagram, an arrow points from a crate to a crate it depends on. + +```mermaid +flowchart TD + App[Application / Rust or guest adapter] --> EQL[eql-bindings] + App --> Engine[stack-encrypt] + EQL -->|optional target integration| Engine + EQL --> Format[stack-encrypt-format] + Engine --> Format + Engine --> Derive[stack-encrypt-derive] + Engine -->|optional ZeroKMS adapter| KMS[stack-zerokms] + Engine --> Vitamin[Vitamin C primitives] +``` + +- The derive crate emits Stack paths. The derive crate does not depend on + the engine as a normal runtime dependency. +- No Vitamin C primitive depends back on Stack Encrypt. +- `stack-zerokms` does not depend on the engine. +- The provider traits belong in `stack_encrypt::provider`. An adapter + that Stack owns implements them with the ZeroKMS client. This avoids a + dependency cycle between the engine and the client. + +### Providers as optional features + +Make ZeroKMS an optional provider feature, separate from the HTTP feature. +Then a different provider does not bring its protocol into the core +contract. Keep support for injected providers, and for guest and native +builds. + +Data key support is the base capability. Index key support, resolving +named keysets, and claims stay explicit optional capabilities. A +required capability that is not supported fails before key I/O, that is, +before any request to the key provider. Future provider adapters can +become separate downstream crates when needed. Do not design invented AWS +or Vault keysets now. + +Do not re-export EQL from Stack Encrypt, because EQL's target integration +already depends on Stack Encrypt. Applications import their EQL types +explicitly. + +## What moves out of Vitamin C + +Move these parts into Stack's value, target, and plan layers: + +- the visitors for plaintext and ciphertext that applications use; +- structural nodes; +- the value conversion traits and their derives; +- tree walking; +- collection composition; +- the application encryption helpers. + +Keep advanced extension points public only where people who implement +targets need them. These extension points are not part of the normal API +at the crate root. Internal nodes do not become a second public type for +opaque ciphertext. + +### Frames and codecs + +Move the generic frame code and the codecs that Stack needs into the +format crate. Stack owns the stored blob format and its compatibility +promise. + +This refines the earlier recommendation to reuse Vitamin C's frame codec. +Reuse its implementation, with a lossless mapping to storage, but change +who owns it in the long term. Coordinate this handover under +[Vitamin C #519](https://github.com/cipherstash/vitaminc/issues/519). Keep +that issue's work on the format specification and the fixtures. This +proposal has not changed any upstream issue or repository. + +### Normalisation and index adapters + +Also move the normalisation, PRF, and ORE adapters that understand Stack's +logical values, traversal, targets, or query semantics. Keep the +independent cryptographic algorithms below them in the dependency graph. + +The current manifests of `vitaminc-normalize`, `vitaminc-prf`, and +`vitaminc-ore` depend on `vitaminc-aead`. Normalisation even uses the +physical scalar types of `vitaminc-aead`. So moving only the encryption +traits would leave a dependency back to the old value model. + +As part of the move, separate primitive inputs from application adapters. +Do not make Vitamin C depend on Stack to get the code to compile. + +### Context encoding + +Keep the construction of canonical context bytes in `vitaminc-context`, +where independent algorithms use it. Stack owns the semantic roles and the selection rules: scopes, bindings, +the query context, the stored context, and the required parts. Stack reuses that canonical encoding +instead of inventing a second encoding that is not compatible. Provider +policy stays a separate role. + +## Retire AsyncCipher + +Recommendation: remove Vitamin C's `AsyncCipher` trait and its helpers for +executing application encryption, as the Stack executor takes over that +work. `AsyncCipher` is the Vitamin C trait that seals and opens leaves +asynchronously. Do not add a replacement public async cipher trait in +Stack that covers every case. + +Stack already plans and groups the remote key operations, and then runs +the cryptography locally and synchronously. Stack's current `MintedKeys` +and `BoundKeys` implementations use synchronous operations of the leaf +cipher. `AsyncCipher` models a different place to put the asynchronous +work. The asynchronous boundary that matters is the provider and the +public pending operation, with Stack controlling the batching. + +Stack does not use `AsyncCipher`. Vitamin C does use it, in these places +in Vitamin C 0.8.0: + +- `aead/src/seal.rs`, `context.rs`, `typed.rs`, `walk.rs`, and + `normalize/src/terms.rs` expose or use async helpers; +- `aead/src/lib.rs` re-exports the trait publicly; +- `aead/src/encrypt_sink.rs` has an `AsyncCipher` bound and imports + `seal_all_async`; +- the tests in `normalize/tests/known_answers.rs`, and the tests of the + modules above, implement the trait. + +This inventory was taken against 0.8.0. `next` has used 0.9 since #1501, +so the inventory must be checked again before the work starts. To retire +the trait: + +1. Move the tests that cover batching, ordering, failures, and + reconstruction with the code they test. +2. Delete the retired trait and its helpers. +3. Audit external consumers before the upstream release. + +Where useful, separate the internal capabilities for sealing leaves and +opening leaves. Do not keep implementations that reject half of a +combined trait. + +## Recommended public glossary + +| Name or path | Meaning | +| --- | --- | +| `Cipher` | The connection, with credentials and the key provider. Replaces `StackCipher`. Decided on 8 November 2026; the clash with Vitamin C's `Cipher` trait is accepted | +| `Keyset` | The connection bound to one resolved keyset, which encrypt and query calls take. Replaces `KeysetCipher` | +| `CipherRef<'c, K>` | One borrowed value for both paths: a connection and an optional keyset ID. Replaces the `CipherScope` trait and the `dynamic::Scope` enum | +| `Ciphertext` | One opaque encrypted value with a specified storage envelope. Replaces the public use of `StackCipherText = Node` | +| `OpaqueBlob` | Explicit adapter that serialises a whole owned value | +| `EncryptInto`, `DecryptFrom` | Convenience traits for encryption directed by the target and decryption directed by the destination, with variants that take context | +| `OpaqueEncode`, `OpaqueDecode` | Traits that represent a value as a single ciphertext | +| `target::{EncryptTarget, DecryptSource}` | Declaration traits. The matching derives are re-exported at the crate root | +| `Plan` | A record's declaration as data, built once, shared by the static and dynamic paths. Built by `Plan::scope(..).fields(..)`. Decided on 8 November 2026; `TargetDefinition` is dropped | +| `Scope`, `Bind` | The context argument's two kinds of part, as the plan has them. Neither selects a keyset. The chain they build is the context input; there is no separate type | +| `Query`, `Stored` | The two marker traits on term types: a value a query sends, and a stored index term. Today `op::QueryTerm` and `LabelledTarget` | +| `Op` | The public dynamic operator enum, today `OpSpec` | +| `Plan`, `Planned` on the wire | The two shapes a binding sends: a serialised `Plan` alone for checks, operator lists, and query plans, and a serialised `Planned` for encrypt, query, and decrypt. There is no `Request` type | +| `encoding::{Base64Text, Base85Text}` | Validated encodings of arbitrary bytes. An EQL payload's key header `h` is Base64 and its ciphertext `c` is Base85; a bare ciphertext as text is Base64. Vitamin C owns them, decided on 8 November 2026, re-exported by Stack Encrypt and EQL. Which Vitamin C crate is still to be confirmed, probably a types crate that also holds key types | +| `encoding::Base64Ciphertext` | The validated, encoded representation of an opaque ciphertext, and a supported field target. Valid encoding alone is not enough | +| `provider` | Neutral provider contracts and capability bounds | +| `provider::zerokms` | The ZeroKMS adapter and the surface for its claims, including `Claim` and `ResolvesClaims` | +| `dynamic` | Loading versioned plans, discovering capabilities, and executing through the common engine | + +### Spellings already agreed + +Keep these agreed spellings: + +- `encryption_plan()` +- `Planned::new(&plan, value)`, for a value under a plan that is data +- `encrypt` and `encrypt_with_context`, where the field reference or the plan fixes + the output type +- `encrypt_into` and `encrypt_into_with_context`, where the caller names + the output type +- `decrypt_from` and `decrypt_from_with_context` + +There is no `using` method. A typed query starts from the field reference. + +Keep the direct `cipher.decrypt` and `decrypt_with_context`. As already +agreed, remove `.encrypt` on plaintext and the redundant `encrypt_as` and +`decrypt_as`. The public `decrypt_into` is already removed, with +`target::legacy`. + +### Definition, layout, seal, and open + +The naming review chose `Plan` for the configured public contract. Use +`Layout` +only for the advanced internal concept of composition, where that +distinction is needed. A layout does not name a plaintext document or a +stored ciphertext. + +Name low-level operations on bytes `seal` and `open`. Keep the words +"encrypt" and "decrypt" for the public operations on application values. + +### Ciphertext types in the format crate + +Keep the ciphertext representations in the format crate independent of +traits. Stack implements its own target traits for those types. Plain +encoded text is not itself an encryption target. Constructing a +ciphertext wrapper must validate both layers: the encoding and the +ciphertext. Avoid a public string constructor without checks. + +## JSON names by role + +Keep the existing EQL package and its version modules. The merged public +Go surface is `eql.JSONSearch`, `JSONSearchQuery`, `JSONSearchLeafQuery`, +and `JSONEntry`, configured through `JsonSearch`. In SQL, the names are +`eql_v4_json_search`, `query_json`, `query_json_leaf`, and +`eql_v4_json_entry`. The prepared Go objects are `encrypt.JSONSelection` +and `JSONRead`. + +The naming review of 8 November 2026 kept the current `JsonTree*` names. +The table below is the proposal the review rejected. It stays here for +the record. + +Its `JsonTree*` names describe the handwritten Rust adapters, not the +registered Go target. The working Go and SQL surface does not need +renaming to match this glossary. Do not rename it for that reason. Later +Rust renames must keep the frozen dynamic IDs. + +| Working or current name | Recommended name | Role | Home | +| --- | --- | --- | --- | +| `JsonPlaintext` | `JsonPlaintext` | Adapter for owned plaintext | `stack_encrypt::json` | +| `JsonOptions` | `JsonTreeOptions` | Validated policy for the tree target | `stack_encrypt::json` | +| `JsonSelection` | `JsonSelection` | Proposed result of a plaintext selection | `stack_encrypt::json` | +| `JsonTreeDocument` | `EncryptedJson` | Stored EQL encrypted document | `eql_bindings::v4` | +| `JsonTreeEntry` | `EncryptedJsonEntry` | Extracted encrypted entry | `eql_bindings::v4` | +| `JsonTreeSubtree` | `EncryptedJsonSubtree` | Encrypted subtree result | `eql_bindings::v4` | +| `JsonTreeQuery` | `JsonContainmentQuery` | Query operand for containment and for a value at a path | `eql_bindings::v4` | +| `JsonTreeLeafQuery` | `JsonOrderingQuery` | Query operand for ordering | `eql_bindings::v4` | +| `JsonTreeSelector` | `JsonSelector` | Encoded path selector | `eql_bindings::v4` | +| `JsonSubtreeKey` | `JsonWalkRequest` | Walk token held by the client, and its binding to the request | Engine type, with a typed EQL adapter | + +### Notes on the JSON names + +The review kept `JsonTreeQuery` as the operand for both containment and +equality at a path. An operation and its wire operand do not need the +same name. The internal engine types keep their names too. + +## Implementation order and acceptance + +1. Specify and validate the Go JSON and opaque storage contracts. Both + are now implemented. Freeze the JSON and search semantics after the cascade + and the exact fixtures. "Post-cascade" means as they are after #1379. + That change made each container's tag cover the tags of its children. + Replace the temporary Go module pins of Vitamin C for the final Go + v0.1.0 release. +2. Complete the outstanding Go match configuration, and close the gaps in + JSON reads and conformance. Short whole-word matching is implemented in + EQL. Its leakage and its compatibility with the stored format still need explicit + acceptance for that release. +3. Set up the shared format crate. Move the + value model, traversal, and the normalisation and index adapters that + depend on it into Stack. Keep the frozen encodings and an acyclic + graph. Move tests with their code. +4. Complete the neutral provider extraction and the renaming of the + protocol package. Then retire Vitamin C's surface for asynchronous + application execution. The policy and routing contracts that Go needs + must be handled before the final Go v0.1.0 release. +5. Complete the public Rust trait and derive names, imports, and + executable examples. The naming review renames four things in the released Go API. `Client` + becomes `Cipher`. The keyset-bound `Cipher` becomes `Keyset`. The + `context=` tag becomes `scope=`. `Extend` becomes `Scope`. And + `ContextLabel()` goes. Nothing + else here renames it or reinterprets stored data. The changes must not require customers to + re-encrypt or reindex. + +Acceptance includes: + +- an acyclic Cargo graph; +- an EQL build of the wire types only, without the engine; +- engine builds without ZeroKMS and without HTTP; +- native and guest builds; +- the plan's Rust examples compile; +- the behaviour tests that moved; +- shared fixtures for formats and operations across Rust, Go, and SQL. + +Full improvements to timing and memory clean-up remain follow-up work. Dan's priority of 7 November 2026 puts the stored +format first. Record only the +guarantees that are true. + +This document does not claim any implementation changes, tests of the +proposed API, code moves, or upstream removals. diff --git a/docs/plans/2026-10-31-stack-encrypt-conformance.md b/docs/plans/2026-10-31-stack-encrypt-conformance.md new file mode 100644 index 0000000000..9471adb85e --- /dev/null +++ b/docs/plans/2026-10-31-stack-encrypt-conformance.md @@ -0,0 +1,326 @@ +# Stack Encrypt cross-language conformance + +Date: 2026-10-31. Status: scalar, declaration, initial runtime, read, context, EQL/JSON, lifecycle, value/refusal/raw-frame and fresh artifact exchange slices implemented; existing value-kind, query-operator and context-field fixtures enrolled. Python/TypeScript enrollment, JSON Schema files, protocol version identifiers, released-version combinations (first, Go rc.3 data read by this checkout) and release gates remain. The complete contract is not frozen. + +This work is stacked on [PR #1404](https://github.com/cipherstash/stack/pull/1404), +at `b684a217e2da629c762efa70fac958ec7e21646a`. It follows the accepted +[SDK principles](../sdk-design-principles.md) and the interoperability deliverable +in [the API redesign](https://github.com/cipherstash/stack/pull/1365). + +## Objective + +Equivalent declarations and operations have the same meaning in native Rust, +Go, Python, and TypeScript. SDKs retain idiomatic APIs and find errors at the +earliest stage their languages permit. Encryption and semantic validation stay +in the shared Rust engine. + +Python bindings are underway; TypeScript bindings are planned. Neither runner +is present in this checkout. Do not report their conformance as passing or +assume they will use Go's WASI backend. Native and WASM backends implement the +same semantic contract and have additional lifecycle tests of their own. + +Vitamin C's transport and storage codecs are dependencies of this contract. +Reference their versions and vectors rather than copying their specifications. +Codec agreement alone does not prove declaration or operation agreement. + +## Approach and order + +1. **Define the layers.** Specify value representation, declarations, operations, + persistence/SQL, binding lifecycle, and language SDK mappings separately. + Keep public SDK syntax distinct from the engine's data grammar and from the + test corpus format. +2. **Inventory the implemented profile.** Map existing tests to requirements, + identifying covered, partial, and missing evidence. Document current `next` + behavior and explicit differences from plaintext SQL. Proposed context roles + and future declarations must not silently become requirements of this profile. +3. **Create one portable corpus.** Give cases stable IDs, required capabilities, + typed inputs, declarations, operations, and expected values or diagnostics. + Use text for integers and other values JSON cannot carry losslessly. Run the + same cases in Rust and Go first; enroll Python early and TypeScript when its + binding exists. Unknown versions, operations, or required cases must fail. +4. **Test SDK mappings separately.** Exercise real host values and public SDK + declarations, not just pre-encoded frames. Cover TypeScript number/bigint, + undefined/null, byte arrays and timestamps; Python integer ranges, bool/int, + bytes/text, decimals and timezones; Go integer widths, pointers and typed nil. + Make unsupported or lossy conversions explicit refusals. +5. **Use independent evidence.** Combine fixed vectors, cross-language writes + and reads, plaintext SQL oracles, malformed requests and tampering. Compare + randomized ciphertext by opening it and querying it, not by byte equality. + Instrument test key providers for batching and validation-before-I/O checks. + Verify cleanup, cancellation and ownership separately for each backend; + do not promise equivalent erasure of host-language values. +6. **Gate claims in CI.** Record corpus/profile, SDK, engine, backend and supported + capabilities. Every required case must run; an absent guest or unknown case + must not create a green conformance result. Keep a fast credential-free lane, + with database, live-provider and cross-version lanes alongside it. Version + expected behavior and require review for changes to frozen expectations. + +## First slice + +The initial `record-scalars-v1` test profile is intentionally small. It covers +typed scalar boundaries, a one-field record declaration, exact equality terms, +cross-opening native scalar leaves through the Go record path, wrong-context +opening, and rejected query inputs. It uses the existing deterministic test +provider, with public test keys only. + +The Rust runner exercises both the owned scalar API from #1404 and dynamic +record/query execution. The Go runner exercises the internal record interface +used by generated SDK code. This proves engine/binding behavior; it does not +replace tests of generated declarations or certify the complete Go SDK. + +The shared corpus and runner contract live in +[`conformance/stack-encrypt`](../../conformance/stack-encrypt/README.md). +The coverage map there identifies existing evidence and remaining gaps. + +## First-slice checkpoint + +Implemented on `feat/stack-encrypt-conformance`, based directly on #1404. +The corpus has eight positive cases and three query refusals. Local validation +passes for native Rust, Go WASI, and fresh Go-to-Rust artifact exchange through +`mise run test:conformance`. Rust clippy, the enabled Go linters, and the CI wiring +checks also pass. The work is in draft [PR #1460](https://github.com/cipherstash/stack/pull/1460), +targeting #1404's branch. Local validation is distinct from hosted CI status. + +The first profile includes frozen typed frames and equality terms, frozen native +ciphertexts, fresh native scalar and record round trips, and forbidden retrieval +under a wrong context. The implementation adds no production API changes. +SQL requirements and Python/TypeScript runners remain open. + +## Declaration checkpoint + +The [declaration grammar](../../conformance/stack-encrypt/declaration-grammar.md) +records the implemented syntax and semantic rules, including accepted enum +aliases, defaults, context composition, all 22 kinds against five scalar indexes, +null policies and target-capability refusal. Its cases run in native Rust +and Go WASI without a cipher. Native Rust checks selected normalized plan +observations; Go's existing checker exposes acceptance and diagnostics only. + +The profile fixes `NoTargets`. EQL resolver/catalog behavior and full JSON/SQL +operation semantics remain later profiles. Malformed frames explicitly distinguish +the native parser's diagnostic from the WASI boundary's earlier refusal. + +Local validation passes for both profiles, fresh ciphertext +exchange, Rust clippy/formatting, Go lint, Biome and the CI wiring checks. + +The [coverage map](../../conformance/stack-encrypt/coverage.md#consolidation-policy) +records consolidation candidates. Shared case tables can replace duplicated +expectations once coverage matches; language-specific and implementation tests +remain. No existing tests have been removed. + +## Runtime checkpoint + +The initial runtime slice is on `feat/stack-encrypt-runtime-conformance`, stacked +on draft [PR #1460](https://github.com/cipherstash/stack/pull/1460). Its shared +cases cover missing/null storage, typed batch round trips, source refusals, and +lossless equality query conversions. Native Rust observes data-key call counts. +Go host source validation preserves the shared structured diagnostic fields. +The [runtime contract](../../conformance/stack-encrypt/runtime-contract.md) +describes the corpus and limits. No production API or existing test is removed. + +Local validation passes for all three profiles, fresh scalar +ciphertext exchange, Rust clippy/formatting, Go lint, Biome and the CI wiring +checks. The deterministic guest is reused from the unchanged parent engine. + +The read checkpoint below adds malformed stored records, authenticated read-type +failures and context preflight. Existing wider value-kind, query-operator, +generated SDK and EQL fixtures remain in place. + +## Read checkpoint + +The read slice is on `feat/stack-encrypt-read-conformance`, stacked on draft +[PR #1461](https://github.com/cipherstash/stack/pull/1461). Its shared cases +cover malformed stored shapes, authenticated type failures, null read-policy +changes and context preflight, including late failures in batches. + +Native Rust distinguishes shape rejection, pending preflight and authenticated +type refusal using data-key counters. Go checks each case against an uninitialised +guest and an active guest; representable cases additionally use `Cipher.Open`. +A test-only entry point supplies shapes the record adapter cannot represent. +The [read contract](../../conformance/stack-encrypt/read-contract.md) records +exact diagnostics and the remaining gaps. The tree hook shares the production +open/decode path, including field-order validation before conversion to maps. +No public API or existing test is removed. + +Local validation passes for all four profiles, fresh scalar +artifact exchange, Rust clippy/formatting, Go lint, Biome and the CI wiring checks. +The deterministic guest is reused from the unchanged parent engine. + +The fixture checkpoint below enrolls the existing wider value-kind and operator +fixtures. Next, extend context composition and EQL/JSON operation profiles. +Repeated-key and malformed-leaf cases need an explicit raw-byte transport path. +Python and TypeScript consumers remain pending. + +## Value-kind and query-operator checkpoint + +Building on the read-compatibility profile, the +[fixture contract](../../conformance/stack-encrypt/fixture-contract.md) and +[enrollment index](../../conformance/stack-encrypt/v1/fixture-enrollment.json) +assign stable requirement IDs to the existing `value_kinds.json` and +`query_operators.json` evidence. The conformance task directly runs their +existing Rust and Go tests. Typed Rust comparisons, generated Go methods, +match verification and fetch sizing remain intact. + +The fixture files stay in place with no duplicated expectations. CI guards +the requirement-to-test mapping, compiled test availability and exact test +selection. The Go selection is generated from the enrollment index. Required Go runs fail if +the guest is missing; required checks cannot regenerate frozen fixtures. +This is consolidation of inventory and execution, not removal of assertions. + +Local validation passes for the expanded conformance command, fresh scalar +artifact exchange, missing-guest regressions, Rust clippy/formatting, Go lint, +Biome and CI wiring checks. All four Rust fixture writers refuse regeneration in +required mode, and the frozen fixture files remain unchanged. + +The coverage is representative, not a complete kind/operator boundary matrix. +Shared operator refusals, wider fresh artifact exchange, Python/TypeScript +consumers and version matrices remain open. The next implementation slice is +shared context-composition vectors, followed by EQL/JSON operation profiles. + +## Follow-up slices + +- Extend the declaration grammar to EQL resolver capabilities and the operation + request profiles. Generate structural schemas from shared models where faithful; + keep semantic validation executable rather than assuming JSON Schema covers it. +- Extend shared cases to runtime source/read/request shapes, missing/null values, + all numeric kinds, and context binding. Consolidate existing duplicate tables + only after their unique assertions have equivalent coverage. +- Bring the existing JSON/SQL suites under named requirements. Add common JSON + vectors across runners and pin the supported predicate grammar and its limits. +- Add Python's runner in its owning repository/worktree, with a declared capability + set and the same artifact exchange. Establish its actual backend and APIs with + that implementation; do not design them by inference here. +- Add TypeScript's runner and SDK mapping tests when its binding exists. Include + native and WASM variants if both are supported. +- Extend artifact exchange to every producer/consumer pair for common profiles, + then supported release versions. Pin SQL bundle and engine versions in reports. +- Add backend lifecycle, cancellation, no-secret-diagnostics, key-I/O and batching + requirements. Reuse current tests and instrument providers where evidence is absent. + +## Completion criteria + +A profile is conformant only when every mandatory requirement has executable +evidence for the claimed language/backend/version. Optional capabilities have +named tests and explicit support status. No unsupported feature is silently +ignored. Released profiles define supported version combinations and evolution +rules; the corpus format version is not a new production wire version. + +Initial success means Rust and Go run the same cases, freshly written Go values +open in native Rust, fixed native values open in Go, and malformed query inputs +produce the specified diagnostics. Python and TypeScript remain visibly pending +until their runners execute. The complete specification, SQL profile, and all +language SDK mappings remain follow-up work. + +## Context composition checkpoint + +Implemented shared composition and boundary cases in +`conformance/stack-encrypt/context-contract.md`: 18 typed extension cases, +eleven read/preflight cases and four query cases, generated Go calls and native +typed chains. Existing +context-field fixture tests and the native plan-grammar suite are required by +`test:conformance`. Repeated Rust `.extend()` now appends, aligning Rust with Go; +the changelog documents compatibility for records written under the old behavior. +The current shared binding/search context remains distinct from the future +binding/search-scope split. + +Next: the EQL/JSON operation profile. Python and TypeScript runner delivery +and the wider fresh artifact exchange remain separate planned work. + +## EQL/JSON operation checkpoint + +Implemented the nine requirements in +`conformance/stack-encrypt/eql-json-contract.md`, enrolling the existing engine, +EQL binding, Go SDK and independent PostgreSQL suites. A shared corpus replaces +duplicate write/refusal tables; existing typed, generated, property and +adversarial assertions remain. Required fast and PostgreSQL commands check +compiled native inventory and exact Go pass events, refuse skipped evidence, +and report engine, lockfile, guest and installed SQL identities in CI artifacts. + +Next: backend lifecycle, cancellation, no-secret diagnostics, provider key-I/O +and batching requirements. Python/TypeScript enrollment and the broader fresh +artifact/version exchange remain separate delivery slices. The EQL/JSON profile +does not complete the refactoring track or introduce the future binding/search +scope split. + +## Lifecycle and key-I/O checkpoint + +Implemented `lifecycle-v1` with eight named requirements and required native/Go +CI evidence. Reuses the pending, KMS chunking, heap, ABI, cancellation, memory, +diagnostic and shared runtime/read suites. New observations cover unpolled and +in-flight operation drops, provider failure, cleanup of decoded prefixes on +late read errors, and bounded chunk concurrency/cancellation. The runner shares +inventory and no-skip checks with EQL conformance. + +Reports distinguish passing requirements from known residue, observer exclusions, +caller-owned values, unobserved live-provider behavior and unenrolled languages. +This does not complete secure-buffer/key-copy refactoring. Next conformance +slices remain value/refusal/raw-frame gaps, broader fresh artifact exchange, +Python/TypeScript enrollment and explicit release gates/version combinations. + +## Value, refusal and raw-frame checkpoint + +Implemented three shared corpora under `conformance/stack-encrypt/v1`, each +with a Rust and a Go runner required by `test:conformance`: +`record-values-v1` ([value contract](../../conformance/stack-encrypt/values-contract.md)), +every kind at its boundaries with frozen typed frames, sealed nulls (with +the runtime profile, every fixed-width kind), SQL nulls for `bool`, `bytes` +and `string`, cross-kind write refusals and the Go host conversions the +host refuses before the engine; +`record-query-refusals-v1` ([query-refusal contract](../../conformance/stack-encrypt/query-refusals-contract.md)), +every scalar operator against every field capability that does not answer +it and the listed range shapes, by refusal +class and diagnostic, with no key I/O, and the stage at which the typed Rust +chain refuses the same query; and `record-raw-frames-v1` +([raw-frame contract](../../conformance/stack-encrypt/raw-frames-contract.md)), +stored batches as transport bytes so repeated keys and malformed leaves reach +both decoders, with the table of error classes. + +The corpora pin three differences rather than fixing them: the order index +on `bytes` stores a term no operator reads; the typed chain refuses +equality, order and block ORE value refusals after its keyset loads where the +binding refuses before any (the query-preparation consolidation is tracked +separately and changes those entries on purpose); and a repeated key in a +stored record is a transport refusal in both codecs, so the engine's own +repeated-key guards are reached natively alone. No frozen fixture, artifact +or existing test changed. Fresh exchange of the wider kinds, Python and +TypeScript runners and release gates remain open. + +## Fresh artifact exchange checkpoint + +Implemented `artifact-exchange-v1` +([exchange contract](../../conformance/stack-encrypt/exchange-contract.md), +`conformance/stack-encrypt/v1/artifact-exchange-v1.cases.json`), run by +`mise run test:conformance:exchange` and at the end of `test:conformance`, and +required in `tests-golang.yml`. In one run, Rust and Go each write fresh +artifacts the other opens: every positive value-boundary case, a structural +record with a passthrough field and equality/order terms (including sealed and +SQL nulls), whole-value opaque blobs (`OpaqueBlob` against the Go opaque +storage path), and the EQL v4 `profiles` rows (eql-bindings' typed targets +against the Go generated code). Consumers compare decrypted values and derive +their own query terms against the stored ones; ciphertext bytes are never +compared. Producer caches are bypassed, a missing runner or guest and an empty +fresh output fail the task, and the report records producer SDKs, engines, +backends, guests, lockfiles and storage versions. Its released-version +section lists the Go rc.3 combination the API plan requires as not yet run, +and its rows stay empty until a lane runs a released artifact. + +Python and TypeScript are reported as not enrolled; no pair is claimed before +both implementations exist. Fresh JSON document exchange, the remaining EQL +types and a SQL lane storing one language's fresh rows through the other +remain open. No frozen fixture, artifact or existing test changed. + +## Consolidation checkpoint + +The first duplicate case tables came out, now that the shared corpora hold +their expectations and both runners execute them. Fifteen Rust unit-test +tables in `src/dynamic/record.rs` and `src/dynamic/query.rs` (ten removed +whole, five trimmed to the rows the corpora cannot spell) and two Go tests +(one removed, one trimmed) were replaced by declaration, runtime, read and +query-refusal cases; five cases were enrolled so every old row had an exact +home. Each removal is recorded in the +[coverage map](../../conformance/stack-encrypt/coverage.md#consolidations) +with its case IDs, its runner and the hand-introduced engine fault the +runner failed on before the old rows went. Compile-fail, ownership and +zeroization, batching, property, frozen-bytes, generated-code, host +conversion, error wrapping, cancellation, guest lifecycle, PostgreSQL and +live-provider tests are untouched, and the mixed-purpose tests whose unique +shapes the corpora lack are kept and listed there with the reason. diff --git a/docs/plans/2026-11-08-stack-encrypt-key-policy.md b/docs/plans/2026-11-08-stack-encrypt-key-policy.md new file mode 100644 index 0000000000..3dd384312c --- /dev/null +++ b/docs/plans/2026-11-08-stack-encrypt-key-policy.md @@ -0,0 +1,556 @@ +# Binds, claims, and labels: key policy in Stack Encrypt + +Date: 8 November 2026. Written from a design discussion with Dan on that +day. The ZeroKMS behaviour described here was read from the Vitur server +code in `cipherstash-suite` at commit `f63c85d5f`. + +A stored value can be tied to facts about it in three ways. A **bind** +ties the data key to a fact the client knows, such as a tenant or a row +ID. A **claim** ties the data key to a fact the key provider resolves, +such as the `sub` of the caller's token. + +A **label** records a fact on +the key tag, verified by the key provider, without restricting who can +read. Binds and claims are access control. Labels are not. + +This document +gives the design of all three, the rules that keep them apart, and what +ZeroKMS must do. + +The [API plan](2026-10-24-stack-encrypt-api-plan.md) lists the work. Its +[Query context and stored +context](2026-10-24-stack-encrypt-api-plan.md#query-context-and-stored-context) +section gives the context model that binds and claims extend. None of +the code below is on `next` today. + +This first API redesign decides the Stack Encrypt interface: how a bind, +a claim, and a label are declared, called, and stored. The interface +supports all three. + +The ZeroKMS side is decided only as far as the interface needs it. The rest, including how ZeroKMS writes a label +and how version 2 derives keys, belongs to the ZeroKMS version 2 work. +Dan set that boundary on 8 November 2026. [Still to +explore](#still-to-explore) lists what is deferred, with the current +thinking on each, so nothing is lost. + +## Contents + +- [Terms](#terms) +- [How ZeroKMS works today](#how-zerokms-works-today) +- [Three mechanisms, and when to use each](#three-mechanisms-and-when-to-use-each) + - [Guards for the developer](#guards-for-the-developer) +- [Binds move from the descriptor to key request items](#binds-move-from-the-descriptor-to-key-request-items) + - [A new envelope version](#a-new-envelope-version) +- [Claims](#claims) + - [Declaring a claim](#declaring-a-claim) + - [Which token](#which-token) + - [Other provider facts](#other-provider-facts) +- [Labels](#labels) + - [How it works](#how-it-works) + - [Rules for labels](#rules-for-labels) + - [ZeroKMS can write a label](#zerokms-can-write-a-label) + - [Labelling in Rust and SQL](#labelling-in-rust-and-sql) + - [Go, and labelling many values](#go-and-labelling-many-values) + - [The labels list in the payload](#the-labels-list-in-the-payload) + - [Example: access intelligence for a notes table](#example-access-intelligence-for-a-notes-table) +- [What ZeroKMS must do](#what-zerokms-must-do) + - [Needed for this redesign](#needed-for-this-redesign) + - [For ZeroKMS version 2](#for-zerokms-version-2) +- [Still to explore](#still-to-explore) + - [A label written by ZeroKMS](#a-label-written-by-zerokms) + - [Enforcement by derivation or by check](#enforcement-by-derivation-or-by-check) + - [Policy over labels](#policy-over-labels) + +## Terms + +The plan's terms table defines every other term used here. + +| Term | Meaning | +| --- | --- | +| Binding | The plan's term: a part of the stored context that is not in the query context, such as a row ID. The data key and the AAD derive under it. A reader must present the same value | +| Bind | Tying a data key to a binding. The mechanism, where "binding" is the part. A bind is access control | +| Claim | A binding whose value the key provider resolves from the caller's verified token, such as `sub`. The client names it and never sees the value | +| Label | A named, typed fact added to a stored value's key tag after encryption. ZeroKMS verifies it when it returns the key, and logs it. It restricts nothing | +| Descriptor | The string a key request names its key under. ZeroKMS derives the data key from it. Today Stack Encrypt renders the whole stored context into it | +| Key request item | One part of the stored context as a key request sends it beside the descriptor: a name and value, or a claim. The ZeroKMS protocol's field for the list is `context`, and its older name was lock context; ZeroKMS version 2 drops that name | +| Key tag | The HMAC ZeroKMS returns with a data key. A reader must present it to get the key again. Stack Encrypt binds it into every leaf's AAD | +| PAE | Pre-authentication encoding: a length-prefixed encoding of several values, so that two values cannot run into each other | + +## How ZeroKMS works today + +These facts were verified in the Vitur server, in +`packages/vitur-server-core/src`: + +- **The data key is derived from the IV, the descriptor, and the + keyset's authority key.** Nothing else goes in. The descriptor is + padded to a 512-byte block. That block is the source of the + descriptor size limit (`client.rs`, `generate_key_material`). +- **The key tag is an HMAC over the IV, the descriptor, and each key request item in order.** An identity claim goes in as its name and + the value ZeroKMS resolved from the caller's token (`tag_key.rs`, + `create_tag`). +- **On retrieve, ZeroKMS resolves the items again from the reader's + token, recomputes the tag, and compares it in constant time.** A + mismatch is refused before any key material is derived. A match + returns the key, derived from the descriptor alone + (`key_retrieval.rs`, `verify_and_retrieve_key`). +- **A second tag version carries a decryption policy** with OR + semantics over claims. It is the earlier policy-engine design. This + plan retires it. + +So a key request item is enforced by a check. The descriptor is +enforced by derivation. If ZeroKMS skipped the check, a key request item +would not stop decryption, because the key does not depend on it. A +descriptor part cannot be skipped, because the key is derived from it. + +## Three mechanisms, and when to use each + +| | Bind | Claim | Label | +| --- | --- | --- | --- | +| Who supplies the value | The client, from the caller or the row | ZeroKMS, from the caller's token | The client or a trigger. ZeroKMS itself, if the version 2 work adopts it | +| Who sets the rule | The client, at write time | The client, at write time | ZeroKMS policy, at any time | +| Can the rule change later | No. Lose the value, lose the data | No. Lose the claim, lose the data | Yes. A policy can be added, changed, or removed | +| Can the rule be overridden | No | No | Yes, by changing the policy | +| Affects search terms | No | No | No | +| Good for | Tenant isolation, a value that must stay in its row | Per-user secrets that no one else may read | Access intelligence, and any rule an operator may need to change | + +A scope, the other kind of context part, does affect search terms. It is +not a bind, and the plan's context rules cover it. + +A bind and a claim are the same mechanism with a different source of the +value. Both are strict by construction. A label is a record, and ZeroKMS +may later apply a policy to it. + +A bind or a claim, and a label, all end with a verified fact on a stored +value. They differ in whether any reader is restricted. So the API +must keep a developer from choosing the strict one by accident. + +### Guards for the developer + +1. **A claim is declared on the type, never added on one call.** + `bind(claim = sub)` in a declaration is visible in code review and in + `contexts()`. A per-call claim would let one code path make a row + unreadable to everyone else without anyone noticing. Binds of values + the caller knows may still be added per call, because the caller + already has the value. +2. **Every bind's documentation says the same sentence.** A value bound + to this part cannot be read without it, by anyone, ever, including a + migration. For a claim it adds: deleting the user deletes access to + the data. +3. **A label is the default suggestion for identity facts.** Where the documentation shows `sub`, it shows it as a label first. ZeroKMS may write that label itself, if the version 2 work adopts it + ([Still to explore](#still-to-explore)). The claim is the + stricter option, with its cost spelled out. + +## Binds move from the descriptor to key request items + +Today Stack Encrypt renders the whole stored context into the descriptor +string, frozen, and sends no key request items. Decided on 8 November +2026: new values send the context's parts as key request items instead. +Each scope and binding becomes a name-and-value item. The descriptor +shrinks to the name scopes, such as the table and column. + +The item never carries the part's kind. The plan's rule is that the kind +is not in the derivation. So a scope and a binding with the same value +are the same item. + +This removes the 512-byte limit on a context, and it gives ZeroKMS the +parts as structure instead of one string it logs and cannot parse. + +### A new envelope version + +A key generated under a descriptor must be retrieved under the same +descriptor. So this is a stored-format change, under the plan's +[stored-format +rule](2026-10-24-stack-encrypt-api-plan.md#the-stored-format-stays-compatible-with-go-rc3). +The `SealedValue` envelope begins with a format version byte, `0x01` +today, and binds it into the leaf AAD. The new form is version `0x02`. + +On decrypt, the engine reads the byte and sends the request in the form +the value was written with. Version 1 renders the descriptor as rc.3 +did. Version 2 sends the name scopes and the items. Go rc.3 data stays +readable without re-encryption. The rc.3 rendering code stays until the +last version 1 value is gone. + +Two things the move changes, for ZeroKMS to know: + +- Under version 2, a context part is enforced by the tag check, not by + key derivation. Under version 1 it was both. [What ZeroKMS must + do](#what-zerokms-must-do) asks version 2 of ZeroKMS to close that gap. +- The ZeroKMS protocol says the items "should never include sensitive + information". A tenant ID or row ID reaches ZeroKMS as an item instead + of inside the descriptor, so nothing new is sent. This document records the protocol's rule, so + a reader does not have to assume it. + +## Claims + +A claim is a binding whose value the key provider resolves. The client +names the claim. ZeroKMS reads its value from the token it verified, and +folds the name and the value into the key tag. On read, ZeroKMS resolves +the claim again from the reader's token. A reader with a different value +gets a tag mismatch and no key. + +A claim is on the stored-context side of the plan's rule, with the +bindings. The client never sees the value, so no search term can derive +from it. A claim is never a scope. + +### Declaring a claim + +The claim type belongs to the provider, and a capability trait gates it +at compile time: + +```rust +// In the ZeroKMS provider. `Name` is validated, as a keyset name is. +pub enum Claim { Sub, Custom(Name) } + +// A provider that can resolve claims. A fake provider, or a future +// provider without verified tokens, does not implement it. +pub trait ResolvesClaims: DataKeySource { type Claim; } +``` + +```rust +// Declared on the type. The caller cannot leave it out. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Note, scope = "notes", bind(claim = sub))] +struct EncryptedNote { + body: Ciphertext, +} + +// Encrypt and decrypt take the keyset as every call does. The engine +// adds the claim item to the key request. Only the same `sub` can read. +let encrypted: EncryptedNote = note.encrypt_into(&keyset).await?; +let note = Note::decrypt_from(encrypted, &keyset).await?; + +// A client-known bind may be added on one call. A claim may not. +let encrypted: EncryptedNote = note + .encrypt_into_with_context(&keyset, Bind::new(row_id)) + .await?; +``` + +The context chain will use typestate to refuse a scope after a bind. The +plan's [One context argument, and paired entry +points](2026-10-24-stack-encrypt-api-plan.md#one-context-argument-and-paired-entry-points) +item builds it. +The same mechanism marks a declaration that contains a claim, and the +entry points accept it only for a keyset whose provider implements +`ResolvesClaims`. A dynamic declaration with a claim part is refused at +load on a provider that cannot resolve claims, before any key I/O. + +`contexts()` and `assert_context!` show a claim as a part whose value +reads "resolved by the provider". Go declares a claim in the struct tag, +and `stashgen` puts the part in the declaration it sends. The dynamic +declaration gains a part kind `claim`. A declaration without one is the +rc.3 form. + +### Which token + +The claim resolves from the bearer token on the ZeroKMS request. For a +per-user claim, that token must have been exchanged from the user's own +JWT. + +The Go SDK passes the call's context into the token call, and the +`@cipherstash/auth` binding has `getTokenForJwt`. The `@cipherstash/stack` +native entry does not: it calls the JavaScript token callback from a +background task, outside the caller's request. Issue #1565 tracks that +defect. A claim on that path is not safe until it is fixed. + +### Other provider facts + +The kind generalises to any fact the provider knows and the client +cannot forge. Examples: the client ID that authenticated, the +provider's clock at generation, and the caller's address as the provider +saw it. Each would be a +variant of `Claim`. Start with `Sub` and `Custom`, and add a variant +when it has a use. + +## Labels + +A label adds a named, typed fact to the key tag of a stored value, after +encryption. The row and the facts of its writing are then recorded on the value. +ZeroKMS can verify the record. + +Its context, its AAD, and its queries do not change. ZeroKMS +verifies the labels when it returns the key, and logs them. That log is +where access intelligence comes from now, and where policy over labels +comes later. + +Labelling was called tag refinement, and a label a caveat, until 8 +November 2026. Dan chose "label" because a caveat is a restriction in +the Macaroons sense, and a label restricts nothing. + +### How it works + +The write path: + +1. ZeroKMS returns a data key and a tag. Stack Encrypt binds the tag in + the leaf AAD and stores the tag with the ciphertext. +2. The stored tag can be labelled in three places: + - in Rust, after encryption; + - in the database, by a trigger, once the primary key is known; - by ZeroKMS, at generate time, if the version 2 work adopts it. +3. Labelling is HMAC chaining, in the style of Macaroons: + `tag' = HMAC(tag, PAE(name, value))`. The label is appended to the + payload's label list. Then `tag'` replaces the stored tag, inside the + ciphertext envelope where it lives. + +The read path: + +1. The client sends the stored tag and the label list to ZeroKMS. +2. ZeroKMS derives the original tag again, applies the chain of labels, + and compares the result with the tag it was sent. +3. ZeroKMS logs the labels. Later it applies policy to them. +4. ZeroKMS returns the original tag with the key material. +5. The client rebuilds the leaf AAD with the original tag, and decrypts. + +The reader passes nothing. The tag and the labels are in the row. + +### Rules for labels + +- **EQL defines the standard names, and an application adds its own.** + EQL publishes a standard set of label names for access intelligence, + such as `row_id`, `created_at`, and `written_from`. ZeroKMS policy + will match on names, so the standard set gives every customer one + vocabulary. An application adds custom names beside them. Stack + Encrypt checks only that a name is non-empty text. +- **Values are typed.** A timestamp and the text of a timestamp are + different MAC inputs. Each value carries its type in the encoding, as + a context part does. +- **Any layer may label, in any order.** A client can label before the + insert. A trigger can label after it. A client can label again later. + The chain records the order, so a client-side label added after the + trigger follows the row ID. +- **A name may repeat.** Two `updated_at` labels, added at different + times, are a history. +- **Values are in the clear.** They are stored beside the tag. Anyone + who can read the row can read them. ZeroKMS verifies them through the + chain. The AEAD does not. +- **A label is not a part of the context.** It is not in the query + context, so it changes no search term. It is not in the AAD, so the + AEAD does not check it. + +### ZeroKMS can write a label + +At generate time, ZeroKMS could resolve a claim and label the tag with +it before returning. `written_by = sub` is the example. The value would +be more trustworthy than a client-written label, because the client +never had the chance to assert it. + +This is deferred to the ZeroKMS version 2 work. The interface needs one +thing for it beyond a client-written label: the response returns the +base tag as well as the labelled tag. [Still to explore](#still-to-explore) +has the analysis and the open points. + +### Labelling in Rust and SQL + +In Rust, `label` adds a label to an EQL value. It returns the labelled +value, so calls chain. A JSON document has one key tag in its header, so it labels the same +way. Decryption is unchanged. + +```rust +let sealed: TextEq = body.encrypt_into_with_context(&keyset, Scope::new(&column)).await?; +let sealed = sealed + .label("written_from", request.ip())? + .label("created_at", now())?; + +// Read the labels without decrypting. +for label in sealed.labels() { + println!("{} = {}", label.name(), label.value()); +} + +// Decrypt. The tag and the labels come from the payload. +let body: String = String::decrypt_from(sealed, &keyset).await?; +``` + +In SQL, `eql_v4.label_tag` does the same to a stored payload. A trigger +can label with the primary key that the database generated: + +```sql +CREATE FUNCTION notes_label_body() RETURNS trigger AS $$ +BEGIN + NEW.body := eql_v4.label_tag(NEW.body, 'row_id', NEW.id::text); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER notes_label_body + BEFORE INSERT ON notes + FOR EACH ROW EXECUTE FUNCTION notes_label_body(); +``` + +### Go, and labelling many values + +Labelling is local. It is an HMAC over the tag, computed in the engine, +with no call to ZeroKMS. So there is no batch to send. No bulk form is +needed. + +Go's `Encrypt` seals a slice in one call. A program then labels the +values it chooses, through a `Label` method on every EQL value type. +`Labels` reads the list. Both go through the module's EQL guest, and +neither touches the network. + +```go +rows, err := Encrypt(ctx, keyset, notes) // []EncryptedNote +for i := range rows { + if err := rows[i].Body.Label("written_from", req.RemoteAddr); err != nil { + return err + } + if err := rows[i].Body.Label("created_at", time.Now()); err != nil { + return err + } +} + +for _, l := range rows[0].Body.Labels() { + fmt.Println(l.Name, l.Value) +} +``` + +The dynamic interface has `label` and `labels` as operations on a stored +value, and the Go methods call them. + +### The labels list in the payload + +An optional `labels` list is added to the EQL payload. The list is +present only once a label has been added. A payload without it is the +rc.3 form, so the change is additive. Every EQL type has the list, +whether it stores a scalar or a JSON document. Each has one key tag. + +The tag lives in the payload's key header `h`, a Base64 field. The +header also contains the header version, the keyset ID, and the IV. The v4 JSON +document stores it that way today, and scalar payloads move to the same +shape as payload version 2. + +So `eql_v4.label_tag` reads the tag from `h` +with PostgreSQL's own Base64 decoder and writes the labelled tag back. +It never parses the ciphertext `c`. The plan's [A key header beside a +Base85 +ciphertext](2026-10-24-stack-encrypt-api-plan.md#a-key-header-beside-a-base85-ciphertext) +item defines the shape. + +The tag moves into `h`. It is not copied. After labelling, the base tag +is gone from the row. That is what makes the chain one-way. + +A bare `Ciphertext` is a raw envelope with no list. No list will be added +to it. Labels are for EQL payloads. Decided by Dan on 8 November 2026. + +### Example: access intelligence for a notes table + +The client adds two labels before the insert. The trigger adds the +primary key. In ZeroKMS version 2, ZeroKMS would add `written_by` as +well. + +A reader selects one column and decrypts. ZeroKMS logs all three labels when it returns the key. No reader is restricted. + +```rust +let sealed: TextEq = note.body + .encrypt_into_with_context(&keyset, Scope::new(&column)) + .await? + .label("written_from", request.ip())? + .label("created_at", now())?; +sqlx::query("INSERT INTO notes (body) VALUES ($1)").bind(&sealed).execute(&db).await?; + +let sealed: TextEq = sqlx::query_scalar("SELECT body FROM notes WHERE id = $1") + .bind(id) + .fetch_one(&db) + .await?; +let body: String = String::decrypt_from(sealed, &keyset).await?; +``` + +The stored payload, after the trigger. The key header `h` contains the +keyset ID, the IV, and the labelled tag. `hm` is the equality term: + +```json +{ "v": 2, + "i": {"t": "notes", "c": "body"}, + "h": "…", + "c": "…", + "hm": "…", + "labels": [ {"n": "written_from", "v": "203.0.113.5"}, + {"n": "created_at", "v": "2026-11-07T10:15:00Z"}, + {"n": "row_id", "v": "7f3c2a9e-…"} + ] +} +``` + +## What ZeroKMS must do + +This work is outside this repository. The first list is what this API +redesign needs from the ZeroKMS that exists today. The second is for ZeroKMS version 2. It is tracked with +that work. + +### Needed for this redesign + +- Accept the name scopes as the descriptor and the parts as key request + items. ZeroKMS does this today. +- Resolve `sub` and custom claims from the verified token. ZeroKMS does + this today. +- The retrieve-key request includes the stored tag and the label list. + ZeroKMS verifies the chain, and refuses a tag it cannot reproduce. +- The response returns the original tag with the key material. Today's + pinned protocol returns key material only. + +### For ZeroKMS version 2 + +- Derive the data key over the key request items as well as the + descriptor. Then a bind or a claim is enforced by derivation, not by a + check that could be skipped. A reader with a different claim value + gets a different key, and the leaf fails to open. +- Retire the decryption policy and its tag version. +- Remove the descriptor size limit. Stop logging the descriptor in the + clear. +- Write labels at generate time, returning the base tag, the labelled + tag, and the label. +- Apply policy over labels, with a way to change the rule that a bind + does not have. +- Resolve other provider facts as claims when they have a use. + +## Still to explore + +None of these blocks the API redesign. Each is connected to the ZeroKMS +version 2 work. Each is decided there. The current thinking is recorded so +it is not lost. + +### A label written by ZeroKMS + +Dan asked on 8 November 2026 whether a label ZeroKMS writes at generate +time becomes a bind. The client would have only the labelled tag to +bind into the leaf AAD. The current thinking is that it does not, +for two reasons. + +- **Nothing about the reader is checked against a label.** The labelled + tag and the label's value are stored in the row in the clear. A reader + presents them as they are. ZeroKMS recomputes the chain from the base + tag and the stored labels. The check passes for any reader whose key request items resolve. A bind is different: ZeroKMS resolves a claim + from the reader's token, or the reader supplies a value, and ZeroKMS + compares that with the tag. A label asks nothing of the reader. +- **Binding the labelled tag into the AAD would add tamper evidence, + not access control.** It would stop a label being stripped or altered + without the AEAD failing. ZeroKMS already refuses a chain it cannot + reproduce, so that evidence is redundant. It would also mean the + client has to know which labels were applied before encryption and + which after, to rebuild the AAD. + +The proposed answer is that ZeroKMS returns two tags: the base tag, and +the labelled tag. The client binds the base tag into the AAD and stores +the labelled tag, as for any label. Then every label is outside the +AAD, whoever wrote it. The read path has one rule. Still to settle: + +- whether version 2 returns both tags, or the client derives one from + the other; +- the privacy rule. A server-written `written_by` puts the writer's + `sub` in the row in the clear. It must be a choice the declaration + makes, never a default; +- whether a label ZeroKMS wrote should be marked as such in the list, so + a policy can trust it more than a client-written one. + +### Enforcement by derivation or by check + +Today a descriptor part is enforced by key derivation and a key request +item by a tag check. The version 2 request above closes that gap. Until +then, the honest difference between a bind and a label is who can change +the rule, not who enforces it. Still to settle: whether version 2 should +also bind the envelope format version, so that a version 1 request +cannot be replayed as version 2. + +### Policy over labels + +ZeroKMS applying policy to labels is the changeable counterpart to a +bind. Still to settle: the policy language, and the standard label names EQL +publishes first. Also how a policy refusal is reported to the client, +so it is never mistaken for a tampered ciphertext. diff --git a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md new file mode 100644 index 0000000000..b506093ccf --- /dev/null +++ b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md @@ -0,0 +1,623 @@ +# Move vitaminc's AEAD crates into the stack, and define the value types once + +Status: draft, rewritten 26 November 2026. Decisions by Dan Draper: + +- Move the AEAD crates into this repository as crates. Do not fold them into + modules of `stack-encrypt`. +- Work in two stages: move first with no change in behaviour, then + consolidate. +- Keep the move as small as possible. `vitaminc-protected` and + `vitaminc-random` never move. +- No more work on the TypeScript SDK until this is done. +- vitaminc's Go packages `vcffi` and `vcvalue` move too, as a third stage, + before the Go SDK's final release. vitaminc's `vcencrypt` is deleted. +- An order index takes no bytes and no UUID. If `vitaminc-ore` ever moves + into this repository, its UUID order target (behind its `uuid` feature) and + its bytes order target are removed. Until then, the engine refuses both in + stage 2.3. +- `vitaminc-aead` describes the complete data model, `json` included. + `ValueKind` moves there with its name, and `stack-encrypt` re-exports it + from the same path. The engine adds no wrapper type. JSON stays a kind a + field declares, not a logical type: no frame or stored byte marks a value + as JSON. +- Fixtures follow the rule in `packages/stack-encrypt/tests/fixtures/README.md` + and `packages/eql/tests/encryption/fixtures/README.md`: every fixture is + Biome-formatted, you run `pnpm run code:fix` after regenerating one, and + each test compares its fixture as parsed JSON. +- The moved code keeps the MIT licence, which is this repository's licence. +- Nobody outside CipherStash uses the moved crates. + +The first draft of this plan (14 November) moved nine crates, with `ore.rs`, +into `stack-encrypt` as modules. This draft replaces it. + +AEAD means authenticated encryption with associated data. The AEAD crates +define the value types, how each is encoded, and how a value is sealed. + +## Summary + +Three crates move from `cipherstash/vitaminc` into this repository: +`vitaminc-aead`, `vitaminc-aead-frame` and `vitaminc-aead-derive`. The frame +crate is renamed `recipher-frame` in step 2.4. `vitaminc-aead` is not +published again under that name: it is renamed `recipher-aead`. They are +published from here with `recipher`, the new name of `stack-encrypt`, and +not before (see "Publishing, with `recipher`"). What becomes of +`vitaminc-aead-derive` is open question 2. + +vitaminc's two Go packages, `vcffi` and `vcvalue`, move into the Go module in +a third stage. + +The value handling is consolidated in stage 2. Today the list of value types is +written down in vitaminc, written again in the engine (`stack-encrypt`), and +reconciled a third time in each language SDK. After this plan: + +- The AEAD crates define the types, the encodings, the null rule, the + canonical form of each type, and the name of each type. Nothing else does. +- The engine depends on the AEAD crates. It does not wrap their types, hold + its own list of them, or rewrite a value. +- A language bridge converts a host language's values to and from the AEAD + types, and does nothing else. + +No stored format changes. A change to stored bytes during this work is a +defect. + +## Why + +### The same list is written at least five times + +vitaminc defines the types as `Logical` and `Physical`. The engine's +`dynamic` module then restates them: + +| Where | What it restates | +|---|---| +| `ValueKind` (`dynamic/kind.rs`) | A second enum of 21 types, with the text names a plan uses | +| `model`, `model_null` (`dynamic/value_frame.rs`) | An allow-list of the types the engine accepts | +| `scalar_kind` (`dynamic/value_frame.rs`) | A value's type as a `ValueKind` | +| `scalar_of` (`dynamic/kind.rs`) | A sample value for each `ValueKind` | +| `ValueKind::sealed_null` (`dynamic/kind.rs`) | The fixed-width type of each kind's null | +| `ordered`, `order_of` (`dynamic/term.rs`) | Which types an order index takes, twice | + +Outside the engine, the Go module (`record.Kind`), EQL (`plaintext_of` and +the `Plaintext` trait) and the TypeScript SDK each hold a copy as well. Go and +EQL call these "vitaminc's ValueKind names". vitaminc has no `ValueKind`. + +### The copies disagree + +- **A UUID.** vitaminc has the type, a sealed form, a null, an equality term + and an order term for it. The JavaScript bridge reads and builds one. The + engine's allow-list leaves it out, and no reason is recorded (#1821). The + engine is not consistent with itself either: `dynamic::term()` gives a UUID + an equality term, and the record path cannot store one. +- **A timestamp.** The JavaScript bridge writes a `Date` in milliseconds. The + engine rewrites every timestamp to nanoseconds. The bridge's README says a + `Date` is stored as its millisecond count, which is false once the value + passes through the engine. +- **An integer.** Go converts an integer to the declared type before it + encodes it. The engine refuses a value of another width on write, and + converts one on a query. The JavaScript bridge sends a `bigint` at the + narrowest width that fits, whatever the field declares. + +### An SDK pays for each disagreement + +The TypeScript SDK's addon classifies a value to explain the engine's refusal +(`is_uuid`), wraps the engine's wrapper to satisfy a trait (`OneValue`), and +copies every value twice: the bridge writes a frame, then the engine parses +it and copies it into a second buffer. + +### `ValueFrame` is not needed for what it is assumed to do + +`ValueFrame` is the engine's wrapper around frame bytes. It is not what wipes +a plaintext. `to_frame` and `decrypt_to_frame` already return +`vitaminc_protected::Buffer`, which wipes its bytes when it grows and when it +drops, and whose `Debug` shows nothing. + +What `ValueFrame` does add: + +- the allow-list; +- an owned value that can be encrypted, and a target a ciphertext opens into; +- comparison in constant time; +- reading a text value as a context label. + +The engine has to write these on a wrapper because it cannot implement the +AEAD crates' traits for a type from another crate. Once the AEAD crates are in +this repository, they can provide them. + +## What moves, and what stays + +### Stage 1 moves three crates + +| Crate | Why | +|---|---| +| `vitaminc-aead` | The types, the sealed leaf, the ciphertext tree, the sinks | +| `vitaminc-aead-frame` (`recipher-frame` from step 2.4) | The frame encoding a binding sends | +| `vitaminc-aead-derive` | `vitaminc-aead` depends on it | + +The JavaScript bridge, `recipher-value-napi`, is already here. It is a renamed +copy of `vitaminc-aead-napi` 0.10.0, and depends only on `vitaminc-aead` and +`vitaminc-protected`. + +### What stays in vitaminc + +- **Never moves:** `vitaminc-protected`, `vitaminc-random`. +- **Stays, and does not depend on the AEAD crates:** `vitaminc-context` + (`vitaminc-aead` depends on it), `vitaminc-hmac` (it depends on + `vitaminc-prf`), `vitaminc-traits`, and the rest. +- **Stays for now, and depends on `vitaminc-aead`:** `vitaminc-normalize`, + `vitaminc-prf`, `vitaminc-ore`, `vitaminc-encrypt`. See the next section. + +`clww-ore` and `ore-rs` stay in `cipherstash/ore.rs`. + +### The four crates that depend on `vitaminc-aead` + +| Crate | What it uses from `vitaminc-aead` | +|---|---| +| `vitaminc-normalize` | The canonical-form helpers (`timestamp_nanos`, `strip_trailing_zeros`, the date and timestamp limits). It implements the `Sink` traits, and uses the encrypting sink's internals (`shape`, `seal_all`, `Tee`). | +| `vitaminc-ore` | `Logical`, `Physical`, the value types. It implements the `Sink` traits. | +| `vitaminc-prf` | `Logical`, `Physical`, behind an optional feature. | +| `vitaminc-encrypt` | `seal::Cipher`, which it implements for the AES cipher, and the ciphertext builder. | + +The engine passes AEAD types into all four. So the engine and these four must +build against the same `vitaminc-aead`. Two consequences: + +- **`vitaminc-aead` cannot be renamed while the four depend on it.** Under + a new name, Cargo would build two crates with two sets of types, and the + engine's calls into the four would not compile. So before it becomes + `recipher-aead`, each of the four moves here or is released against + `recipher-aead`. The same holds for the other crates on crates.io that + depend on it: the `vitaminc` umbrella crate, `clww-ore` and `ore-rs` + (see the `[patch.crates-io]` table in the root `Cargo.toml`). + + The frame crate is not bound this way: none of the four depends on it, + and only `stack-encrypt` and `stack-guest-abi` do, both by path. So it + could be renamed without breaking anything outside this repository, and + step 2.4 renames it `recipher-frame`. +- **A breaking change to `vitaminc-aead` needs new releases of all four**, + and then of `clww-ore` and `ore-rs`, which the root `Cargo.toml` pins with + `=`. A change that only adds a type, a method or a `Logical` variant does + not break them. A change to the `Sink` traits or to `Physical` does. + +Stage 2 decides, step by step, whether a change can be made without breaking +them. If one cannot, the four move too. `vitaminc-normalize` is the most +likely: it holds rules about canonical forms, which this plan gives to the +AEAD crates. + +## Stage 0: pin the bytes + +Before any code moves, every stored and wire format has a test that fails +when its bytes change. Most exist: the conformance corpus +(`conformance/stack-encrypt/v1`), the engine's stored-row fixtures, and +vitaminc's own storage corpus. The known gaps: + +- **What the JavaScript bridge writes.** No TypeScript runner exists for the + corpus, so nothing compares a `Date`'s frame with the engine's. +- **A host's typed null.** One engine unit test covers it. No conformance + case does. +- **A JSON document's leaf.** The dynamic path writes a bytes leaf and the + typed path seals a text leaf. Which one each path stores has not been + traced. +- **The contents of `stored_rows_v1.json` and + `record-scalars-v1.expected.rust-native.json`** have not been listed by + type. + +The work is to list what each fixture freezes, fill the gaps, and run the +whole set against the crates.io versions in use today. + +## Stage 1: move the three crates, unchanged + +1. Copy the three crates in at the version the root `Cargo.lock` resolves. + Keep their names. Bring their git history, as was done for the stack-* + crates. +2. Bring their tests, fuzz targets and benchmarks, and the checks under + "Checks that must move with the code". +3. Point every workspace at them. Each resolves vitaminc on its own today: + - the root workspace, where `stack-encrypt` and `stack-guest-abi` name + the crates, and where the `vitaminc` umbrella crate depends on + `vitaminc-aead`; + - the TypeScript SDK's workspace, and the bridge's test addon, which is a + workspace of its own; + - the two Go guests; + - EQL's workspace, for its encryption test crate; + - the detached fuzz crate `packages/stack-encrypt/fuzz`. +4. Do not publish them yet. In each workspace, a `[patch.crates-io]` table + makes the four crates from crates.io resolve the in-repository + `vitaminc-aead`. That works while its version stays on the 0.10 line. +5. Move the open vitaminc issues about this code with it: vitaminc #643, + #473 and #632. + +This stage changes no behaviour. The copied source can be compared with the +published crates file by file. + +While the crates are unpublished: + +- **A release from this repository builds against crates.io's copy.** + `cargo publish` drops `[patch]` tables, so a published `stack-encrypt`, + `stack-kms` or `stack-auth` depends on crates.io's `vitaminc-aead` 0.10.x, + not on the copy here. Stage 2 changed the copies, so there is no further + `stack-encrypt` release: the next release is `recipher`, with the renamed + crates (see "Publishing, with `recipher`"). +- **The Go and TypeScript SDKs are not affected.** Both build the engine by + path from the tree. +- **`eql-bindings` can be published until step 2.4.** Its `stack-encrypt` + feature is compiled against the `stack-encrypt` on crates.io when it is + published. Stage 1 changes no API, so that still compiles. Step 2.4 changes + the API that `eql-bindings` uses, and from then an EQL release with that + feature waits for the first release of `recipher`. +- **vitaminc stops changing these three crates as soon as the copy is + taken**, or the two copies diverge. The crates stay in vitaminc, unchanged, + until everything in this plan is settled, so that the move can be backed + out. They are deleted from vitaminc only then. + +### Publishing, with `recipher` + +Decided on 2 December 2026, in place of publishing the crates under their +vitaminc names: `vitaminc-aead` is not published again. `stack-encrypt` is +renamed `recipher`, and the AEAD crates are published with it, under new +names, and not before. In order: + +1. For each crate on crates.io that depends on `vitaminc-aead` (the four + above, the `vitaminc` umbrella crate, `clww-ore` and `ore-rs`), decide + whether it moves here or is released against `recipher-aead`. The + rename cannot happen before that is done. +2. Rename `vitaminc-aead` to `recipher-aead`, and `stack-encrypt` to + `recipher`. Settle `vitaminc-aead-derive` (open question 2). +3. Publish `recipher` with `recipher-aead`, `recipher-frame`, and the + derive crate or crates that open question 2 leaves. The names are new + on crates.io, so this needs trusted publishing set up for them here. + +Until then, the three crates keep `publish = false` and their +`release = false` entries in `release-plz.toml`. + +## Stage 2: consolidate + +Each step is its own pull request or small set of them. Each passes the +stage 0 tests with no change to pinned bytes. The steps are in dependency +order. + +### 2.1 One canonical form for a timestamp + +The sealed leaf has a short form for a timestamp in nanoseconds. Any other +unit is sealed in a longer envelope of a different length. Every value stored +through the engine is in nanoseconds, because the engine rewrites it. + +Move the rule into the AEAD crates, so that no caller can seal another unit +by accident, and change the JavaScript bridge to write a `Date` in +nanoseconds. Then delete the engine's rewrite. + +If this were skipped, a JavaScript `Date` would seal to a different length +from the same instant written by Go or Rust, and from its own sealed null. + +### 2.2 One description of a type, with its name + +Move `ValueKind` into the AEAD crates, keeping its name, and have +`stack-encrypt` re-export it from the same path. It describes a value's type +without a value, and has a text name. The names are a wire format: plans, +error payloads, the Go module, EQL's generated code and the conformance +corpus all use them, so they do not change. + +`scalar_kind`, `scalar_of` and `sealed_null` become methods of that type, or +are deleted. + +The type covers every scalar, an array and an object, which are shapes of +the AEAD encoding, and `json`. A JSON value is carried as UTF-8 JSON text in +a text or bytes leaf, so a value read from a frame is `string` or `bytes`. +`json` is a kind a field declares: it tells the engine to treat the text as +a JSON document, and the JSON index parses it. Nothing on the wire marks a +value as JSON. + +The type also gives the width a sealed null is padded to. A field's declared +type is the only thing that decides that width. A host can send a null with +a type of its own, and the frame writer drops that type, as it does today. +If the host's type counted, it could disagree with the declaration, and a +null padded to the wrong length would show that it is a null. + +vitaminc has no such type today. `Kind`, `Width`, `KnownLogical` and +`FixedType` each cover part of it, and its only text names include a +parameter (`timestamp(ms)`, `decimal(2)`). + +### 2.3 Each index says which types it takes + +Delete the allow-list. An index refuses a type it cannot handle: + +- **Equality:** already asks `vitaminc-normalize`. +- **Order:** no boolean, no 8-bit integer, no bytes and no UUID. + `vitaminc-ore` already refuses the first two. It allows bytes, and a UUID + behind its `uuid` feature, so the engine's order index refuses those, in + one place. Nothing in this repository turns on `vitaminc-ore`'s `uuid` + feature, and `stack-encrypt` names no bytes order target. +- **Match:** text only. + +A plan is refused when it is built, before a value arrives. The index answers +that for a type from 2.2, with no sample value. + +### 2.4 The AEAD crates provide the owned value + +Add to the AEAD crates an owned, wiped frame that can be encrypted, that a +ciphertext opens into, and that compares in constant time. Delete +`ValueFrame`, `Modeled`, `Opening`, `Children` and `FromFrameError`. + +This is the widest step. `ValueFrame` is named in about 50 files of +`stack-encrypt`, 23 of EQL, and both SDK guests. It is in the public API of +`eql-bindings`, which is published, so this is a breaking release of that +crate. + +Done in #1955: + +- The frame crate is renamed `recipher-frame` first, in a commit of its own. + No workspace patches crates.io for it any more. +- Most uses need no owned value. A value read only within a call is a + `Frame` borrowed from its bytes: `Frame::parse` checks everything the old + `from_bytes` checked, and `Frame` is `Encrypt`. `kind`, `is_null`, + `has_passthrough` and `elements` are on `Frame`, and `elements` lends + each element as a `Frame` with no copy. The engine's readers, the + `TargetResolver`'s `encrypt` and `query`, and the `eql-bindings` by-name + entry points and generated dispatch take a `Frame<'_>`. `FieldHandle` and + `DynamicQuery` take any source, and `Planned` is a target over an + `OwnedFrame` or a `Frame`. +- The owned value is `vitaminc_aead::frame::OwnedFrame`, re-exported by + `recipher-frame` and so by `stack_encrypt::dynamic::frame`: a newtype + over a `Buffer` that `Frame::parse` accepted, with `of`, `from_buffer`, + `null`, `typed_null`, `frame` and `into_buffer`. It is `Encrypt`, + `Decrypt` and `Zeroize`, and has no `==`: two frames compare through + `Frame`'s constant-time `==`. Two places need it: a record's field slots + (`plan/values.rs`), which hold an owned value, and the TypeScript addon's + async calls. It is not a `Buffer` with `Encrypt` added, because + `Protected>` already encrypts as a bytes scalar. +- The decrypt sink writes the opened value into one buffer: the frame + writer is generic over a borrowed or an owned buffer and over the error + it reports, so a container's children are written in place, with no + copy per child. +- A zeroized `OwnedFrame` holds the plain null, so it is always one frame + and `frame()` cannot fail. +- `Planned` is `Zeroize` only for an `OwnedFrame`, which it wipes, and a + `Frame`, whose owner wipes it. `Frame` does not implement `Zeroize`: + wiping a view would wipe nothing, and `EncryptTarget`'s `Zeroize` bound + is on the `Planned`, not on the value. +- The Go guest reads every plaintext input with `Frame::parse` on the + host's bytes, the page of values to verify included, and the TypeScript + addon keeps the bridge's buffer with `OwnedFrame::from_buffer`: one copy + fewer at each boundary. +- In `eql-bindings`, a plaintext that may be absent reads any null, plain + or typed, as `None`, and seals it padded to its own type. +- `ValueFrame::check` is not replaced: a caller checks a record source with + `Frame::parse`. `FromFrameError` is replaced by `FrameError`. +- What stays in the engine is engine logic, not a wrapper: reading a text + frame as a context label (`IntoLabel`, the engine's trait) and splitting a + record source into one frame per field (`dynamic::source`). The split + writes with vitaminc's `FrameWriter` and names the field a refusal came + from itself. +- The `eql-bindings` API that took `ValueFrame` was not released yet, so its + breaking change is in an unreleased changelog entry. + +### 2.5 One place converts a value to its declared type + +Today Go converts a value to the field's type on the host, the engine +refuses a write whose width differs from the declared type, and the engine +converts a query's value when the conversion is exact. A JavaScript `bigint` +has no width, so the bridge writes the narrowest one that fits, and a +JavaScript user cannot write `34n` to an `int64` field. + +The exact conversion the engine uses for a query also runs on a write, in +one place. A bridge is never told the declared type. The conversion is never +lossy, never between a number and a value that is not a number, and never +from a float to a decimal. The value is sealed at the declared width, so no +stored bytes change. The conformance cases that pin today's refusal change +from refused to accepted. + +A typed field takes a value of its type or a null, and nothing else. +JavaScript's `undefined` is refused with an error of its own, and a +conformance case pins that. Today it is refused only because it has no type, +with a general error, and no test covers it. Storing it as a null would hide +a misspelt property name. Inside an untyped value, `undefined` is kept as it +is today. + +Done (#1990): + +- `dynamic::read` and the write path share one function, `kind::convert`. + It takes a `Frame` and returns `None` when the value is already of the + kind, so a value that needs no conversion is not copied. `read` is + `convert` over any source. +- The write path converts in `check_field`, which now takes the field's + `OwnedFrame` and returns the value the field stores: the one it came as, + or the converted one, with the other wiped. `source_rows` calls it for + each field, so `record::encrypt`, `encrypt_with`, `check_source` and + `Planned` all convert, and `check_source` and `encrypt` still share the + code. A target field's `record::query` calls it too. +- The rule for containers: the value is read as a whole. A scalar converts + to a scalar kind. An `array` or `object` field takes a container as it + is, and nothing inside one converts, since the field declares no type for + its elements. A `json` field takes its text or bytes as they are. +- `undefined` is refused in `convert` with the new `Reason::Undefined` + (`"undefined"`), on a write and on a query, whatever the field's null + policy. In an untyped field, or inside a container, it is kept. +- No stored bytes moved. `value_bytes_v1.json` pinned two of the changed + refusals; its `float64_for_float32` case now seals the same leaf as the + `float32` 1.5, and the test asserts that, and `undefined_for_string` now + reports `undefined`. +- Conformance: five `record-values-v1` cases (an `int16` for `int8`, an + `int8` for `uint8`, an `int64` for `int128`, a `uint64` for `uint128`, a + `float64` 1.5 for `float32`) changed from refused to accepted, with a new + `stored` key naming the converted value. The runners seal it as a second + row and compare terms, ciphertext length and the opened value. Three + `record-runtime-v1` "wrong width" cases became `*-other-width` and are + accepted; `required-integral-float` and `required-fractional-float` + were added. A new `int32-given-undefined` case pins the refusal. Go has + no `undefined`, so its runner skips that case. +- Go needed no change to its reason handling: `Diagnostic.Reason()` + passes the engine's reason through, and no Go code lists the reasons. + `Cipher.Seal` now takes a number of another width for a typed field, so + the Go changelog says so. The Go guest's own test of a refused float now + uses a fraction. +- The TypeScript addon needs no change: it hands the bridge's frame to the + engine, which converts. `value-napi`'s README says a typed field reads + `5` and `5n` alike and refuses `undefined`. + +### 2.6 The bridges and the SDKs + +- **TypeScript:** `OneValue`, `is_uuid`, and the `recipher_js::uuid` code + are deleted. (Step 2.4 already hands the bridge's buffer to the engine + with no second copy.) +- **Go:** the guest stops calling `Frame::parse` itself. (Step 2.4 already + removed its `OwnedFrame::from_bytes` call.) +- **EQL:** the `Plaintext` trait and the generated code use the type from + 2.2. + +A UUID then works in every SDK, which closes #1821. + +Done (#1992): + +- **TypeScript:** nothing removed on `next`. `is_uuid` and the + `recipher_js::uuid` code are only on the values and records branches + (#1775, #1776), and are removed there when they rebase. `OneValue` stays + on `next`: the addon's `keyset.encrypt` takes a string only, through the + engine's opaque scalar path, and that path needs a `Scalar`. An + `OwnedFrame` is not one, because it can hold an array. +- **Go:** the guest keeps its `Frame::parse`. It is not a second check: + the engine's readers take a `Frame`, and `Frame::parse` is the only way + to make one from the host's bytes. It also gives the Go SDK its "not a + frame" error before any key request. The two identical helpers are now + one, `parse_frame`, with a comment that says why. +- **EQL:** `Target::plaintext` is an `Option`, and + `plaintext_kind` is gone. `eql-codegen`'s `plaintext_of` returns a + `ValueKind`, the generated table writes `ValueKind::Int32` and so on, and + the Go table writes `ValueKind::name`. The `Plaintext` trait already used + `ValueKind`. The wire format and the Go file did not change. +- **UUID:** Rust stores, queries by equality and reads a `uuid` field + (`dynamic::record`'s tests). The Go guest does too, through its record + and query exports (a new guest test). The Go SDK's `gensupport` takes a + UUID, but `stashgen` maps no Go type to the `uuid` kind, so generated + code cannot declare one yet. The TypeScript addon on `next` encrypts a + string only, so it cannot store a UUID. The values and records branches + still refuse a `VcUuid` with `recipher_js::uuid`, and test that refusal; + once they drop it, they need a test that stores, queries and reads one. + So #1821 stays open for `stashgen` and the addon. +- No stored bytes changed: the pinned fixtures and conformance cases pass + unchanged. + +## Stage 3: move the Go packages + +vitaminc has two Go packages that the Go module imports in about 60 places: + +| Package | What it is | +|---|---| +| `vcvalue` | The Go value types: `Date`, `Decimal`, `Int128`, `Uint128`, `Timestamp`, `UUID`, `TypedNull`, `Plain`, `Object`. No dependencies. | +| `vcffi` | The frame codec in Go: frames, ciphertext trees and the storage profile (`MarshalStorage`). | + +They do not link the Rust crates. The Go host encodes a frame and the guest +decodes it, so the two share a byte format and no code. That is why this +stage does not have to run with stage 1. It starts after stage 1 and can run +beside stage 2. + +It must finish before the Go SDK's final release: + +- **The types are in the SDK's public API.** `encrypt.Date`, + `encrypt.Decimal`, `encrypt.Int128` and `encrypt.Uint128` are aliases of + `vcvalue` types. Moving a type changes its package path, which breaks a + user's code after a release. +- **The release is blocked on them.** The packages have no tags, so `go.mod` + pins an unreleased commit, and `scripts/go-release-version.mjs` refuses a + final version while that pin is there. +- **The codec's test data moves in stage 1.** `vcffi`'s tests read the + storage corpus that sits beside `recipher-frame` (`vitaminc-aead-frame` + until step 2.4). + +The work: + +1. Move both packages into `languages/golang`, with their tests and fuzz + targets. Decide where each type is declared: the value types are public, + and the codec need not be. +2. Update the imports. Remove the pin from `languages/golang/go.mod` and + from the two nested modules that carry it. +3. Remove the matching refusal from `scripts/go-release-version.mjs`. +4. Apply stage 2 to them. `vcvalue.FixedType` is one more copy of the type + list. +5. Delete `vcencrypt` and its guest from vitaminc. It was a demonstration of + the approach, and the Go module replaces it. + +### Done + +Items 1 to 4 are done, in #2003: + +- The two packages moved, and stay two packages. `vcffi` is now + `languages/golang/encrypt/frame`: the codec and the storage profile. + `vcvalue` is now `languages/golang/encrypt/value`: the value model, which + imports nothing outside the standard library. Both are public, as they + were in vitaminc. Both were copied from vitaminc commit `f1fc9ae74`, with + their tests and fuzz targets. The tests read the value corpus + (`conformance/vitaminc-aead`) and the storage corpus + (`packages/recipher-frame/testdata`) from this repository. +- `encrypt.Date`, `Decimal`, `Int128`, and `Uint128` are still aliases, + now of the types in `encrypt/value`. `encrypt.UUID`, `Encryptable`, and + `Encoder` are new aliases, of `value.UUID`, `frame.Encryptable` and + `frame.Encoder`. Each type is declared once, so the codec needs no + conversion. +- The sealed leaf family, `VCValueLeaves`, `TypedNull`, `FixedWidth`, and + `FixedType` are removed. The typed null for a nil pointer is built from + the tag table, so the codec has no list of types. `record.Kind` is the + only list of type names. +- No `go.mod` names a vitaminc module: not the one of the module, and not + those of its two nested modules. `scripts/go-release-version.mjs` no + longer refuses a final version because of a vitaminc pin. +- The Go campaign in `fuzz.yml` fuzzes the three decoders every night. + +Two things are still to do: + +- Item 5, in vitaminc: cipherstash/vitaminc#646 deletes `bindings/go` + (`vcffi`, `vcvalue` and `vcencrypt` with its guest). +- The differential fuzzers that compared the Go codec with a Rust guest, in + vitaminc's `vcencrypt`, are to run against + `languages/golang/encrypt/guest` (#2004). + +## What waits on this plan + +- The TypeScript SDK: #1775, #1776 and the prototype #1829. +- `ScalarFrame` (#1825, draft #1827). It wraps `ValueFrame`, which step 2.4 + replaced with `OwnedFrame`. +- The language integration guide's new sections on the value model (#1828). + They describe the model this plan removes. +- The UUID fix (#1821). +- The Go SDK's final release, on stage 3. + +## Checks that must move with the code + +Every check vitaminc ran on these crates runs here, or does not apply: + +| vitaminc check | Here | +|---|---| +| Storage corpus append-only | `storage-corpus.yml`, on a pull request that changes the corpus or the script. | +| `kani-storage` (the storage reader's proofs) | `kani.yml`: on a pull request that changes the reader or its proofs, and nightly when anything it compiles from changed in the last day. About ten minutes. | +| `kani` | Not here: it proves `vitaminc-protected`, which stays in vitaminc. | +| `cargo deny` | `supply-chain-vitaminc-aead.yml`, per pull request and nightly, over the three crates' graph only (`supply-chain/vitaminc-aead/deny.toml`). | +| `cargo vet` | The same workflow, per pull request, with a store started from vitaminc's (`supply-chain/vitaminc-aead/`), over the three crates' graph only. | +| Mutation testing | `mutants.yml`, `--in-diff`, as for `stack-encrypt`. | +| Per-feature tests, and the release-only jiff tests | `test:vitaminc-aead:features`, in `tests-crates.yml`. | +| Miri, sanitizers | Not needed. vitaminc ran them on `vitaminc-protected` only, and the three crates `#![deny(unsafe_code)]`. A change that adds `unsafe` adds both. | +| Fuzzing | vitaminc's targets are Go, over `vcffi`, and move with it in stage 3. stack-encrypt's targets reach parts of the crates and replay when they change. | + +`cargo deny` and `cargo vet` over the rest of the root workspace are #1842. + +Pull requests may change the three crates. + +## Open questions + +1. **What is a frame called?** Resolved in step 2.4: "frame" stays the + name of the encoding, and the crate that holds its codec is + `recipher-frame`. The owned value is `OwnedFrame`. +2. **What becomes of `vitaminc-aead-derive`?** The current intent is to + remove it, and to move its derives, changed as needed, into + `recipher-derive`. Today there are two derive crates: + - `vitaminc-aead-derive` derives `Encrypt` and `Decrypt` (attribute + `aead`). `vitaminc-aead` depends on it and re-exports the derives. + - `stack-encrypt-derive` derives `EncryptTarget` and `DecryptSource` + (attribute `stash`). + + To decide: + - whether `recipher-derive` is `stack-encrypt-derive` renamed, with the + AEAD derives added, or a new crate; + - whether `recipher-aead` still offers `Encrypt` and `Decrypt`, and so + depends on `recipher-derive`, or whether only `recipher` does; + - what changes in the derives and their `aead` attribute when they move. + +## Rules this changes + +- "A fix always belongs in vitaminc." A fix to the AEAD crates belongs here. +- `AGENTS.md` describes vitaminc as a dependency from crates.io. Update it in + the stage that changes that. diff --git a/docs/plans/2026-11-22-recipher-typescript-sdk.md b/docs/plans/2026-11-22-recipher-typescript-sdk.md new file mode 100644 index 0000000000..1ce7d36edf --- /dev/null +++ b/docs/plans/2026-11-22-recipher-typescript-sdk.md @@ -0,0 +1,1392 @@ +# `@cipherstash/recipher`: the TypeScript SDK on Stack Encrypt + +Date: 2026-11-22. Revised 2026-11-23: the SDK is a general-purpose core +with EQL as an extension, and the work is in three phases. Revised +2026-11-29: the value rules now match the code of #1775 and #1996. Revised +again that day: a record's declaration holds Stack Encrypt's plan, and the +language binding only reads it. + +Status: in progress. Steps 1 and 2 of the build order are built, in #1774 +and #1775. Step 3 and the UUID are in open pull requests: #1776 and #1996. +The record pull request is being reworked to follow +[A record](#a-record). + +This plan says how to build the TypeScript SDK on Stack Encrypt +(`packages/stack-encrypt`). It is one new npm package and an addition to +another: + +- `@cipherstash/recipher`, the core. It encrypts values, files, whole + objects and records, and derives search terms. It knows nothing about a + database. +- `@cipherstash/eql`, which exists and holds EQL's wire types, schemas and + SQL. It gains an extension to the core, `@cipherstash/eql/recipher`. The + extension adds the EQL v4 types, so a record's fields can be stored in + PostgreSQL columns and queried there. + +The split is the one Rust has: `stack-encrypt` does the encryption, and +`eql-bindings` adds the EQL types to it. The plan also says how the +Drizzle, Supabase and Prisma Next adapters move onto the two packages. + +It follows the [SDK design principles](../sdk-design-principles.md). Stack +Encrypt's own documentation (`packages/stack-encrypt/src/lib.rs`) sets the +order: a value first, then a whole object, then a record, then search +terms. A database comes last, through EQL. The Go SDK +(`languages/golang/encrypt`, with `encrypt/eql`) is the reference for what +an SDK does. + +The crate `stack-encrypt` is to be renamed `recipher`. This plan +uses the current name. The Rust crates of the TypeScript SDK are named +`recipher-js`, so they never share that name. + +## Contents + +- [What it is](#what-it-is) +- [Scope](#scope) +- [Phases](#phases) +- [Packages and build targets](#packages-and-build-targets) +- [The core](#the-core) +- [Context: policies, labels and partitions](#context-policies-labels-and-partitions) +- [Values](#values) +- [The EQL extension](#the-eql-extension) +- [Credentials, keysets and audit metadata](#credentials-keysets-and-audit-metadata) +- [Results and errors](#results-and-errors) +- [Plaintext hygiene](#plaintext-hygiene) +- [Promises and cancellation](#promises-and-cancellation) +- [The adapters](#the-adapters) +- [Room for EQL v3 and v2](#room-for-eql-v3-and-v2) +- [Tests](#tests) +- [Packaging and release](#packaging-and-release) +- [Documentation and skills](#documentation-and-skills) +- [Order of work](#order-of-work) +- [Decisions](#decisions) +- [What was checked](#what-was-checked) + +## What it is + +A TypeScript program declares what it encrypts, in TypeScript. It encrypts +values, builds search terms for them, and decrypts them again. The +compiler refuses a value of the wrong type and a query that a field cannot +answer. + +The core is enough for a program that keeps its ciphertext anywhere: a +file, an object store, a key-value store, or a database column of bytes. +A program that wants PostgreSQL to compare encrypted values adds the EQL +extension. + +Stack Encrypt does all the work, and that code exists once. The SDK sends +a plan and values across a language binding, and Stack Encrypt returns +ciphertexts, terms, and values. A plan is Stack Encrypt's description of how +to encrypt each field of a record: see [A record](#a-record). The bytes are +the same as Go's and Rust's for the same plan, because they run the same +code. + +The language binding is thin. A small team cannot maintain the same +behaviour written again in each language. Three rules keep the binding +thin: + +- **The binding does not repeat Stack Encrypt.** It does not read a plan, + check a row, convert a value to its field's kind, or build the encrypted + form itself. It calls `stack_encrypt::dynamic` for each of those. +- **A gap is fixed in Stack Encrypt.** When the SDK needs something that + `dynamic` cannot do, the change goes into Stack Encrypt, where every SDK + gets it. The binding does not work around the gap. +- **Stack Encrypt's names are not renamed.** A plan's outputs are named + `c`, `eq`, `match`, `ore`, `ope`, and `passthrough`. The SDK uses those + names. If a name is hard to read, an alias is added to Stack Encrypt's + plan, and every SDK gets it. + +It runs in two places: + +- **Node.js**, through a native extension built with napi-rs. +- **Edge runtimes and browsers**, through the same Rust code built for + `wasm32-unknown-unknown` with `wasm-bindgen`. + +It does not use the WASI guest that the Go SDK uses. + +## Scope + +In scope, for the core: + +- A value, a file and a whole object, each as one ciphertext, with a + context or with none. +- A record: fields that are encrypted, indexed or passed through. +- Stack Encrypt's indexes (`eq`, `match`, `ore`, `ope`) and the query + terms for them. +- The parts of a context: policies, labels and partitions. +- Nulls, credentials, keysets and audit metadata. +- Every profile of `conformance/stack-encrypt` that needs no EQL type. + +In scope, for the EQL extension: + +- EQL v4 only. The extension writes and reads EQL v4 values. It does not + read EQL v3 values or anything `cipherstash-client` wrote. +- Every EQL v4 type Stack Encrypt produces, including `JsonSearch` documents. +- The EQL/JSON profile, and the EQL rows of the exchange profile. + +In scope, after both, and after `recipher-compat`: + +- The Drizzle, Supabase and Prisma Next adapters, moved onto the two + packages in a new major version each. +- The DynamoDB integration, moved onto the core. + +Not in scope: + +- A change to a declaration over time. The principles leave it undecided. +- Streaming. A file is encrypted in memory, as one value. +- EQL v3 and v2. A separate crate, `recipher-compat`, is planned to read + and write them. This plan does not design it, but leaves room for it: + see [Room for EQL v3 and v2](#room-for-eql-v3-and-v2). + +## Phases + +Stack Encrypt issues this plan first waited for are still open. The design of +a context is decided, in ADR-0016 +(`packages/stack-encrypt/docs/adr/0016-a-context-is-a-field-path-and-named-parts.md`, +PR #1772), but Stack Encrypt does not have it yet. So the work is in three +phases, and the first starts now. + +| Phase | Starts | What it builds | +|---|---|---| +| 1 | Now | Everything that needs no context from the caller. The core first: values, records, query terms, credentials and the wasm build. Then the EQL extension, and a pre-release of both on npm. | +| 2 | When Stack Encrypt has ADR-0016's named parts | Labels and partitions, a value with a context, and the policies Stack Encrypt has. | +| 3 | When the issues that change stored bytes are closed | Refinements, the first stable release and, when `recipher-compat` exists, the adapters. | + +[Order of work](#order-of-work) lists the steps of each phase. + +### What phase 1 leaves out + +A phase 1 value has no parts. A value encrypted alone has no context. A +record field's context is its field path: the record's name and the +field's name. So phase 1 has no `.withContext`, no `with(..)`, no part +declared in a record and no `.partition`. + +These are the two forms that ADR-0016 says keep their stored bytes: a +value with no context, and a value whose whole context is a field path. + +Two rules keep phase 1 clear of the open design: + +- **Only the Rust crate names a Stack Encrypt type.** The TypeScript code does + not. A rename in Stack Encrypt changes one crate. +- **No phase 1 build promises that a later build opens its stored values.** + The README says so. The promise starts with the first stable release. + +### Issues that are still open + +Phase 1 does not wait for these. Each one changes a small, known part of +phase 1 when it lands. + +| Issue | State on 2026-11-23 | What it changes here | +|---|---|---| +| #1669 (`encrypt_with` and `decrypt_with` become `Planned`) | Closed | Nothing. The crate calls `Planned` from the first record step. | +| #1489 (the naming review) | Open | Stack Encrypt names in the crate (`StackCipher` becomes `Cipher`, `stack-kms` becomes `stack-zerokms`, and the rest). The TypeScript names already follow the review: `Cipher` and `Keyset`. | +| #1594 (a binding sends a serialised `Planned`) | Open | The conformance runners' reader of the corpus. The crate calls `Planned` directly. | +| #1672 (the closed `FieldIndexes` shape) | Open | `record()`, which writes the plan in TypeScript. | +| #1673 (match options as one analyzer pipeline) | Open | The options of a `match` index. Phase 1 offers the default options only. | +| #1678 (JSON Schemas and a protocol version) | Open | Nothing in phase 1. Phase 3 checks the plan that `record()` writes against the schema. | + +The record step found two gaps in Stack Encrypt. Each is fixed in Stack +Encrypt. The binding works around neither: + +- **One field of a plan (#2028).** No call encrypts or decrypts one field of a + plan. A row that lacks a field is refused. `{ record, field }` needs + this call. +- **Serde for the encrypted tree (#2029).** The tree that a record encrypts to + (`StackCipherText`) cannot be serialised. Only its leaves can. So each + binding writes its own conversion: the Go guest has `encode_tree` and + `decode_tree`. With serde on the tree, the binding writes it to a frame, + and the value bridge builds the JavaScript value from the frame. + +Phase 2 waits for Stack Encrypt to have ADR-0016: + +- **#1663**: the `Label` struct becomes `FieldPath`, and `IntoLabel` goes. +- **Named parts in Stack Encrypt.** The traits `Policy`, `Label` and + `Partition`, the built-in parts, and `.partition(..)` on a query. The + untyped `Scope` and `Bind` are removed. No issue tracks this yet. +- **#1566**: a value's parts go to ZeroKMS as named key request items. + +A policy also needs ZeroKMS to check it. Phase 2 offers each policy when +Stack Encrypt and ZeroKMS have it. #1683 is to be rewritten for that. + +Phase 3 waits for these, because they change stored bytes or the +compatibility promise: + +- **#1567**, which ADR-0016 turns into refinements: a label or a policy + added to a value that is already stored. +- **#1399** (a character filter in the match index), which changes match + terms. #1398, its pair, is closed. +- **#1490** (stable gates and conformance versions) and **#1314** + (the compatibility policy). +- EQL v4 installable through `stash eql install`, and `recipher-compat`, + for the adapters. + +The rest of the milestone *Stable Stack Encrypt Rust release* does not +block this plan. The Go-only issues, the internal ones (#1458, #1676, +#1670, #1671, #1063, #1684) and the typed Rust ones (#1668, #1569, #1570) +do not change a binding. #1572 is to be rewritten or closed by ADR-0016. #1479 (the TypeScript conformance runner) is part of this plan. +#561 and #1565 are answered by this design. + +## Packages and build targets + +The SDK has two Rust crates: the language binding for Node, and the value bridge it +converts values with. + +| Path | Name | What it is | +|---|---|---| +| `languages/typescript/packages/recipher-js/crate` | crate `recipher-js` | Rust, napi-rs 3. The language binding for Node. It defines the classes TypeScript uses, runs every operation through Stack Encrypt, and maps errors. It depends on `stack-encrypt` (`dynamic`) by path, and converts values with `recipher-value-napi`. | +| `languages/typescript/packages/recipher-js/value-napi` | crate `recipher-value-napi` | Rust, napi-rs 3. The value bridge: reads a JavaScript value into vitaminc's plaintext model, and builds one from it. Not published. | +| `languages/typescript/packages/recipher-js` | npm `@cipherstash/recipher` | The core SDK, its types and the loaders. Its builds hold no EQL type (`NoTargets`). | +| `languages/typescript/packages/recipher-js/platforms/*` | npm `@cipherstash/recipher-` | One package per Node platform, holding its `.node` file. | +| `packages/eql/packages/eql` | npm `@cipherstash/eql`, entry `./recipher` | The EQL extension: the EQL v4 types in TypeScript, and the loaders of the builds that hold them. The package exists; the entry is new. | +| `packages/eql/packages/eql-` | npm `@cipherstash/eql-` | One package per Node platform, holding the EQL build's `.node` file. | + +**How the extension reaches Stack Encrypt.** Stack Encrypt runs a named type +through a `TargetResolver` that the host links in. `NoTargets` is the +build without one. So the crate has a cargo feature, `eql`, which links +`eql-bindings` (`targets`) by path and uses its resolver. The core package +ships the builds without +the feature. `@cipherstash/eql` ships the builds with it. This is what Go +does: `encrypt/eql` holds a second build of the guest, with the EQL types. + +A cipher runs in one build. A program names its extensions when it builds +the cipher, and the cipher loads the build that holds them: + +```ts +import { Cipher } from "@cipherstash/recipher"; +import { eql } from "@cipherstash/eql/recipher"; + +const cipher = await Cipher.create({ extensions: [eql] }).unwrap(); +``` + +The extension is passed as a value, not registered by an import, because a +bundler can drop an import that is used only for its side effect. + +**Versions.** The core and EQL are released apart. Several versions of +`@cipherstash/eql` work with one version of `@cipherstash/recipher`. What +they share is the binding interface: the functions the core's TypeScript +calls on a build. The interface has a version number. Each build reports +the number it implements, and `Cipher.create` refuses a build with another +number. A change to EQL's SQL changes `eql-bindings` with it, so those two +are released together, as they are today. + +**No crate is split off before it is needed.** The value bridge is a +crate of its own because it came from vitaminc as one. The wasm build of +step 6 cannot use napi, so it needs a crate of its own. The code the two +builds share moves into a common crate then, when both exist and what +they share can be seen. + +**Rust defines the API, and TypeScript does not copy it.** `Cipher`, +`Keyset` and `Ciphertext` are napi classes written in Rust. napi-rs +generates their TypeScript types, and the generated file is committed and +checked for drift in CI, as `@cipherstash/auth`'s `native.d.ts` is. There +is no hand-written description of the native interface, and no TypeScript +class that wraps a native one. Each native method returns the `Result` +itself: the package's TypeScript hands the binding its `Ok`, `Err` and +`RecipherError` classes once, when it loads the binding, and Rust builds +`new Ok(value)` or `new Err(error)`. Each method's public signature is +written in Rust, in napi-rs's `ts_type` attribute, one overload per line, +and the generated `native.d.ts` is the public type. A small header that +napi-rs puts at the top of that file gives `Ciphertext` its type +parameter. TypeScript holds only what Rust cannot express: + +- `Result` and its methods, because `isOk()` narrows a type; +- the types of a declaration, such as `Plaintext<..>` and `Stored<..>`, + and the compile-time checks of a query, which the signatures in Rust + name; +- the loader, and stand-in classes for when the binding did not load. + +**The crate uses Stack Encrypt's and vitaminc's types.** It does not wrap +`ValueFrame`, a ciphertext or an error in a type of its own. A type that +holds a secret derives vitaminc's `OpaqueDebug`. The vitaminc skill +(`.claude/skills/vitaminc/`, added by #1777) lists the type for each task. + +**What `@cipherstash/eql` keeps.** Its root, `./schema` and `./sql` entries +load no native build and do not import the core. The CLI and +`stash eql install` use those entries, and they stay as light as they are. +Only `./recipher` loads a build. `@cipherstash/recipher` is an optional +peer dependency, for that entry alone. + +The core package and the `./recipher` entry each pick their build by export +condition, as `@cipherstash/auth` does: + +- `node` loads the napi binding for the platform. +- `default` loads the wasm build, as a separate `.wasm` file. +- `./wasm-inline` (`./recipher/wasm-inline` in `@cipherstash/eql`) loads + the wasm build inlined into the JavaScript, for bundlers and edge + runtimes that cannot load a second file. + +The six platforms are the ones `@cipherstash/auth` ships: `darwin-arm64`, +`darwin-x64`, `linux-arm64-gnu`, `linux-x64-gnu`, `linux-x64-musl` and +`win32-x64-msvc`. + +The cargo workspace is detached, with its own `Cargo.lock`. +Each package's `build` and `test` scripts never run cargo, so root +`pnpm test` needs no Rust toolchain; `build:native`, `build:wasm` and +`test:cargo` do. This is the rule protect-ffi and `@cipherstash/auth` follow. + +## The core + +The core follows Stack Encrypt's own order: a value, a whole object, a record, +then search terms. Nothing in this section needs a database. + +### A value + +```ts +import { Cipher } from "@cipherstash/recipher"; + +const cipher = await Cipher.create().unwrap(); +const keyset = cipher.defaultKeyset(); + +const sealed = await keyset.encrypt("a secret message"); +if (sealed.isErr()) { + return sealed; // a RecipherError, as a value +} + +const opened = await cipher.decrypt(sealed.value); +``` + +This is plain encryption, with no context. It is Stack Encrypt's +`keyset.encrypt(value)`. + +- **One value in, one ciphertext out.** The next section encrypts an + array. +- **No call throws, apart from a method called without its object.** + Every call resolves to a `Result`. See + [Results and errors](#results-and-errors). +- **The value's type picks how it is encrypted.** A `string` is encrypted + as text, a `boolean` as a boolean, a `number` as a float, a `bigint` as + an integer, a `Uint8Array` as bytes and a `Date` as a timestamp. This is + the value bridge's mapping, and [Values](#values) has the table. + No call names a kind. +- **A plain object is refused.** It has no one encoding, so the caller + chooses `opaque(..)` or `json(..)`. Stack Encrypt has the same rule: it has + no fallback that picks the stored bytes of a struct. +- **Encrypting needs a keyset; decrypting does not.** Every data key is + made under one keyset, and a ciphertext names the keyset it was made + under. `cipher.decrypt` opens a value from any of the cipher's keysets. + `keyset.decrypt` refuses a value from another keyset. This is Stack + Encrypt's rule. +- **A `Ciphertext` is opaque bytes.** `ciphertext.toBytes()` gives a + `Uint8Array` to store, and `Ciphertext.fromBytes(..)` reads one back. + Each ciphertext has its own data key. +- **A ciphertext knows its type.** `encrypt("..")` returns a + `Ciphertext`, and decrypting it gives a `string`. A ciphertext + read from storage is typed by naming the type: + `Ciphertext.fromBytes(bytes, kinds.string)`. Decrypting it refuses a value + that was encrypted as another type. With no type named, the value comes + back as what it was encrypted as, typed as the union of them. + +### An array of values + +```ts +const sealed = await keyset.encrypt(["first secret", "second secret"]).unwrap(); +// sealed is an array of two ciphertexts, in the same order. + +const opened = await cipher.decrypt(sealed).unwrap(); +``` + +An array in is an array out, and it makes one ZeroKMS request however long +it is. This is Stack Encrypt's rule for a collection. There is one `encrypt` +and one `decrypt`: no second function for a batch, and no loop over single +calls. + +### A file, and a whole object + +A file or a stored object is a `Uint8Array`, so it needs no kind: + +```ts +const sealed = await keyset.encrypt(await readFile("invoice.pdf")).unwrap(); +await writeFile("invoice.pdf.enc", sealed.toBytes()); +``` + +A whole object is one ciphertext with `opaque`: + +```ts +import { opaque } from "@cipherstash/recipher"; + +const card = { number: "4111 1111 1111 1111", expiry: { month: 4, year: 2031 } }; +const sealed = await keyset.encrypt(opaque(card)).unwrap(); +``` + +`opaque` stores what Stack Encrypt's `OpaqueBlob` stores, in the same format +as a Go opaque struct. Nothing inside it can be searched. + +An opaque value is a storage blob, vitaminc's storage profile, encrypted +as bytes. Rust's `OpaqueBlob` writes the blob from a `Serialize`, and Go +writes it with `vcffi.MarshalStorage`. The SDK needs the same from a +JavaScript value, which reaches Rust as a frame, and nothing converts a +frame to a blob yet (#1822). Stack Encrypt needs no change. Version 1 of the +profile holds plain scalars only, so a `Date` or an `RcDecimal` inside an +opaque object is refused. + +### A record + +A record declares each field once. A field is encrypted, encrypted and +indexed, or passed through. The words are Stack Encrypt's. + +```ts +import { encrypt, kinds, passthrough, record } from "@cipherstash/recipher"; + +export const UserRecord = record("users", { + id: passthrough(), + email: encrypt(kinds.string, { index: ["eq"] }), + name: encrypt(kinds.string, { index: ["match"] }), + age: encrypt(kinds.int32, { index: ["eq", "ore"] }), + notes: encrypt(kinds.string), +}); + +const user = { id: 1n, email: "ada@example.com", name: "Ada Lovelace", age: 36n, notes: "maths" }; + +// One row. An array of rows returns an array, in one ZeroKMS request. +const stored = await keyset.encrypt(user, { record: UserRecord }).unwrap(); +const opened = await cipher.decrypt(stored, { record: UserRecord }).unwrap(); +``` + +- **The plaintext comes first.** Every `encrypt` takes the value first and + an options object second. The options are `{ kind }` for one value, + `{ record }` for a row, and `{ record, field }` for one field of a row. A declaration is + named for what it is (`UserRecord`), so a reader can tell it from the + row (`user`). A context will be another key of the same object, so no + call takes a third argument (#1776). +- **A field names its kind.** A declaration has no value to read a type + from, and the stored type is fixed before any row exists. So + `encrypt(kinds.string)` names it, in Stack Encrypt's word for the kind. +- **`record()` writes Stack Encrypt's plan.** The plan is the form that + `Plan::from_frame` reads, and the form that Go sends. The + declaration above holds this plan: + + ```ts + { + id: { context: ["users", "id"], outputs: ["passthrough"] }, + email: { context: ["users", "email"], outputs: ["c", "eq"], type: "string" }, + name: { context: ["users", "name"], outputs: ["c", "match"], type: "string" }, + age: { context: ["users", "age"], outputs: ["c", "eq", "ore"], type: "int32" }, + notes: { context: ["users", "notes"], outputs: ["c"], type: "string" }, + } + ``` + + There is no second format. The binding has no declaration type of its + own, and builds no plan by hand. +- **The user never sees the plan.** A program calls `record`, `encrypt`, + and `passthrough`. The program passes the declaration to a call. The + declaration's public type shows the record's name and the types of its + fields. It does not show the plan. The plan still shapes the API: each + option of `encrypt(..)` is an option that a plan has, under the plan's + name for it. +- **The binding reads the plan and calls Stack Encrypt.** The value bridge + converts the plan object to a frame, as it converts any value, so + TypeScript writes no frame. `Plan::from_frame` reads the frame. + `dynamic::Planned` encrypts and decrypts the rows. The binding keeps + each plan it has read, keyed by the plan's bytes, so each plan is read + once. +- **Stack Encrypt checks the plan and each row.** + `Cipher.create({ records: [UserRecord] })` reads each plan before it + looks for credentials. A refusal is an `Err` that names the field and + the reason. A `checkDeclarations()` function runs the same check with no + credentials, for a test or a CI step. For a row, Stack Encrypt refuses a + field that the plan does not name. It also refuses a missing field, + unless the field stores a null as SQL `NULL`. So a field that is not + encrypted must be declared as a passthrough. Stack Encrypt also converts + each value to its field's kind. The binding makes none of these checks + itself. +- **An encrypted row is Stack Encrypt's representation, unchanged.** Each + encrypted field is an object with one property for each output, under + the plan's names. `c` is the ciphertext. `eq`, `match`, `ore`, and `ope` + are the indexes that the field declares. Each is opaque bytes. A + passthrough field keeps its value. The binding renames nothing. +- **The compiler checks the row.** `Plaintext` is + `{ id: bigint; email: string; name: string; age: bigint; notes: string }`. + A row of another shape does not compile. `Stored` is + the encrypted row's type. `stored.notes.eq` does not compile. +- **Index names are the plan's.** `index: ["eq"]` names the output `eq`. A + longer alias, such as `equality`, would be added to Stack Encrypt's + plan, so that every SDK reads it. This plan adds none. +- **Context.** A field's context is its field path: the record's name and + the field's name. Phase 2 adds parts; see + [Context](#context-policies-labels-and-partitions). +- **Nulls.** A field that can be `null` declares it, with the null modes + that a plan has: `sealed` and `sql`. +- **A declaration is plain data**: a frozen object with the record's name + and its plan. The package's own adapters read a field's kind and outputs + from the plan. An application does not. + +One field of a record, for an update of that field: + +```ts +const email = await keyset.encrypt("ada@example.com", { record: UserRecord, field: "email" }).unwrap(); +const opened = await cipher.decrypt(email, { record: UserRecord, field: "email" }).unwrap(); +``` + +Stack Encrypt has no call for one field of a plan yet (#2028). These two calls +wait for it. The binding does not build a second plan for each field. + +### Search terms + +A query names a field, an operator and a value. The result is the term to +compare with the stored term. + +```ts +const byEmail = await keyset.query(user, { field: "email", op: "eq", value: "ada@example.com" }); + +// An array of queries is a batch, which may span fields. +const terms = await keyset.query(user, [ + { field: "email", op: "eq", value: "ada@example.com" }, + { field: "age", op: "gte", value: 36n }, +]); +``` + +- **The compiler checks queries.** A query on `name` with `eq` does not + compile, because a `match` index answers no equality. The operators of + each index are generated from Stack Encrypt. A test asks Stack Encrypt + (`dynamic::field_operators`) and compares the answer with the generated + file. +- **A term is opaque bytes**, byte-equal to the term Rust and Go derive. + An equality term compares with `=`. `OreTerm.compare` orders two terms + in TypeScript. +- **Probabilistic queries.** A match term comes with `targetLimit` and + `verify`, which call `dynamic::target_limit` and `dynamic::verify`. +- **Match options.** A `match` index takes no options until #1673 decides + them. + +### The shape of a call + +- **Batch by default.** Every call takes one value or an array of them. + One value returns one result. An array returns an array, in the same + order, and makes at most one key request however long it is. It is the + same call, so the natural way to encrypt many values is the efficient + way. +- **All or nothing.** A batch that fails is one `Err`. It returns no + partial array. +- **Each call returns a pending result.** Awaiting it runs the call and + gives a `Result`. `.audit`, `.withCredential`, and `.signal` set up + the call. They come before any `Result` method. Phase 2 adds `.withContext` + and `.partition` to the same object, so it changes no phase 1 call. See + [Results and errors](#results-and-errors). + +## Context: policies, labels and partitions + +This section is phase 2. It is the TypeScript form of ADR-0016, which +decides the words, the wire names and the rules for every SDK. + +A context is a field path and a list of named parts. A part is one of +three kinds: + +- A **policy** restricts who can read a value. ZeroKMS checks it. +- A **label** is a fact that is safe to show, such as a row ID. It proves + a value was written for that row. It restricts no reader. +- A **partition** splits data into groups, such as tenants. It keeps one + group's values and search terms apart from another's. It restricts no + reader. + +The built-in parts have Stack Encrypt's wire names: + +| TypeScript | Wire name | Kinds | +|---|---|---| +| `notBefore(date)` | `not_before` | policy, label | +| `notAfter(date)` | `not_after` | policy, label | +| `forSub` | `for_sub` | policy | +| `forTenant` | `for_tenant` | policy, partition | +| `tenantId(value)` | `tenant_id` | label, partition | +| `recordId(value)` | `record_id` | label | +| `note(value)` | `note` | label | + +### A value with a context + +```ts +const sealed = await keyset.encrypt("a secret message").withContext("notes").unwrap(); +const opened = await cipher.decrypt(sealed).withContext("notes").unwrap(); +``` + +A bare value in `.withContext` is a `note`, which is a label. This is Stack +Encrypt's `encrypt_with_context`. It also takes named parts: +`.withContext(tenantId(42n), recordId(id))`. + +### A record with parts + +```ts +import { encrypt, forSub, kinds, passthrough, record, recordId, tenantId } from "@cipherstash/recipher"; + +export const notes = record("notes", { + id: passthrough().label(recordId), + title: encrypt(kinds.string, { index: ["eq"] }), +}, { context: [tenantId(), forSub] }); + +const tenant = keyset.with(tenantId(42n)); + +const stored = await tenant.encrypt(row, { record: notes }).unwrap(); +const term = await tenant.query(notes, { field: "title", op: "eq", value: "Renewal" }).unwrap(); +const opened = await tenant.decrypt(stored, { record: notes }).unwrap(); +``` + +- **A record lists its parts.** `context: [..]` names the parts a caller + supplies, or that ZeroKMS takes from the reader's token, such as + `forSub`. +- **A part can be read from a field.** `.label(recordId)` on a field reads + the value from that field and stores it in the clear. `.partition(..)` + on a field does the same for a partition. This replaces a context field. +- **What changes from one caller to the next attaches to the keyset.** + `keyset.with(..)` returns a keyset that carries the parts, for the write, + the query and the read. No call takes a part of its own, so the three + cannot differ. Go's `Cipher.With` is the same. +- **A query takes partitions only.** A query through a keyset that carries + a label does not compile. `.partition(..)` on one query narrows it + without a new keyset. +- **The compiler checks the parts.** A record that lists a part does not + compile against a keyset that lacks it. A value for a policy that + ZeroKMS takes only from the token, such as `forTenant`, does not compile + either. +- **A custom part.** `label("region")` and `partition("region")` define a + label or a partition of the application's own. A built-in wire name is + refused. There is no function that defines a policy, because `Policy` + is sealed in Stack Encrypt. +- **The order is Stack Encrypt's.** Parts are sorted by wire name, not by + the order they are written in. +- **A label that does not match is refused before any key is requested**, + as an `Err` with the code `stack_encrypt::context_mismatch`. +- **Refinements** (phase 3). `refine` adds a label or a policy to a stored + value without encrypting it again. It waits for #1567. + +## Values + +The conversion between JavaScript values and Stack Encrypt is the value +bridge, `recipher-value-napi`, in `recipher-js/value-napi`. It reads +JavaScript values into vitaminc's plaintext model, which Stack Encrypt +encrypts, and builds them back. It is a copy of vitaminc's +`vitaminc-aead-napi` 0.10.0, moved here because only this SDK uses it. It +is not published. + +- `JsRef` reads a live JavaScript value as an `Encrypt`, on the JavaScript + thread. `JsRef::to_frame` snapshots it as a frame, which a worker thread + then seals with no access to JavaScript. +- `JsBuilder` is a `Sink` that builds the JavaScript value of a decrypt. +- `Wrappers` defines the classes for the types JavaScript lacks. + +So no JSON text of a row crosses the boundary. + +| JavaScript | Encrypted as | Decrypts as | +|---|---|---| +| `string` | text | `string` | +| `boolean` | boolean | `boolean` | +| `number` | a 64-bit float | `number`. A 32-bit float widens exactly | +| `bigint` | an integer, at the narrowest width that holds it | `bigint`, for every width | +| `Uint8Array`, `Buffer` | bytes | `Uint8Array` | +| `Date` | a timestamp, in milliseconds | `Date` | +| `RcTimestamp.from("2026-11-23T01:02:03.000000001Z")` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | +| `RcDate.from("2026-11-23")` | a calendar date | `RcDate` | +| `RcDecimal.from("1.50")` | a decimal, with its scale | `RcDecimal` | +| `RcUuid.from("..")` | a universally unique identifier (UUID), from #1996, as a value or a record field | `RcUuid` | +| `null` | a typed null, with `nullable(kind)` of a fixed-width kind | `null`, with `nullable(kind)`. In a record, only where the field declares `null` | + +- **Integers are a `bigint`.** A `number` is a float, and `5` does not + match the integer `5n` in a query. Integer data uses `bigint`. +- **An integer's width is not chosen.** The bridge stores a `bigint` at the + narrowest width that holds it. Equality terms are the same across + widths, so `5n` here matches an `int64` 5 from Go. +- **A UUID is an `RcUuid`.** Stack Encrypt's dynamic value model has a UUID + kind, `ValueKind::Uuid` (#1929). A UUID field takes an equality index + only. The SDK encrypts an `RcUuid` as that kind from #1996, as a value + on its own or in a record field declared `kinds.uuid`. A decrypted + `RcUuid` contains lowercase hyphenated hex. A string that contains a + UUID is encrypted as text. Until #1996 merges, the SDK refuses an + `RcUuid` with `recipher_js::uuid`. +- **A null is asked for, as with Rust's `Option`.** A plain kind, such as + `kinds.int64`, reads as `bigint`, and a stored null is an `Err` with + `recipher_js::opened_null`. `nullable(kinds.int64)` reads as + `bigint | null`. To encrypt a null, a caller gives `nullable(..)` of a + fixed-width kind: `keyset.encrypt(null, { kind: nullable(kinds.int64) })`. + Stack Encrypt refuses that until it seals typed nulls (#2023). A lone `null` + with no kind is refused with `recipher_js::null_value`. +- **No precision is lost.** A timestamp finer than a millisecond opens as + an `RcTimestamp`, never as a rounded `Date`. +- **The wrapper classes are the bridge's.** Each is made with `from`, such + as `RcDecimal.from("1.50")`. `from` checks the text and returns a + `Result`. Each instance holds its text and is frozen. The classes have + no public constructor. The core package re-exports the + four the binding defines. The classes were renamed in #1775 to + `RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`. vitaminc's own + bridge names them `VcDate`, `VcTimestamp`, `VcDecimal`, and `VcUuid`. +- **The bridge's safety rules apply.** Only a plain object is read, by its + own enumerable string keys. A `Map`, a `Set`, a class instance, a sparse + array and a string with an unpaired surrogate are refused. A polluted + prototype cannot add a key or see a decrypted value. +- **Nesting has two limits.** Both count levels the same way. The top + value is level 0, and each array or object puts its items one level + further down. So in `[[1]]`, the `1` is two levels down. + - The bridge reads no value more than 128 levels down. That is the + frame's limit. + - A JSON document has no array or object more than 126 levels down, + counted from the document's own top. So at most 127 arrays and + objects nest inside one another, and a scalar can be 127 levels + down. Stack Encrypt's JSON parser reads no deeper. #1775 checks this + limit when `json(..)` reads the document, and refuses a deeper one + with `recipher_js::too_deep`. + - A `Json` never sits inside a value tree. In #1775, `encrypt` takes a + `Json` as one value, or as one item of an array of values. Each item + is read from level 0. A `Json` anywhere deeper is refused. So only + the document's own limit applies to a document. +- **A failed conversion is an `Err`.** The bridge reports which rule a + value broke as a typed refusal, a diagnostic with a `recipher_js::` code, + such as `recipher_js::not_plain` or `recipher_js::too_deep`. A scalar out of + range keeps its own code, such as `ERR_INTEGER_RANGE`. The SDK returns + either as an `Err` with that code. + +**A record field's kind.** A record field declares its kind, because the +stored type is fixed before any row exists. The kind checks the value: an +`int32` field refuses a `bigint` outside 32 bits. The TypeScript type of +each kind is the one in the table, so an integer field is a `bigint`, at +every width. A `number` in an integer field does not compile. + +**Integers in an adapter.** An ORM such as Drizzle gives an integer column +as a `number`. The adapter converts, because the adapter has the column's +type. The column's TypeScript type is `number | bigint`. + +- On the way in, a `number` that is a safe integer becomes a `bigint`. A + `bigint` is accepted as it is. A whole `number` outside the safe range + is refused, because it may have lost digits. +- On the way out, an integer within 2^53 - 1 of zero becomes a `number`. + A larger integer comes back as a `bigint`. So the adapter can read every + stored row, such as an `int64` above 2^53 that Go wrote. + +The core has one mapping, and it is the bridge's. + +**The wasm build.** The value bridge is for Node bindings only. The wasm +build needs the same mapping over `wasm-bindgen`'s `JsValue`, with the same +wrapper classes and the same refusals. It belongs beside the napi bridge, +in `recipher-js`. cipherstash/vitaminc#632 asked for it in vitaminc, and +moves here. vitaminc's other binding package, `vcffi`, is the Go transport +into a WASI guest and does not apply here. Both builds run the bridge's +value conformance cases (`value-napi/tests/value-conformance.cjs`). + +**JSON documents.** `json(value)` encrypts a JSON document, for a `json` +field or an EQL `Json` type. A JavaScript `number` cannot hold every +integer a JSON document can. So an integer outside the safe range is a +`bigint` in the tree. + +On encrypt, #1775 stores a whole number in a document by these rules. +Each range includes both ends. + +| The whole number | As a `number` | As a `bigint` | +|---|---|---| +| -(2^53 - 1) to 2^53 - 1 | an integer | an integer | +| 2^53 to 2^64 - 1 | refused, and the refusal asks for a `bigint` | an integer | +| -2^63 to -2^53 | refused, and the refusal asks for a `bigint` | an integer | +| -(2^64 - 1) to -(2^63 + 1) | refused: no exact form in a document | refused | +| 2^64 or more, or -2^64 or less | a float, such as `1e20` or `-1e20` | refused | + +A whole `number` outside the safe range may have lost digits, so the +refusal asks for a `bigint` where one fits. Below -2^63 no `bigint` +fits, so the refusal says the integer has no exact form. A `number` with +a fraction is a float. `NaN` and the infinities are refused. + +On decrypt, an integer outside the safe range comes back as a `bigint`. +The conversion is in Rust, and Stack Encrypt's one parser reads the result. +On the native build, a test in #1775 (`__tests__/addon/values.test.ts`, +"keeps an integer outside the safe range as a bigint") round-trips +2^64 - 1. The wasm build is not built yet. The plan is for the wasm build +to pass the same test, and the `eql-json-v1` case that contains +`18446744073709551615`. + +The value profile of the conformance suite (`record-values-v1`) is the +contract for the record kinds. Its cases include every kind at its edges +and the conversions the host refuses. + +## The EQL extension + +`@cipherstash/eql/recipher` adds one thing to the core: a field that is +stored as an EQL v4 type. In Stack Encrypt's words, the field names a target. +In Go it is the `encrypt_into=` tag. + +```ts +import { Cipher, passthrough, record } from "@cipherstash/recipher"; +import { eql, types } from "@cipherstash/eql/recipher"; + +export const users = record("users", { + id: passthrough(), + email: types.TextEq(), + name: types.TextMatch(), + age: types.IntegerEq({ null: "sealed" }), + profile: types.JsonSearch({ ordered: ["$.score"] }), +}); + +const cipher = await Cipher.create({ extensions: [eql], records: [users] }).unwrap(); +const keyset = cipher.defaultKeyset(); + +const stored = await keyset.encrypt(rows, { record: users }).unwrap(); +const byEmail = await keyset.query(users, { field: "email", op: "eq", value: "ada@example.com" }); +``` + +- **The same declaration and the same calls.** An EQL type goes where + `encrypt(..)` goes in a record. `encrypt`, `query`, and `decrypt` + are the core's. The extension adds no + call of its own for a scalar type. +- **A record is a table, and a field is a column.** The record's name is + the table's name and the field's name is the column's name. EQL stores + both in the value. +- **A field is plain verbs or one EQL type, never both.** A record can mix + the two kinds of field, as a Stack Encrypt plan can. +- **The stored field is EQL v4 JSON**, ready for a SQL parameter. A query + term carries the SQL domain it binds as (`term.domain`), as Stack Encrypt's + `QueryTerm` does, so an adapter writes the cast without a table of its + own. +- **The types come from the EQL catalog.** `eql-codegen` writes the Go + types today (`go_eql.rs` writes `languages/golang/encrypt/eql/eql_gen.go`). + It gains a TypeScript writer, which writes each type's plaintext type, its + operators and its options. A drift check fails CI when the file is stale, + as `types:check` does for Go. +- **The compiler checks that the extension is there.** A record that names + an EQL type does not compile against a cipher built without `eql`. +- **JSON documents.** A `JsonSearch` field has its document operators: + `contains`, `contained_by`, the comparisons at a path, `element_match`, + `match`, and the reads `selector`, `subtree`, `children` and + `child_count`. A read's rows open through `cipher.openJson(..)`, over + `dynamic::json_open`. These are the extension's only calls of its own. +- **Parts** (phase 2). An EQL record takes parts as any record does. Its + field path is the table and the column, which EQL stores in the value. + A tenant is a `tenantId` part, read from a column or supplied through + the keyset. + +## Credentials, keysets and audit metadata + +- **Credentials.** `Cipher.create()` finds credentials as every SDK does: + the `CS_*` variables, then the profile that `stash auth login` writes. On + Node, `stack-kms`'s profile store reads the file. The wasm build has no + file system, so its credentials come from the variables or the cipher's + options. +- **A credential with each call.** A cipher built over a strategy that + takes a credential with each call, such as OIDC federation, has a + different type. Its calls return a builder that cannot be awaited until + `.withCredential(jwt)` is called. Forgetting it is a type error, as it is + a compile error in Rust. It is the one mistake with a call that is not + an `Err`, because the compiler finds it first. The JWT is read in the caller's request, which is + what #1565 asks of `@cipherstash/stack`. +- **Keysets.** `cipher.defaultKeyset()` is the keyset a ZeroKMS + administrator set for the client. `cipher.keyset(name)` is any other, + loaded on first use. +- **Audit metadata.** `.audit({ ... })` on `encrypt`, `decrypt`, + and `openJson`. A date and time in it is sent + as RFC 3339 text in UTC, the form every SDK sends. A query has no + data-key request, so it has no `.audit`. +- **Testing without ZeroKMS.** `@cipherstash/recipher/testing` builds a + cipher over Stack Encrypt's deterministic test keys, with no credentials and + no network, as Go's `encrypttest.NewClient` does. + +## Results and errors + +No promise the SDK returns rejects. Every call returns, or resolves to, a +`Result`, as a Rust call returns one. `Cipher.create` +does too. One case throws: a method called without its object, as in +`stored.map(cipher.decrypt)`. The JavaScript engine throws a `TypeError` +before any of the SDK's code runs (#1801). + +```ts +const sealed = await keyset.encrypt("a secret message"); + +// Narrow it. +if (sealed.isOk()) { + store(sealed.value.toBytes()); +} else { + log(sealed.error.code); +} + +// Or combine it. +const bytes = sealed.map((ciphertext) => ciphertext.toBytes()).unwrapOr(null); + +// Or combine it before the await, on the pending result. +const stored = await keyset + .encrypt("a secret message") + .map((ciphertext) => ciphertext.toBytes()) + .unwrapOr(null); +``` + +- **The methods are Rust's `Result` methods,** in camelCase: `isOk`, + `isErr`, `ok`, `err`, `map`, `mapErr`, `mapOr`, `and`, `andThen`, `or`, + `orElse`, `unwrapOr`, `unwrapOrElse`, `unwrap` and `expect`. Each does + what Rust's does. `unwrap()` and `expect(..)` are the only functions that + throw, as they are the only ones that panic in Rust. They are for a + script, a test or a startup path. +- **An async call returns a pending result (#2026).** It is a thenable, + not a `Promise`. It has the methods that set up the call (`.audit`, + `.withCredential`, `.signal`, and in phase 2 `.withContext` and + `.partition`). It also has the `Result` methods that need no value + before it arrives: `map`, `mapErr`, `andThen`, `orElse`, `unwrap`, + `unwrapOr`, `expect`, and `match`. So `await x.unwrap()` needs no + parentheses. The setup methods come first, because a `Result` method + starts the call. `isOk` and `isErr` are left out, because the value + has not arrived. +- **Awaiting a pending result never rejects.** `await x` gives a `Result`. + Only `unwrap` and `expect` reject, on an `Err`, as they throw on a + `Result`. +- **The binding returns the pending result itself.** No TypeScript code + wraps a native method. The package's TypeScript hands the binding the + pending-result class when it loads the binding, as it hands over `Ok` + and `Err`. +- **A call that does not wait returns a plain `Result`:** + `Ciphertext.fromBytes`, `RcDate.from`, and the other factories. +- **`Result` is the core's own type**, with no dependency, so it can stay + as close to Rust's as TypeScript allows. `Ok` and `Err` are its two + cases, and `isOk()` narrows the type as a Rust `match` does. +- **An error is Stack Encrypt's diagnostic, as a value.** Stack Encrypt's errors + are miette diagnostics, and a `RecipherError` carries all of one, as the + Go SDK's `Diagnostic` does: the stable `code` (`stack_encrypt::aead`), + the one-line `message`, the `help`, the `url` of its documentation page, + the `severity`, + the structured `fields` (a refusal's `reason` among them), and the + `causes` behind it. `field` and `record` name the field and the record + at fault, which the SDK knows where Stack Encrypt does not. A cause from another library is + named as one and its message is never copied. Stack Encrypt sets no `url` + yet (#1790); the property shows the link when it does. +- **The SDK adds nothing of its own to an error's description.** A caller + switches on `code`. There is no coarser grouping that the SDK invents: + a grouping the SDK made up would have to be kept in step with every + Stack Encrypt error, in every language. The SDK's own errors (a value that is + not a record, a build that did not load) are diagnostics too, declared + the way Stack Encrypt declares its own, with codes under `recipher_js::`, + named after the crate as Stack Encrypt's are, so that no SDK code can clash + with a Stack Encrypt code when Stack Encrypt takes the name `recipher`. The + value bridge says which rule a refused value broke as a typed value, so + nothing reads the wording of a message. +- **Nothing else escapes as an exception.** A failure in the binding, + such as a build that does not load, is an `Err` too. A test passes each + call a wrong argument and a failing key service, and asserts that none + throws or rejects. Another asserts that a method called without its + object throws a `TypeError`, so the one exception stays documented. +- **No error holds a secret.** No message, property or `toString()` holds + a plaintext, a key, a token, a ciphertext or a context value. A + decrypted row's `inspect` output names its fields and hides their + values, as Go's `Redacted` does. + +## Plaintext hygiene + +A JavaScript string cannot be wiped. The SDK keeps the number of copies +down instead: + +- The value bridge reads a JavaScript value into a frame, which lives + in a buffer wiped when it drops. Every copy Rust makes of a string on + the way in is wiped. No intermediate JSON text holds the row. +- A decrypted frame is converted straight into JavaScript values. +- The wasm build follows the same rules. When a call ends, the buffers + that call owned are wiped: on success, on failure and on cancellation. + Other calls in flight share the same linear memory and still hold theirs. + +A heap-hygiene test in the crate runs each operation under the watching +allocator of `packages/stack-encrypt/tests/heap_hygiene.rs`. A wasm test checks the three endings of a +call. The plaintext the JavaScript engine holds is outside what any test +can check, and the README says so. + +## Promises and cancellation + +- Every operation returns a `Promise` of a `Result`, which never rejects. + napi-rs runs Stack Encrypt's future on its tokio runtime. The wasm build + runs it through `wasm-bindgen-futures`, + and ZeroKMS requests go out through the runtime's `fetch`. +- A call takes an `AbortSignal`. Aborting drops the future, which wipes what + it held, and the call resolves to an `Err` with a code of its own for a cancelled call. Only that call fails; the + cipher goes on serving others. The Go SDK's cancellation tests + (`languages/golang/encrypt/cancel_test.go`) are the list of cases. + +## The adapters + +`@cipherstash/stack-drizzle`, `@cipherstash/stack-supabase` and +`@cipherstash/stack-prisma` move onto `@cipherstash/recipher` and +`@cipherstash/eql/recipher`. Each takes a new major version that depends on +them and drops `@cipherstash/stack`. + +No adapter moves until `recipher-compat` exists. A new major then reads +the EQL v3 rows the current major wrote, so no customer upgrades into data +they cannot read. + +- **Columns.** Each adapter maps its own column objects to a record and a + field name, as each maps them to a table and a column name today: + Drizzle by its column builder's table and name, Supabase.js by the table + and the column string it filters on, and Prisma Next by its routing key. +- **Batches.** Drizzle's batched query terms map to `keyset.query`. + Supabase's model encryption maps to `keyset.encrypt` and + `cipher.decrypt`. Prisma Next's middleware encrypts and decrypts column + by column, which maps to `keyset.encrypt` and `cipher.decrypt` with + `{ record, field }`. +- **SQL.** Each adapter writes EQL v3 SQL today: `eql_v3` operators and + casts, and Prisma Next's baseline migration installs the v3 bundle. Each + moves to the EQL v4 functions and query domains, taking the cast from the + query term's `domain`. +- **Installing EQL v4.** `@cipherstash/eql` ships the v3 bundle, and + `stash eql install` installs it. Both need the v4 bundle before an + adapter can move. That is its own piece of work, in the CLI and in + `packages/eql`, and step 17 depends on it. +- **Supabase.js.** The v3 adapter refuses some operators because PostgREST + cannot write the `eql_v3.query_*` cast they need. Whether PostgREST can + write the v4 query domains is checked before the Supabase step; the + answer decides which operators the new major offers. +- **DynamoDB.** `@cipherstash/stack/dynamodb` is a subpath of + `@cipherstash/stack`, not an adapter package. DynamoDB has no EQL, so it + needs the core only. It moves to `@cipherstash/recipher/dynamodb` after + the adapters, and also waits for `recipher-compat`, which reads the + items the current integration wrote. +- **Skills.** `skills/stash-drizzle`, `stash-supabase`, `stash-prisma`, + `stash-dynamodb`, `stash-encryption` and `stash-indexing` change with + their adapters, in the same pull requests. + +## Room for EQL v3 and v2 + +`recipher-compat` is planned to read and write EQL v3 and v2 on Stack +Encrypt too. In TypeScript it arrives as another extension, beside +`@cipherstash/eql/recipher`, with no new call shape. So this plan holds to +three rules: + +- **The EQL version is in the field's type, never in a call.** A + declaration names an EQL v4 type from the catalog. A v3 type would be + another type in the same record, through the same `encrypt`, `query` and + `decrypt`. +- **The core never names an EQL type.** The crate takes its + `TargetResolver` from a cargo feature, and an extension's build turns on + its own. + A resolver that knows the v3 and v2 types is another extension's. +- **Nothing outside an extension's generated catalog knows a type's + version.** Query terms carry their SQL domain, and adapters write casts + from it, so an adapter does not branch on the version. + +A cipher runs in one build, so two extensions in one cipher need one build +that holds both. That is decided when `recipher-compat` is designed, and +these rules are checked then. + +## Tests + +- **Conformance.** A Vitest runner for every profile in + `conformance/stack-encrypt/v1`, against both the napi build and the wasm + build (#1479). The core package runs the profiles that name no EQL type. + `@cipherstash/eql` runs `eql-json-v1`. Phase 1 runs the cases that take no + context from the caller. Phase 2 adds the context profiles, as Stack + Encrypt rewrites them for named parts. Today they are + `record-contexts-v1`, `record-context-boundaries-v1` and + `record-bindings-v1`. A case a phase skips is listed as not run, never as + passed. The exchange profile enrols TypeScript in + `scripts/stack-exchange-conformance.mjs`, so TypeScript opens what Rust + and Go wrote in the same run, and they open what TypeScript wrote. +- **The core has no EQL in it.** A test fails if the core package's + builds link `eql-bindings`, or if its TypeScript names an EQL type. +- **The SQL entries stay light.** A test fails if the root, `./schema` or + `./sql` entry of `@cipherstash/eql` imports the core or loads a build. +- **A frozen stored-rows file** (phase 3). Rows the first stable release + wrote, opened on every build and never regenerated. +- **Value conversion.** The bridge's value conformance cases on both builds, + and the value profile for the record kinds. A fuzz target on the wasm + build compares its frame for a value with the napi bridge's. +- **Rust quality gates.** The two crates get the checks the stack-* + crates have: mutation testing, the CRAP gate, unused dependencies, and + fuzz targets for the bridge's text parsers and the JSON conversion. The + copied JavaScript comes under Biome. #1797 lists them. +- **Type tests.** A wrong row, a wrong value, an unknown field, an + operator a field cannot answer, and an EQL type + against a cipher without the extension do not compile. +- **Nothing throws.** Every call is run with a wrong argument, a failing + key service and an aborted signal. Each must resolve to an `Err`. A + method called without its object is the exception: it throws a + `TypeError`, and a test says so. +- **Extension versions.** A build with another binding interface number is + refused by `Cipher.create`, and two EQL builds with the same number both + load. +- **Edge runtime.** Each package's wasm build runs one encrypt, query and + decrypt under an edge runtime in CI (Miniflare or `workerd`). +- **Live.** One credentialed round trip of the core against ZeroKMS, and + one of the EQL extension against ZeroKMS and PostgreSQL with EQL v4 + installed, in a path-filtered workflow like the other `integration-*.yml` + jobs. Each adapter's live suite moves to EQL v4 with its major. + +## Packaging and release + +The packages follow `@cipherstash/auth`: + +- `release.yml` builds the six platform bindings and the wasm build of each + package, and publishes the platform packages before the wrapper, as + `publish-auth` does. npm trusted publishing is set up for each package, + bound to `release.yml`. +- `@cipherstash/eql` keeps EQL's version, which its SQL bundle, its docs, + its image and the `eql-bindings` crate share. Its release gains the six + platform bindings and the wasm build of the extension. A change to EQL's + SQL and the bindings for it ship together, in one EQL release. +- `@cipherstash/recipher` has its own version. An EQL release is built + against one version of Stack Encrypt, and works with every core version that has the same + binding interface number. The peer dependency of `@cipherstash/eql` names + that range. A new EQL release is needed for the core only when the + interface number changes. +- Each package gets a changeset like any other workspace package. +- The crates depend on `stack-encrypt` and `eql-bindings` by path, so one + release carries Stack Encrypt of its own commit. Each package names that + commit in an `engineCommit` export, for a bug report. + +## Documentation and skills + +- The core's README starts with the steps to encrypt and decrypt one + value, then a record, then a query term. It needs no database. The + README of `@cipherstash/eql` gains the steps to a working round trip + through PostgreSQL. Both are tested in CI. +- A skill under `skills/` for the core at its stable release, since skills + ship to customers. `skills/stash-postgres` and `skills/stash-indexing` + gain the extension. +- `AGENTS.md` (repository layout) and `SECURITY.md` (package list) gain + each package in the pull request that adds it. + +## Order of work + +Each step is one pull request, and each ends with its tests passing in CI. + +### Phase 1: now + +The core, with no EQL: + +1. **Walking skeleton.** The crate, its generated types and the core npm + package. + `Cipher.create`, `Result`, and plain `encrypt` and `decrypt` of one + `string` value on Node, with no context. CI builds it on Linux. Proves that Stack Encrypt's futures run on + napi-rs's runtime. Adds the test that the crate links no + `eql-bindings`. +2. **Values.** The value bridge for every type in the table above + except `RcUuid`. The wrapper classes, an array of values, `bytes` for + a file, the value profile, and the fuzz target. `opaque` for a whole + object follows the storage-blob converter (#1822). #1996 adds + `RcUuid` after step 3, over Stack Encrypt's UUID kind (#1929). A + `RcUuid` then encrypts as a value on its own, with no record. The + pull request comes after step 3 so that its tests can also store a + UUID record field. +3. **Records.** `record`, `encrypt`, `passthrough`, nulls, the encrypted + row's type, the type tests, and the declaration, runtime, and read + profiles. This step is the first to call `Plan::from_frame` and + `Planned`. One field with `{ record, field }` comes later, when Stack + Encrypt has a call for it (#2028). The pending result (#2026) follows + the records, and changes every async call before search terms add more. +4. **Search terms.** The indexes, `query`, every operator, match `verify` + and `targetLimit` with the default match options, and the scalar and + query-refusal profiles. +5. **Credentials, keysets, audit metadata and cancellation.** The + per-call credential type, the testing cipher and the lifecycle profile. +6. **The wasm build.** The `wasm-bindgen` crate, the common crate for + what the two builds share, the value mapping over + `JsValue`, the export conditions, the inlined build and the edge-runtime + test. + +Then the EQL extension: + +7. **EQL types.** The `./recipher` entry of `@cipherstash/eql`, the `eql` + cargo feature, the extension passed to `Cipher.create`, the `eql-codegen` writer and its drift check, + and the scalar EQL types on Node and on wasm. +8. **JSON documents.** `JsonSearch` and the EQL/JSON profile. +9. **Exchange.** The exchange enrolment, so TypeScript, Rust and Go open + each other's values in one run. + +10. **Pre-release.** The platform packages, the release jobs and npm + trusted publishing, and the READMEs. Both packages are published to + npm under a pre-release version and tag, never as `latest`. + +Phase 1 ends with a core and an extension that pass every conformance case +with no caller context, on Node and on wasm, and that anyone can install +as a pre-release. Each README says that a pre-release makes no promise +that a later version opens its stored values. + +### Phase 2: when Stack Encrypt has named parts + +11. **Labels and partitions.** The built-in parts, `keyset.with(..)`, a + part declared on a record and on a field, `.partition(..)`, custom + labels and partitions, `.withContext` on a value, and the context + profiles. +12. **Policies.** `forSub`, `forTenant`, `notBefore` and `notAfter`, each + when Stack Encrypt and ZeroKMS have it, with a live test of a refused + reader. + +Each phase 2 step is published as a pre-release too. + +### Phase 3: after the issues that change stored bytes + +13. **Catch up with Stack Encrypt.** Match options (#1673), refinements + (#1567), the plan checked against the JSON Schemas (#1678), and any + rename from #1489 not yet taken. +14. **Stored rows.** The frozen stored-rows file. +15. **Stable release.** The first versions published as `latest`, with the + promise that later versions open their stored values, and the skills. +16. **The adapters.** Drizzle, then Prisma Next, then Supabase, each a + major version in its own pull request. This step waits for EQL v4 to + install through `stash eql install`, and for `recipher-compat`. +17. **DynamoDB.** `@cipherstash/recipher/dynamodb`, on the core. + +## Decisions + +Decided on 2026-11-23: + +- The adapters' new majors wait for `recipher-compat`. No customer + upgrades before it. +- A timestamp is a `Date`. The types JavaScript lacks are the value + bridge's wrapper classes, not `Temporal`. +- DynamoDB moves onto the core, after the adapters. +- The EQL extension is part of `@cipherstash/eql`, not a new package. +- The core has plain encryption, with no context. +- The core and EQL are released apart, so several EQL versions work with + one core. The EQL builds are published beside `@cipherstash/eql`, as + `@cipherstash/eql-`. +- Values convert through the value bridge. A value's type picks how it + is encrypted, and no call names a kind. +- Integers are a `bigint` in the core, at every width. An adapter converts + for an ORM whose integer columns are a `number`. +- A plain object is refused, as in Rust. The caller chooses `opaque` or + `json`. +- One value returns one result. An array returns an array. +- Calls return a `Result` and never throw. `Result` is the core's own + type, with Rust's methods. +- Phase 1 ends with a pre-release on npm. +- The SDK has two Rust crates until the wasm build needs more. The two + are the language binding and the value bridge. +- Rust defines the classes and napi-rs generates their types. TypeScript + keeps `Result` and the declaration types. (The typed signatures moved + into Rust's `ts_type` attributes on 2026-11-25.) +- A context follows ADR-0016: policies, labels and partitions, with Stack + Encrypt's wire names. Parts attach to the keyset with `with(..)`. + +Decided on 2026-11-25: + +- The value bridge is `recipher-value-napi`, an unpublished crate in this + repository, copied from vitaminc's `vitaminc-aead-napi`. Its refusals + are typed diagnostics. +- An error is Stack Encrypt's whole diagnostic: `code`, `message`, `help`, + `url`, `severity`, `fields` and `causes`, with `field` and `record` + added by the SDK. A refusal's reason is in `fields`. +- An error has no `kind`. A caller switches on `code`, as in every + language SDK, so no grouping has to be kept in step across languages. +- A method called without its object, as in `stored.map(cipher.decrypt)`, + throws a `TypeError` (#1801). The JavaScript engine checks the object + before any Rust runs, and no napi-rs setting turns the check off. + Everything else, a wrong argument included, is an `Err`. So Rust + returns each `Result` itself, and the TypeScript layer that wrapped + each native method, and the hand-written interfaces that typed it, are + gone. + +Decided on 2026-11-29: + +- The language binding is thin. `record()` writes Stack Encrypt's plan, + and the binding reads it and calls `dynamic`. A gap is fixed in Stack + Encrypt. The rules are in [What it is](#what-it-is). +- Stack Encrypt's names for a plan's outputs are used as they are. An + alias is a change to Stack Encrypt's plan. +- A record's field can name an EQL type, through the plan's `target`. The + EQL types are optional, and `@cipherstash/eql` defines them. The design + is in [The EQL extension](#the-eql-extension). The record pull request + does not include them. + +## What was checked + +Run on 2026-11-22, on `next` at `38db57856`: + +- `cargo check --target wasm32-unknown-unknown -p stack-encrypt --features dynamic`: + passes. +- `cargo check --manifest-path packages/eql/Cargo.toml -p eql-bindings --features targets --target wasm32-unknown-unknown`: + passes. +- `stack-kms`'s HTTP connection on `wasm32` uses reqwest's `fetch` backend + (read in `packages/stack-kms/src/connection/http.rs`). +- `@cipherstash/auth` uses napi-rs 2 with napi's tokio runtime, and a + `wasm-bindgen` sibling crate (`stack-auth-wasm`), chosen by the `node` and + `default` export conditions (read in their `Cargo.toml` and + `package.json`). +- The adapters name columns by table and column name: Drizzle passes + `{ table, column }` to `encryptQuery` (`stack-drizzle/src/operators.ts`), + Supabase passes the table and column strings + (`stack-supabase/src/query-encrypt.ts`), and Prisma Next passes a + routing key per column (`stack-prisma/src/execution/sdk.ts`). +- The CLI's installer and `@cipherstash/eql` carry no EQL v4 bundle + (searched `languages/typescript/packages/cli/src` and + `packages/eql/packages/eql/src`). +- `dynamic::Planned`, `Plan::query`, `Plan::field`, `QueryTerm::domain` and + the per-call credential exist on `next` and are covered by their + doctests. + +Read on 2026-11-23, on `next` at `e62420d8e`: + +- The state of each issue in [Phases](#phases): #1669 and #1398 are + closed; the others named there are open. +- A plan field declares its context as a list of names + (`"context": ["users", "email"]`, in the module example of + `packages/stack-encrypt/src/dynamic/record/planned.rs`), and a `Planned` + encrypts and decrypts with no context from the caller (`encrypt_into` + and `decrypt_from` in the tests of `dynamic/record.rs`). An expected + context is an `Option, leaf: &mut impl FnMut(A) -> Result, -) -> Result, E> { +) -> Result, E> { Ok(match tree { CipherText::Single(l) => CipherText::Single(leaf(l)?), - CipherText::None(l) => CipherText::None(leaf(l)?), CipherText::EmptySequence(l) => CipherText::EmptySequence(leaf(l)?), CipherText::EmptyMap(l) => CipherText::EmptyMap(leaf(l)?), CipherText::Sequence(items) => CipherText::Sequence( @@ -460,41 +738,14 @@ fn exact_buffer(len: Option) -> Result, u32> { Ok(out) } -/// Exact byte length of the codec's encoding of `value`. `None` on overflow -/// or on a length the codec's `u32` frames cannot express — the encode would -/// fail on those anyway, so the caller reports an encoding error. -fn value_encoded_len(value: &FfiValue) -> Option { - // tag byte + fixed payload, or tag + u32 length prefix + payload. - let framed = |len: usize| u32::try_from(len).ok().and_then(|_| len.checked_add(5)); - match value { - FfiValue::Null | FfiValue::Undefined | FfiValue::Bool(_) => Some(1), - FfiValue::Int32(_) | FfiValue::UInt32(_) | FfiValue::Float32(_) => Some(5), - FfiValue::Int64(_) | FfiValue::UInt64(_) | FfiValue::Float64(_) => Some(9), - FfiValue::String(s) => framed(s.risky_ref().len()), - FfiValue::Bytes(b) => framed(b.risky_ref().len()), - FfiValue::Array(items) => items.iter().try_fold(5usize, |acc, item| { - acc.checked_add(value_encoded_len(item)?) - }), - FfiValue::Object(entries) => entries.iter().try_fold(5usize, |acc, (key, value)| { - acc.checked_add(framed(key.len())?.checked_sub(1)?)? - .checked_add(value_encoded_len(value)?) - }), - FfiValue::Passthrough(inner) => value_encoded_len(inner)?.checked_add(1), - } -} - -/// Exact byte length of the codec's encoding of a ciphertext tree. The -/// passthrough payloads are read (not consumed) through `Any::downcast_ref`, -/// matching what `encode_ciphertext_boxed` will re-home them to; a payload -/// that is not an [`FfiValue`] is `None`, which is the same rejection the -/// encoder would make. +/// Exact byte length of the codec's encoding of a ciphertext tree. A +/// passthrough is its node byte and its frame, written as it is. fn tree_encoded_len(tree: &BytesTree) -> Option { let framed = |len: usize| u32::try_from(len).ok().and_then(|_| len.checked_add(5)); match tree { - CipherText::Single(l) - | CipherText::None(l) - | CipherText::EmptySequence(l) - | CipherText::EmptyMap(l) => framed(l.len()), + CipherText::Single(l) | CipherText::EmptySequence(l) | CipherText::EmptyMap(l) => { + framed(l.len()) + } CipherText::Sequence(items) => items .iter() .try_fold(5usize, |acc, item| acc.checked_add(tree_encoded_len(item)?)), @@ -502,63 +753,39 @@ fn tree_encoded_len(tree: &BytesTree) -> Option { acc.checked_add(framed(key.len())?.checked_sub(1)?)? .checked_add(tree_encoded_len(value)?) }), - CipherText::Passthrough(p) => { - value_encoded_len((**p).downcast_ref::()?)?.checked_add(1) - } + CipherText::Passthrough(p) => p.0.len().checked_add(1), } } #[cfg(test)] mod tests { use super::*; - use vitaminc_protected::Protected; - - // `value_encoded_len` / `tree_encoded_len` re-derive the codec's framing - // arithmetic; the codec exports no `encoded_len` of its own, so these - // pins are the only thing that fails if the two drift. Drift is not a - // cosmetic bug: an undersized reservation makes `encode_value` - // reallocate mid-encode, leaving unwiped partial plaintext in the - // abandoned allocation — silently. - - fn every_value_shape() -> Vec { - vec![ - FfiValue::Null, - FfiValue::Undefined, - FfiValue::Bool(true), - FfiValue::Int32(-5), - FfiValue::UInt32(5), - FfiValue::Float32(1.5), - FfiValue::Int64(-9), - FfiValue::UInt64(9), - FfiValue::Float64(2.5), - FfiValue::String("".into()), - FfiValue::String("héllo".into()), - FfiValue::Bytes(Protected::new(Vec::new())), - FfiValue::Bytes(Protected::new(vec![0u8; 300])), - FfiValue::Array(Vec::new()), - FfiValue::Array(vec![FfiValue::Bool(false), FfiValue::String("x".into())]), - FfiValue::Object(Vec::new()), - FfiValue::Object(vec![ - ("a".to_string(), FfiValue::Int32(1)), - ( - "nested".to_string(), - FfiValue::Object(vec![("b".to_string(), FfiValue::Null)]), - ), - ]), - FfiValue::Passthrough(Box::new(FfiValue::Int64(7))), - FfiValue::Passthrough(Box::new(FfiValue::Array(vec![FfiValue::String( - "deep".into(), - )]))), - ] - } + use crate::support::{protect, Tree}; + use stack_encrypt::Controlled; + // `tree_encoded_len` re-derives the codec's arithmetic; the codec exports + // no `encoded_len` of its own, so this pin is the only thing that fails if + // the two drift. Drift is not a cosmetic bug: an undersized reservation + // makes `encode_tree` reallocate mid-encode, leaving unwiped partial + // plaintext in the abandoned allocation — silently. + + /// The registry wipes the buffer it is handed, and `into_boxed_slice` + /// reallocates one whose capacity exceeds its length. So every answer's + /// capacity is its length. #[test] - fn value_encoded_len_matches_the_codec_exactly() { - for (i, value) in every_value_shape().into_iter().enumerate() { - let expected = value_encoded_len(&value).expect("encodable shape"); - let mut out = Vec::new(); - codec::encode_value(value, &mut out).expect("codec encode"); - assert_eq!(out.len(), expected, "shape {i}"); + fn an_encoded_answer_has_no_spare_capacity() { + let entries = [ + dynamic::OperatorEntry::new(dynamic::Op::Eq, &IndexSpec::Equality), + dynamic::OperatorEntry::new(dynamic::Op::Between, &IndexSpec::Ope), + ]; + for out in [ + encode_answer(&vec![true, false, true]), + encode_answer(&Some(11u64)), + encode_answer(&None::), + encode_answer(&entries), + ] { + let out = out.expect("encodes"); + assert_eq!(out.capacity(), out.len()); } } @@ -568,10 +795,9 @@ mod tests { let trees: Vec = vec![ leaf(b""), leaf(&[7u8; 40]), - CipherText::None(vec![1, 2]), CipherText::EmptySequence(vec![3]), CipherText::EmptyMap(Vec::new()), - CipherText::Sequence(vec![leaf(b"a"), CipherText::None(vec![9])]), + CipherText::Sequence(vec![leaf(b"a"), CipherText::EmptyMap(vec![9])]), CipherText::Map(vec![ ("name".to_string(), leaf(b"ct")), ( @@ -579,32 +805,33 @@ mod tests { CipherText::Map(vec![("x".to_string(), leaf(b"y"))]), ), ]), - CipherText::Passthrough( - Box::new(FfiValue::Bytes(Protected::new(vec![1, 2, 3]))) as BoxedPassthrough - ), + CipherText::Passthrough(stack_encrypt::PassthroughFrame( + Tree::Bytes(vec![1, 2, 3]) + .to_frame() + .expect("a frame") + .risky_unwrap(), + )), ]; for (i, tree) in trees.into_iter().enumerate() { let expected = tree_encoded_len(&tree).expect("encodable shape"); let mut out = Vec::new(); - codec::encode_ciphertext_boxed(tree, &mut out).expect("codec encode"); + encode_ciphertext(&tree, &mut out).expect("codec encode"); assert_eq!(out.len(), expected, "tree {i}"); } } // ---- the EQL target path, native, over FakeDataKeySource ----------------- - fn encoded(value: FfiValue) -> Vec { - let mut out = Vec::new(); - codec::encode_value(value, &mut out).expect("encode"); - out + fn encoded(value: Tree) -> Vec { + value.to_frame().expect("encode").risky_unwrap() } - fn text(value: &str) -> FfiValue { - FfiValue::String(value.into()) + fn text(value: &str) -> Tree { + Tree::String(value.into()) } - fn object(entries: Vec<(&str, FfiValue)>) -> FfiValue { - FfiValue::Object( + fn object(entries: Vec<(&str, Tree)>) -> Tree { + Tree::Object( entries .into_iter() .map(|(k, v)| (k.to_string(), v)) @@ -619,10 +846,7 @@ mod tests { ( "email", object(vec![ - ( - "context", - FfiValue::Array(vec![text("users"), text("email")]), - ), + ("context", Tree::Array(vec![text("users"), text("email")])), ("target", text("TextEq")), ("type", text("string")), ]), @@ -630,11 +854,8 @@ mod tests { ( "notes", object(vec![ - ( - "context", - FfiValue::Array(vec![text("users"), text("notes")]), - ), - ("outputs", FfiValue::Array(vec![text("c")])), + ("context", Tree::Array(vec![text("users"), text("notes")])), + ("outputs", Tree::Array(vec![text("c")])), ("type", text("string")), ]), ), @@ -644,22 +865,22 @@ mod tests { #[test] fn targets_lists_what_this_build_holds_in_the_wire_shape() { let out = targets().expect("encodes"); - let FfiValue::Object(entries) = decode_value(&out).expect("decodes") else { + let Tree::Object(entries) = Tree::from_frame(&out).expect("decodes") else { panic!("an object"); }; assert_eq!(entries.len(), 1); assert_eq!(entries[0].0, "targets"); - let FfiValue::Array(items) = &entries[0].1 else { + let Tree::Array(items) = &entries[0].1 else { panic!("a list"); }; if !crate::targets::HOLDS_EQL { assert!(items.is_empty(), "the build without EQL types lists none"); return; } - let FfiValue::Object(text_eq) = items + let Tree::Object(text_eq) = items .iter() .find(|item| { - matches!(item, FfiValue::Object(fields) if fields.iter().any(|(k, v)| k == "name" && matches!(v, FfiValue::String(s) if s.risky_ref() == b"TextEq"))) + matches!(item, Tree::Object(fields) if fields.iter().any(|(k, v)| k == "name" && matches!(v, Tree::String(s) if s.as_bytes() == b"TextEq"))) }) .expect("TextEq is listed") else { @@ -678,35 +899,41 @@ mod tests { "query", "query_sql_domain", "producible", - "reason" + "reason", + "operators" ] ); - assert!(matches!(text_eq[8].1, FfiValue::Bool(true))); + assert!(matches!(text_eq[8].1, Tree::Bool(true))); + assert!( + matches!(&text_eq[10].1, Tree::Array(operators) if operators.len() == 1), + "TextEq answers one operator" + ); } #[test] fn a_plan_naming_a_target_is_accepted_exactly_by_the_eql_build() { let plan = target_plan(); if crate::targets::HOLDS_EQL { - assert_eq!(plan_check(&plan), Ok(()), "the eql build runs TextEq"); - // A type the engine cannot produce, and one that does not exist, - // are refused at plan_check. - for name in ["TextOrdOre", "Nope"] { - let refused = encoded(object(vec![( + assert_eq!( + plan_check(&protect(&plan)), + Ok(()), + "the eql build runs TextEq" + ); + // The storage-only document is a target too, and a type that + // does not exist is refused at plan_check. + for (name, expected) in [("Json", Ok(())), ("Nope", Err(STATUS_ENCODING))] { + let named = encoded(object(vec![( "email", object(vec![ - ( - "context", - FfiValue::Array(vec![text("users"), text("email")]), - ), + ("context", Tree::Array(vec![text("users"), text("email")])), ("target", text(name)), ]), )])); - assert_eq!(plan_check(&refused), Err(STATUS_ENCODING), "{name}"); + assert_eq!(plan_check(&protect(&named)), expected, "{name}"); } } else { assert_eq!( - plan_check(&plan), + plan_check(&protect(&plan)), Err(STATUS_ENCODING), "the build without EQL types refuses a target name" ); @@ -728,10 +955,16 @@ mod tests { ("email", text("alice@example.com")), ("notes", text("likes cats")), ])); - validate::record(&source, &plan).expect("the source fits"); - let sealed = block_on(encrypt_record(&keyset, &source, &plan)).expect("seals"); + validate::record(&protect(&source), &protect(&plan)).expect("the source fits"); + let sealed = block_on(encrypt_record( + &keyset, + &protect(&source), + &protect(&plan), + AuditMetadata::new(), + )) + .expect("seals"); - // The stored tree carries the EQL JSON under "eql": the v3 envelope + // The stored tree carries the EQL JSON under "eql": the v4 envelope // with the column as its i and a stack-encrypt ciphertext. let tree = decode_tree(&sealed).expect("a tree"); let CipherText::Map(mut fields) = tree else { @@ -749,32 +982,54 @@ mod tests { let CipherText::Passthrough(payload) = &outputs[0].1 else { panic!("a passthrough") }; - let FfiValue::Bytes(bytes) = payload.downcast_ref::().expect("a value") else { + let Tree::Bytes(bytes) = Tree::from_frame(&payload.0).expect("a value") else { panic!("bytes") }; - let eql: serde_json::Value = serde_json::from_slice(bytes.risky_ref()).expect("JSON"); - assert_eq!(eql["v"], 3); + let eql: serde_json::Value = serde_json::from_slice(bytes.as_slice()).expect("JSON"); + assert_eq!(eql["v"], 4, "Stack Encrypt writes EQL v4"); assert_eq!(eql["i"], serde_json::json!({"t": "users", "c": "email"})); assert!(eql["c"].as_str().unwrap().starts_with("stack-encrypt:1:")); assert_eq!(eql["hm"].as_str().unwrap().len(), 64); // Opens back through the EQL type's own decryption. - validate::record_tree(&sealed, &plan, None).expect("the tree fits"); - let opened = - block_on(decrypt_record(Scope::Client(&cipher), &sealed, &plan, None)).expect("opens"); - let FfiValue::Object(values) = decode_value(&opened).expect("a value") else { + validate::record_tree(&sealed, &protect(&plan), None).expect("the tree fits"); + let opened = block_on(decrypt_record( + &cipher, + &sealed, + &protect(&plan), + None, + AuditMetadata::new(), + )) + .expect("opens"); + let Tree::Object(values) = Tree::from_frame(&opened).expect("a value") else { panic!("an object") }; - assert!( - matches!(&values[0].1, FfiValue::String(s) if s.risky_ref() == b"alice@example.com") - ); - assert!(matches!(&values[1].1, FfiValue::String(s) if s.risky_ref() == b"likes cats")); + assert!(matches!(&values[0].1, Tree::String(s) if s.as_bytes() == b"alice@example.com")); + assert!(matches!(&values[1].1, Tree::String(s) if s.as_bytes() == b"likes cats")); - // The query value matches the stored term. + // The eq query's term is the type's query value, and it matches the + // stored term. let probe = encoded(text("alice@example.com")); - validate::query(&probe, &plan, b"email").expect("a target field"); - let query_bytes = block_on(query(&keyset, &probe, &plan, b"email")).expect("derives"); - let probe_json: serde_json::Value = serde_json::from_slice(&query_bytes).expect("JSON"); + validate::query_term(&protect(&probe), &protect(&plan), b"email", b"eq") + .expect("a target field answers eq"); + let term = block_on(query_term( + &keyset, + &protect(&probe), + &protect(&plan), + b"email", + b"eq", + )) + .expect("derives"); + let Tree::Object(term) = Tree::from_frame(&term).expect("a value") else { + panic!("a query term is an object") + }; + assert!(matches!(&term[3].1, Tree::String(s) if s.as_bytes() == b"eql_v4.query_text_eq")); + assert!(matches!(&term[4].1, Tree::String(s) if s.as_bytes() == b"eql")); + let Tree::Bytes(query_bytes) = &term[5].1 else { + panic!("the term is the query value's bytes") + }; + let probe_json: serde_json::Value = + serde_json::from_slice(query_bytes.as_slice()).expect("JSON"); assert_eq!( probe_json["hm"], eql["hm"], "the query matches the stored value" @@ -786,15 +1041,89 @@ mod tests { // A query on a sealed field, an unknown field, or a wrong kind is // refused at validation. assert_eq!( - validate::query(&probe, &plan, b"notes"), + validate::query_term(&protect(&probe), &protect(&plan), b"notes", b"eq"), + Err(STATUS_ENCODING) + ); + assert_eq!( + validate::query_term(&protect(&probe), &protect(&plan), b"nope", b"eq"), Err(STATUS_ENCODING) ); assert_eq!( - validate::query(&probe, &plan, b"nope"), + validate::query_term( + &protect(&encoded(Tree::UInt32(1))), + &protect(&plan), + b"email", + b"eq" + ), + Err(STATUS_ENCODING) + ); + } + + /// `match` on a JsonSearch field through the query exports: a + /// predicate compiles to the predicate operand, and one the grammar + /// refuses is the caller's input (`STATUS_ENCODING`), never the + /// guest's own failure. + #[cfg(feature = "eql")] + #[test] + fn a_compiled_predicate_derives_and_a_refused_one_is_the_callers_input() { + use futures::executor::block_on; + use stack_encrypt::StackCipher; + use stack_kms::FakeDataKeySource; + + let cipher = block_on(StackCipher::builder().kms(FakeDataKeySource::new()).init()) + .expect("a cipher"); + let keyset = cipher.default_keyset(); + let plan = encoded(object(vec![( + "profile", + object(vec![ + ("context", Tree::Array(vec![text("users"), text("profile")])), + ("type", text("json")), + ("null", text("sql")), + ("target", text("JsonSearch")), + ]), + )])); + let input = |predicate: &str| { + encoded(object(vec![ + ("predicate", text(predicate)), + ("vars", text(r#"{"v": "nz"}"#)), + ])) + }; + + let accepted = input("$.country == $v && exists($.tags[*])"); + validate::query_term(&protect(&accepted), &protect(&plan), b"profile", b"match") + .expect("a field answers match"); + let term = block_on(query_term( + &keyset, + &protect(&accepted), + &protect(&plan), + b"profile", + b"match", + )) + .expect("derives"); + let Tree::Object(term) = Tree::from_frame(&term).expect("a value") else { + panic!("a query term is an object") + }; + let text = |key: &str| match term.iter().find(|(k, _)| k == key) { + Some((_, Tree::String(s))) => s.as_bytes().to_vec(), + other => panic!("{key}: {other:?}"), + }; + assert_eq!(text("operator"), b"match"); + assert_eq!(text("domain"), b"eql_v4.query_json_predicate"); + assert_eq!(text("encoding"), b"eql"); + + let refused = input(r#"$.country like_regex "n""#); + assert_eq!( + validate::query_term(&protect(&refused), &protect(&plan), b"profile", b"match"), Err(STATUS_ENCODING) ); assert_eq!( - validate::query(&encoded(FfiValue::UInt32(1)), &plan, b"email"), + block_on(query_term( + &keyset, + &protect(&refused), + &protect(&plan), + b"profile", + b"match" + )), Err(STATUS_ENCODING) ); } diff --git a/languages/golang/encrypt/guest/src/options.rs b/languages/golang/encrypt/guest/src/options.rs index 02db276e17..ebdad1db91 100644 --- a/languages/golang/encrypt/guest/src/options.rs +++ b/languages/golang/encrypt/guest/src/options.rs @@ -1,9 +1,10 @@ //! The per-call options object, and the keyset selector it carries. //! //! Every export that touches a keyset takes one more codec-encoded -//! argument: an [`FfiValue::Object`] with one required key, `keyset`, whose -//! value is a tagged object naming the keyset the call binds to, and on -//! `se_decrypt_record` one optional key, `context` (below): +//! argument: a frame object with one required key, `keyset`, whose +//! value is a tagged object naming the keyset the call binds to, and two +//! optional keys: `context` on `se_decrypt_record`, and `audit` on the +//! exports that request data keys (both below): //! //! | selector | meaning | //! |-------------------|---------| @@ -26,7 +27,7 @@ //! //! `context` is the context the host expects a record's context field to //! hold, for a plan that takes its context from a field (the plan-level -//! `"context_field"` key of `dynamic::record::plan`): a string that parses +//! `"context_field"` key of `dynamic::record::Plan::from_frame`): a string that parses //! as a plain label, `"tenants/acme"`, which the engine checks against each //! record's stored context field before any key is retrieved and refuses //! with [`STATUS_CONTEXT_MISMATCH`](crate::status::STATUS_CONTEXT_MISMATCH). @@ -37,18 +38,51 @@ //! and a term's context arrives as its own argument. A `context` that is //! not a string, or not a plain label, is [`STATUS_ENCODING`] too. //! +//! `audit` is audit metadata: facts about the call, which the engine sends +//! with every data-key request the call makes, for the ZeroKMS audit log. +//! It is the data form of the Rust call's `.audit(metadata)`, and +//! [`AuditMetadata`] reads it. The value is an object with text keys. A +//! value in it is a bool, an integer that fits a signed 64-bit integer, a +//! float, text, null, a list of these, or another such object. Bytes, a +//! wider integer and a value with a logical type (a date, a timestamp, a +//! decimal) are [`STATUS_ENCODING`], and so is an `audit` that is not an +//! object. A float that is not finite is sent as null. An empty object +//! sends nothing, as an absent key does. ZeroKMS does not verify the facts, +//! and no key depends on them. +//! +//! ZeroKMS has no type for a time, so a time crosses as text. A language +//! SDK that takes its language's time type in audit metadata sends this +//! text, so that every language SDK logs one form: +//! +//! - RFC 3339, in UTC, with the suffix `Z`; +//! - a fraction of a second only when it is not zero, with no trailing +//! zeros and at most nine digits; +//! - a year from 0000 to 9999. The language SDK refuses a time outside +//! those years. +//! +//! For example, `2026-11-20T10:00:00Z` and `2026-11-20T10:00:00.5Z`. The +//! guest cannot hold a language SDK to this rule, because the text arrives +//! as any other text does. +//! +//! `audit` is accepted where the call requests data keys: +//! `se_encrypt_record`, `se_decrypt_record` and `se_json_open`. On `se_term` +//! and `se_query_term` it is [`STATUS_ENCODING`]: a term is derived from the +//! keyset's index key, so the call makes no data-key request to send the +//! facts with, and a host that sent them there would log nothing. +//! [`Export::accepts`] states which export takes which key. +//! //! This object is a cross-language contract: every binding builds it, so -//! it is objects, strings, bytes and nothing else, and this module is its -//! one home. The Go bindings plan points here. +//! it is objects, strings, bytes and, inside `audit`, the plain values +//! listed above, and this module is its one home. The Go bindings plan +//! points here. -use stack_encrypt::dynamic::Scope; -use stack_encrypt::{KeysetCipher, Label, StackCipher}; -use stack_kms::{IdentifiedBy, IndexKeySource}; +use stack_encrypt::CipherRef; +use stack_encrypt::{AuditMetadata, KeysetCipher, Label, StackCipher}; +use stack_kms::{DataKeySource, IdentifiedBy, IndexKeySource}; use uuid::Uuid; -use vitaminc_aead_value::FfiValue; -use vitaminc_protected::Controlled; use zerokms_protocol::Name; +use stack_encrypt::dynamic::frame::serde::from_slice; use stack_guest_abi::last_error::malformed; use crate::status::fail_error; @@ -68,104 +102,226 @@ pub enum KeysetSelector { Any, } -/// Which side of the boundary an options object is parsed for: the sealing -/// and term exports need a keyset to mint under, so `{"any"}` is refused -/// there. +/// The export an options object is parsed for. The export decides which +/// keys the object may carry: see [`Export::accepts`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Side { - /// `se_encrypt_record`, `se_term`. - Mint, +pub enum Export { + /// `se_encrypt_record`. + EncryptRecord, /// `se_decrypt_record`. - Open, + DecryptRecord, + /// `se_json_open`. + JsonOpen, + /// `se_term`. + Term, + /// `se_query_term`. + QueryTerm, +} + +/// What an export takes in its options object, beyond one keyset. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Accepts { + /// The `{"any"}` selector: the call opens leaves from any keyset. + pub any_keyset: bool, + /// The `context` key. + pub context: bool, + /// The `audit` key: the call requests data keys. + pub audit: bool, +} + +impl Export { + /// Every export this module parses options for. + pub const ALL: [Export; 5] = [ + Export::EncryptRecord, + Export::DecryptRecord, + Export::JsonOpen, + Export::Term, + Export::QueryTerm, + ]; + + /// What this export takes. This function is the one statement of the + /// rules, and [`parse_options`] refuses whatever it does not list. + /// + /// - Decrypting a record opens leaves from any keyset, checks a stored + /// context, and retrieves data keys. + /// - Encrypting a record and reading a JSON document work under one + /// keyset, and request data keys. + /// - A term and a query term derive under one keyset, from its index + /// key. They request no data key. + pub const fn accepts(self) -> Accepts { + match self { + Export::DecryptRecord => Accepts { + any_keyset: true, + context: true, + audit: true, + }, + Export::EncryptRecord | Export::JsonOpen => Accepts { + any_keyset: false, + context: false, + audit: true, + }, + Export::Term | Export::QueryTerm => Accepts { + any_keyset: false, + context: false, + audit: false, + }, + } + } } /// The parsed options object. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct Options { pub keyset: KeysetSelector, /// The context the host expects a record's context field to hold; /// opening only. See the [module docs](self). pub context: Option