From e4cb011a4de9b238d14221b456e6e468bb972b4d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 13:01:35 +1100 Subject: [PATCH 1/4] refactor(stack-encrypt)!: make the lone term methods crate-private KeysetCipher::equality_term, match_terms, ore_term, and ope_term each built one term on its own, outside the target path and the query path. A term built that way had nothing tying it to the context of the ciphertext stored beside it. For most indexes it was also the wrong query term: with MatchOptions::short_words on, the match_terms filter of "Mike Ng" misses "Mike Nguyen". The four methods are now pub(crate) and #[cfg(test)]. No library code called them. The dynamic path derives through equality_term_normalized, match_terms_under, and order_pending, and only its tests called the four methods. So the methods stay, as the terms that this crate's tests compare other paths against. New unit tests in sem::lone_terms check that each method derives its target's bytes. The tests run with the keyset loaded, and with it not yet loaded. equality_term_normalized and match_terms_under are now cfg(any(test, feature = "dynamic")). That replaces an allow(dead_code). Callers outside the crate now use the public paths: - A stored term comes from encrypting the value into its term type with encrypt_into_with_context, or from KeysetCipher::run with an operation. The term types are EqualityTerm, MatchTerms, OreTerm, and OpeTerm. - A query comes from a field reference (AccountTerms::EMAIL.eq) or from target::matching_query run on its own. The change covers 13 stack-encrypt integration test files, the EQL encryption test text_eq.rs, and the Go guest's native_ops.rs. The frozen byte pins in term_bytes.rs and frozen_bytes.rs keep the same expected bytes. The check in target.rs that the target's equality term equals the method's moved into sem::lone_terms. The rustdoc that named the methods now says how to get each term. The EqualityTerm docs take the normalisation rules from equality_term. ADR-0004 decision 5 has an amendment. The CHANGELOG has a Breaking entry with the upgrade steps. ore_block_term stays public. The issue did not name it, though it also builds a term outside a target. No stored byte changes. Closes #1760 --- .../golang/encrypt/guest/tests/native_ops.rs | 111 ++-- .../eql/tests/encryption/tests/text_eq.rs | 12 +- packages/stack-encrypt/CHANGELOG.md | 35 ++ ...t-threaded-through-the-declaration-tree.md | 17 + packages/stack-encrypt/src/dynamic/mod.rs | 4 +- packages/stack-encrypt/src/dynamic/term.rs | 11 +- packages/stack-encrypt/src/lib.rs | 6 +- packages/stack-encrypt/src/sem/mod.rs | 505 +++++++++++------- packages/stack-encrypt/tests/audit.rs | 12 +- .../tests/context_conformance.rs | 10 +- packages/stack-encrypt/tests/credential.rs | 38 +- packages/stack-encrypt/tests/frozen_bytes.rs | 10 +- packages/stack-encrypt/tests/heap_hygiene.rs | 82 +-- packages/stack-encrypt/tests/keysets.rs | 26 +- .../stack-encrypt/tests/match_short_words.rs | 8 +- packages/stack-encrypt/tests/sem_terms.rs | 264 ++++----- packages/stack-encrypt/tests/source_mode.rs | 47 +- packages/stack-encrypt/tests/target.rs | 33 +- packages/stack-encrypt/tests/term_bytes.rs | 144 +++-- packages/stack-encrypt/tests/transcode.rs | 10 +- packages/stack-encrypt/tests/value_kinds.rs | 11 +- 21 files changed, 803 insertions(+), 593 deletions(-) diff --git a/languages/golang/encrypt/guest/tests/native_ops.rs b/languages/golang/encrypt/guest/tests/native_ops.rs index d542d07e90..77b57fb336 100644 --- a/languages/golang/encrypt/guest/tests/native_ops.rs +++ b/languages/golang/encrypt/guest/tests/native_ops.rs @@ -6,7 +6,8 @@ //! * a leaf inside a guest ciphertext tree **is** the frozen `SealedValue` //! storage encoding — a native cipher decrypts it; //! * terms derived through the guest dispatch are byte-identical to the -//! native `sem` calls (the cross-language contract); +//! terms a native value encrypted into its term type derives (the +//! cross-language contract); //! * record encryption follows its plan, keeps to **one** ZeroKMS call per //! invocation however many rows, and round-trips; //! * hostile/malformed inputs and wrong-AAD decrypts map to the documented @@ -22,10 +23,10 @@ use std::future::IntoFuture; mod support; use stack_encrypt::dynamic::frame::{decode_ciphertext, encode_ciphertext}; -use stack_encrypt::sem::DefaultMatch; +use stack_encrypt::sem::{DefaultMatch, EqualityTerm, MatchTerms, OpeTerm, OreTerm}; use stack_encrypt::{ - nonempty, CipherText, Label, Node, PassthroughFrame, PendingStackCipherText, SealedValue, - StackCipher, + nonempty, CipherText, EncryptInto, Label, Node, PassthroughFrame, PendingStackCipherText, + SealedValue, StackCipher, }; use stack_encrypt::{AuditMetadata, Controlled, Protected}; use stack_encrypt_guest::ops::{self, TERM_EQUALITY, TERM_MATCH, TERM_OPE, TERM_ORE}; @@ -269,12 +270,9 @@ fn guest_terms_match_the_native_sem_derivations() { TERM_EQUALITY, )) .expect("eq term"); - let native = block_on( - cipher - .default_keyset() - .equality_term(42u32, nonempty!("users/age")), - ) - .expect("native eq"); + let native: EqualityTerm = + block_on(42u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users/age"))) + .expect("native eq"); assert_eq!(eq, native.as_bytes()); let ore = block_on(ops::term( @@ -284,12 +282,9 @@ fn guest_terms_match_the_native_sem_derivations() { TERM_ORE, )) .expect("ore term"); - let native = block_on( - cipher - .default_keyset() - .ore_term(42u32, nonempty!("users/age")), - ) - .expect("native ore"); + let native: OreTerm = + block_on(42u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users/age"))) + .expect("native ore"); assert_eq!(ore, native.as_ref()); let ope = block_on(ops::term( @@ -299,12 +294,9 @@ fn guest_terms_match_the_native_sem_derivations() { TERM_OPE, )) .expect("ope term"); - let native = block_on( - cipher - .default_keyset() - .ope_term(42u32, nonempty!("users/age")), - ) - .expect("native ope"); + let native: OpeTerm = + block_on(42u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users/age"))) + .expect("native ope"); assert_eq!(ope, native.as_ref()); let m = block_on(ops::term( @@ -314,10 +306,10 @@ fn guest_terms_match_the_native_sem_derivations() { TERM_MATCH, )) .expect("match term"); - let native = block_on( - cipher - .default_keyset() - .match_terms::("alice smith", nonempty!("users/name")), + let native: MatchTerms = block_on( + "alice smith" + .to_string() + .encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users/name")), ) .expect("native"); assert_eq!(m, native.to_bytes()); @@ -339,17 +331,15 @@ fn guest_terms_match_the_native_sem_derivations() { )) .expect("bytes term"); assert_ne!(eq_text, eq_bytes); - let native_text = block_on( - cipher - .default_keyset() - .equality_term("ab".to_string(), nonempty!("f")), + let native_text: EqualityTerm = block_on( + "ab".to_string() + .encrypt_into_with_context(&cipher.default_keyset(), nonempty!("f")), ) .expect("native"); assert_eq!(eq_text, native_text.as_bytes()); - let native_bytes = block_on( - cipher - .default_keyset() - .equality_term(Protected::new(b"ab".to_vec()), nonempty!("f")), + let native_bytes: EqualityTerm = block_on( + Protected::new(b"ab".to_vec()) + .encrypt_into_with_context(&cipher.default_keyset(), nonempty!("f")), ) .expect("native"); assert_eq!(eq_bytes, native_bytes.as_bytes()); @@ -840,19 +830,17 @@ fn record_terms_equal_the_native_derivations_and_probe_them() { "output order is the plan's" ); - // The stored terms are byte-identical to query-time probes built the - // native way — the property that makes the index searchable. - let eq_probe = block_on( - cipher - .default_keyset() - .equality_term(34u32, nonempty!("users").with("age")), + // The stored terms are byte-identical to the terms a native value + // encrypted into its term type derives. For equality, ORE, and this + // match text, that is also the query's term. That is what makes the + // index searchable. + let eq_probe: EqualityTerm = block_on( + 34u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users").with("age")), ) .expect("probe"); assert_eq!(term_bytes(&age_outputs[1].1), eq_probe.as_bytes()); - let ore_probe = block_on( - cipher - .default_keyset() - .ore_term(34u32, nonempty!("users").with("age")), + let ore_probe: OreTerm = block_on( + 34u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users").with("age")), ) .expect("probe"); assert_eq!(term_bytes(&age_outputs[2].1), ore_probe.as_ref()); @@ -860,10 +848,10 @@ fn record_terms_equal_the_native_derivations_and_probe_them() { let (_, CipherText::Map(name_outputs)) = &fields[1] else { panic!("expected an output map for the second field"); }; - let match_probe = block_on( - cipher - .default_keyset() - .match_terms::("alice smith", nonempty!("users").with("name")), + let match_probe: MatchTerms = block_on( + "alice smith" + .to_string() + .encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users").with("name")), ) .expect("probe"); assert_eq!(term_bytes(&name_outputs[1].1), match_probe.to_bytes()); @@ -920,14 +908,14 @@ fn a_structured_plan_context_seals_what_the_native_extended_context_does() { }; let native = nonempty!("users").with("age").with(7u64); - let eq_probe = block_on(cipher.default_keyset().equality_term(34u32, native)).expect("probe"); + let eq_probe: EqualityTerm = + block_on(34u32.encrypt_into_with_context(&cipher.default_keyset(), native)).expect("probe"); assert_eq!(term_bytes(&age_outputs[1].1), eq_probe.as_bytes()); - let ore_probe = block_on(cipher.default_keyset().ore_term(34u32, native)).expect("probe"); + let ore_probe: OreTerm = + block_on(34u32.encrypt_into_with_context(&cipher.default_keyset(), native)).expect("probe"); assert_eq!(term_bytes(&age_outputs[2].1), ore_probe.as_ref()); - let flat_probe = block_on( - cipher - .default_keyset() - .equality_term(34u32, nonempty!("users").with("age")), + let flat_probe: EqualityTerm = block_on( + 34u32.encrypt_into_with_context(&cipher.default_keyset(), nonempty!("users").with("age")), ) .expect("probe"); assert_ne!( @@ -948,12 +936,12 @@ fn a_structured_plan_context_seals_what_the_native_extended_context_does() { let (_, CipherText::Map(name_outputs)) = &fields[1] else { panic!("expected an output map for the second field"); }; - let match_probe = block_on( - cipher - .default_keyset() - .match_terms::("alice smith", nonempty!("users").with("name").with(7u64)), - ) - .expect("probe"); + let match_probe: MatchTerms = + block_on("alice smith".to_string().encrypt_into_with_context( + &cipher.default_keyset(), + nonempty!("users").with("name").with(7u64), + )) + .expect("probe"); assert_eq!(term_bytes(&name_outputs[1].1), match_probe.to_bytes()); let CipherText::Single(leaf) = &age_outputs[0].1 else { @@ -1367,7 +1355,8 @@ fn terms_derive_under_the_selected_keyset() { .expect("globex term"); assert_ne!(acme_term, globex_term); - let native = block_on(acme.equality_term(42u32, nonempty!("users/age"))).expect("native"); + let native: EqualityTerm = + block_on(42u32.encrypt_into_with_context(&acme, nonempty!("users/age"))).expect("native"); assert_eq!(acme_term, native.into_bytes().to_vec()); } diff --git a/packages/eql/tests/encryption/tests/text_eq.rs b/packages/eql/tests/encryption/tests/text_eq.rs index 0d246d0189..57d6bdffc0 100644 --- a/packages/eql/tests/encryption/tests/text_eq.rs +++ b/packages/eql/tests/encryption/tests/text_eq.rs @@ -6,6 +6,7 @@ use eql_bindings::v3::terms::{Ciphertext, Hmac256}; use eql_bindings::v4::text::{TextEq, TextEqQuery}; use eql_bindings::v4::SchemaVersion; use eql_bindings::Identifier; +use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::transcode::{Reader, Transcode}; use stack_encrypt::{DecryptFrom, Encrypt, EncryptInto, NonEmpty}; use vitaminc_aead::plaintext::Sink; @@ -62,8 +63,9 @@ async fn text_round_trips_through_json_and_both_canonical_directions() { v: SchemaVersion::CURRENT, i: column().into_inner(), c: native.read(Ciphertext::visitor()).unwrap(), - hm: keyset - .equality_term(value.clone(), column()) + hm: value + .clone() + .encrypt_into_with_context::(&keyset, column()) .await .unwrap() .read(Hmac256::visitor()) @@ -125,9 +127,9 @@ async fn independent_queries_match_native_terms_without_requesting_data_keys() { .await .unwrap(); assert_eq!(query.hm, stored.hm); - let canonical = reader - .default_keyset() - .equality_term(value.clone(), column()) + let canonical = value + .clone() + .encrypt_into_with_context::(&reader.default_keyset(), column()) .await .unwrap() .read(Hmac256::visitor()) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index fe57fdcac2..fa7c01c661 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,6 +481,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, and + `ope_term` are no longer public** (#1760). Each method built one term + on its own, outside the target path and the query path. A term built + that way was easy to get wrong. Nothing tied it to the context of the ciphertext stored + beside it. For most indexes, the term a query sends is not the term a + row stores. With `MatchOptions::short_words` on, the `match_terms` + filter of "Mike Ng" misses "Mike Nguyen". To upgrade, build each term + one of two ways: + - **To store a value**, encrypt it into its target type, or into a + derived record with a field of that type. Use `EqualityTerm` for + `equality_term`, `MatchTerms` for `match_terms`, `OreTerm` for + `ore_term`, and `OpeTerm` for `ope_term`. The target builds the + term under the context it seals the ciphertext under. + `OreTerm::inner()` and `OpeTerm::inner()` return the ciphertext the + old methods returned. A target takes text as a `String`, not a + `&str`. + - **To query**, use the field reference's operator method, such as + `EncryptedUser::EMAIL.eq(&email)` or + `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its + own, such as `target::matching_query`, also works. + + ```rust + // Before + let term = keyset.equality_term("alice@example.com", nonempty!("users/email")).await?; + + // After: the term to store + let term: EqualityTerm = String::from("alice@example.com") + .encrypt_into_with_context(&keyset, nonempty!("users/email")) + .await?; + // After: the query + let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; + ``` + + `ore_block_term` does not change. No stored byte changes. + - **`Index` and `Indexes` each gain a required method** (#1398). A field query now derives its terms through these methods. - `Index::query_operation` derives the term that a query of the index diff --git a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md index 6b69068b92..7c4a2353da 100644 --- a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md +++ b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md @@ -224,6 +224,23 @@ cannot tell which they are producing. > query path for a match index. ADR-0009's amendment of the same date gives > the full rule. +> **Amended 2026-11-23 (#1760).** The four methods are now crate-private, +> so the compiler enforces the rule, not the documentation. The methods +> stay inside the crate, where tests compare other paths against them. +> Outside the crate, each term is built one way: +> +> - **To store a value**, encrypt it into its target type with +> `value.encrypt_into_with_context(&keyset, context)`. The target type +> is `EqualityTerm`, `MatchTerms`, `OreTerm`, or `OpeTerm`, or +> a derived record with a field of that type. The target builds the +> term under the context it seals the ciphertext under. +> - **To query**, use the field reference's operator method +> (`EncryptedUser::EMAIL.eq(..)`, `EncryptedUser::NAME.matches(..)`), or +> a query target run on its own, such as `target::matching_query`. +> +> `ore_block_term` is still public. That method builds a block +> order-revealing encryption (ORE) term outside a target, as the four did. + ### 6. Targets declare their sources; `FfiValue` is not one A target names the plaintext it accepts (`TextEq` from `Protected`), and diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 833698c527..d9c8e6185a 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -3,8 +3,8 @@ //! Everything else in this crate is typed: a target names its source type, //! and the operations it composes are reached through bounds — `Encrypt` for //! a ciphertext or an equality term, `AsRef` for a match term. That is what makes a term a cross-language -//! contract: `equality_term(34u32)` derives the same bytes wherever it is -//! called from, because `34u32` is the same value everywhere. +//! contract. `34u32` encrypted into an `EqualityTerm` derives the same bytes +//! wherever it is encrypted, because `34u32` is the same value everywhere. //! //! An FFI binding cannot reach those bounds. Its field types arrive as wire //! data, so there is no Rust type to name — and no dynamic value can satisfy diff --git a/packages/stack-encrypt/src/dynamic/term.rs b/packages/stack-encrypt/src/dynamic/term.rs index 805797eafa..38b7b406d2 100644 --- a/packages/stack-encrypt/src/dynamic/term.rs +++ b/packages/stack-encrypt/src/dynamic/term.rs @@ -5,9 +5,9 @@ //! [`ValueFrame`] the engine holds, a Rust value. It is walked to the one //! scalar it must be, and the term derives there, from the scalar vitaminc //! hands the sink, so this module restates none of vitaminc's vocabulary. -//! The derivation is the typed path's, which is what makes a term a -//! cross-language contract: an equality term for a frame holding `34` is the -//! term `equality_term(34u32)` derives. +//! The derivation is the typed path's. That makes a term a cross-language +//! contract: an equality term for a frame that contains `34` is the term +//! that `34u32` derives as an [`EqualityTerm`](crate::sem::EqualityTerm). //! //! - **Equality** normalizes the scalar with `vitaminc-normalize` and runs //! the PRF over the result, as the typed path does through that crate's @@ -429,8 +429,9 @@ impl TryFrom for MatchWire { /// /// ``` /// use stack_encrypt::dynamic::{context, term}; +/// use stack_encrypt::sem::EqualityTerm; /// use stack_encrypt::target::IndexSpec; -/// use stack_encrypt::{AsProtectedRef, StackCipher}; +/// use stack_encrypt::{AsProtectedRef, EncryptInto, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from @@ -444,7 +445,7 @@ impl TryFrom for MatchWire { /// // `["users", "age"]`, as a binding writes it. /// let ctx = context(vitaminc_aead_frame::serde::to_vec(&("users", "age"))?.as_protected_ref())?; /// let probe = term(&keyset, &34u32, &IndexSpec::Equality, ctx.clone()).await?; -/// let typed = keyset.equality_term(34u32, ctx).await?; +/// let typed: EqualityTerm = 34u32.encrypt_into_with_context(&keyset, ctx).await?; /// assert_eq!(probe, typed.into_bytes().to_vec()); /// # Ok::<(), Box>(()) /// # }).unwrap(); diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index ec27fe80ef..53fa5a8d24 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -789,9 +789,9 @@ pub use vitaminc_aead::{ /// vitaminc-ore's table also has jiff's `civil::Date` and `Timestamp`, and /// rust_decimal's `Decimal`. Those types are `Copy` and are not `Zeroize`, /// so nothing wipes them. A target and an owned index need `Zeroize`, so -/// neither takes them. The keyset's term functions -/// ([`KeysetCipher::ore_term`] and the others) and a borrowed index do take -/// them: a value passed by value is a copy the caller still holds. To have +/// neither takes them. [`KeysetCipher::ore_block_term`] and a borrowed +/// index do take them: a value passed by value is a copy the caller still +/// holds. To have /// the plaintext wiped, use `value::Date`, `value::Timestamp`, or /// `value::Decimal`. /// diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index c8bf0682e2..ed1833a531 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -30,15 +30,21 @@ //! one tenant's [`KeysetCipher`] compares only against terms derived through //! the same keyset. //! -//! Alongside the target-directed path, the keyset cipher carries descriptor -//! methods ([`KeysetCipher::equality_term`] and friends) for call sites that -//! want a single term rather than a whole record — query builders, mostly. -//! Each returns a [`Pending`], as the record path does; they derive no data -//! keys, and under the local HMAC backend the pending carries no requests, -//! so a probe settles without a ZeroKMS call — though a backend that derives -//! terms at ZeroKMS settles it through the same pending. The -//! descriptor is the same [`NonEmpty`] context the target-directed path -//! takes, so the two agree byte for byte. +//! A term that your app stores comes from a target. Encrypt the value into +//! its term type, or into a record with the term as a field. The target +//! builds the term under the context it seals the ciphertext under. +//! +//! A query term comes from the field's reference, such as +//! `EncryptedUser::EMAIL.eq(..)` or `EncryptedUser::NAME.matches(..)`. The +//! reference supplies the field's index and context. A query target run on +//! its own, such as [`matching_query`](crate::target::matching_query), also +//! builds one. A query term is not always the stored term: a match query +//! with [`MatchOptions::short_words`] on is cut differently. +//! +//! Each of these returns a [`Pending`]. A term needs no data key. Under the +//! local HMAC backend, the pending makes no request, so it settles without +//! a ZeroKMS call. A backend that derives terms at ZeroKMS settles the term +//! through the same pending. //! //! # PRF backends, visitors, and the 2-party future //! @@ -175,7 +181,7 @@ use std::fmt; use std::marker::PhantomData; // Re-exported because they appear in this module's public signatures -// ([`KeysetCipher::ore_term`], [`OreTerm::inner`], ...): a caller can name +// ([`OreTerm::inner`], [`OpeTerm::new`], ...): a caller can name // the ciphertext types without depending on `clww-ore` directly. use clww_ore::{ClwwOpe, ClwwOre}; pub use clww_ore::{OpeClww8VariableV1, OreClww8VariableV1}; @@ -518,8 +524,23 @@ impl TermError { // Equality // ============================================================================= -/// An equality (exact-match) index term: one PRF block over the value's -/// normalized bytes (see [`KeysetCipher::equality_term`]). +/// An equality (exact-match) index term: one block of a pseudorandom +/// function (PRF) over the value's normalized bytes. The same value under +/// the same context always yields the same term, at write time and at +/// query time. +/// +/// The value is one scalar. `vitaminc-normalize` normalizes it before the +/// PRF reads it: +/// +/// - Every integer width of one number is one term, so `34u32` and `34i64` +/// match. Both float widths of one number are one term too. +/// - Text is compared in Unicode 16 NFC. +/// - A date, timestamp, decimal, or uuid derives in a domain of its own. +/// - Every null shares one term. +/// +/// A boolean or a container has no term ([`TermError::NoEqualityTerm`]). +/// Text with a code point unassigned in Unicode 16 is refused +/// ([`TermError::Normalize`]). /// /// Terms are pseudorandom under the index key; they are stored server-side and /// are not secret key material. @@ -828,17 +849,19 @@ impl MatchOptions { /// reference use one configuration: the field's type names its match index, /// [`Match`](struct@crate::target::Match), through /// [`Answers`](crate::op::Answers), and the query derives its filter through -/// that index. You can also derive a filter directly, with -/// [`match_terms`](crate::KeysetCipher::match_terms) or a `Match` you -/// name. That filter uses whatever configuration you give it. The filter -/// matches a stored filter only when that configuration is the field's. +/// that index. /// -/// `match_terms` and `Match`'s [`operation`](crate::target::Index::operation) -/// build a stored value's filter. With [`MatchOptions::short_words`] on, -/// build a query's filter with -/// [`matching_query`](crate::target::matching_query). That function keeps -/// the query's short words only when its whole text is shorter than one -/// n-gram. +/// You can also derive a filter directly: encrypt text into a +/// `MatchTerms`, or run a `Match` that you name. That filter uses +/// whatever configuration you give it. The filter matches a stored filter +/// only when that configuration is the field's. +/// +/// A `MatchTerms` target and `Match`'s +/// [`operation`](crate::target::Index::operation) build a stored value's +/// filter. With [`MatchOptions::short_words`] on, build a query's filter +/// with [`matching_query`](crate::target::matching_query). That function +/// keeps the query's short words only when its whole text is shorter than +/// one n-gram. /// /// A plan that is data has one match index per field. The plan's stored /// filter and its query both read that index's options. @@ -2088,139 +2111,24 @@ order_term! { // Term generation on the cipher // ============================================================================= -/// Descriptor term generation, for call sites that want one term rather than -/// a whole record: query builders probing an index, re-indexers, tests of a -/// single scheme. -/// -/// Each returns a [`Pending`], the same carrier the record path hands back, -/// so probes combine ([`Pending::zip`], [`Pending::all`]) and a batch of -/// them settles as one. Under the local HMAC backend a term is derived -/// during the synchronous build and the pending carries no requests — -/// awaiting it does no I/O — but that is the backend's property, not the -/// API's: a backend that derives terms at ZeroKMS settles them the way it -/// settles data keys, through the same pending. -/// -/// # These are the query-probe path -/// -/// A term derived here is bound to the descriptor you pass and to nothing -/// else: it builds no [`Descriptor`](crate::Descriptor), makes no ZeroKMS -/// request, and has no relation to the ciphertext of the field it indexes. -/// Nothing checks that the two agree, and the two mistakes fail differently — -/// a ciphertext under the wrong context is refused at first read, while a -/// term under the wrong context is a valid term in another domain that -/// matches nothing, forever, with no error anywhere. -/// -/// So derive a term here to *query*: a probe has no ciphertext to agree with, -/// and needs the field's context because that is what it is matching against. -/// A term that is going to be **stored** should come from a target instead, -/// where the one context the target is handed reaches the ciphertext and the -/// term beside it alike, and giving either a context of its own is written -/// in the declaration rather than plumbed. A derived record does -/// this per field and cannot get it wrong; a hand-written target can still -/// put a subtree under its own context, but has to say so. The bytes are -/// identical either way; what differs is whether anything holds the two in -/// agreement. +/// Term derivations that the `dynamic` path shares, and one block ORE term +/// made on its own. /// -/// Do not use [`match_terms`](Self::match_terms) to build a match query when -/// [`MatchOptions::short_words`] is on. `match_terms` is the exception to -/// the rule above, because it derives a stored value's filter. That filter -/// is also a query's filter only while the option is off. +/// A term that your app stores comes from a target. Encrypt the value into +/// its term type, such as [`EqualityTerm`], [`MatchTerms`], or +/// [`OreTerm`], or into a derived record's field. The target builds the +/// term under the context it seals the ciphertext under. /// -/// With the option on, a query keeps its short words only when its whole -/// text is shorter than one n-gram. A query for "Mike Ng" built with -/// `match_terms` asks for the word `ng`, so it does not find "Mike Nguyen". -/// Build a match query from the field's reference (`matches(..)`), or with -/// [`matching_query`](crate::target::matching_query). -/// -/// The descriptor is a context -/// as the target-directed leaves take it — a [`NonEmpty`]: -/// `nonempty!("users").with("email")`, `NonEmpty::new(column)?`, -/// `nonempty!("users").with("email").with(row_id)` — and each method is -/// byte-identical to that path for the same descriptor, so a term generated -/// here compares against one generated by `encrypt_into_with_context`. +/// A query term comes from the field's reference, such as +/// `EncryptedUser::EMAIL.eq(..)`. A query target run on its own, such as +/// [`matching_query`](crate::target::matching_query), also builds one. A +/// stored term and a query term are the same bytes for some indexes only. impl KeysetCipher<'_, K> { - /// Generate an equality (exact-match) term for `value` under the field - /// `descriptor`. Deterministic: the same value + descriptor always yields - /// the same term, at write time and at query time. Byte-identical to - /// `value.encrypt_into_with_context(&keyset, descriptor)` into an - /// `EqualityTerm`. - /// - /// The value is one scalar, normalized by `vitaminc-normalize` before the - /// PRF sees it: every integer width of one number is one term - /// (`34u32` and `34i64` match), both float widths of one number are one - /// term, text is compared in Unicode 16 NFC, and a date, timestamp, - /// decimal or uuid derives in a domain of its own, and every null shares - /// one term. A boolean or a container has no term - /// ([`TermError::NoEqualityTerm`]), and text with a code point - /// unassigned in Unicode 16 is refused ([`TermError::Normalize`]). - pub fn equality_term<'c, T>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, EqualityTerm, K> - where - T: Encrypt, - { - match self.loaded_state() { - Some(keyset) => { - let term = equality(&keyset.prf, value, descriptor.into_prf_context()); - Pending::ready(self, term.map_err(Error::from)) - } - None => match normalized(value) { - Ok(normalized) => self.equality_term_normalized(normalized, descriptor), - Err(error) => Pending::ready(self, Err(error.into())), - }, - } - } - - /// Generate a match (full-text) term for `text` under the field - /// `descriptor` and the type-level config `O`: tokenize locally, PRF each - /// token, fold the outputs into Bloom-filter bit positions. - /// - /// The config is a *type* parameter (not runtime options), so the - /// filter's type says which configuration cut it. A filter cut under - /// one config is not comparable with one cut under another: a query - /// would miss rows it should match, with no error. So a filter derived - /// here matches a stored one only when `O` is the field's own. A query - /// made from the field's reference takes the field's `O` ([`MatchConfig`] - /// says how). Byte-identical to the target-directed path for the same - /// `O`. For custom options, define a marker type implementing - /// [`MatchConfig`]. - /// - /// Use this to build the filter of a value you store, not a query. With - /// [`MatchOptions::short_words`] on, a stored filter contains every - /// n-gram, plus each short word as a whole word. A query must not ask for - /// the whole word. A query for "Mike Ng" built with `match_terms` asks - /// for the word `ng`, so it does not find "Mike Nguyen". - /// - /// Build a query with a field reference's `matches(..)`. That gives the - /// other type, [`MatchQuery`]. Or build a query's filter with - /// [`matching_query`](crate::target::matching_query). Both keep a - /// query's short words only when its whole text is shorter than one - /// n-gram. - /// - /// Text with no token is the empty filter. No query matches it. Such - /// text is empty, separators only, or shorter than one n-gram (see - /// [`Tokenizer::Ngram`]). So a short value can be stored, and this method - /// refuses nothing. A query of such text is refused - /// ([`TermError::EmptyTermText`]), because its filter would match every - /// row. - pub fn match_terms<'c, O>( - &self, - text: &str, - descriptor: NonEmpty>, - ) -> Pending<'_, MatchTerms, K> - where - O: MatchConfig + MaybeSend, - { - self.match_terms_under(text, descriptor, O::options(), Side::Stored) - } - - /// [`equality_term`](Self::equality_term) of one scalar the caller has - /// normalized already, for the `dynamic` path, which walks a value to - /// its one scalar and normalizes it there, with the same - /// `vitaminc_normalize::normalize` the typed path's sink applies. - #[cfg_attr(not(feature = "dynamic"), allow(dead_code))] + /// The equality term of one scalar that the caller has already + /// normalized. The `dynamic` path walks a value to its one scalar and + /// normalizes it there, with the `vitaminc_normalize::normalize` that + /// the typed path's sink applies. + #[cfg(any(test, feature = "dynamic"))] pub(crate) fn equality_term_normalized<'c>( &self, normalized: Normalized, @@ -2241,14 +2149,15 @@ impl KeysetCipher<'_, K> { } } - /// [`match_terms`](Self::match_terms) under runtime options, for `side`, - /// for the `dynamic` path. That path's plan carries a match index's - /// options as data (an `IndexSpec::Match`). The path derives both stored - /// and query filters. + /// The match filter of `text` under runtime options, for `side`, for the + /// `dynamic` path. That path's plan carries a match index's options as + /// data (an `IndexSpec::Match`). The path derives both stored and query + /// filters. /// - /// This method is not public. The typed API keeps the options on the - /// type, so a stored field and its query cannot disagree. A binding - /// reaches this only through a plan that names the options for both. + /// The typed API keeps the options on the type, so a stored field and + /// its query cannot disagree. A binding reaches this method only through + /// a plan that names the options for both. + #[cfg(any(test, feature = "dynamic"))] pub(crate) fn match_terms_under<'c, O>( &self, text: &str, @@ -2262,45 +2171,24 @@ impl KeysetCipher<'_, K> { match_pending(self, text, descriptor.into_prf_context(), options, side) } - /// Generate an order-revealing (CLLW ORE) term for a range-queryable value - /// under the field `descriptor`. The PRF input is the descriptor alone — - /// the plaintext never enters the PRF; it travels in the visitor, which - /// derives the per-descriptor CLLW key from the PRF block and encrypts - /// under it in one step. The key never leaves the visitor. + /// Generate a block ORE term: ore-rs's 6-bit block order-revealing + /// encryption (ORE), the scheme that EQL v4's `_ord_ore` domains store. + /// The PRF input is the descriptor alone. The plaintext never enters + /// the PRF, and one visitor derives the per-descriptor key and uses it. + /// See [`OreBlockTerm`] for which scheme a type is encrypted with, and + /// what is refused. /// - /// Supported inputs: every [`Orderable`] type, each encoded as its - /// target. Bytes are not one. A value handed over by value is wiped by - /// the walk that encodes it, and a reference (`&String`, `&str`) is read - /// in place. Returns the raw CLLW ciphertext; the target-directed path - /// wraps the same bytes in [`OreTerm`]. - pub fn ore_term<'c, T: Orderable>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, OreClww8VariableV1, K> { - let context = descriptor.into_prf_context().into_owned(); - order_pending(self, target_of::(), value, context, order_error, ore) - } - - /// Generate an order-preserving (CLLW OPE) term: ciphertexts compare with - /// plain lexicographic byte order, no custom comparator required. - /// Encrypt-only — pair with the record ciphertext for round-trips. Key - /// handling and input bounds as for [`ore_term`](Self::ore_term). - pub fn ope_term<'c, T: Orderable>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, OpeClww8VariableV1, K> { - let context = descriptor.into_prf_context().into_owned(); - order_pending(self, target_of::(), value, context, order_error, ope) - } - - /// Generate a block ORE term: ore-rs's 6-bit block ORE, the scheme - /// EQL v4's `_ord_ore` domains store. Key handling and inputs as for - /// [`ore_term`](Self::ore_term), under a key of its own; see - /// [`OreBlockTerm`] for which scheme a type is encrypted with and what - /// is refused. Byte-identical to the target-directed path's left half - /// for the same descriptor; the right half carries a random nonce. + /// Every [`Orderable`] type is supported, each encoded as its target. + /// The walk that encodes a value wipes a value handed over by value. A + /// reference (`&String`, `&str`) is read in place. The term's left half + /// is byte-identical to the target-directed path's for the same + /// descriptor. The right half contains a random nonce. + /// + /// The descriptor is the context the target-directed path takes, a + /// [`NonEmpty`]: `nonempty!("users").with("age")`. Nothing ties a + /// term made here to the context of the ciphertext beside it. So a term + /// that you will store should come from a target instead. The target + /// hands one context to the term and the ciphertext. pub fn ore_block_term<'c, T: Orderable>( &self, value: T, @@ -2320,6 +2208,72 @@ impl KeysetCipher<'_, K> { } } +/// One term of each kind on its own, under a descriptor, outside any +/// target. This crate's tests compare another path's term against these. +/// Each method derives the bytes that a target derives for the same +/// descriptor. The `lone_terms` tests check that. +#[cfg(test)] +impl KeysetCipher<'_, K> { + /// The equality term of `value` under `descriptor`: the term an + /// [`EqualityTerm`] target derives. + pub(crate) fn equality_term<'c, T>( + &self, + value: T, + descriptor: NonEmpty>, + ) -> Pending<'_, EqualityTerm, K> + where + T: Encrypt, + { + match self.loaded_state() { + Some(keyset) => { + let term = equality(&keyset.prf, value, descriptor.into_prf_context()); + Pending::ready(self, term.map_err(Error::from)) + } + None => match normalized(value) { + Ok(normalized) => self.equality_term_normalized(normalized, descriptor), + Err(error) => Pending::ready(self, Err(error.into())), + }, + } + } + + /// The stored match filter of `text` under `descriptor` and the + /// config `O`: the filter a [`MatchTerms`] target derives. A query + /// of the same text is cut differently when + /// [`MatchOptions::short_words`] is on. + pub(crate) fn match_terms<'c, O>( + &self, + text: &str, + descriptor: NonEmpty>, + ) -> Pending<'_, MatchTerms, K> + where + O: MatchConfig + MaybeSend, + { + self.match_terms_under(text, descriptor, O::options(), Side::Stored) + } + + /// The CLLW ORE ciphertext of `value` under `descriptor`: the bytes an + /// [`OreTerm`] target wraps. + pub(crate) fn ore_term<'c, T: Orderable>( + &self, + value: T, + descriptor: NonEmpty>, + ) -> Pending<'_, OreClww8VariableV1, K> { + let context = descriptor.into_prf_context().into_owned(); + order_pending(self, target_of::(), value, context, order_error, ore) + } + + /// The CLLW OPE ciphertext of `value` under `descriptor`: the bytes an + /// [`OpeTerm`] target wraps. + pub(crate) fn ope_term<'c, T: Orderable>( + &self, + value: T, + descriptor: NonEmpty>, + ) -> Pending<'_, OpeClww8VariableV1, K> { + let context = descriptor.into_prf_context().into_owned(); + order_pending(self, target_of::(), value, context, order_error, ope) + } +} + #[cfg(test)] mod tests { use std::collections::BTreeMap; @@ -2938,3 +2892,160 @@ mod order_terms_before_the_keyset_loads { ); } } + +/// Each lone term method derives the bytes that a target derives for the +/// same value and descriptor. The tests check this with the keyset loaded, +/// and with the keyset not yet loaded when the call is built. +#[cfg(test)] +mod lone_terms { + use stack_kms::{FakeCredentialKeySource, FakeDataKeySource, SecretToken}; + + use super::*; + use crate::{nonempty, EncryptInto, StackCipher}; + + const EMAIL: &str = "bob@example.com"; + const TEXT: &str = "bob the builder"; + const AGE: u32 = 42; + + fn field() -> NonEmpty<(&'static str, &'static str)> { + nonempty!("users").with("email") + } + + /// Settle a pending: awaited as it is, or with a credential, which a + /// cipher over a credential key source needs for every call. + macro_rules! settle { + ($pending:expr, plain) => { + $pending.await.unwrap() + }; + ($pending:expr, credentialed) => { + $pending + .with_credential(SecretToken::new("alice.jwt")) + .await + .unwrap() + }; + } + + /// Each lone term is the target's term of the same value. The lone + /// call is built and settled first, so on a keyset that is not loaded + /// it is the call that loads it. + macro_rules! each_lone_term_is_the_targets_term { + ($keyset:expr, $state:ident) => {{ + let keyset = $keyset; + let equality = settle!(keyset.equality_term(String::from(EMAIL), field()), $state); + let target: EqualityTerm = settle!( + String::from(EMAIL).encrypt_into_with_context(keyset, field()), + $state + ); + assert_eq!(equality, target, "the lone equality term is the target's"); + + let matching = settle!(keyset.match_terms::(TEXT, field()), $state); + let target: MatchTerms = settle!( + String::from(TEXT).encrypt_into_with_context(keyset, field()), + $state + ); + assert_eq!(matching, target, "the lone match filter is the target's"); + + let ore = settle!(keyset.ore_term(AGE, field()), $state); + let target: OreTerm = + settle!(AGE.encrypt_into_with_context(keyset, field()), $state); + assert_eq!(&ore, target.inner(), "the lone ORE term is the target's"); + + let ope = settle!(keyset.ope_term(AGE, field()), $state); + let target: OpeTerm = + settle!(AGE.encrypt_into_with_context(keyset, field()), $state); + assert_eq!(&ope, target.inner(), "the lone OPE term is the target's"); + }}; + } + + mod given_a_loaded_keyset { + use super::*; + + async fn scenario() -> StackCipher { + StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .unwrap() + } + + #[tokio::test] + async fn each_lone_term_is_the_targets_term() { + let cipher = scenario().await; + let keyset = cipher.default_keyset(); + assert!(keyset.loaded_state().is_some(), "init loads the keyset"); + each_lone_term_is_the_targets_term!(&keyset, plain); + } + } + + mod given_a_keyset_that_is_not_loaded { + use super::*; + + async fn scenario() -> StackCipher { + StackCipher::builder() + .kms(FakeCredentialKeySource::new()) + .init() + .await + .unwrap() + } + + #[tokio::test] + async fn each_lone_term_is_the_targets_term() { + let cipher = scenario().await; + let keyset = cipher.default_keyset(); + assert!( + keyset.loaded_state().is_none(), + "nothing has loaded the keyset" + ); + each_lone_term_is_the_targets_term!(&keyset, credentialed); + } + + /// Each lone term built before the load is the term the loaded + /// keyset derives through the same method. + #[tokio::test] + async fn each_lone_term_built_before_the_load_is_the_term_after_it() { + let cipher = scenario().await; + let keyset = cipher.default_keyset(); + let equality = keyset.equality_term(String::from(EMAIL), field()); + let matching = keyset.match_terms::(TEXT, field()); + let ore = keyset.ore_term(AGE, field()); + let ope = keyset.ope_term(AGE, field()); + assert!( + keyset.loaded_state().is_none(), + "building a lone term loads nothing" + ); + let (equality, matching, ore, ope) = ( + settle!(equality, credentialed), + settle!(matching, credentialed), + settle!(ore, credentialed), + settle!(ope, credentialed), + ); + assert!(keyset.loaded_state().is_some(), "the calls loaded it"); + assert_eq!( + equality, + settle!( + keyset.equality_term(String::from(EMAIL), field()), + credentialed + ), + "the equality term" + ); + assert_eq!( + matching, + settle!( + keyset.match_terms::(TEXT, field()), + credentialed + ), + "the match filter" + ); + assert_eq!( + ore, + settle!(keyset.ore_term(AGE, field()), credentialed), + "the ORE term" + ); + assert_eq!( + ope, + settle!(keyset.ope_term(AGE, field()), credentialed), + "the OPE term" + ); + } + } +} diff --git a/packages/stack-encrypt/tests/audit.rs b/packages/stack-encrypt/tests/audit.rs index 850500235a..9947498acf 100644 --- a/packages/stack-encrypt/tests/audit.rs +++ b/packages/stack-encrypt/tests/audit.rs @@ -275,16 +275,18 @@ async fn an_audited_call_that_requests_no_data_key_succeeds_and_sends_nothing() let email = String::from("bob@example.com"); // A query term is derived from the keyset's index key. - let audited = keyset - .equality_term(email.clone(), nonempty!("users/email")) + let audited = AccountTerms::EMAIL + .eq(&email) + .encrypt(&keyset) .audit(list_issues()) .await .unwrap(); - let plain = keyset - .equality_term(email.clone(), nonempty!("users/email")) + let plain = AccountTerms::EMAIL + .eq(&email) + .encrypt(&keyset) .await .unwrap(); - assert_eq!(audited, plain); + assert_eq!(audited, plain, "the audited query is the plain query"); // A record whose only field is a term. let account = Account { email }; diff --git a/packages/stack-encrypt/tests/context_conformance.rs b/packages/stack-encrypt/tests/context_conformance.rs index 51779d8300..2cb537b9e6 100644 --- a/packages/stack-encrypt/tests/context_conformance.rs +++ b/packages/stack-encrypt/tests/context_conformance.rs @@ -22,8 +22,8 @@ use stack_encrypt::target::{ }; use stack_encrypt::AsProtectedRef as _; use stack_encrypt::{ - CipherText, Descriptor, Equality, IntoAad, IntoPrfContext, Label, NonEmpty, SealedValue, - StackCipherText, + CipherText, Descriptor, EncryptInto, Equality, IntoAad, IntoPrfContext, Label, NonEmpty, + SealedValue, StackCipherText, }; use std::collections::{BTreeMap, BTreeSet}; @@ -272,7 +272,11 @@ async fn shared_context_composition() { let descriptor = Descriptor::of(ctx.clone()).as_str().to_owned(); let aad = hex(ctx.clone().into_aad().as_bytes()); let prf = hex(ctx.clone().into_prf_context().as_bytes()); - let term = keyset.equality_term("hello", ctx.clone()).await.unwrap(); + let term: EqualityTerm = "hello" + .to_string() + .encrypt_into_with_context(&keyset, ctx.clone()) + .await + .unwrap(); let plan = plan(&case); let fresh = record::encrypt(&keyset, source(&case), &plan) .unwrap() diff --git a/packages/stack-encrypt/tests/credential.rs b/packages/stack-encrypt/tests/credential.rs index 5fdc8383bd..a9487613c1 100644 --- a/packages/stack-encrypt/tests/credential.rs +++ b/packages/stack-encrypt/tests/credential.rs @@ -666,18 +666,20 @@ async fn init_still_checks_a_key_source_with_its_own_identity_at_startup() { /// the loaded keyset derives. The first one awaited loads the keyset. #[tokio::test] async fn terms_built_before_the_load_are_the_terms_built_after_it() { - use stack_encrypt::sem::DefaultMatch; + use stack_encrypt::sem::{MatchTerms, OpeTerm, OreTerm}; let (shared, source) = unloaded().await; let early = shared.default_keyset(); let field = || nonempty!("users").with("email"); // Built before the load: none of these has a keyset to derive under. - let equality = early.equality_term(String::from("bob@example.com"), field()); - let refused = early.equality_term(true, field()); - let matching = early.match_terms::("bob the builder", field()); - let ore = early.ore_term(42u32, field()); - let ope = early.ope_term(42u32, field()); + let equality = String::from("bob@example.com") + .encrypt_into_with_context::(&early, field()); + let refused = true.encrypt_into_with_context::(&early, field()); + let matching = + String::from("bob the builder").encrypt_into_with_context::(&early, field()); + let ore = 42u32.encrypt_into_with_context::, _>(&early, field()); + let ope = 42u32.encrypt_into_with_context::, _>(&early, field()); let block = early.ore_block_term(42u32, field()); assert_eq!(source.take(), vec![], "building makes no request"); @@ -704,31 +706,39 @@ async fn terms_built_before_the_load_are_the_terms_built_after_it() { let late = shared.default_keyset(); assert_eq!( equality, - late.equality_term(String::from("bob@example.com"), field()) + String::from("bob@example.com") + .encrypt_into_with_context::(&late, field()) .with_credential(alice()) .await - .unwrap() + .unwrap(), + "the equality term built before the load" ); assert_eq!( matching, - late.match_terms::("bob the builder", field()) + String::from("bob the builder") + .encrypt_into_with_context::(&late, field()) .with_credential(alice()) .await - .unwrap() + .unwrap(), + "the match filter built before the load" ); assert_eq!( ore, - late.ore_term(42u32, field()) + 42u32 + .encrypt_into_with_context::, _>(&late, field()) .with_credential(alice()) .await - .unwrap() + .unwrap(), + "the ORE term built before the load" ); assert_eq!( ope, - late.ope_term(42u32, field()) + 42u32 + .encrypt_into_with_context::, _>(&late, field()) .with_credential(alice()) .await - .unwrap() + .unwrap(), + "the OPE term built before the load" ); let late_block = late .ore_block_term(42u32, field()) diff --git a/packages/stack-encrypt/tests/frozen_bytes.rs b/packages/stack-encrypt/tests/frozen_bytes.rs index e6d2d60315..313e7198c6 100644 --- a/packages/stack-encrypt/tests/frozen_bytes.rs +++ b/packages/stack-encrypt/tests/frozen_bytes.rs @@ -331,8 +331,9 @@ async fn seal_rejects_a_key_tag_the_length_field_cannot_frame() { async fn equality_term_encoding_is_the_raw_prf_bytes() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let term = keyset - .equality_term("alice", nonempty!("users/email")) + let term: EqualityTerm = "alice" + .to_string() + .encrypt_into_with_context(&keyset, nonempty!("users/email")) .await .expect("equality term"); @@ -372,8 +373,9 @@ fn equality_term_try_from_rejects_wrong_length() { async fn match_term_bytes_are_pinned() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let term = keyset - .match_terms::("alice smith", nonempty!("users/name")) + let term: MatchTerms = "alice smith" + .to_string() + .encrypt_into_with_context(&keyset, nonempty!("users/name")) .await .expect("match term"); diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index fc3414ff29..3707564165 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -861,8 +861,9 @@ fn a_typed_query_leaves_no_plaintext_on_the_heap() { #[test] fn a_call_through_a_keyset_that_is_not_loaded_leaves_no_plaintext_on_the_heap() { use stack_encrypt::kms::{FakeCredentialKeySource, SecretToken}; - use stack_encrypt::sem::DefaultMatch; - use stack_encrypt::{Ciphertext, StackCipher}; + use stack_encrypt::sem::{DefaultMatch, EqualityTerm, MatchTerms, OreTerm}; + use stack_encrypt::target::{matching, Borrowed, CallerContext}; + use stack_encrypt::{Ciphertext, EncryptInto, StackCipher}; let rt = runtime(); let not_loaded = || { rt.block_on( @@ -877,14 +878,14 @@ fn a_call_through_a_keyset_that_is_not_loaded_leaves_no_plaintext_on_the_heap() let cipher = not_loaded(); let keyset = cipher.default_keyset(); let text = marked("equality"); - watched("equality_term (keyset not loaded)", || { - rt.block_on(async { - keyset - .equality_term(text, nonempty!("users/email")) - .with_credential(credential()) - .await - }) - .unwrap(); + watched("equality term (keyset not loaded)", || { + let _: EqualityTerm = rt + .block_on(async { + text.encrypt_into_with_context(&keyset, nonempty!("users/email")) + .with_credential(credential()) + .await + }) + .unwrap(); }); let cipher = not_loaded(); @@ -892,28 +893,33 @@ fn a_call_through_a_keyset_that_is_not_loaded_leaves_no_plaintext_on_the_heap() // The caller's own text stays alive across the watch: the pending // works on its copy. let text = marked("match these words"); - watched("match_terms (keyset not loaded)", || { - rt.block_on(async { - keyset - .match_terms::(&text, nonempty!("users/bio")) - .with_credential(credential()) - .await - }) - .unwrap(); + watched("match filter (keyset not loaded)", || { + let _: MatchTerms = rt + .block_on(async { + keyset + .run( + matching::<_, _, Borrowed, DefaultMatch>(), + &text, + CallerContext::from(nonempty!("users/bio")), + ) + .with_credential(credential()) + .await + }) + .unwrap(); }); drop(text); let cipher = not_loaded(); let keyset = cipher.default_keyset(); let text = marked("order"); - watched("ore_term (keyset not loaded)", || { - rt.block_on(async { - keyset - .ore_term(text, nonempty!("users/surname")) - .with_credential(credential()) - .await - }) - .unwrap(); + watched("ORE term (keyset not loaded)", || { + let _: OreTerm = rt + .block_on(async { + text.encrypt_into_with_context(&keyset, nonempty!("users/surname")) + .with_credential(credential()) + .await + }) + .unwrap(); }); let cipher = not_loaded(); @@ -926,25 +932,33 @@ fn a_call_through_a_keyset_that_is_not_loaded_leaves_no_plaintext_on_the_heap() }); } -/// An order term takes its plaintext by value, so the engine owns the -/// `String` or `Vec` it is handed (a clone of the caller's, on the -/// target path) and must wipe it. Both paths hand a bare one; the engine -/// wraps it in `Zeroizing` on receipt, before anything can fail. +/// Text encrypted into an order term is handed over by value. The engine +/// owns the `String` and must wipe it. #[test] fn an_order_term_of_owned_text_or_bytes_leaves_no_plaintext_on_the_heap() { + use stack_encrypt::sem::{OpeTerm, OreTerm}; + use stack_encrypt::EncryptInto; let rt = runtime(); let cipher = rt.block_on(common::stack_cipher()); let keyset = cipher.default_keyset(); // Each plaintext is built before its watch: building one can free a // partly written copy, which is the test's own residue, not the term's. let text = marked("order"); - watched("ore_term (String)", || { - rt.block_on(async { keyset.ore_term(text, nonempty!("users/surname")).await }) + watched("ORE term (String)", || { + let _: OreTerm = rt + .block_on(async { + text.encrypt_into_with_context(&keyset, nonempty!("users/surname")) + .await + }) .unwrap(); }); let text = marked("order"); - watched("ope_term (String)", || { - rt.block_on(async { keyset.ope_term(text, nonempty!("users/surname")).await }) + watched("OPE term (String)", || { + let _: OpeTerm = rt + .block_on(async { + text.encrypt_into_with_context(&keyset, nonempty!("users/surname")) + .await + }) .unwrap(); }); } diff --git a/packages/stack-encrypt/tests/keysets.rs b/packages/stack-encrypt/tests/keysets.rs index f24b4b7fcc..ca2b84be7b 100644 --- a/packages/stack-encrypt/tests/keysets.rs +++ b/packages/stack-encrypt/tests/keysets.rs @@ -8,6 +8,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Mutex; use std::time::Duration; +use stack_encrypt::sem::EqualityTerm; use stack_encrypt::{ nonempty, CipherText, DecryptFrom, EncryptInto, Error, SealedValue, StackCipher, StackCipherText, @@ -551,16 +552,16 @@ async fn keysets_derive_distinct_index_keys() { let a = load(&cipher, Uuid::from_u128(1)).await.expect("a"); let b = load(&cipher, Uuid::from_u128(2)).await.expect("b"); - let term_a = a - .equality_term(7u32, nonempty!("users/age")) + let term_a: EqualityTerm = 7u32 + .encrypt_into_with_context(&a, nonempty!("users/age")) .await .expect("term"); - let term_b = b - .equality_term(7u32, nonempty!("users/age")) + let term_b: EqualityTerm = 7u32 + .encrypt_into_with_context(&b, nonempty!("users/age")) .await .expect("term"); - let term_a_again = a - .equality_term(7u32, nonempty!("users/age")) + let term_a_again: EqualityTerm = 7u32 + .encrypt_into_with_context(&a, nonempty!("users/age")) .await .expect("term"); @@ -616,8 +617,6 @@ async fn a_sealed_leaf_names_the_keyset_it_was_sealed_under() { /// leaf. A new selection by the name gets the other keyset. #[tokio::test] async fn calls_built_before_the_load_settle_under_the_keyset_their_handle_keeps() { - use stack_encrypt::sem::EqualityTerm; - // No name is trusted, so every lookup of a name asks. let cipher = StackCipher::builder() .kms(Observed::default()) @@ -632,7 +631,8 @@ async fn calls_built_before_the_load_settle_under_the_keyset_their_handle_keeps( let first = acme.encrypt_tree("hello".to_string(), "greeting"); let second = acme.encrypt_tree("hello".to_string(), "greeting"); let third = acme.encrypt_tree("hello".to_string(), "greeting"); - let term = acme.equality_term(String::from("a@example.com"), field()); + let term = + String::from("a@example.com").encrypt_into_with_context::(&acme, field()); let first = first.await.expect("seal"); let kept = acme.keyset_id().await.unwrap(); @@ -660,13 +660,13 @@ async fn calls_built_before_the_load_settle_under_the_keyset_their_handle_keeps( assert_eq!(opened, "hello"); let term: EqualityTerm = term.await.expect("term"); - let same = acme - .equality_term(String::from("a@example.com"), field()) + let same: EqualityTerm = String::from("a@example.com") + .encrypt_into_with_context(&acme, field()) .await .expect("term"); assert_eq!(term, same, "derived under the handle's keyset"); - let under_the_other = elsewhere - .equality_term(String::from("a@example.com"), field()) + let under_the_other: EqualityTerm = String::from("a@example.com") + .encrypt_into_with_context(&elsewhere, field()) .await .expect("term"); assert_ne!(term, under_the_other); diff --git a/packages/stack-encrypt/tests/match_short_words.rs b/packages/stack-encrypt/tests/match_short_words.rs index 45775dd61c..0cc04ed910 100644 --- a/packages/stack-encrypt/tests/match_short_words.rs +++ b/packages/stack-encrypt/tests/match_short_words.rs @@ -587,11 +587,15 @@ mod calibration { Config::default(), TestRng::from_seed(RngAlgorithm::ChaCha, &[7; 32]), ); + // The stored filter of the text, for the rows and the queries + // alike: a one-word or one-trigram query's filter is its stored + // filter, and the control's stored filter keeps its two words. let derive = |text: String| { let keyset = &keyset; async move { - let filter = keyset - .match_terms::(&text, nonempty!("people/name")) + let filter: MatchTerms = text + .clone() + .encrypt_into_with_context(keyset, nonempty!("people/name")) .await .expect("derives"); (text, filter) diff --git a/packages/stack-encrypt/tests/sem_terms.rs b/packages/stack-encrypt/tests/sem_terms.rs index 3090ffecfd..29abf8177f 100644 --- a/packages/stack-encrypt/tests/sem_terms.rs +++ b/packages/stack-encrypt/tests/sem_terms.rs @@ -1,11 +1,16 @@ //! SEM term-generation tests against the local HMAC PRF backend, keyed by the //! deterministic fake index key — no ZeroKMS credentials or network required. +//! +//! Each test derives a stored term by encrypting a value into its term +//! type. A match query comes from the query target, `matching_query`. use std::cmp::Ordering; -use stack_encrypt::nonempty; -use stack_encrypt::sem::{DefaultMatch, MatchConfig, MatchOptions, MatchTerms, Tokenizer}; -use stack_encrypt::{Error, StackCipher}; +use stack_encrypt::sem::{ + DefaultMatch, EqualityTerm, MatchConfig, MatchOptions, MatchTerms, OpeTerm, OreTerm, Tokenizer, +}; +use stack_encrypt::target::{matching_query, AcceptsContext, Borrowed, CallerContext}; +use stack_encrypt::{EncryptInto, EncryptTarget, Error, KeysetCipher, NonEmpty, StackCipher}; use stack_kms::{FakeDataKeySource, IdentifiedBy}; use uuid::Uuid; @@ -47,6 +52,57 @@ async fn generator() -> StackCipher { .expect("build cipher") } +type Keyset<'a> = KeysetCipher<'a, FakeDataKeySource>; + +fn field(name: &'static str) -> NonEmpty<&'static str> { + NonEmpty::new(name).expect("a field name") +} + +/// The term `value` stores as a `T` under `name`: the value encrypted into +/// its term type. +async fn stored(keyset: &Keyset<'_>, value: S, name: &'static str) -> Result +where + S: EncryptInto, + T: EncryptTarget + 'static, + T::ContextInput: AcceptsContext, + NonEmpty<&'static str>: Into<::Value>, +{ + value.encrypt_into_with_context(keyset, field(name)).await +} + +/// The equality term of `text` under `name`. +async fn equality(keyset: &Keyset<'_>, text: &str, name: &'static str) -> EqualityTerm { + stored(keyset, text.to_owned(), name) + .await + .expect("an equality term derives") +} + +/// The match filter `text` stores under `name`, cut as `O` declares. +async fn filter( + keyset: &Keyset<'_>, + text: &str, + name: &'static str, +) -> Result, Error> { + stored(keyset, text.to_owned(), name).await +} + +/// The match filter a query of `text` under `name` sends, cut as `O` +/// declares. +async fn query( + keyset: &Keyset<'_>, + text: &str, + name: &'static str, +) -> MatchTerms { + keyset + .run( + matching_query::<_, _, Borrowed, O>(), + &text.to_owned(), + CallerContext::from(field(name)), + ) + .await + .expect("a query of text that cuts a token derives") +} + async fn generator_for(keyset: Uuid) -> StackCipher { let cipher = generator().await; // Warm the cache so the caller's `keyset(..)` is a lookup; the cipher's @@ -59,14 +115,8 @@ async fn generator_for(keyset: Uuid) -> StackCipher { async fn equality_terms_are_deterministic() { let cipher = generator().await; let gen = cipher.default_keyset(); - let a = gen - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); - let b = gen - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); + let a = equality(&gen, "alice", "users/email").await; + let b = equality(&gen, "alice", "users/email").await; assert_eq!(a, b, "same value + descriptor must yield the same term"); } @@ -74,14 +124,8 @@ async fn equality_terms_are_deterministic() { async fn equality_terms_bind_the_descriptor() { let cipher = generator().await; let gen = cipher.default_keyset(); - let a = gen - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); - let b = gen - .equality_term("alice", nonempty!("users/name")) - .await - .unwrap(); + let a = equality(&gen, "alice", "users/email").await; + let b = equality(&gen, "alice", "users/name").await; assert_ne!(a, b, "the descriptor must domain-separate terms"); } @@ -89,15 +133,9 @@ async fn equality_terms_bind_the_descriptor() { async fn equality_terms_differ_by_value() { let cipher = generator().await; let gen = cipher.default_keyset(); - let a = gen - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); - let b = gen - .equality_term("bob", nonempty!("users/email")) - .await - .unwrap(); - assert_ne!(a, b); + let a = equality(&gen, "alice", "users/email").await; + let b = equality(&gen, "bob", "users/email").await; + assert_ne!(a, b, "different values must yield different terms"); } #[tokio::test] @@ -106,14 +144,8 @@ async fn equality_terms_bind_the_index_key() { let cipher_b = generator_for(Uuid::from_u128(2)).await; let gen_a = cipher_a.keyset(IdentifiedBy::Uuid(Uuid::from_u128(1))); let gen_b = cipher_b.keyset(IdentifiedBy::Uuid(Uuid::from_u128(2))); - let a = gen_a - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); - let b = gen_b - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); + let a = equality(&gen_a, "alice", "users/email").await; + let b = equality(&gen_b, "alice", "users/email").await; assert_ne!(a, b, "different keysets must yield different terms"); } @@ -122,14 +154,10 @@ async fn match_query_terms_are_contained_in_stored_terms() { let cipher = generator().await; let gen = cipher.default_keyset(); - let stored = gen - .match_terms::("alice wonderland", nonempty!("users/bio")) - .await - .unwrap(); - let query = gen - .match_terms::("wonder", nonempty!("users/bio")) + let stored = filter::(&gen, "alice wonderland", "users/bio") .await .unwrap(); + let query = query::(&gen, "wonder", "users/bio").await; assert!( stored.contains(&query), @@ -172,14 +200,10 @@ async fn match_query_terms_for_other_text_are_not_contained() { let cipher = generator().await; let gen = cipher.default_keyset(); - let stored = gen - .match_terms::("alice wonderland", nonempty!("users/bio")) - .await - .unwrap(); - let query = gen - .match_terms::("zebra", nonempty!("users/bio")) + let stored = filter::(&gen, "alice wonderland", "users/bio") .await .unwrap(); + let query = query::(&gen, "zebra", "users/bio").await; assert!( !stored.contains(&query), @@ -192,15 +216,14 @@ async fn match_is_case_insensitive_by_default() { let cipher = generator().await; let gen = cipher.default_keyset(); - let stored = gen - .match_terms::("Alice", nonempty!("users/name")) - .await - .unwrap(); - let query = gen - .match_terms::("alice", nonempty!("users/name")) + let stored = filter::(&gen, "Alice", "users/name") .await .unwrap(); - assert_eq!(stored, query); + let query = query::(&gen, "alice", "users/name").await; + assert_eq!( + stored, query, + "a query in another case is the stored filter" + ); } #[tokio::test] @@ -208,14 +231,10 @@ async fn match_binds_the_descriptor() { let cipher = generator().await; let gen = cipher.default_keyset(); - let stored = gen - .match_terms::("alice", nonempty!("users/bio")) - .await - .unwrap(); - let query = gen - .match_terms::("alice", nonempty!("users/name")) + let stored = filter::(&gen, "alice", "users/bio") .await .unwrap(); + let query = query::(&gen, "alice", "users/name").await; assert_ne!(stored, query, "match tokens must be descriptor-bound"); } @@ -233,8 +252,7 @@ async fn match_positions_stay_within_the_filter() { let cipher = generator().await; let gen = cipher.default_keyset(); - let term = gen - .match_terms::("a longer piece of text", nonempty!("users/bio")) + let term = filter::(&gen, "a longer piece of text", "users/bio") .await .unwrap(); assert!(!term.positions().is_empty()); @@ -250,40 +268,41 @@ async fn match_rejects_invalid_options() { // The v1 match indexer's bounds apply: k in 3..=16, m a power of two in // [32, 65536]. - assert!(gen - .match_terms::("xxx", nonempty!("d")) - .await - .is_err()); - assert!(gen - .match_terms::("xxx", nonempty!("d")) - .await - .is_err()); - assert!(gen - .match_terms::("xxx", nonempty!("d")) - .await - .is_err()); - assert!(gen - .match_terms::("xxx", nonempty!("d")) - .await - .is_err()); + assert!( + filter::(&gen, "xxx", "d").await.is_err(), + "k above 16 is refused" + ); + assert!( + filter::(&gen, "xxx", "d").await.is_err(), + "k below 3 is refused" + ); + assert!( + filter::(&gen, "xxx", "d").await.is_err(), + "an m that is not a power of two is refused" + ); + assert!( + filter::(&gen, "xxx", "d").await.is_err(), + "an m below 32 is refused" + ); // A zero-length n-gram must be an options error, not a panic. - assert!(matches!( - gen.match_terms::("xxx", nonempty!("d")).await, - Err(Error::Term(stack_encrypt::sem::TermError::InvalidOptions( - _ - ))) - )); + let zero = filter::(&gen, "xxx", "d").await; + assert!( + matches!( + zero, + Err(Error::Term(stack_encrypt::sem::TermError::InvalidOptions( + _ + ))) + ), + "a zero-length n-gram is an options error: {zero:?}" + ); } #[tokio::test] async fn match_stores_text_that_yields_no_tokens_as_the_empty_filter() { let cipher = generator().await; let gen = cipher.default_keyset(); - let query = gen - .match_terms::("hello", nonempty!("users/bio")) - .await - .unwrap(); + let query = query::(&gen, "hello", "users/bio").await; // Empty or separator-only text, and text shorter than the n-gram, cut // no token. The stored side keeps such a value as the empty filter: a @@ -291,8 +310,7 @@ async fn match_stores_text_that_yields_no_tokens_as_the_empty_filter() { // positions, so no query matches the value. (A query of such text is // refused by the query chain instead; `tests/op.rs` holds that.) for text in ["", " ", "hi"] { - let stored = gen - .match_terms::(text, nonempty!("users/bio")) + let stored = filter::(&gen, text, "users/bio") .await .unwrap_or_else(|error| panic!("{text:?} stores: {error}")); assert!( @@ -313,11 +331,13 @@ async fn match_stores_text_that_yields_no_tokens_as_the_empty_filter() { } // Separator-only text under the Standard tokenizer. - let stored = gen - .match_terms::(" ,;:! ", nonempty!("users/bio")) + let stored = filter::(&gen, " ,;:! ", "users/bio") .await .unwrap(); - assert!(stored.positions().is_empty()); + assert!( + stored.positions().is_empty(), + "separator-only text is the empty filter" + ); } #[tokio::test] @@ -325,15 +345,11 @@ async fn word_tokenizer_matches_whole_words() { let cipher = generator().await; let gen = cipher.default_keyset(); - let stored = gen - .match_terms::("alice in wonderland", nonempty!("users/bio")) + let stored = filter::(&gen, "alice in wonderland", "users/bio") .await .unwrap(); - let query = gen - .match_terms::("wonderland", nonempty!("users/bio")) - .await - .unwrap(); - assert!(stored.contains(&query)); + let query = query::(&gen, "wonderland", "users/bio").await; + assert!(stored.contains(&query), "a whole word is contained"); } #[tokio::test] @@ -341,23 +357,20 @@ async fn ore_terms_preserve_order_and_determinism() { let cipher = generator().await; let gen = cipher.default_keyset(); - let ten = gen.ore_term(10u64, nonempty!("users/age")).await.unwrap(); - let ten_again = gen.ore_term(10u64, nonempty!("users/age")).await.unwrap(); - let twenty = gen.ore_term(20u64, nonempty!("users/age")).await.unwrap(); + let ten: OreTerm = stored(&gen, 10u64, "users/age").await.unwrap(); + let ten_again: OreTerm = stored(&gen, 10u64, "users/age").await.unwrap(); + let twenty: OreTerm = stored(&gen, 20u64, "users/age").await.unwrap(); assert_eq!(ten, ten_again, "ORE terms must be deterministic"); - assert_eq!(ten.cmp(&twenty), Ordering::Less); + assert_eq!(ten.cmp(&twenty), Ordering::Less, "10 orders below 20"); } #[tokio::test] async fn ore_terms_bind_the_descriptor() { let cipher = generator().await; let gen = cipher.default_keyset(); - let a = gen.ore_term(10u64, nonempty!("users/age")).await.unwrap(); - let b = gen - .ore_term(10u64, nonempty!("users/height")) - .await - .unwrap(); + let a: OreTerm = stored(&gen, 10u64, "users/age").await.unwrap(); + let b: OreTerm = stored(&gen, 10u64, "users/height").await.unwrap(); assert_ne!(a, b, "per-descriptor ORE keys must differ"); } @@ -365,15 +378,17 @@ async fn ore_terms_bind_the_descriptor() { async fn string_ore_terms_preserve_lexicographic_order() { let cipher = generator().await; let gen = cipher.default_keyset(); - let apple = gen - .ore_term("apple".to_string(), nonempty!("users/name")) + let apple: OreTerm = stored(&gen, "apple".to_string(), "users/name") .await .unwrap(); - let banana = gen - .ore_term("banana".to_string(), nonempty!("users/name")) + let banana: OreTerm = stored(&gen, "banana".to_string(), "users/name") .await .unwrap(); - assert_eq!(apple.cmp(&banana), Ordering::Less); + assert_eq!( + apple.cmp(&banana), + Ordering::Less, + "\"apple\" orders below \"banana\"" + ); } #[tokio::test] @@ -381,11 +396,14 @@ async fn ope_terms_compare_with_plain_byte_order() { let cipher = generator().await; let gen = cipher.default_keyset(); - let ten = gen.ope_term(10u64, nonempty!("users/age")).await.unwrap(); - let twenty = gen.ope_term(20u64, nonempty!("users/age")).await.unwrap(); + let ten: OpeTerm = stored(&gen, 10u64, "users/age").await.unwrap(); + let twenty: OpeTerm = stored(&gen, 20u64, "users/age").await.unwrap(); // OPE ciphertexts order with standard lexicographic comparison. - assert!(ten.as_ref() < twenty.as_ref()); + assert!( + ten.as_bytes() < twenty.as_bytes(), + "the bytes of 10 order below those of 20" + ); } #[tokio::test] @@ -394,7 +412,11 @@ async fn ore_and_ope_keys_are_domain_separated() { // schemes; equal plaintexts should produce different ciphertext bytes. let cipher = generator().await; let gen = cipher.default_keyset(); - let ore = gen.ore_term(42u64, nonempty!("users/age")).await.unwrap(); - let ope = gen.ope_term(42u64, nonempty!("users/age")).await.unwrap(); - assert_ne!(ore.as_ref(), ope.as_ref()); + let ore: OreTerm = stored(&gen, 42u64, "users/age").await.unwrap(); + let ope: OpeTerm = stored(&gen, 42u64, "users/age").await.unwrap(); + assert_ne!( + ore.as_bytes(), + ope.as_bytes(), + "ORE and OPE derive under different keys" + ); } diff --git a/packages/stack-encrypt/tests/source_mode.rs b/packages/stack-encrypt/tests/source_mode.rs index 63fb083264..e8d28001b3 100644 --- a/packages/stack-encrypt/tests/source_mode.rs +++ b/packages/stack-encrypt/tests/source_mode.rs @@ -22,7 +22,7 @@ use stack_encrypt::target::{ }; use stack_encrypt::target::{EncryptTarget, RequiredContext, StoredContext}; use stack_encrypt::{ - nonempty, DecryptFrom, Encrypt, EncryptInto, Label, NonEmpty, StackCipherText, + nonempty, DecryptFrom, Encrypt, EncryptInto, KeysetCipher, Label, NonEmpty, StackCipherText, }; use stack_kms::FakeDataKeySource; use vitaminc_aead::plaintext::Sink; @@ -45,6 +45,25 @@ fn caller() -> CallerContext { CallerContext::from(context()) } +/// The equality term `NUMBER` stores as a `String`: what each operation +/// below must derive from a plaintext holding the same text. +async fn text_equality(keyset: &KeysetCipher<'_, FakeDataKeySource>) -> EqualityTerm { + NUMBER + .to_string() + .encrypt_into_with_context(keyset, context()) + .await + .expect("the text's equality term") +} + +/// The match filter `NUMBER` stores as a `String`. +async fn text_filter(keyset: &KeysetCipher<'_, FakeDataKeySource>) -> MatchTerms { + NUMBER + .to_string() + .encrypt_into_with_context(keyset, context()) + .await + .expect("the text's match filter") +} + /// A secret that is deliberately not `Clone`: it is moved, never copied, and /// `Protected` wipes the one copy when it drops. It encrypts, derives terms /// and reads as text exactly as the `String` it holds does. @@ -177,7 +196,7 @@ async fn a_plaintext_that_is_not_clone_derives_an_equality_term_alone() { .await .unwrap(); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!( term, expected, "an owned equality term should be byte-identical to the same text's term" @@ -194,7 +213,7 @@ async fn a_plaintext_that_is_not_clone_derives_a_match_term_alone() { .await .unwrap(); - let expected: MatchTerms = keyset.match_terms(NUMBER, context()).await.unwrap(); + let expected = text_filter(&keyset).await; assert_eq!( term, expected, "an owned match term should be byte-identical to the same text's term" @@ -282,7 +301,7 @@ async fn an_owned_zip_makes_no_copy() { .await .unwrap(); assert_eq!(opened, NUMBER, "the zipped ciphertext opens to the text"); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!(term, expected, "the zipped term is the text's term"); let (value, clones) = Counted::new(NUMBER); @@ -316,7 +335,7 @@ async fn a_plaintext_that_is_not_clone_seals_beside_a_term() { .await .unwrap(); assert_eq!(opened, NUMBER, "the ciphertext opens to the text"); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!(term, expected, "the term is the text's term"); } @@ -346,7 +365,7 @@ async fn a_borrowed_operation_makes_no_copy() { 0, "a borrowed ciphertext beside a borrowed term reads the one value" ); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!(term, expected, "the borrowed term is the text's term"); } @@ -493,7 +512,7 @@ async fn a_record_with_two_derived_fields_copies_nothing() { .await .unwrap(); assert_eq!(opened, NUMBER); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!(record.hm, expected); } @@ -600,7 +619,7 @@ async fn an_owned_plaintext_is_dropped_before_its_key_request_is_sent() { 1, "equality: dropped exactly once" ); - let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + let expected = text_equality(&keyset).await; assert_eq!(term, expected, "the term is the text's term"); let (value, drops) = Dropped::new(NUMBER); @@ -616,7 +635,7 @@ async fn an_owned_plaintext_is_dropped_before_its_key_request_is_sent() { 1, "matching: dropped exactly once" ); - let expected: MatchTerms = keyset.match_terms(NUMBER, context()).await.unwrap(); + let expected = text_filter(&keyset).await; assert_eq!(term, expected, "the term is the text's term"); } @@ -694,10 +713,14 @@ async fn a_value_with_a_ciphertext_and_two_terms_is_wiped_once() { let (equal, matched) = sealed.terms; assert_eq!( equal, - keyset.equality_term(NUMBER, context()).await.unwrap() + text_equality(&keyset).await, + "the equality term is the text's" + ); + assert_eq!( + matched, + text_filter(&keyset).await, + "the match filter is the text's" ); - let expected: MatchTerms = keyset.match_terms(NUMBER, context()).await.unwrap(); - assert_eq!(matched, expected); let (value, wipes) = Wiped::new(NUMBER); let refused = keyset diff --git a/packages/stack-encrypt/tests/target.rs b/packages/stack-encrypt/tests/target.rs index 0b8345b1b7..c3661fa45b 100644 --- a/packages/stack-encrypt/tests/target.rs +++ b/packages/stack-encrypt/tests/target.rs @@ -35,27 +35,6 @@ async fn generator() -> StackCipher { // --- Leaf implementations --------------------------------------------------- -#[tokio::test] -async fn equality_leaf_agrees_with_the_descriptor_api() { - let generator = generator().await; - let generator = generator.default_keyset(); - - let via_target: EqualityTerm = "alice" - .to_string() - .encrypt_into_with_context(&generator, nonempty!("users/email")) - .await - .unwrap(); - let via_descriptor = generator - .equality_term("alice", nonempty!("users/email")) - .await - .unwrap(); - - assert_eq!( - via_target, via_descriptor, - "target-directed and descriptor-string call sites must agree on term bytes" - ); -} - #[tokio::test] async fn terms_agree_between_independently_built_ciphers() { // Query-side code in another process, holding its own cipher over the same @@ -555,15 +534,17 @@ async fn an_explicit_keyset_is_honoured() { // a different index key. let default = stack_cipher().await; let default = default.default_keyset(); - let a = explicit - .equality_term("alice", nonempty!("users/email")) + let a: EqualityTerm = "alice" + .to_string() + .encrypt_into_with_context(&explicit, nonempty!("users/email")) .await .unwrap(); - let b = default - .equality_term("alice", nonempty!("users/email")) + let b: EqualityTerm = "alice" + .to_string() + .encrypt_into_with_context(&default, nonempty!("users/email")) .await .unwrap(); - assert_ne!(a, b); + assert_ne!(a, b, "the keysets' index keys differ"); } #[test] diff --git a/packages/stack-encrypt/tests/term_bytes.rs b/packages/stack-encrypt/tests/term_bytes.rs index e08096d875..119ea64573 100644 --- a/packages/stack-encrypt/tests/term_bytes.rs +++ b/packages/stack-encrypt/tests/term_bytes.rs @@ -41,9 +41,11 @@ //! changing the bytes encrypted. As with vitaminc 0.5, nothing of this //! crate's own derivation moved, so the `/v2` suffixes stay. -use stack_encrypt::nonempty; -use stack_encrypt::sem::{DefaultMatch, MatchConfig, MatchOptions}; -use stack_encrypt::StackCipher; +use stack_encrypt::sem::{ + DefaultMatch, EqualityTerm, MatchConfig, MatchOptions, MatchTerms, OpeTerm, OreTerm, +}; +use stack_encrypt::target::AcceptsContext; +use stack_encrypt::{EncryptInto, EncryptTarget, Error, KeysetCipher, NonEmpty, StackCipher}; use stack_kms::FakeDataKeySource; async fn cipher() -> StackCipher { @@ -54,6 +56,23 @@ async fn cipher() -> StackCipher { .expect("build cipher") } +/// The term `value` stores as a `T` under the field `name`: the value +/// encrypted into its term type. Every term here is derived this way. +async fn stored( + keyset: &KeysetCipher<'_, FakeDataKeySource>, + value: S, + name: &'static str, +) -> Result +where + S: EncryptInto, + T: EncryptTarget + 'static, + T::ContextInput: AcceptsContext, + NonEmpty<&'static str>: Into<::Value>, +{ + let field = NonEmpty::new(name).expect("a field name"); + value.encrypt_into_with_context(keyset, field).await +} + fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } @@ -61,9 +80,7 @@ fn hex(bytes: &[u8]) -> String { #[tokio::test] async fn equality_term_bytes_are_pinned() { let cipher = cipher().await; - let term = cipher - .default_keyset() - .equality_term("alice", nonempty!("users/email")) + let term: EqualityTerm = stored(&cipher.default_keyset(), "alice".to_string(), "users/email") .await .unwrap(); @@ -80,19 +97,18 @@ async fn equality_term_bytes_are_pinned() { async fn equality_terms_are_one_per_normal_form() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let term = |value: &'static str| keyset.equality_term(value, nonempty!("users/email")); + let term = + |value: &'static str| stored::<_, EqualityTerm>(&keyset, value.to_string(), "users/email"); assert_eq!( term("cafe\u{301}").await.unwrap(), term("caf\u{e9}").await.unwrap(), "a combining accent and the precomposed letter are one string" ); assert_eq!( - keyset - .equality_term(34u32, nonempty!("users/age")) + stored::<_, EqualityTerm>(&keyset, 34u32, "users/age") .await .unwrap(), - keyset - .equality_term(34i64, nonempty!("users/age")) + stored::<_, EqualityTerm>(&keyset, 34i64, "users/age") .await .unwrap(), "34 is one number at every width" @@ -102,11 +118,13 @@ async fn equality_terms_are_one_per_normal_form() { #[tokio::test] async fn match_term_positions_are_pinned() { let cipher = cipher().await; - let term = cipher - .default_keyset() - .match_terms::("alice smith", nonempty!("users/name")) - .await - .unwrap(); + let term: MatchTerms = stored( + &cipher.default_keyset(), + "alice smith".to_string(), + "users/name", + ) + .await + .unwrap(); // Pins the tokenizer, the per-token PRF framing, and the Bloom folding // together: any of the three moving changes this set. @@ -124,9 +142,7 @@ async fn ore_term_bytes_are_pinned() { // The ORE key is a PRF of the descriptor, so this pins the key derivation // as much as the CLLW encryption. let cipher = cipher().await; - let term = cipher - .default_keyset() - .ore_term(42u32, nonempty!("users/age")) + let term: OreTerm = stored(&cipher.default_keyset(), 42u32, "users/age") .await .unwrap(); @@ -142,9 +158,7 @@ async fn ope_term_bytes_are_pinned() { // schemes derive their keys under different domains and must never share // one (OPE ciphertexts are encrypt-only). let cipher = cipher().await; - let term = cipher - .default_keyset() - .ope_term(42u32, nonempty!("users/age")) + let term: OpeTerm = stored(&cipher.default_keyset(), 42u32, "users/age") .await .unwrap(); @@ -171,11 +185,13 @@ impl MatchConfig for WideMatch { #[tokio::test] async fn match_term_positions_are_pinned_for_a_wide_filter() { let cipher = cipher().await; - let term = cipher - .default_keyset() - .match_terms::("alice smith", nonempty!("users/name")) - .await - .unwrap(); + let term: MatchTerms = stored( + &cipher.default_keyset(), + "alice smith".to_string(), + "users/name", + ) + .await + .unwrap(); assert_eq!( term.positions(), @@ -196,12 +212,10 @@ async fn match_term_positions_are_pinned_for_a_wide_filter() { async fn text_order_term_bytes_are_pinned() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let ore = keyset - .ore_term("Ab".to_string(), nonempty!("users/surname")) + let ore: OreTerm = stored(&keyset, "Ab".to_string(), "users/surname") .await .unwrap(); - let ope = keyset - .ope_term("Ab".to_string(), nonempty!("users/surname")) + let ope: OpeTerm = stored(&keyset, "Ab".to_string(), "users/surname") .await .unwrap(); assert_eq!( @@ -220,8 +234,8 @@ async fn text_order_term_bytes_are_pinned() { async fn text_order_terms_fold_case_and_accents() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let ore = |text: String| keyset.ore_term(text, nonempty!("users/surname")); - let ope = |text: String| keyset.ope_term(text, nonempty!("users/surname")); + let ore = |text: String| stored::<_, OreTerm>(&keyset, text, "users/surname"); + let ope = |text: String| stored::<_, OpeTerm>(&keyset, text, "users/surname"); let want_ore = ore("cafe".into()).await.unwrap(); let want_ope = ope("cafe".into()).await.unwrap(); for text in ["Caf\u{e9}", "CAF\u{c9}", "cafe\u{301}", "CAFE"] { @@ -236,14 +250,10 @@ async fn text_order_terms_fold_case_and_accents() { async fn text_with_no_fold_has_no_order_term() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - assert!(keyset - .ore_term("a\u{378}b".to_string(), nonempty!("users/surname")) - .await - .is_err()); - assert!(keyset - .ope_term("a\u{378}b".to_string(), nonempty!("users/surname")) - .await - .is_err()); + let ore = stored::<_, OreTerm>(&keyset, "a\u{378}b".to_string(), "users/surname").await; + assert!(ore.is_err(), "no ORE term: {ore:?}"); + let ope = stored::<_, OpeTerm>(&keyset, "a\u{378}b".to_string(), "users/surname").await; + assert!(ope.is_err(), "no OPE term: {ope:?}"); } /// A float's order term: clww-ore's encryption of its ADR-0002 order key, @@ -253,14 +263,8 @@ async fn text_with_no_fold_has_no_order_term() { async fn float_order_term_bytes_are_pinned() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let ore = keyset - .ore_term(1.5f64, nonempty!("users/score")) - .await - .unwrap(); - let ope = keyset - .ope_term(1.5f64, nonempty!("users/score")) - .await - .unwrap(); + let ore: OreTerm = stored(&keyset, 1.5f64, "users/score").await.unwrap(); + let ope: OpeTerm = stored(&keyset, 1.5f64, "users/score").await.unwrap(); assert_eq!(hex(ore.as_ref()), "6c487f77b33ab3b4e0d37e79f84b24b92843d9cb591d492fd8d092afebba96e50e7d6733935a6e94faa8e7945f04471385553a35aa00ca30fb77d0b7a7a9a9a3"); assert_eq!(hex(ope.as_ref()), "00836260f898d58c06c8e23b8754e05d7d352c676b714e8523582c930f9e83640ad87d56aa35b7c3ecdc44dfb29a7378fb95738bca93f5ee9ca2a066c63ecb6aaf"); } @@ -272,8 +276,8 @@ async fn float_order_term_bytes_are_pinned() { async fn float_order_terms_follow_the_semantic_baseline() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let ore = |value: f64| keyset.ore_term(value, nonempty!("users/score")); - let ope = |value: f64| keyset.ope_term(value, nonempty!("users/score")); + let ore = |value: f64| stored::<_, OreTerm>(&keyset, value, "users/score"); + let ope = |value: f64| stored::<_, OpeTerm>(&keyset, value, "users/score"); assert_eq!(ore(-0.0).await.unwrap(), ore(0.0).await.unwrap()); assert_eq!(ope(-0.0).await.unwrap(), ope(0.0).await.unwrap()); @@ -329,28 +333,12 @@ async fn an_f32_is_ordered_as_the_f64_it_widens_to() { let keyset = cipher.default_keyset(); for value in [1.5f32, -0.0, f32::NAN, f32::MIN_POSITIVE, f32::INFINITY] { let wide = f64::from(value); - assert_eq!( - keyset - .ore_term(value, nonempty!("users/score")) - .await - .unwrap(), - keyset - .ore_term(wide, nonempty!("users/score")) - .await - .unwrap(), - "ore {value:?}" - ); - assert_eq!( - keyset - .ope_term(value, nonempty!("users/score")) - .await - .unwrap(), - keyset - .ope_term(wide, nonempty!("users/score")) - .await - .unwrap(), - "ope {value:?}" - ); + let narrow_ore: OreTerm = stored(&keyset, value, "users/score").await.unwrap(); + let wide_ore: OreTerm = stored(&keyset, wide, "users/score").await.unwrap(); + assert_eq!(narrow_ore.as_bytes(), wide_ore.as_bytes(), "ore {value:?}"); + let narrow_ope: OpeTerm = stored(&keyset, value, "users/score").await.unwrap(); + let wide_ope: OpeTerm = stored(&keyset, wide, "users/score").await.unwrap(); + assert_eq!(narrow_ope.as_bytes(), wide_ope.as_bytes(), "ope {value:?}"); } } @@ -369,8 +357,8 @@ async fn every_integer_width_orders_by_its_own_key() { let mut ores = Vec::new(); let mut opes = Vec::new(); for value in values { - let ore = keyset.ore_term(value, nonempty!("users/n")).await.unwrap(); - let ope = keyset.ope_term(value, nonempty!("users/n")).await.unwrap(); + let ore: OreTerm<$ty> = stored(&keyset, value, "users/n").await.unwrap(); + let ope: OpeTerm<$ty> = stored(&keyset, value, "users/n").await.unwrap(); assert_eq!(ore.as_ref().len(), bits, "{} ore", stringify!($ty)); assert_eq!(ope.as_ref().len(), bits + 1, "{} ope", stringify!($ty)); ores.push(ore); @@ -403,8 +391,7 @@ impl MatchConfig for WideShortWords { async fn short_word_positions_are_pinned() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let word = keyset - .match_terms::("Ng", nonempty!("users/name")) + let word: MatchTerms = stored(&keyset, "Ng".to_string(), "users/name") .await .unwrap(); assert_eq!( @@ -412,8 +399,7 @@ async fn short_word_positions_are_pinned() { PINNED_NG, "the word token's positions are frozen" ); - let whole = keyset - .match_terms::("Mike Ng", nonempty!("users/name")) + let whole: MatchTerms = stored(&keyset, "Mike Ng".to_string(), "users/name") .await .unwrap(); assert!( diff --git a/packages/stack-encrypt/tests/transcode.rs b/packages/stack-encrypt/tests/transcode.rs index a515a317fc..e577f814c4 100644 --- a/packages/stack-encrypt/tests/transcode.rs +++ b/packages/stack-encrypt/tests/transcode.rs @@ -130,8 +130,9 @@ async fn stored_identifier_supplies_every_operations_context() { 1, "one ciphertext leaf means one data key, in one batch" ); - let probe = keyset - .equality_term(email.clone(), Identifier::email()) + let probe: EqualityTerm = email + .clone() + .encrypt_into_with_context(&keyset, Identifier::email()) .await .unwrap(); assert_eq!( @@ -161,8 +162,9 @@ async fn canonical_ciphertext_opens_through_the_record() { .encrypt_tree(email.clone(), Identifier::email()) .await .unwrap(); - let probe = keyset - .equality_term(email.clone(), Identifier::email()) + let probe: EqualityTerm = email + .clone() + .encrypt_into_with_context(&keyset, Identifier::email()) .await .unwrap(); let record = TextEq { diff --git a/packages/stack-encrypt/tests/value_kinds.rs b/packages/stack-encrypt/tests/value_kinds.rs index 06a7ecdcf2..7e730576e8 100644 --- a/packages/stack-encrypt/tests/value_kinds.rs +++ b/packages/stack-encrypt/tests/value_kinds.rs @@ -29,7 +29,8 @@ use stack_encrypt::dynamic::record::{self, Plan as DataPlan}; use stack_encrypt::dynamic::{ context, query_term, NoTargets, Op, Operand, Reason, ValueFrame, ValueKind, }; -use stack_encrypt::target::IndexSpec; +use stack_encrypt::sem::EqualityTerm; +use stack_encrypt::target::{equality, Borrowed, CallerContext, IndexSpec}; use stack_encrypt::{CipherText, KeysetCipher, SealedValue, StackCipher, StackCipherText}; use vitaminc_aead::plaintext::{Int, Logical, Physical, Raw, TimeUnit}; use vitaminc_aead::plaintext::{MapSink, Sink}; @@ -373,8 +374,12 @@ async fn every_new_kind_seals_opens_and_queries_as_the_typed_path() { .as_protected_ref(), ) .expect("context"); - let typed_eq = keyset - .equality_term(kind.value, ctx.clone()) + let typed_eq: EqualityTerm = keyset + .run( + equality::<_, _, Borrowed>(), + &kind.value, + CallerContext::from(ctx.clone()), + ) .await .expect("the typed path derives"); assert_eq!( From 19f4519dac7a13e41258d00b97b896929f008b5f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 13:58:12 +1100 Subject: [PATCH 2/4] fix(stack-encrypt): address review on the lone term methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The test-only KeysetCipher::equality_term, match_terms, ore_term, and ope_term were copies of the target path. Each repeated the derivation that the term type's Term::encrypt_from already makes. So the lone_terms tests compared each copy with its original. The four methods and the lone_terms tests are removed. The dynamic tests that compared a dynamic term with a typed one now derive the typed term through its target, with encrypt_into_with_context. That keeps two separate paths in each comparison. The test file `tests/credential.rs` already checks that a term built before the keyset loads is the term built after it. The helpers equality_term_normalized and match_terms_under now compile only with the dynamic feature, because only that path calls them. The docs no longer say that the compiler enforces one context for a term and its ciphertext. A bare term target still takes any context. The term shares its ciphertext's context only as a field of a derived record, or beside its ciphertext in Encrypted<(…)>. The wording changes in ADR-0004's amendment, the CHANGELOG, and the sem module and impl docs. Each also says that a bare MatchTerms with short words on is a stored filter, not a query. The CHANGELOG upgrade note now covers jiff's civil::Date and Timestamp, and rust_decimal's Decimal. OreTerm and OpeTerm need T: Zeroize, so those types take value::Date, value::Timestamp, or value::Decimal, or the borrowed operation target::ope::<_, _, Borrowed>(). A scratch test checked that both routes compile and give the same bytes. The sem module docs say that a target and a field query's encrypt return a Pending, since a field reference's operator returns a FieldQuery. ADR-0009's match_terms bullet points to ADR-0004's amendment. Two paragraphs are rewrapped. --- packages/stack-encrypt/CHANGELOG.md | 61 +++-- ...t-threaded-through-the-declaration-tree.md | 33 ++- ...and-a-query-term-is-not-the-stored-term.md | 3 +- packages/stack-encrypt/src/dynamic/record.rs | 23 +- packages/stack-encrypt/src/dynamic/term.rs | 90 ++++-- packages/stack-encrypt/src/lib.rs | 14 +- packages/stack-encrypt/src/sem/mod.rs | 259 ++---------------- 7 files changed, 176 insertions(+), 307 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index fa7c01c661..d6402e3daf 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -483,24 +483,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, and `ope_term` are no longer public** (#1760). Each method built one term - on its own, outside the target path and the query path. A term built - that way was easy to get wrong. Nothing tied it to the context of the ciphertext stored - beside it. For most indexes, the term a query sends is not the term a - row stores. With `MatchOptions::short_words` on, the `match_terms` - filter of "Mike Ng" misses "Mike Nguyen". To upgrade, build each term - one of two ways: - - **To store a value**, encrypt it into its target type, or into a - derived record with a field of that type. Use `EqualityTerm` for - `equality_term`, `MatchTerms` for `match_terms`, `OreTerm` for - `ore_term`, and `OpeTerm` for `ope_term`. The target builds the - term under the context it seals the ciphertext under. - `OreTerm::inner()` and `OpeTerm::inner()` return the ciphertext the - old methods returned. A target takes text as a `String`, not a - `&str`. + on its own, outside the target path and the query path. Nothing tied + that term to the context of the ciphertext stored beside it. For most + indexes, the term a query sends is not the term a row stores. With + `MatchOptions::short_words` on, the `match_terms` filter of "Mike Ng" + misses "Mike Nguyen". + + Removing the methods removes one way to build a term under the wrong + context. The change does not make a wrong context impossible. A term + shares its ciphertext's context only when it is a field of a derived + record, or sits beside its ciphertext in `Encrypted<(…)>`. A bare term + target, such as `EqualityTerm`, still takes any context. + + To upgrade, build each term one of two ways: + - **To store a value**, encrypt it into a derived record with a field + of the term type, or run `target::indexed` over it. Use + `EqualityTerm` for `equality_term`, `MatchTerms` for + `match_terms`, `OreTerm` for `ore_term`, and `OpeTerm` for + `ope_term`. Encrypting the value into the bare term type gives the + same term, with no ciphertext beside it. `OreTerm::inner()` and + `OpeTerm::inner()` return the ciphertext the old methods returned. A + target takes text as a `String`, not a `&str`. - **To query**, use the field reference's operator method, such as `EncryptedUser::EMAIL.eq(&email)` or `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its - own, such as `target::matching_query`, also works. + own, such as `target::matching_query`, also works. A bare + `MatchTerms` with `short_words` on is a stored filter, not a + query. ```rust // Before @@ -514,7 +523,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; ``` - `ore_block_term` does not change. No stored byte changes. + `OreTerm` and `OpeTerm` need `T: Zeroize`. The old `ore_term` + and `ope_term` also took three types that are not `Zeroize`: jiff's + `civil::Date` and `Timestamp`, and rust_decimal's `Decimal`. For these, + convert the value to `value::Date`, `value::Timestamp`, or + `value::Decimal` first. Or run the borrowed operation, as below, to + read the value in place: + + ```rust + let term: OpeTerm = value::Date::new(dob) + .encrypt_into_with_context(&keyset, nonempty!("users/dob")) + .await?; + // Or, with the jiff date as it is + let context = CallerContext::from(nonempty!("users/dob")); + let term: OpeTerm = keyset + .run(target::ope::<_, _, Borrowed>(), &dob, context) + .await?; + ``` + + `target::ore` gives the order-revealing encryption (ORE) term the same + way. The two routes give the same bytes. `ore_block_term` does not + change. No stored byte changes. - **`Index` and `Indexes` each gain a required method** (#1398). A field query now derives its terms through these methods. diff --git a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md index 7c4a2353da..a418be63ae 100644 --- a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md +++ b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md @@ -224,19 +224,32 @@ cannot tell which they are producing. > query path for a match index. ADR-0009's amendment of the same date gives > the full rule. -> **Amended 2026-11-23 (#1760).** The four methods are now crate-private, -> so the compiler enforces the rule, not the documentation. The methods -> stay inside the crate, where tests compare other paths against them. -> Outside the crate, each term is built one way: +> **Amended 2026-11-23 (#1760).** The four methods are no longer public. +> Removing them removes one way to build a term under the wrong context. +> The change does not make a wrong context impossible. > -> - **To store a value**, encrypt it into its target type with -> `value.encrypt_into_with_context(&keyset, context)`. The target type -> is `EqualityTerm`, `MatchTerms`, `OreTerm`, or `OpeTerm`, or -> a derived record with a field of that type. The target builds the -> term under the context it seals the ciphertext under. +> The bare term targets `EqualityTerm`, `MatchTerms`, `OreTerm`, +> and `OpeTerm` are still public. A bare target takes any context, and +> seals no ciphertext beside its term. A term shares its ciphertext's +> context in two cases only: +> +> - the term is a field of a derived record; +> - the term sits beside its ciphertext in `Encrypted<(…)>`, the output +> of `target::indexed`. +> +> Outside the crate, build each term this way: +> +> - **To store a value**, encrypt it into a derived record with a field of +> the term type, or run `target::indexed` over it. Each builds the term +> under the context it seals the ciphertext under. A bare target +> (`value.encrypt_into_with_context(&keyset, context)` into +> `EqualityTerm`) builds the same term, but nothing ties its context to +> a ciphertext. > - **To query**, use the field reference's operator method > (`EncryptedUser::EMAIL.eq(..)`, `EncryptedUser::NAME.matches(..)`), or -> a query target run on its own, such as `target::matching_query`. +> a query target run on its own, such as `target::matching_query`. A +> bare `MatchTerms` with `MatchOptions::short_words` on is a stored +> filter, not a query. > > `ore_block_term` is still public. That method builds a block > order-revealing encryption (ORE) term outside a target, as the four did. diff --git a/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md b/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md index 956b2d7a1d..81d009a6e0 100644 --- a/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md +++ b/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md @@ -1377,7 +1377,8 @@ The changes: query's `prepare`. `target::matching` stores such text as the empty filter. - **`KeysetCipher::match_terms` builds a stored value's filter.** With - short words on, it is not a way to build a query. + short words on, it is not a way to build a query. ADR-0004's #1760 + amendment removes the method from the public API. - **EQL v4's query twins carry `QueryBloomFilter`.** A query twin is the eql-bindings struct that contains a query's terms, such as `TextMatchQuery`. `QueryBloomFilter` has `BloomFilter`'s JSON and JSON diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index ee13cf764c..545b486dae 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -4130,10 +4130,13 @@ mod tests { "the same term as the combinator extended by the same part" ); let native = nonempty!("users").with("age").with(7u64); - let probe = keyset.equality_term(34u32, native).await.expect("probe"); + let probe: EqualityTerm = 34u32 + .encrypt_into_with_context(&keyset, native) + .await + .expect("probe"); assert_eq!(stored, probe.to_bytes()); - let flat = keyset - .equality_term(34u32, nonempty!("users").with("age")) + let flat: EqualityTerm = 34u32 + .encrypt_into_with_context(&keyset, nonempty!("users").with("age")) .await .expect("probe"); assert_ne!( @@ -4178,12 +4181,18 @@ mod tests { assert_eq!(stored, typed_age.terms.to_bytes()); let nested = nonempty!("users").with("age").with(7u64).with("eu"); - let probe = keyset.equality_term(34u32, nested).await.expect("probe"); + let probe: EqualityTerm = 34u32 + .encrypt_into_with_context(&keyset, nested) + .await + .expect("probe"); assert_eq!(stored, probe.to_bytes(), "left-nested, part by part"); let one_piece = nonempty!("users") .with("age") .with(NonEmpty::from(7u64).with("eu")); - let probe = keyset.equality_term(34u32, one_piece).await.expect("probe"); + let probe: EqualityTerm = 34u32 + .encrypt_into_with_context(&keyset, one_piece) + .await + .expect("probe"); assert_ne!(stored, probe.to_bytes(), "not one two-part piece"); let opened: Tree = cipher @@ -5952,8 +5961,8 @@ mod tests { let mut row = map(sealed); let mut age = map(node(&mut row, "age")); let eq = term_bytes(&node(&mut age, "eq")); - let typed = keyset - .equality_term(34u64, nonempty!("users").with("age")) + let typed: EqualityTerm = 34u64 + .encrypt_into_with_context(&keyset, nonempty!("users").with("age")) .await .expect("typed"); assert_eq!(eq, typed.into_bytes().to_vec(), "the u64 term"); diff --git a/packages/stack-encrypt/src/dynamic/term.rs b/packages/stack-encrypt/src/dynamic/term.rs index 38b7b406d2..6bec8c133e 100644 --- a/packages/stack-encrypt/src/dynamic/term.rs +++ b/packages/stack-encrypt/src/dynamic/term.rs @@ -971,8 +971,8 @@ mod tests { use super::*; use crate::dynamic::test_frame::Tree; use crate::dynamic::{context, Output}; - use crate::sem::TermError; - use crate::{nonempty, StackCipher}; + use crate::sem::{EqualityTerm, MatchTerms, OpeTerm, OreTerm, TermError}; + use crate::{nonempty, EncryptInto, StackCipher}; use stack_kms::FakeDataKeySource; use vitaminc_aead::plaintext::Raw; use vitaminc_protected::AsProtectedRef as _; @@ -1153,8 +1153,8 @@ mod tests { async fn term_bytes_read_as_the_typed_terms_bytes() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let typed = keyset - .equality_term(34u32, nonempty!("users/age")) + let typed = 34u32 + .encrypt_into_with_context::(&keyset, nonempty!("users/age")) .await .expect("typed") .into_bytes() @@ -1264,12 +1264,14 @@ mod tests { let ctx = ctx.clone(); async move { term(ks, &value, &kind, ctx).await } }; - let eq = |t: crate::sem::EqualityTerm| t.into_bytes().to_vec(); + let eq = |t: EqualityTerm| t.into_bytes().to_vec(); // Equality, per variant with an equality domain. macro_rules! equal { ($value:expr, $leaf:expr, $label:literal) => { - let typed = keyset.equality_term($value, nonempty!("users/x")).await; + let typed = $value + .encrypt_into_with_context::(&keyset, nonempty!("users/x")) + .await; assert_eq!( dynamic($leaf, IndexSpec::Equality).await.expect("eq"), eq(typed.expect("typed")), @@ -1290,8 +1292,8 @@ mod tests { equal!(b"ab".to_vec(), bytes(b"ab"), "bytes"); // Match, text only. - let typed = keyset - .match_terms::("alice smith", nonempty!("users/x")) + let typed = String::from("alice smith") + .encrypt_into_with_context::(&keyset, nonempty!("users/x")) .await .expect("typed"); assert_eq!( @@ -1307,16 +1309,20 @@ mod tests { // because each is its own type. macro_rules! ordered { ($value:expr, $leaf:expr, $label:literal) => { - let typed = keyset.ore_term($value, nonempty!("users/x")).await; + let typed = $value + .encrypt_into_with_context::, _>(&keyset, nonempty!("users/x")) + .await; assert_eq!( dynamic($leaf, IndexSpec::Ore).await.expect("ore"), - typed.expect("typed").as_ref().to_vec(), + typed.expect("typed").inner().as_ref().to_vec(), concat!($label, " ore") ); - let typed = keyset.ope_term($value, nonempty!("users/x")).await; + let typed = $value + .encrypt_into_with_context::, _>(&keyset, nonempty!("users/x")) + .await; assert_eq!( dynamic($leaf, IndexSpec::Ope).await.expect("ope"), - typed.expect("typed").as_ref().to_vec(), + typed.expect("typed").inner().as_ref().to_vec(), concat!($label, " ope") ); }; @@ -1358,11 +1364,21 @@ mod tests { // is `F64`, so a dynamic `f32` and the typed `f64` it widens to // are one term. let ore = term(ks, 1.5f32, &IndexSpec::Ore, ctx.clone()).await; - let typed = keyset.ore_term(1.5f64, nonempty!("users/x")).await; - assert_eq!(ore.expect("ore"), typed.expect("typed").as_ref().to_vec()); + let typed: Result, _> = 1.5f64 + .encrypt_into_with_context(&keyset, nonempty!("users/x")) + .await; + assert_eq!( + ore.expect("ore"), + typed.expect("typed").inner().as_ref().to_vec() + ); let ope = term(ks, 1.5f32, &IndexSpec::Ope, ctx.clone()).await; - let typed = keyset.ope_term(1.5f64, nonempty!("users/x")).await; - assert_eq!(ope.expect("ope"), typed.expect("typed").as_ref().to_vec()); + let typed: Result, _> = 1.5f64 + .encrypt_into_with_context(&keyset, nonempty!("users/x")) + .await; + assert_eq!( + ope.expect("ope"), + typed.expect("typed").inner().as_ref().to_vec() + ); } /// Equality normalizes: every integer width of one number is one @@ -1396,8 +1412,8 @@ mod tests { assert_eq!(composed, eq(s("caf\u{e9}")).await, "one string in NFC"); assert_eq!( composed, - keyset - .equality_term("caf\u{e9}", nonempty!("users/x")) + String::from("caf\u{e9}") + .encrypt_into_with_context::(&keyset, nonempty!("users/x")) .await .expect("typed") .into_bytes() @@ -1431,8 +1447,11 @@ mod tests { .to_vec(); assert_eq!( derive(frame.clone(), IndexSpec::Equality).await, - keyset - .equality_term($value, nonempty!("users/x")) + $value + .encrypt_into_with_context::( + &keyset, + nonempty!("users/x") + ) .await .expect("typed") .into_bytes() @@ -1441,20 +1460,28 @@ mod tests { ); assert_eq!( derive(frame.clone(), IndexSpec::Ore).await, - keyset - .ore_term($value, nonempty!("users/x")) + $value + .encrypt_into_with_context::, _>( + &keyset, + nonempty!("users/x") + ) .await .expect("typed") + .inner() .as_ref() .to_vec(), concat!($label, " ore") ); assert_eq!( derive(frame, IndexSpec::Ope).await, - keyset - .ope_term($value, nonempty!("users/x")) + $value + .encrypt_into_with_context::, _>( + &keyset, + nonempty!("users/x") + ) .await .expect("typed") + .inner() .as_ref() .to_vec(), concat!($label, " ope") @@ -2091,8 +2118,8 @@ mod tests { ) .await .expect("wide"); - let typed = keyset - .match_terms::("Alice Smith", nonempty!("users/x")) + let typed = String::from("Alice Smith") + .encrypt_into_with_context::, _>(&keyset, nonempty!("users/x")) .await .expect("typed"); assert_eq!(wide, typed.to_bytes(), "the options are the typed config's"); @@ -2135,8 +2162,11 @@ mod tests { let stored = |text: &'static str| { let keyset = &keyset; async move { - keyset - .match_terms::(text, nonempty!("users/x")) + String::from(text) + .encrypt_into_with_context::, _>( + keyset, + nonempty!("users/x"), + ) .await .expect("stored") .to_bytes() @@ -2147,8 +2177,8 @@ mod tests { stored("Ng").await, "\"Ng\" is its word token, the filter it stores" ); - let trigrams = keyset - .match_terms::("Mike Ng", nonempty!("users/x")) + let trigrams = String::from("Mike Ng") + .encrypt_into_with_context::(&keyset, nonempty!("users/x")) .await .expect("stored without the option") .to_bytes(); diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 53fa5a8d24..9f6b47592c 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -787,12 +787,14 @@ pub use vitaminc_aead::{ /// `Zeroize` ([`target::WipeSource`]). /// /// vitaminc-ore's table also has jiff's `civil::Date` and `Timestamp`, and -/// rust_decimal's `Decimal`. Those types are `Copy` and are not `Zeroize`, -/// so nothing wipes them. A target and an owned index need `Zeroize`, so -/// neither takes them. [`KeysetCipher::ore_block_term`] and a borrowed -/// index do take them: a value passed by value is a copy the caller still -/// holds. To have -/// the plaintext wiped, use `value::Date`, `value::Timestamp`, or +/// rust_decimal's `Decimal`. Those types are `Copy` but not `Zeroize`, so +/// nothing wipes them. A target and an owned index need `Zeroize`, so +/// neither takes them. +/// +/// [`KeysetCipher::ore_block_term`], a borrowed index, and a borrowed +/// operation such as `target::ope::<_, _, Borrowed>()` take them. A value +/// passed by value is a copy that the caller still holds. To have the +/// plaintext wiped, use `value::Date`, `value::Timestamp`, or /// `value::Decimal`. /// /// Bytes have no order term. No ordering operator compares bytes, so such diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index ed1833a531..b30f85233f 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -30,21 +30,26 @@ //! one tenant's [`KeysetCipher`] compares only against terms derived through //! the same keyset. //! -//! A term that your app stores comes from a target. Encrypt the value into -//! its term type, or into a record with the term as a field. The target -//! builds the term under the context it seals the ciphertext under. +//! A term that your app stores comes from a target. The term shares its +//! ciphertext's context only in two cases. Either the term is a field of a +//! derived record, or it sits beside its ciphertext in an +//! [`Encrypted`](crate::target::Encrypted). A bare term target, such as +//! [`EqualityTerm`], takes any context and seals no ciphertext beside the +//! term. Nothing checks that its context is the context of a ciphertext. //! //! A query term comes from the field's reference, such as //! `EncryptedUser::EMAIL.eq(..)` or `EncryptedUser::NAME.matches(..)`. The //! reference supplies the field's index and context. A query target run on //! its own, such as [`matching_query`](crate::target::matching_query), also //! builds one. A query term is not always the stored term: a match query -//! with [`MatchOptions::short_words`] on is cut differently. +//! with [`MatchOptions::short_words`] on is cut differently. With that +//! option on, a bare [`MatchTerms`] is a stored filter, not a query. //! -//! Each of these returns a [`Pending`]. A term needs no data key. Under the -//! local HMAC backend, the pending makes no request, so it settles without -//! a ZeroKMS call. A backend that derives terms at ZeroKMS settles the term -//! through the same pending. +//! A target, and a field query's `.encrypt(&keyset)`, each return a +//! [`Pending`]. A term needs no data key. Under the local HMAC backend, the +//! pending makes no request, so it settles without a ZeroKMS call. A +//! backend that derives terms at ZeroKMS settles the term through the same +//! pending. //! //! # PRF backends, visitors, and the 2-party future //! @@ -2114,21 +2119,24 @@ order_term! { /// Term derivations that the `dynamic` path shares, and one block ORE term /// made on its own. /// -/// A term that your app stores comes from a target. Encrypt the value into -/// its term type, such as [`EqualityTerm`], [`MatchTerms`], or -/// [`OreTerm`], or into a derived record's field. The target builds the -/// term under the context it seals the ciphertext under. +/// A term that your app stores comes from a target. The term shares its +/// ciphertext's context only as a field of a derived record, or beside its +/// ciphertext in an [`Encrypted`](crate::target::Encrypted). A bare term +/// target, such as [`EqualityTerm`], [`MatchTerms`], or [`OreTerm`], takes +/// any context and seals no ciphertext beside the term. /// /// A query term comes from the field's reference, such as /// `EncryptedUser::EMAIL.eq(..)`. A query target run on its own, such as /// [`matching_query`](crate::target::matching_query), also builds one. A /// stored term and a query term are the same bytes for some indexes only. +/// A bare [`MatchTerms`] with [`MatchOptions::short_words`] on is a stored +/// filter, not a query. impl KeysetCipher<'_, K> { /// The equality term of one scalar that the caller has already /// normalized. The `dynamic` path walks a value to its one scalar and /// normalizes it there, with the `vitaminc_normalize::normalize` that /// the typed path's sink applies. - #[cfg(any(test, feature = "dynamic"))] + #[cfg(feature = "dynamic")] pub(crate) fn equality_term_normalized<'c>( &self, normalized: Normalized, @@ -2157,7 +2165,7 @@ impl KeysetCipher<'_, K> { /// The typed API keeps the options on the type, so a stored field and /// its query cannot disagree. A binding reaches this method only through /// a plan that names the options for both. - #[cfg(any(test, feature = "dynamic"))] + #[cfg(feature = "dynamic")] pub(crate) fn match_terms_under<'c, O>( &self, text: &str, @@ -2208,72 +2216,6 @@ impl KeysetCipher<'_, K> { } } -/// One term of each kind on its own, under a descriptor, outside any -/// target. This crate's tests compare another path's term against these. -/// Each method derives the bytes that a target derives for the same -/// descriptor. The `lone_terms` tests check that. -#[cfg(test)] -impl KeysetCipher<'_, K> { - /// The equality term of `value` under `descriptor`: the term an - /// [`EqualityTerm`] target derives. - pub(crate) fn equality_term<'c, T>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, EqualityTerm, K> - where - T: Encrypt, - { - match self.loaded_state() { - Some(keyset) => { - let term = equality(&keyset.prf, value, descriptor.into_prf_context()); - Pending::ready(self, term.map_err(Error::from)) - } - None => match normalized(value) { - Ok(normalized) => self.equality_term_normalized(normalized, descriptor), - Err(error) => Pending::ready(self, Err(error.into())), - }, - } - } - - /// The stored match filter of `text` under `descriptor` and the - /// config `O`: the filter a [`MatchTerms`] target derives. A query - /// of the same text is cut differently when - /// [`MatchOptions::short_words`] is on. - pub(crate) fn match_terms<'c, O>( - &self, - text: &str, - descriptor: NonEmpty>, - ) -> Pending<'_, MatchTerms, K> - where - O: MatchConfig + MaybeSend, - { - self.match_terms_under(text, descriptor, O::options(), Side::Stored) - } - - /// The CLLW ORE ciphertext of `value` under `descriptor`: the bytes an - /// [`OreTerm`] target wraps. - pub(crate) fn ore_term<'c, T: Orderable>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, OreClww8VariableV1, K> { - let context = descriptor.into_prf_context().into_owned(); - order_pending(self, target_of::(), value, context, order_error, ore) - } - - /// The CLLW OPE ciphertext of `value` under `descriptor`: the bytes an - /// [`OpeTerm`] target wraps. - pub(crate) fn ope_term<'c, T: Orderable>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, OpeClww8VariableV1, K> { - let context = descriptor.into_prf_context().into_owned(); - order_pending(self, target_of::(), value, context, order_error, ope) - } -} - #[cfg(test)] mod tests { use std::collections::BTreeMap; @@ -2892,160 +2834,3 @@ mod order_terms_before_the_keyset_loads { ); } } - -/// Each lone term method derives the bytes that a target derives for the -/// same value and descriptor. The tests check this with the keyset loaded, -/// and with the keyset not yet loaded when the call is built. -#[cfg(test)] -mod lone_terms { - use stack_kms::{FakeCredentialKeySource, FakeDataKeySource, SecretToken}; - - use super::*; - use crate::{nonempty, EncryptInto, StackCipher}; - - const EMAIL: &str = "bob@example.com"; - const TEXT: &str = "bob the builder"; - const AGE: u32 = 42; - - fn field() -> NonEmpty<(&'static str, &'static str)> { - nonempty!("users").with("email") - } - - /// Settle a pending: awaited as it is, or with a credential, which a - /// cipher over a credential key source needs for every call. - macro_rules! settle { - ($pending:expr, plain) => { - $pending.await.unwrap() - }; - ($pending:expr, credentialed) => { - $pending - .with_credential(SecretToken::new("alice.jwt")) - .await - .unwrap() - }; - } - - /// Each lone term is the target's term of the same value. The lone - /// call is built and settled first, so on a keyset that is not loaded - /// it is the call that loads it. - macro_rules! each_lone_term_is_the_targets_term { - ($keyset:expr, $state:ident) => {{ - let keyset = $keyset; - let equality = settle!(keyset.equality_term(String::from(EMAIL), field()), $state); - let target: EqualityTerm = settle!( - String::from(EMAIL).encrypt_into_with_context(keyset, field()), - $state - ); - assert_eq!(equality, target, "the lone equality term is the target's"); - - let matching = settle!(keyset.match_terms::(TEXT, field()), $state); - let target: MatchTerms = settle!( - String::from(TEXT).encrypt_into_with_context(keyset, field()), - $state - ); - assert_eq!(matching, target, "the lone match filter is the target's"); - - let ore = settle!(keyset.ore_term(AGE, field()), $state); - let target: OreTerm = - settle!(AGE.encrypt_into_with_context(keyset, field()), $state); - assert_eq!(&ore, target.inner(), "the lone ORE term is the target's"); - - let ope = settle!(keyset.ope_term(AGE, field()), $state); - let target: OpeTerm = - settle!(AGE.encrypt_into_with_context(keyset, field()), $state); - assert_eq!(&ope, target.inner(), "the lone OPE term is the target's"); - }}; - } - - mod given_a_loaded_keyset { - use super::*; - - async fn scenario() -> StackCipher { - StackCipher::builder() - .kms(FakeDataKeySource::new()) - .init() - .await - .unwrap() - } - - #[tokio::test] - async fn each_lone_term_is_the_targets_term() { - let cipher = scenario().await; - let keyset = cipher.default_keyset(); - assert!(keyset.loaded_state().is_some(), "init loads the keyset"); - each_lone_term_is_the_targets_term!(&keyset, plain); - } - } - - mod given_a_keyset_that_is_not_loaded { - use super::*; - - async fn scenario() -> StackCipher { - StackCipher::builder() - .kms(FakeCredentialKeySource::new()) - .init() - .await - .unwrap() - } - - #[tokio::test] - async fn each_lone_term_is_the_targets_term() { - let cipher = scenario().await; - let keyset = cipher.default_keyset(); - assert!( - keyset.loaded_state().is_none(), - "nothing has loaded the keyset" - ); - each_lone_term_is_the_targets_term!(&keyset, credentialed); - } - - /// Each lone term built before the load is the term the loaded - /// keyset derives through the same method. - #[tokio::test] - async fn each_lone_term_built_before_the_load_is_the_term_after_it() { - let cipher = scenario().await; - let keyset = cipher.default_keyset(); - let equality = keyset.equality_term(String::from(EMAIL), field()); - let matching = keyset.match_terms::(TEXT, field()); - let ore = keyset.ore_term(AGE, field()); - let ope = keyset.ope_term(AGE, field()); - assert!( - keyset.loaded_state().is_none(), - "building a lone term loads nothing" - ); - let (equality, matching, ore, ope) = ( - settle!(equality, credentialed), - settle!(matching, credentialed), - settle!(ore, credentialed), - settle!(ope, credentialed), - ); - assert!(keyset.loaded_state().is_some(), "the calls loaded it"); - assert_eq!( - equality, - settle!( - keyset.equality_term(String::from(EMAIL), field()), - credentialed - ), - "the equality term" - ); - assert_eq!( - matching, - settle!( - keyset.match_terms::(TEXT, field()), - credentialed - ), - "the match filter" - ); - assert_eq!( - ore, - settle!(keyset.ore_term(AGE, field()), credentialed), - "the ORE term" - ); - assert_eq!( - ope, - settle!(keyset.ope_term(AGE, field()), credentialed), - "the OPE term" - ); - } - } -} From 2a7951f219144ea79678f470e5ac05323ee83e4e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 14:42:53 +1100 Subject: [PATCH 3/4] refactor(stack-encrypt)!: remove KeysetCipher::ore_block_term KeysetCipher::ore_block_term built a block order-revealing encryption (ORE) term outside a target, as the four term methods removed earlier on this branch did. Nothing tied that term to the context of the ciphertext stored beside it. The method is removed. The term type OreBlockTerm, the operation target::ore_block, and the index OreBlock stay public. No helper becomes dead. order_pending, ore_block, and ore_block_error still serve the OreBlockTerm target through the order_term macro. The tests that called the method now build each term through its target, with encrypt_into_with_context. The borrowed-value test runs target::ore_block with a Borrowed source through KeysetCipher::run. The credential test still checks that a term built before the keyset loads equals one built after it. A block ORE term contains a random nonce, so the test compares by the scheme's comparison. The pinned left halves pass with the same bytes. A scratch test, since deleted, checked the upgrade route for the three types that are not Zeroize: jiff's civil::Date and Timestamp, and rust_decimal's Decimal. KeysetCipher::run with target::ore_block::<_, _, Borrowed>() compiles for each. The term it builds has the same left half as the term of value::Date, value::Timestamp, or value::Decimal built with encrypt_into_with_context. The CHANGELOG Breaking entry and the Orderable rustdoc in lib.rs now name that route. The amendment to architecture decision record 0004 now says that the method is removed. --- packages/stack-encrypt/CHANGELOG.md | 43 +++++----- ...t-threaded-through-the-declaration-tree.md | 4 +- packages/stack-encrypt/src/lib.rs | 10 +-- packages/stack-encrypt/src/sem/mod.rs | 39 +-------- packages/stack-encrypt/tests/credential.rs | 11 +-- packages/stack-encrypt/tests/ore_block.rs | 85 +++++++++---------- packages/stack-encrypt/tests/source_mode.rs | 4 +- packages/stack-encrypt/tests/term_serde.rs | 9 +- 8 files changed, 86 insertions(+), 119 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index d6402e3daf..9356bb0bb7 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,13 +481,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking -- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, and - `ope_term` are no longer public** (#1760). Each method built one term - on its own, outside the target path and the query path. Nothing tied - that term to the context of the ciphertext stored beside it. For most - indexes, the term a query sends is not the term a row stores. With - `MatchOptions::short_words` on, the `match_terms` filter of "Mike Ng" - misses "Mike Nguyen". +- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, + `ope_term`, and `ore_block_term` are no longer public** (#1760). Each + method built one term on its own, outside the target path and the + query path. Nothing tied that term to the context of the ciphertext + stored beside it. For most indexes, the term a query sends is not the + term a row stores. With `MatchOptions::short_words` on, the + `match_terms` filter of "Mike Ng" misses "Mike Nguyen". Removing the methods removes one way to build a term under the wrong context. The change does not make a wrong context impossible. A term @@ -499,11 +499,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **To store a value**, encrypt it into a derived record with a field of the term type, or run `target::indexed` over it. Use `EqualityTerm` for `equality_term`, `MatchTerms` for - `match_terms`, `OreTerm` for `ore_term`, and `OpeTerm` for - `ope_term`. Encrypting the value into the bare term type gives the - same term, with no ciphertext beside it. `OreTerm::inner()` and - `OpeTerm::inner()` return the ciphertext the old methods returned. A - target takes text as a `String`, not a `&str`. + `match_terms`, `OreTerm` for `ore_term`, `OpeTerm` for + `ope_term`, and `OreBlockTerm` for `ore_block_term`. Encrypting + the value into the bare term type gives the same term, with no + ciphertext beside it. `OreTerm::inner()` and `OpeTerm::inner()` + return the ciphertext the old methods returned. A target takes text + as a `String`, not a `&str`. - **To query**, use the field reference's operator method, such as `EncryptedUser::EMAIL.eq(&email)` or `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its @@ -523,12 +524,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; ``` - `OreTerm` and `OpeTerm` need `T: Zeroize`. The old `ore_term` - and `ope_term` also took three types that are not `Zeroize`: jiff's - `civil::Date` and `Timestamp`, and rust_decimal's `Decimal`. For these, - convert the value to `value::Date`, `value::Timestamp`, or - `value::Decimal` first. Or run the borrowed operation, as below, to - read the value in place: + `OreTerm`, `OpeTerm`, and `OreBlockTerm` need `T: Zeroize`. + The old `ore_term`, `ope_term`, and `ore_block_term` also took three + types that are not `Zeroize`: jiff's `civil::Date` and `Timestamp`, + and rust_decimal's `Decimal`. For these, convert the value to + `value::Date`, `value::Timestamp`, or `value::Decimal` first. Or run + the borrowed operation, as below, to read the value in place: ```rust let term: OpeTerm = value::Date::new(dob) @@ -542,8 +543,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ``` `target::ore` gives the order-revealing encryption (ORE) term the same - way. The two routes give the same bytes. `ore_block_term` does not - change. No stored byte changes. + way. The two routes give the same bytes. `target::ore_block` gives the + block ORE term the same way. A block ORE term contains a random nonce, + so its two routes give terms that compare equal, with the same left + half. No stored byte changes. - **`Index` and `Indexes` each gain a required method** (#1398). A field query now derives its terms through these methods. diff --git a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md index a418be63ae..c1f908e3ae 100644 --- a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md +++ b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md @@ -251,8 +251,10 @@ cannot tell which they are producing. > bare `MatchTerms` with `MatchOptions::short_words` on is a stored > filter, not a query. > -> `ore_block_term` is still public. That method builds a block +> `ore_block_term` is removed too. That method built a block > order-revealing encryption (ORE) term outside a target, as the four did. +> The bare target `OreBlockTerm` is still public, as the four bare +> targets above are. ### 6. Targets declare their sources; `FfiValue` is not one diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 9f6b47592c..fefef9a762 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -791,11 +791,11 @@ pub use vitaminc_aead::{ /// nothing wipes them. A target and an owned index need `Zeroize`, so /// neither takes them. /// -/// [`KeysetCipher::ore_block_term`], a borrowed index, and a borrowed -/// operation such as `target::ope::<_, _, Borrowed>()` take them. A value -/// passed by value is a copy that the caller still holds. To have the -/// plaintext wiped, use `value::Date`, `value::Timestamp`, or -/// `value::Decimal`. +/// A borrowed index takes them, and so does a borrowed operation, such as +/// `target::ope::<_, _, Borrowed>()` or +/// `target::ore_block::<_, _, Borrowed>()`. Each reads the value in place, +/// and the caller keeps it. To have the plaintext wiped, use `value::Date`, +/// `value::Timestamp`, or `value::Decimal`. /// /// Bytes have no order term. No ordering operator compares bytes, so such /// a term would answer no query, and would still reveal the order of the diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index b30f85233f..ff73694953 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -2116,8 +2116,7 @@ order_term! { // Term generation on the cipher // ============================================================================= -/// Term derivations that the `dynamic` path shares, and one block ORE term -/// made on its own. +/// Term derivations that the `dynamic` path shares. /// /// A term that your app stores comes from a target. The term shares its /// ciphertext's context only as a field of a derived record, or beside its @@ -2178,42 +2177,6 @@ impl KeysetCipher<'_, K> { { match_pending(self, text, descriptor.into_prf_context(), options, side) } - - /// Generate a block ORE term: ore-rs's 6-bit block order-revealing - /// encryption (ORE), the scheme that EQL v4's `_ord_ore` domains store. - /// The PRF input is the descriptor alone. The plaintext never enters - /// the PRF, and one visitor derives the per-descriptor key and uses it. - /// See [`OreBlockTerm`] for which scheme a type is encrypted with, and - /// what is refused. - /// - /// Every [`Orderable`] type is supported, each encoded as its target. - /// The walk that encodes a value wipes a value handed over by value. A - /// reference (`&String`, `&str`) is read in place. The term's left half - /// is byte-identical to the target-directed path's for the same - /// descriptor. The right half contains a random nonce. - /// - /// The descriptor is the context the target-directed path takes, a - /// [`NonEmpty`]: `nonempty!("users").with("age")`. Nothing ties a - /// term made here to the context of the ciphertext beside it. So a term - /// that you will store should come from a target instead. The target - /// hands one context to the term and the ciphertext. - pub fn ore_block_term<'c, T: Orderable>( - &self, - value: T, - descriptor: NonEmpty>, - ) -> Pending<'_, OreBlockTerm, K> { - let context = descriptor.into_prf_context().into_owned(); - order_pending( - self, - target_of::(), - value, - context, - ore_block_error, - |prf, encoding, context| { - ore_block(prf, encoding, context).map(|term| OreBlockTerm(term, PhantomData)) - }, - ) - } } #[cfg(test)] diff --git a/packages/stack-encrypt/tests/credential.rs b/packages/stack-encrypt/tests/credential.rs index a9487613c1..16e3e420e4 100644 --- a/packages/stack-encrypt/tests/credential.rs +++ b/packages/stack-encrypt/tests/credential.rs @@ -666,7 +666,7 @@ async fn init_still_checks_a_key_source_with_its_own_identity_at_startup() { /// the loaded keyset derives. The first one awaited loads the keyset. #[tokio::test] async fn terms_built_before_the_load_are_the_terms_built_after_it() { - use stack_encrypt::sem::{MatchTerms, OpeTerm, OreTerm}; + use stack_encrypt::sem::{MatchTerms, OpeTerm, OreBlockTerm, OreTerm}; let (shared, source) = unloaded().await; let early = shared.default_keyset(); @@ -680,7 +680,7 @@ async fn terms_built_before_the_load_are_the_terms_built_after_it() { String::from("bob the builder").encrypt_into_with_context::(&early, field()); let ore = 42u32.encrypt_into_with_context::, _>(&early, field()); let ope = 42u32.encrypt_into_with_context::, _>(&early, field()); - let block = early.ore_block_term(42u32, field()); + let block = 42u32.encrypt_into_with_context::, _>(&early, field()); assert_eq!(source.take(), vec![], "building makes no request"); let equality = equality.with_credential(bob()).await.unwrap(); @@ -740,8 +740,8 @@ async fn terms_built_before_the_load_are_the_terms_built_after_it() { .unwrap(), "the OPE term built before the load" ); - let late_block = late - .ore_block_term(42u32, field()) + let late_block = 42u32 + .encrypt_into_with_context::, _>(&late, field()) .with_credential(alice()) .await .unwrap(); @@ -750,7 +750,8 @@ async fn terms_built_before_the_load_are_the_terms_built_after_it() { "block ORE terms of one value under one keyset compare equal" ); assert!( - late.ore_block_term(41u32, field()) + 41u32 + .encrypt_into_with_context::, _>(&late, field()) .with_credential(alice()) .await .unwrap() diff --git a/packages/stack-encrypt/tests/ore_block.rs b/packages/stack-encrypt/tests/ore_block.rs index 094c05a706..aa1d5a3db2 100644 --- a/packages/stack-encrypt/tests/ore_block.rs +++ b/packages/stack-encrypt/tests/ore_block.rs @@ -15,11 +15,13 @@ use std::cmp::Ordering; use stack_encrypt::sem::{OreBlockTerm, TermBytesError, TermError}; +use stack_encrypt::target::{self, Borrowed, CallerContext}; #[cfg(all(feature = "jiff", feature = "rust_decimal"))] use stack_encrypt::value::{Date, Decimal, Timestamp}; use stack_encrypt::Orderable; -use stack_encrypt::{nonempty, Error, KeysetCipher, StackCipher}; +use stack_encrypt::{nonempty, EncryptInto, EncryptRef, Error, KeysetCipher, StackCipher}; use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; async fn cipher() -> StackCipher { StackCipher::builder() @@ -33,12 +35,12 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } -async fn term( +async fn term( keyset: &KeysetCipher<'_, FakeDataKeySource>, value: T, ) -> OreBlockTerm { - keyset - .ore_block_term(value, nonempty!("users/n")) + value + .encrypt_into_with_context(keyset, nonempty!("users/n")) .await .expect("a block ORE term") } @@ -365,16 +367,17 @@ async fn every_view_of_a_term_is_its_ciphertext() { async fn left_halves_are_pinned() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let i32_term = keyset - .ore_block_term(42i32, nonempty!("users/age")) + let i32_term: OreBlockTerm = 42i32 + .encrypt_into_with_context(&keyset, nonempty!("users/age")) .await .unwrap(); - let f64_term = keyset - .ore_block_term(1.5f64, nonempty!("users/score")) + let f64_term: OreBlockTerm = 1.5f64 + .encrypt_into_with_context(&keyset, nonempty!("users/score")) .await .unwrap(); - let text_term = keyset - .ore_block_term("Ab".to_string(), nonempty!("users/surname")) + let text_term: OreBlockTerm = "Ab" + .to_string() + .encrypt_into_with_context(&keyset, nonempty!("users/surname")) .await .unwrap(); assert_eq!( @@ -398,12 +401,12 @@ const PINNED_TEXT: &str = "02030016010010172510373d14172510363017212d163e161a103 async fn terms_are_keyed_by_their_context() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let users = keyset - .ore_block_term(7i32, nonempty!("users/age")) + let users: OreBlockTerm = 7i32 + .encrypt_into_with_context(&keyset, nonempty!("users/age")) .await .unwrap(); - let orders = keyset - .ore_block_term(7i32, nonempty!("orders/age")) + let orders: OreBlockTerm = 7i32 + .encrypt_into_with_context(&keyset, nonempty!("orders/age")) .await .unwrap(); assert_ne!(left(users.as_bytes()), left(orders.as_bytes())); @@ -420,43 +423,31 @@ async fn refusals_name_no_part_of_the_value() { Error::Term(error) => error, other => panic!("not a term refusal: {other:?}"), }; + let derive = |text: String| { + text.encrypt_into_with_context::, _>(&keyset, nonempty!("users/n")) + }; let long = "secret".repeat(200); - assert!(keyset - .ore_block_term("a".repeat(1023), nonempty!("users/n")) - .await - .is_ok()); - let too_long = refused( - keyset - .ore_block_term(long.clone(), nonempty!("users/n")) - .await - .unwrap_err(), + assert!( + derive("a".repeat(1023)).await.is_ok(), + "a fold of 1023 bytes fits" ); + let too_long = refused(derive(long.clone()).await.unwrap_err()); assert!( matches!(too_long, TermError::OreBlockTooLong), "{too_long:?}" ); assert!(!too_long.to_string().contains("secret")); - let nul = refused( - keyset - .ore_block_term("secret\0".to_string(), nonempty!("users/n")) - .await - .unwrap_err(), - ); + let nul = refused(derive("secret\0".to_string()).await.unwrap_err()); assert!(matches!(nul, TermError::OreBlockTrailingNul), "{nul:?}"); assert!(!nul.to_string().contains("secret")); - let unassigned = refused( - keyset - .ore_block_term("a\u{378}b".to_string(), nonempty!("users/n")) - .await - .unwrap_err(), - ); + let unassigned = refused(derive("a\u{378}b".to_string()).await.unwrap_err()); assert!( matches!(unassigned, TermError::Normalize(_)), "{unassigned:?}" ); // A boolean and an 8-bit integer have no block ORE term, as they have - // no ORE or OPE term: `ore_block_term(true, ..)` and - // `ore_block_term(7u8, ..)` do not compile (`Orderable`). + // no ORE or OPE term: `OreBlockTerm` and `OreBlockTerm` do + // not compile (`Orderable`). } /// Decoding is structural: a ciphertext of either scheme decodes, and @@ -494,20 +485,26 @@ async fn decoding_checks_the_shape() { assert!(a != b); } -/// A reference to a local value takes a term too, read in place, and it +/// The borrowed operation reads a local value in place, and its term /// orders equal to the term of the value itself. #[tokio::test] async fn a_borrowed_value_takes_the_term_its_value_takes() { let cipher = cipher().await; let keyset = cipher.default_keyset(); let local = String::from("ada"); - let borrowed = keyset - .ore_block_term(&local, nonempty!("users/n")) + let borrowed: OreBlockTerm = keyset + .run( + target::ore_block::<_, _, Borrowed>(), + &local, + CallerContext::from(nonempty!("users/n")), + ) .await .unwrap(); let owned = term(&keyset, String::from("ada")).await; - // The term of a `&String` is an `OreBlockTerm<&String>`; read its bytes - // back as a `String`'s to compare them. - let borrowed = OreBlockTerm::::try_from(borrowed.into_bytes()).unwrap(); - assert_eq!(borrowed.compare(&owned), Some(Ordering::Equal)); + assert_eq!( + borrowed.compare(&owned), + Some(Ordering::Equal), + "the borrowed term orders equal to the owned one" + ); + assert_eq!(local, "ada", "the caller keeps the value"); } diff --git a/packages/stack-encrypt/tests/source_mode.rs b/packages/stack-encrypt/tests/source_mode.rs index e8d28001b3..ad45f2fe2d 100644 --- a/packages/stack-encrypt/tests/source_mode.rs +++ b/packages/stack-encrypt/tests/source_mode.rs @@ -942,8 +942,8 @@ async fn a_date_with_a_ciphertext_and_two_terms_is_not_copied() { .encrypt_into_with_context(&keyset, context()) .await .unwrap(); - let later = keyset - .ore_block_term(Date::new(jiff::civil::date(2024, 3, 1)), context()) + let later: OreBlockTerm = Date::new(jiff::civil::date(2024, 3, 1)) + .encrypt_into_with_context(&keyset, context()) .await .unwrap(); assert_eq!( diff --git a/packages/stack-encrypt/tests/term_serde.rs b/packages/stack-encrypt/tests/term_serde.rs index eb9797d962..96faa3e8ad 100644 --- a/packages/stack-encrypt/tests/term_serde.rs +++ b/packages/stack-encrypt/tests/term_serde.rs @@ -7,8 +7,9 @@ use stack_encrypt::nonempty; use stack_encrypt::sem::{OpeTerm, OreBlockTerm, OreTerm, TermBytesError}; use stack_encrypt::Orderable; -use stack_encrypt::{EncryptInto, KeysetCipher, StackCipher}; +use stack_encrypt::{EncryptInto, EncryptRef, KeysetCipher, StackCipher}; use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; async fn cipher() -> StackCipher { StackCipher::builder() @@ -22,12 +23,12 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } -async fn block( +async fn block( keyset: &KeysetCipher<'_, FakeDataKeySource>, value: T, ) -> OreBlockTerm { - keyset - .ore_block_term(value, nonempty!("users/n")) + value + .encrypt_into_with_context(keyset, nonempty!("users/n")) .await .expect("a block ORE term") } From ea7135cedde9912cefec2b1020b623e5af535be2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 14:46:18 +1100 Subject: [PATCH 4/4] docs(stack-encrypt): give the real reason the lone term methods are gone The earlier text said the methods were removed because nothing tied a term to its ciphertext's context, and that most indexes send a query term unlike the term they store. Neither is the reason. A term does not have to share its ciphertext's context; a type that needs that ties the two together, as an EQL type does with its one context field. And of the indexes behind these methods, only match sends a different query term. The reason is that a query must be built in the same domain as the stored term it searches. A field reference does this from the field's own context and options, and the removed methods copied their target's code without that tie. The CHANGELOG entry, the ADR-0004 amendment and the sem docs now say so. --- packages/stack-encrypt/CHANGELOG.md | 16 +++--- ...t-threaded-through-the-declaration-tree.md | 48 +++++++++--------- packages/stack-encrypt/src/sem/mod.rs | 49 ++++++++++--------- 3 files changed, 56 insertions(+), 57 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 9356bb0bb7..3876572d76 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -484,16 +484,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, `ope_term`, and `ore_block_term` are no longer public** (#1760). Each method built one term on its own, outside the target path and the - query path. Nothing tied that term to the context of the ciphertext - stored beside it. For most indexes, the term a query sends is not the - term a row stores. With `MatchOptions::short_words` on, the + query path, and copied its target's code. A query built with one of + them was not tied to the field it searched. Not all query terms are + the same as the stored terms. With `MatchOptions::short_words` on, the `match_terms` filter of "Mike Ng" misses "Mike Nguyen". - Removing the methods removes one way to build a term under the wrong - context. The change does not make a wrong context impossible. A term - shares its ciphertext's context only when it is a field of a derived - record, or sits beside its ciphertext in `Encrypted<(…)>`. A bare term - target, such as `EqualityTerm`, still takes any context. + A query must be built in the same domain as the stored term it + searches. A field reference does this: it builds the query under the + field's own context and options. A term does not have to share its + ciphertext's context. A type that needs that ties the two together, as + an EQL type does with its one context field. To upgrade, build each term one of two ways: - **To store a value**, encrypt it into a derived record with a field diff --git a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md index c1f908e3ae..cd2f6464f3 100644 --- a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md +++ b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md @@ -224,37 +224,35 @@ cannot tell which they are producing. > query path for a match index. ADR-0009's amendment of the same date gives > the full rule. -> **Amended 2026-11-23 (#1760).** The four methods are no longer public. -> Removing them removes one way to build a term under the wrong context. -> The change does not make a wrong context impossible. +> **Amended 2026-11-23 (#1760).** The four methods, and `ore_block_term`, +> are no longer public. Each copied its target's code. A query built with +> one of them was not tied to the field it searched. > -> The bare term targets `EqualityTerm`, `MatchTerms`, `OreTerm`, -> and `OpeTerm` are still public. A bare target takes any context, and -> seals no ciphertext beside its term. A term shares its ciphertext's -> context in two cases only: +> The rule that matters is that a query is built in the same domain as +> the stored term it searches. Not all query terms are the same as the +> stored terms: a match query is a different filter from the stored one. +> A field reference builds its query under the field's own context and +> options, so it meets the rule. > -> - the term is a field of a derived record; -> - the term sits beside its ciphertext in `Encrypted<(…)>`, the output -> of `target::indexed`. +> A term does not have to share its ciphertext's context. This changes +> the reason decision 5 gives. A type that needs the two under one +> context ties them together. An EQL type does it with its one context +> field. `Encrypted<(…)>`, the output of `target::indexed`, does it too. +> The bare term targets `EqualityTerm`, `MatchTerms`, +> `OreTerm`, `OpeTerm`, and `OreBlockTerm` stay public, for a +> type that needs a term on its own. > > Outside the crate, build each term this way: > -> - **To store a value**, encrypt it into a derived record with a field of -> the term type, or run `target::indexed` over it. Each builds the term -> under the context it seals the ciphertext under. A bare target -> (`value.encrypt_into_with_context(&keyset, context)` into -> `EqualityTerm`) builds the same term, but nothing ties its context to -> a ciphertext. +> - **To store a value**, encrypt it into its type. That is a derived +> record with a field of the term type, the output of +> `target::indexed`, or the bare term type. > - **To query**, use the field reference's operator method -> (`EncryptedUser::EMAIL.eq(..)`, `EncryptedUser::NAME.matches(..)`), or -> a query target run on its own, such as `target::matching_query`. A -> bare `MatchTerms` with `MatchOptions::short_words` on is a stored -> filter, not a query. -> -> `ore_block_term` is removed too. That method built a block -> order-revealing encryption (ORE) term outside a target, as the four did. -> The bare target `OreBlockTerm` is still public, as the four bare -> targets above are. +> (`EncryptedUser::EMAIL.eq(..)`, `EncryptedUser::NAME.matches(..)`). +> A query target run on its own, such as `target::matching_query`, also +> builds a query. It takes its context from the caller, so pass the +> stored term's context. A bare `MatchTerms` with +> `MatchOptions::short_words` on is a stored filter, not a query. ### 6. Targets declare their sources; `FfiValue` is not one diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index ff73694953..149a592b17 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -30,20 +30,22 @@ //! one tenant's [`KeysetCipher`] compares only against terms derived through //! the same keyset. //! -//! A term that your app stores comes from a target. The term shares its -//! ciphertext's context only in two cases. Either the term is a field of a -//! derived record, or it sits beside its ciphertext in an -//! [`Encrypted`](crate::target::Encrypted). A bare term target, such as -//! [`EqualityTerm`], takes any context and seals no ciphertext beside the -//! term. Nothing checks that its context is the context of a ciphertext. +//! A term that your app stores comes from a target. A term does not have +//! to share its ciphertext's context. A type that needs the two under one +//! context ties them together. A derived record does it for its fields. +//! An [`Encrypted`](crate::target::Encrypted) does it too. A bare term +//! target, such as [`EqualityTerm`], takes the context you give it and +//! seals no ciphertext. //! -//! A query term comes from the field's reference, such as -//! `EncryptedUser::EMAIL.eq(..)` or `EncryptedUser::NAME.matches(..)`. The -//! reference supplies the field's index and context. A query target run on -//! its own, such as [`matching_query`](crate::target::matching_query), also -//! builds one. A query term is not always the stored term: a match query -//! with [`MatchOptions::short_words`] on is cut differently. With that -//! option on, a bare [`MatchTerms`] is a stored filter, not a query. +//! A query must be built in the same domain as the stored term it +//! searches. The field's reference does this, such as +//! `EncryptedUser::EMAIL.eq(..)` or `EncryptedUser::NAME.matches(..)`: it +//! supplies the field's index, options, and context. A query target run on +//! its own, such as [`matching_query`](crate::target::matching_query), takes +//! its context from you, so pass the stored term's context. Not all query +//! terms are the same as the stored terms. With +//! [`MatchOptions::short_words`] on, a bare [`MatchTerms`] is a stored +//! filter, not a query. //! //! A target, and a field query's `.encrypt(&keyset)`, each return a //! [`Pending`]. A term needs no data key. Under the local HMAC backend, the @@ -2118,18 +2120,17 @@ order_term! { /// Term derivations that the `dynamic` path shares. /// -/// A term that your app stores comes from a target. The term shares its -/// ciphertext's context only as a field of a derived record, or beside its -/// ciphertext in an [`Encrypted`](crate::target::Encrypted). A bare term -/// target, such as [`EqualityTerm`], [`MatchTerms`], or [`OreTerm`], takes -/// any context and seals no ciphertext beside the term. +/// A term that your app stores comes from a target. That is a derived +/// record's field, an [`Encrypted`](crate::target::Encrypted), or a bare +/// term target such as [`EqualityTerm`] or [`MatchTerms`]. /// -/// A query term comes from the field's reference, such as -/// `EncryptedUser::EMAIL.eq(..)`. A query target run on its own, such as -/// [`matching_query`](crate::target::matching_query), also builds one. A -/// stored term and a query term are the same bytes for some indexes only. -/// A bare [`MatchTerms`] with [`MatchOptions::short_words`] on is a stored -/// filter, not a query. +/// A query comes from the field's reference, such as +/// `EncryptedUser::EMAIL.eq(..)`. The reference builds it in the stored +/// term's domain. A query target run on its own, such as +/// [`matching_query`](crate::target::matching_query), also builds one, under +/// the context you pass. Not all query terms are the same as the stored +/// terms. A bare [`MatchTerms`] with [`MatchOptions::short_words`] on is a +/// stored filter, not a query. impl KeysetCipher<'_, K> { /// The equality term of one scalar that the caller has already /// normalized. The `dynamic` path walks a value to its one scalar and