diff --git a/languages/golang/encrypt/guest/tests/native_ops.rs b/languages/golang/encrypt/guest/tests/native_ops.rs index d542d07e9..77b57fb33 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 0d246d018..57d6bdffc 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 fe57fdcac..3876572d7 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,6 +481,73 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **`KeysetCipher::equality_term`, `match_terms`, `ore_term`, + `ope_term`, and `ore_block_term` are no longer public** (#1760). Each + method built one term on its own, outside the target path and the + query path, and copied its target's code. A query built with one of + them was not tied to the field it searched. Not all query terms are + the same as the stored terms. With `MatchOptions::short_words` on, the + `match_terms` filter of "Mike Ng" misses "Mike Nguyen". + + A query must be built in the same domain as the stored term it + searches. A field reference does this: it builds the query under the + field's own context and options. A term does not have to share its + ciphertext's context. A type that needs that ties the two together, as + an EQL type does with its one context field. + + To upgrade, build each term one of two ways: + - **To store a value**, encrypt it into a derived record with a field + of the term type, or run `target::indexed` over it. Use + `EqualityTerm` for `equality_term`, `MatchTerms` for + `match_terms`, `OreTerm` for `ore_term`, `OpeTerm` for + `ope_term`, and `OreBlockTerm` for `ore_block_term`. Encrypting + the value into the bare term type gives the same term, with no + ciphertext beside it. `OreTerm::inner()` and `OpeTerm::inner()` + return the ciphertext the old methods returned. A target takes text + as a `String`, not a `&str`. + - **To query**, use the field reference's operator method, such as + `EncryptedUser::EMAIL.eq(&email)` or + `EncryptedUser::NAME.matches("Mike Ng")`. A query target run on its + own, such as `target::matching_query`, also works. A bare + `MatchTerms` with `short_words` on is a stored filter, not a + query. + + ```rust + // Before + let term = keyset.equality_term("alice@example.com", nonempty!("users/email")).await?; + + // After: the term to store + let term: EqualityTerm = String::from("alice@example.com") + .encrypt_into_with_context(&keyset, nonempty!("users/email")) + .await?; + // After: the query + let query = EncryptedUser::EMAIL.eq(&email).encrypt(&keyset).await?; + ``` + + `OreTerm`, `OpeTerm`, and `OreBlockTerm` need `T: Zeroize`. + The old `ore_term`, `ope_term`, and `ore_block_term` also took three + types that are not `Zeroize`: jiff's `civil::Date` and `Timestamp`, + and rust_decimal's `Decimal`. For these, convert the value to + `value::Date`, `value::Timestamp`, or `value::Decimal` first. Or run + the borrowed operation, as below, to read the value in place: + + ```rust + let term: OpeTerm = value::Date::new(dob) + .encrypt_into_with_context(&keyset, nonempty!("users/dob")) + .await?; + // Or, with the jiff date as it is + let context = CallerContext::from(nonempty!("users/dob")); + let term: OpeTerm = keyset + .run(target::ope::<_, _, Borrowed>(), &dob, context) + .await?; + ``` + + `target::ore` gives the order-revealing encryption (ORE) term the same + 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. - `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 6b69068b9..cd2f6464f 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,36 @@ 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, 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 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. +> +> 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 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(..)`). +> 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 A target names the plaintext it accepts (`TextEq` from `Protected`), and 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 956b2d7a1..81d009a6e 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/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 833698c52..d9c8e6185 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/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index ee13cf764..545b486da 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 805797eaf..6bec8c133 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(); @@ -970,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 _; @@ -1152,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() @@ -1263,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")), @@ -1289,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!( @@ -1306,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") ); }; @@ -1357,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 @@ -1395,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() @@ -1430,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() @@ -1440,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") @@ -2090,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"); @@ -2134,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() @@ -2146,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 ec27fe80e..fefef9a76 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -787,13 +787,15 @@ 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. 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 -/// the plaintext wiped, use `value::Date`, `value::Timestamp`, or -/// `value::Decimal`. +/// 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. +/// +/// 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 c8bf0682e..149a592b1 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -30,15 +30,28 @@ //! 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. 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 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 +//! 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 +188,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 +531,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 +856,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. +/// +/// 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. /// -/// `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. +/// 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 +2118,25 @@ 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. +/// Term derivations that the `dynamic` path shares. /// -/// # These are the query-probe path +/// 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 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. -/// -/// 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. -/// -/// 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 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> { - /// 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(feature = "dynamic")] pub(crate) fn equality_term_normalized<'c>( &self, normalized: Normalized, @@ -2241,14 +2157,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(feature = "dynamic")] pub(crate) fn match_terms_under<'c, O>( &self, text: &str, @@ -2261,63 +2178,6 @@ 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. - /// - /// 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. - 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/audit.rs b/packages/stack-encrypt/tests/audit.rs index 850500235..9947498ac 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 51779d830..2cb537b9e 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 5fdc8383b..16e3e420e 100644 --- a/packages/stack-encrypt/tests/credential.rs +++ b/packages/stack-encrypt/tests/credential.rs @@ -666,19 +666,21 @@ 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, OreBlockTerm, 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 block = early.ore_block_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 = 42u32.encrypt_into_with_context::, _>(&early, field()); assert_eq!(source.take(), vec![], "building makes no request"); let equality = equality.with_credential(bob()).await.unwrap(); @@ -704,34 +706,42 @@ 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()) + let late_block = 42u32 + .encrypt_into_with_context::, _>(&late, field()) .with_credential(alice()) .await .unwrap(); @@ -740,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/frozen_bytes.rs b/packages/stack-encrypt/tests/frozen_bytes.rs index e6d2d6031..313e7198c 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 fc3414ff2..370756416 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 f24b4b7fc..ca2b84be7 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 45775dd61..0cc04ed91 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/ore_block.rs b/packages/stack-encrypt/tests/ore_block.rs index 094c05a70..aa1d5a3db 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/sem_terms.rs b/packages/stack-encrypt/tests/sem_terms.rs index 3090ffecf..29abf8177 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 63fb08326..ad45f2fe2 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 @@ -919,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/target.rs b/packages/stack-encrypt/tests/target.rs index 0b8345b1b..c3661fa45 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 e08096d87..119ea6457 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/term_serde.rs b/packages/stack-encrypt/tests/term_serde.rs index eb9797d96..96faa3e8a 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") } diff --git a/packages/stack-encrypt/tests/transcode.rs b/packages/stack-encrypt/tests/transcode.rs index a515a317f..e577f814c 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 06a7ecdcf..7e730576e 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!(