diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index 858f489de..a2bea966e 100644 --- a/.changeset/eql-v4-match-short-words.md +++ b/.changeset/eql-v4-match-short-words.md @@ -2,10 +2,35 @@ '@cipherstash/eql': minor --- -**EQL v4's match types index each two-letter word whole, so a two-letter surname such as "Ng" is searchable** (#1309). `eql-bindings`' `EqlMatch`, the match configuration of `TextMatch`, `TextSearch` and `TextSearchOre`, turns on Stack Encrypt's `MatchOptions::short_words`: beside the 3-grams of the whole text, every word of exactly two characters (words split on space, comma, semicolon, colon and exclamation mark) is one more token, the word itself, hashed under a domain of its own and folded into the same 2048-bit filter by the same 6 positions. "Ng" now stores into `TextMatch` (it was refused, cutting no 3-gram), a `TextSearch` holding "Ng" stores a filter rather than the empty one, and `@@` with the query "ng" finds the rows holding the word "Ng" ("Ng", "Mike Ng", "NG, Anna"), not "Nguyen". A query's two-letter words must be whole words of the row, so "Mike Ng" does not find "Mike Nguyen". Text that still cuts no token (one letter, or none) is refused by `TextMatch` and stored with the empty filter by the search types, as before. +**EQL v4's match types now index each two-letter word as a whole word, so a two-letter surname such as "Ng" is searchable** (#1309). `eql-bindings`' `EqlMatch` is the match configuration of `TextMatch`, `TextSearch`, and `TextSearchOre`. `EqlMatch` now turns on Stack Encrypt's `MatchOptions::short_words`. + +A stored value's filter contains the 3-grams of the whole text. A 3-gram is a run of three characters, such as "mik" in "Mike". The filter now also contains each word of exactly two characters, as one more token. Words are split on space, comma, semicolon, colon, and exclamation mark. + +The word token is hashed under a domain of its own. Like a 3-gram, it sets 6 positions in the same 2048-bit filter. + +- "Ng" can now be stored in `TextMatch`. Before, `TextMatch` refused it, because "Ng" has no 3-gram. +- A `TextSearch` value of "Ng" now stores a filter, not the empty filter. +- `@@` with the query "ng" finds the rows that contain the word "Ng", such as "Ng", "Mike Ng", and "NG, Anna". The query does not find "Nguyen". + +A query asks for its two-letter words only when the whole query is one two-letter word. A query of three characters or more asks for its 3-grams alone, as it would without word tokens. So "Mike Ng" finds "Mike Ng" and "Mike Nguyen". A name typed in part, such as "ke Ng" or "san fr", still finds its row. + +Every query path follows this rule, so a query's filter and its verify agree. The paths are: + +- a field reference's `matches`; +- the query twins' `EncryptTarget`; +- the by-name query dispatch that a binding runs; +- `verify`. + +A query twin's filter has a new field type, `v4::terms::QueryBloomFilter`. A query twin is the struct that contains a query's terms. The new type is the `bf` of `TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, `TextSearchQuery`, and `TextSearchOreQuery`. `QueryBloomFilter` has the JSON and JSON Schema of `BloomFilter`. Only fields of the `v4` module change, and that module is not released yet. + +Text with no token at all, such as one letter or nothing, is handled as before. `TextMatch` refuses it. The search types store it with the empty filter. **The v4 match format now includes short-word tokens.** A filter of text holding a two-letter word gains that word's bits; text with none derives the filter it did. EQL v4 is unreleased, so this is the format it ships with: a v4 value written by an earlier build that holds a two-letter word lacks the word's bits, and a query naming that word does not find it until the value is re-encrypted. -**What it reveals.** One more token per two-letter word, under the same PRF, in the same filter, by the same containment rule, so no new class of leakage. The token is specific to the word: someone who clusters tokens across rows can tell the rows holding the word "Ng" from those holding "Nguyen", where before only the boundary trigram `" ng"` they share was visible. No bigram of a longer word is indexed. +**What it reveals.** Each stored value gains one more token for each two-letter word it contains. The token uses the same pseudorandom function (PRF), the same filter, and the same containment rule. No two-character piece of a longer word is indexed. + +The word token is unique to the word. Someone who groups tokens across rows can tell the rows that contain "Ng" from the rows that contain "Nguyen", and count them. Without the word token, they see only the 3-gram `" ng"` that both names share. + +A query of one two-letter word shows which word it asks for. A longer query sends no word token. No SQL function changes (one doc comment in the bundle is reworded), and the TypeScript types do not change. diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 0c70e9a5d..358b43c1b 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -152,6 +152,26 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. token derives under the cipher's scopes alone. The children open under the scopes and the binding. A cipher with a binding still refuses `ChildCount`, since a count opens nothing. + +- **`Matches` on `TextMatch`, `TextSearch`, and `TextSearchOre` finds a + name typed in part again** (#1398). Before this fix, "Mike Ng" did not + find "Mike Nguyen". A stored value contains its 3-grams, and each + two-letter word as a whole word. A 3-gram is a run of three characters, + such as "mik" in "Mike". A query also asked for each of its two-letter + words as a whole word. "Nguyen" contains "ng" only inside a longer word, + so the query missed it. + + Now a query asks for its two-letter words only when the whole query is + one two-letter word. A query of three characters or more asks for its + 3-grams alone. + - "Mike Ng" finds "Mike Ng" and "Mike Nguyen". + - "ke Ng" finds "Mike Ng". + - "Ng" still asks for the whole word. The query finds "Ng" and "Mike + Ng", and not "Nguyen". + + `Verify` keeps the same rows that the filter selects. Stored values do + not change, so nothing needs re-encrypting. + - `vcffi` and `vcvalue` move to vitaminc `f1fc9ae74`, the commit vitaminc 0.10.0 was released from. The host now checks the same date and timestamp range as the guests. diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 8c6c392f8..5c4b1800a 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -436,7 +436,7 @@ The `Eq` types answer `Eq`; the `Ord`, `OrdOpe` and `OrdOre` types answer `Lt`, The ordered date, timestamp and numeric types answer the four comparisons, as do the other ordered EQL types. The generated EQL fields have no `Between` method yet: EQL v4 has range query domains, but `stashgen` does not construct their operands. A JSON document's declared ordered paths have their own `Between` method, which returns two leaf query values; see [Encrypted JSON documents](#encrypted-json-documents). Any built-in Go integer field takes an integer type (ADR-0002) and seals at the type's width: an `int16` field always fits an `Integer`, and an `int64` field is range checked value by value, `Encrypt` refusing a value that does not fit with `encrypt.ErrEncoding`. `encrypt.Int128` and `encrypt.Uint128` are not converted. A float's width must match: a `float64` field is not a `Real`. -A `TextMatch` field indexes the 3-grams of its text and each two-letter word whole, so a two-letter surname such as "Ng" is stored and found by the query "ng"; a query's two-letter words must be whole words of the row. +A `TextMatch` field indexes the 3-grams of its text, and each two-letter word as a whole word. A 3-gram is a run of three characters, such as "mik" in "Mike". So a two-letter surname such as "Ng" is stored, and the query "ng" finds it. A query asks for its two-letter words only when the whole query is one two-letter word. So the query "Mike Ng" asks for its 3-grams alone, and finds "Mike Nguyen" too. A `TextMatch` field refuses text that cuts no token, such as an empty string or one letter; its query refuses such text too. A `TextSearch` field stores such text with an empty match filter, so its `Eq`, `Lt`, `Lte`, `Gt` and `Gte` queries find it and no `Matches` query does; those queries take such text too, and its `Matches` query refuses it. Put the column on the left of `@@` (`WHERE name @@ $1::eql_v4.query_text_match`): the other operand order finds nothing until #1171 is fixed. diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index f90e23a74..e88e10efd 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -661,13 +661,23 @@ with `ErrEncoding`, naming the field's kind and not the value. `encrypt.Int128` and `encrypt.Uint128` are not converted, and floats take exactly their own width. -A `TextMatch` value is indexed by its 3-grams and by each two-letter word -whole, so a two-letter surname such as "Ng" is stored, and `Matches` with -"ng" finds the rows holding the word "Ng" ("Ng", "Mike Ng"), not "Nguyen". -A query's two-letter words must be whole words of the row, so "Mike Ng" does -not find "Mike Nguyen". The word token reveals one more token per two-letter -word, in the same filter: someone who clusters tokens across rows can tell -"Ng" from "Nguyen", where before only the trigram they share was visible. +A `TextMatch` index contains the 3-grams of a value, and each two-letter +word as a whole word. A 3-gram is a run of three characters, such as "mik" in +"Mike". The whole-word token lets you store a two-letter surname such as +"Ng". `Matches` with "ng" finds the rows that contain the word "Ng", such as +"Ng" and "Mike Ng", and not "Nguyen". + +A query asks for its two-letter words only when the whole query is one +two-letter word. A query of three characters or more asks for its 3-grams +alone. So "Mike Ng" finds "Mike Ng" and "Mike Nguyen". A name typed in part, +such as "ke Ng", finds its row. + +The word token adds one token for each two-letter word in a stored value. +The token is unique to the word. Someone who groups tokens across rows can +tell the rows that contain "Ng" from the rows that contain "Nguyen", and +count them. Without the word token, they see only the 3-gram that both +names share. + Text that cuts no token, such as an empty string or one letter, is refused. A `TextSearch` value of such text is stored with an empty match filter: `Eq`, `Lt`, `Lte`, `Gt` and `Gte` find it through its other terms, and no diff --git a/languages/golang/encrypt/eql_v4_test.go b/languages/golang/encrypt/eql_v4_test.go index fbc6d7814..ccd402cc7 100644 --- a/languages/golang/encrypt/eql_v4_test.go +++ b/languages/golang/encrypt/eql_v4_test.go @@ -297,6 +297,15 @@ func TestV4QueriesMatchTheRustFixture(t *testing.T) { if ok, err := ng.Verify(ctx, []string{"Ng", "Mike Ng", "Nguyen"}); err != nil || !ok[0] || !ok[1] || ok[2] { t.Errorf("Verify(Ng, Mike Ng, Nguyen) = %v, %v, want true, true, false", ok, err) } + // A query of three characters or more keeps no two-letter word. So a + // name typed in part finds the longer name too. + mikeNg, err := testusers.ProfileFields.Name.Matches(ctx, cipher, "Mike Ng") + if err != nil { + t.Fatalf("Name.Matches(%q): %v", "Mike Ng", err) + } + if ok, err := mikeNg.Verify(ctx, []string{"Mike Ng", "Mike Nguyen", "Ng"}); err != nil || !ok[0] || !ok[1] || ok[2] { + t.Errorf("Verify(Mike Ng, Mike Nguyen, Ng) = %v, %v, want true, true, false", ok, err) + } } // rowsFixture is v4_rows.json: the profiles above as the generated code seals diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 01ff964ac..cfd46a5c8 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -224,6 +224,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **A match query asks for its two-letter words only when the whole query + is one two-letter word** (#1398, `stack-encrypt` feature). Before this + fix, "Mike Ng" did not find "Mike Nguyen". `EqlMatch` stores the 3-grams + of a value, and each two-letter word as a whole-word token. A 3-gram is + a run of three characters, such as "mik" in "Mike". A query that + contained a two-letter word also asked for that word whole. "Nguyen" + contains "ng" only inside a longer word, so the query missed it. + + Now a query of three characters or more asks for its 3-grams alone. + "Mike Ng" finds "Mike Ng" and "Mike Nguyen". "ke Ng" and "san fr" find + the names they are part of. A query of one two-letter word asks for that + word: "Ng" finds "Ng" and "Mike Ng", and not "Nguyen". Stored values do + not change. + - The `bf` of every v4 query twin is now the new + `v4::terms::QueryBloomFilter`. A query twin is the struct that contains + a query's terms. The twins are `TextMatchQuery`, + `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, `TextSearchQuery`, + and `TextSearchOreQuery`. In the last two, `bf` is an + `Option`. + - `QueryBloomFilter` has the JSON and JSON Schema of `BloomFilter`. + `From for BloomFilter` unwraps it. + - The `EncryptTarget` of `QueryBloomFilter` derives the query's filter. + So a query twin follows the rule however it is built: directly, by a + field reference's `matches`, or by the by-name query dispatch. + - `TwinIndex` forwards Stack Encrypt's `Index::query_operation` to the + indexes whose terms its twin contains, through + `Indexes::query_operations`. So `matches` on `TextMatch`, `TextSearch`, + and `TextSearchOre` sends the query's filter. Every other operator + sends the term its index stores. - **A v4 order term is Stack Encrypt's own, typed by its plaintext** (`stack-encrypt` feature). An `ob` field is `stack_encrypt::sem::OreBlockTerm` and an `op` field diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index d781e2d62..4ea64bec4 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -186,14 +186,29 @@ not `=` either. Text with a code point Unicode 16 does not assign has no order term and is refused, stored or queried. A family's `Ord` and `OrdOpe` types store the same term under one column. The query value carries one bound: `BETWEEN` needs EQL v4's range query domains and is not produced yet. -`TextMatch` builds its filter under a configuration pinned in this crate -(`EqlMatch`: 3-grams of the lower-cased text, plus each two-letter word whole -as one more token, `k = 6`, a 2048-bit filter) for stored values and queries -alike. The word token makes a two-letter surname such as "Ng" storable and -searchable: `@@` with "ng" finds "Ng" and "Mike Ng", not "Nguyen". A query's -two-letter words must be whole words of the row (words split on space, -comma, semicolon, colon and exclamation mark), so "Mike Ng" does not find -"Mike Nguyen", and a query is not a plain substring test. The configuration is part of the stored + +`TextMatch` builds its filter under a configuration pinned in this crate, +`EqlMatch`. Stored values and queries both use it. + +`EqlMatch` takes the 3-grams of the lower-cased text. A 3-gram is a run of +three characters, such as "mik" in "Mike". `EqlMatch` also takes each +two-letter word as one more token, whole. Each token sets `k = 6` +positions in a 2048-bit filter. Words are split on space, comma, semicolon, +colon, and exclamation mark. + +The word token lets you store and search a two-letter surname such as "Ng". +`@@` with "ng" finds "Ng" and "Mike Ng", and not "Nguyen". A query asks for +its two-letter words only when the whole query is one two-letter word. A +query of three characters or more asks for its 3-grams alone. So "Mike Ng" +finds "Mike Ng" and "Mike Nguyen", and "san fr" finds "San Francisco". + +A query's filter is a `QueryBloomFilter`, with the same JSON as +`BloomFilter`. A query is not a plain substring test. The word token adds +one token for each two-letter word in a stored value. The token is unique +to the word, so someone can tell the rows that contain "Ng" from the rows +that contain "Nguyen". + +The configuration is part of the stored format, so changing it means a new domain or payload version. A filter can match a row that does not contain the query, so re-check after decrypting where that matters. Write the stored column on the left, `col @@ query`: the diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index c3ed40c1e..7df390c53 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -125,7 +125,7 @@ use zeroize::Zeroize; use crate::{ v3::terms::{BloomFilter, Ciphertext, Hmac256}, - v4::terms::SearchBloomFilter, + v4::terms::{QueryBloomFilter, SearchBloomFilter}, Identifier, }; @@ -365,15 +365,23 @@ impl DecryptField for Hmac256 { /// /// The short-word tokens are what make a two-letter surname searchable: "Ng" /// cuts no 3-gram, so without them it would be no `TextMatch` value at all, -/// and the query "ng" would be refused. With them "Ng" stores one token, and -/// `@@` with the query "ng" finds the rows holding the word "Ng" ("Ng", -/// "Mike Ng", "Ng, Mike"), not "Nguyen". A query's two-letter words must be -/// whole words of the row, so "Mike Ng" does not find "Mike Nguyen". What it -/// reveals: one more token per two-letter word, under the same PRF (in a -/// domain of its own), in the same filter, by the same containment rule, so -/// no new class of leakage; the token is specific to the word, so someone who -/// clusters tokens across rows can tell "Ng" from "Nguyen", where before only -/// the boundary trigram `" ng"` they share was visible. +/// and the query "ng" would be refused. With them, "Ng" stores one token. +/// `@@` with the query "ng" finds the rows that contain the word "Ng", such +/// as "Ng", "Mike Ng", and "Ng, Mike". The query does not find "Nguyen". +/// +/// A query asks for its word token only when the whole query is one +/// two-letter word. A query of three characters or more asks for its +/// 3-grams alone ([`QueryBloomFilter`]). So "Mike Ng" finds "Mike Ng" and +/// "Mike Nguyen", and "san fr" finds "San Francisco". +/// +/// What it reveals: one more token per two-letter word, in every stored +/// value that contains one. The token uses the same PRF in a domain of its +/// own, the same filter, and the same containment rule. The token is unique +/// to the word. Someone who clusters tokens across rows can tell "Ng" from +/// "Nguyen". Without the word token, they see only the trigram `" ng"` that +/// both share. +/// +/// [`QueryBloomFilter`]: crate::v4::terms::QueryBloomFilter /// /// Pinned here rather than taken from Stack Encrypt's default, because it is /// part of the stored format: a stored filter and a query filter agree only @@ -401,20 +409,23 @@ impl MatchConfig for EqlMatch { } /// Builds EQL's bloom filter, the set bit positions as `smallint`s, from the -/// native match terms built under [`EqlMatch`]. Stored values and queries -/// take it from the same type, so they always agree; matching +/// native match terms built under [`EqlMatch`]: `TextMatch`'s stored +/// filter. Every stored filter and every query filter is built under +/// [`EqlMatch`], so they agree on every token a query keeps. A query can +/// keep fewer tokens than the same text stores. A query's filter is a +/// [`QueryBloomFilter`] ([`QueryMatchVisitor`]). Matching /// cipherstash-client's parameters is not a goal, because cipherstash-client /// never writes an `eql_v4` column. /// /// Text that cuts no token (empty, separator-only, or shorter than a 3-gram /// with no two-letter word, such as one letter) is refused with -/// [`TermError::EmptyTermText`], stored or queried. Stack -/// Encrypt stores such a value as the empty filter, but this type is the -/// filter of every match query, and a query's filter must never be empty; -/// it is also `TextMatch`'s stored filter, and a `TextMatch` value with an -/// empty filter is a row no operator can find. A search domain's stored -/// filter, which `=` and `<` find through its other terms, is -/// [`SearchBloomFilter`] and takes the empty filter ([`SearchMatchVisitor`]). +/// [`TermError::EmptyTermText`]. Stack Encrypt stores such a value as the +/// empty filter, but a `TextMatch` value with an empty filter is a row no +/// operator can find. A query's filter is refused for such text too, +/// because it must never be empty. A search domain's stored filter is a +/// [`SearchBloomFilter`]. That filter can be empty +/// ([`SearchMatchVisitor`]), since `=` and `<` find the value through its +/// other terms. #[doc(hidden)] pub struct MatchVisitor; impl Visitor for MatchVisitor { @@ -516,6 +527,51 @@ impl DecryptField for SearchBloomFilter { } } +/// Builds a query's filter from the tokens the query keeps (see +/// [`QueryBloomFilter`]). The filter is [`MatchVisitor`]'s, so text with no +/// token is refused. +#[doc(hidden)] +pub struct QueryMatchVisitor; +impl Visitor for QueryMatchVisitor { + type Value = QueryBloomFilter; + fn matching(self, terms: MatchTerms) -> Result { + MatchVisitor.matching(terms).map(QueryBloomFilter) + } +} +impl Transcode for QueryBloomFilter { + type Visitor = QueryMatchVisitor; + fn visitor() -> Self::Visitor { + QueryMatchVisitor + } +} +impl + Zeroize> EncryptTarget for QueryBloomFilter { + type ContextInput = RequiredContext; + fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> + where + S: 's, + { + // A query's tokens: its two-letter words only when the whole query is + // one two-letter word. The annotation names the match configuration, + // as for `BloomFilter`. + let terms: Encryption<'s, S, MatchTerms, K, CallerContext> = + target::matching_query(); + terms.accepting().transcode() + } + /// The match index under [`EqlMatch`], as for [`BloomFilter`]. A query + /// twin with a `bf` is a query of that index. + fn indexes() -> Vec { + vec![IndexSpec::Match(EqlMatch::options())] + } +} +impl Decryptable for QueryBloomFilter { + const DECRYPTABLE: bool = false; +} +impl DecryptField for QueryBloomFilter { + fn decryption_field(self, _: Ctx) -> Option> { + None + } +} + #[cfg(test)] mod tests { use stack_encrypt::{nonempty, Descriptor, Label}; diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 06e24a50e..fdaf9e153 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -257,7 +257,8 @@ use stack_encrypt::{Encrypt, EncryptRef, Equality, Error, Label, Match, NonEmpty use zeroize::Zeroize; use super::{bloom_filter, hmac256, EqlMatch}; -use crate::v3::terms::{BloomFilter, Hmac256}; +use crate::v3::terms::Hmac256; +use crate::v4::terms::QueryBloomFilter; use crate::Identifier; /// An EQL v4 query twin, assembled from the column it queries and the @@ -265,7 +266,7 @@ use crate::Identifier; /// stores them. eql-codegen implements it for the twin of every type that /// answers an operator, with the version every v4 value carries: /// [`TextEqQuery`] from an [`Hmac256`], [`TextMatchQuery`] from a -/// [`BloomFilter`], `IntegerOrdQuery` from an +/// [`QueryBloomFilter`], `IntegerOrdQuery` from an /// [`OpeTerm`](stack_encrypt::sem::OpeTerm), and /// [`TextOrdQuery`] from the pair `(Hmac256, OpeTerm)`, its terms in /// catalog order. A twin whose terms are optional, such as @@ -346,7 +347,9 @@ impl fmt::Debug for TwinIndex { /// Declared as `I` is, so it is the index that answers the operator, and /// derives the terms of `D` for one value, under one context: `I`'s term -/// alone when `D` is `I`. +/// alone when `D` is `I`. A query derives each index's query term +/// ([`Indexes::query_operations`]). So a match term is the filter of the +/// tokens the query keeps, as in `I`'s own query. impl, Q, D: Indexes> Index for TwinIndex { type Term = D::Terms; fn spec(&self) -> IndexSpec { @@ -360,6 +363,14 @@ impl, Q, D: Indexes> Index for TwinIndex { { self.terms.operations() } + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + self.terms.query_operations() + } } /// Refuse a label no EQL query value can record: one that names no column @@ -544,15 +555,17 @@ macro_rules! twin_orderings { } twin_orderings!(Lt, Lte, Gt, Gte); -/// Text match: the twin's `bf` is the filter EQL's match index derives -/// over the query's text, and the query keeps that text's tokens to -/// [`verify`](Probabilistic::verify) each decrypted row, as Stack Encrypt's -/// `MatchQuery` does. A query whose text cuts no token is refused before -/// any term exists. Only for the plaintext the twin's type is produced -/// from. +/// Text match. The twin's `bf` is the filter EQL's match index derives over +/// the tokens the query keeps ([`QueryBloomFilter`]). The query keeps its +/// two-letter words only when the whole query is one two-letter word. The +/// query also keeps those tokens to [`verify`](Probabilistic::verify) each +/// decrypted row, as Stack Encrypt's `MatchQuery` does. +/// +/// A query whose text has no token is refused before any term exists. Only +/// for the plaintext the twin's type is produced from. impl Supports for TwinIndex, Q> where - Q: QueryTwin + MaybeSend + 'static, + Q: QueryTwin + MaybeSend + 'static, Q::Plaintext: AsRef + Zeroize + 'static, { type Query = MatchTwin; @@ -573,7 +586,7 @@ where let bf = bloom_filter(query.positions()) .expect("EqlMatch's 2048-bit filter keeps every position within a smallint"); MatchTwin { - twin: Q::assemble(column, bf), + twin: Q::assemble(column, QueryBloomFilter(bf)), query, } } diff --git a/packages/eql/crates/eql-bindings/src/v4/answers.rs b/packages/eql/crates/eql-bindings/src/v4/answers.rs index 9bb121f1a..cca59ec25 100644 --- a/packages/eql/crates/eql-bindings/src/v4/answers.rs +++ b/packages/eql/crates/eql-bindings/src/v4/answers.rs @@ -2,7 +2,7 @@ //! How a Stack Encrypt typed query, from a field reference, queries a producible EQL v4 type: per type that answers an operator, its `op::Answers` impls, its `op::LabelledTarget` impl and its query twin's assembly (`crate::encryption::query`). Generated from the catalog, by the rule the data path answers a field that names the type with. use crate::encryption::query::{QueryTwin, TwinIndex}; use crate::encryption::EqlMatch; -use crate::v4::terms::{BloomFilter, Hmac256}; +use crate::v4::terms::{Hmac256, QueryBloomFilter}; use crate::v4::SchemaVersion; use crate::Identifier; use stack_encrypt::op; @@ -758,9 +758,9 @@ impl op::Answers for super::text::TextEq { /// `TextMatch` is sealed under the column a two-segment label names, so a field of this type is queried under its field reference's label. impl op::LabelledTarget for super::text::TextMatch {} /// `TextMatchQuery` from the column it queries and its `bf` term, at version 4. -impl QueryTwin for super::text::TextMatchQuery { +impl QueryTwin for super::text::TextMatchQuery { type Plaintext = String; - fn assemble(i: Identifier, bf: BloomFilter) -> Self { + fn assemble(i: Identifier, bf: QueryBloomFilter) -> Self { Self { v: SchemaVersion::default(), i, @@ -909,9 +909,9 @@ impl QueryTwin> for super::text::TextSearchOreQuery { } } /// `TextSearchOreQuery` from the column it queries and its `bf` term alone, at version 4: the query through its match index. -impl QueryTwin for super::text::TextSearchOreQuery { +impl QueryTwin for super::text::TextSearchOreQuery { type Plaintext = String; - fn assemble(i: Identifier, bf: BloomFilter) -> Self { + fn assemble(i: Identifier, bf: QueryBloomFilter) -> Self { Self { v: SchemaVersion::default(), i, @@ -976,9 +976,9 @@ impl QueryTwin> for super::text::TextSearchQuery { } } /// `TextSearchQuery` from the column it queries and its `bf` term alone, at version 4: the query through its match index. -impl QueryTwin for super::text::TextSearchQuery { +impl QueryTwin for super::text::TextSearchQuery { type Plaintext = String; - fn assemble(i: Identifier, bf: BloomFilter) -> Self { + fn assemble(i: Identifier, bf: QueryBloomFilter) -> Self { Self { v: SchemaVersion::default(), i, diff --git a/packages/eql/crates/eql-bindings/src/v4/mod.rs b/packages/eql/crates/eql-bindings/src/v4/mod.rs index e4a19ce22..d33ffffa6 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -38,9 +38,10 @@ //! The other term newtypes and the [`DomainType`] trait are shared with v3: //! a v4 `Ciphertext` or `Hmac256` is v3's type, so a change to its //! validation in `v3::terms` changes v4 too. v3's order terms -//! (`OreBlock256`, `OpeCllw`) are not among them. The one v4 term v3 has no -//! use for is [`terms::SearchBloomFilter`], the stored filter of a search -//! domain. What separates the two on the wire is the envelope's +//! (`OreBlock256`, `OpeCllw`) are not among them. Two v4 terms have no use +//! in v3: [`terms::SearchBloomFilter`], the stored filter of a search +//! domain, and [`terms::QueryBloomFilter`], the filter of a match query. +//! What separates the two generations on the wire is the envelope's //! [`SchemaVersion`], which refuses the other generation's `v`. /// Generated: the `op::Answers` impls through which a field reference of a @@ -83,10 +84,14 @@ pub mod timestamp; pub use crate::v3::domain_type::{DomainType, SQL_SCHEMA}; pub use inventory::{all, all_query, all_range_query}; -/// The wire-field types of the v4 payloads: v3's that are not order terms, -/// shared; [`SearchBloomFilter`](terms::SearchBloomFilter); and the JSON of -/// the order terms, [`OreBlockHex`](terms::OreBlockHex) and -/// [`OpeHex`](terms::OpeHex), whose fields hold Stack Encrypt's terms. +/// The wire-field types of the v4 payloads: +/// +/// - v3's types that are not order terms, shared with v3; +/// - [`SearchBloomFilter`](terms::SearchBloomFilter) and +/// [`QueryBloomFilter`](terms::QueryBloomFilter); +/// - the JSON of the order terms, [`OreBlockHex`](terms::OreBlockHex), +/// and [`OpeHex`](terms::OpeHex), whose fields contain Stack Encrypt's +/// terms. pub mod terms { pub use super::term_formats::{OpeHex, OreBlockHex}; pub use crate::v3::terms::{BloomFilter, Ciphertext, Hmac256}; @@ -107,10 +112,11 @@ pub mod terms { /// query's, and an EQL v4 search query's filter is never empty (the /// match projection refuses such text, and the SQL refuses `"bf": []`). /// - /// [`BloomFilter`], the filter of `TextMatch` and of every query, still - /// refuses such text: `TextMatch` has no other term to find it by. The - /// JSON is [`BloomFilter`]'s, and so is the JSON Schema; only what Stack - /// Encrypt derives into it differs. + /// [`BloomFilter`], `TextMatch`'s stored filter, still refuses such + /// text, since `TextMatch` has no other term to find it by. + /// [`QueryBloomFilter`], the filter of every query, refuses it too. The + /// JSON and JSON Schema are [`BloomFilter`]'s. Only what Stack Encrypt + /// derives into it differs. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] #[serde(transparent)] pub struct SearchBloomFilter(pub BloomFilter); @@ -135,6 +141,55 @@ pub mod terms { filter.0 } } + + /// The `bf` term of a match query: a [`BloomFilter`] of the tokens the + /// query keeps. `QueryBloomFilter` is the `bf` of `TextMatchQuery`, + /// `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, `TextSearchQuery`, + /// and `TextSearchOreQuery`. + /// + /// A stored value's filter contains every token of its text: its + /// 3-grams, and each two-letter word as a whole word. A query keeps its + /// two-letter words only when the whole query is one two-letter word. + /// A query of three characters or more keeps its 3-grams alone. + /// + /// - The query "ng" is the word token `ng`. The query finds the rows + /// that contain the word "Ng", such as "Ng" and "Mike Ng", and not + /// "Nguyen". + /// - The query "Mike Ng" is its 3-grams alone. The query finds "Mike Ng" + /// and "Mike Nguyen", as does "ke Ng". + /// - The query "san fr" finds "San Francisco". + /// + /// A query sends no token that a stored value of its own text lacks. So + /// the rule changes no stored filter. + /// + /// Text with no token is refused, as for [`BloomFilter`]: a query's + /// filter is never empty. Such text is empty, separators only, or one + /// letter. The JSON and JSON Schema are [`BloomFilter`]'s. Only what + /// Stack Encrypt derives into it differs. + #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] + #[serde(transparent)] + pub struct QueryBloomFilter(pub BloomFilter); + + /// [`BloomFilter`]'s schema, under its name: the wire format is one. + impl JsonSchema for QueryBloomFilter { + fn schema_name() -> std::borrow::Cow<'static, str> { + BloomFilter::schema_name() + } + + fn schema_id() -> std::borrow::Cow<'static, str> { + BloomFilter::schema_id() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + BloomFilter::json_schema(generator) + } + } + + impl From for BloomFilter { + fn from(filter: QueryBloomFilter) -> Self { + filter.0 + } + } } /// The PostgreSQL typname prefix every `public` v4 domain carries. diff --git a/packages/eql/crates/eql-bindings/src/v4/text.rs b/packages/eql/crates/eql-bindings/src/v4/text.rs index a5d645235..c4b7165bf 100644 --- a/packages/eql/crates/eql-bindings/src/v4/text.rs +++ b/packages/eql/crates/eql-bindings/src/v4/text.rs @@ -1,6 +1,8 @@ // @generated by eql-codegen from the eql-domains catalog — do not edit //! The `text` encrypted-domain family — generated from the eql-domains catalog. -use crate::v4::terms::{BloomFilter, Ciphertext, Hmac256, OpeHex, OreBlockHex, SearchBloomFilter}; +use crate::v4::terms::{ + BloomFilter, Ciphertext, Hmac256, OpeHex, OreBlockHex, QueryBloomFilter, SearchBloomFilter, +}; use crate::v4::{DomainType, SchemaVersion}; use crate::Identifier; use schemars::{schema_for, JsonSchema, Schema}; @@ -512,7 +514,7 @@ pub struct TextMatchQuery { pub v: SchemaVersion, #[stash(context_field)] pub i: Identifier, - pub bf: BloomFilter, + pub bf: QueryBloomFilter, } impl DomainType for TextMatchQuery { fn sql_domain_static() -> &'static str { @@ -721,7 +723,7 @@ pub struct TextSearchOreQuery { #[schemars(with = "Option")] pub ob: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] - pub bf: Option, + pub bf: Option, } impl DomainType for TextSearchOreQuery { fn sql_domain_static() -> &'static str { @@ -811,7 +813,7 @@ pub struct TextSearchOreMatchQuery { pub v: SchemaVersion, #[stash(context_field)] pub i: Identifier, - pub bf: BloomFilter, + pub bf: QueryBloomFilter, } impl From for TextSearchOreQuery { fn from(query: TextSearchOreMatchQuery) -> Self { @@ -846,7 +848,7 @@ pub struct TextSearchQuery { #[schemars(with = "Option")] pub op: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] - pub bf: Option, + pub bf: Option, } impl DomainType for TextSearchQuery { fn sql_domain_static() -> &'static str { @@ -936,7 +938,7 @@ pub struct TextSearchMatchQuery { pub v: SchemaVersion, #[stash(context_field)] pub i: Identifier, - pub bf: BloomFilter, + pub bf: QueryBloomFilter, } impl From for TextSearchQuery { fn from(query: TextSearchMatchQuery) -> Self { diff --git a/packages/eql/crates/eql-codegen/src/bindings.rs b/packages/eql/crates/eql-codegen/src/bindings.rs index 528ed013d..1b0d38972 100644 --- a/packages/eql/crates/eql-codegen/src/bindings.rs +++ b/packages/eql/crates/eql-codegen/src/bindings.rs @@ -310,7 +310,7 @@ fn render_query_struct(eql: EqlVersion, family: &DomainFamily, domain: &Domain) fields.extend(quote! { #context pub i: Identifier, }); for term in Term::payload_terms(domain.terms) { let fid = format_ident!("{}", term.json_key()); - let ty = term_type(eql, family, term, term.binding_newtype()); + let ty = term_type(eql, family, term, query_term_newtype(eql, term)); let attrs = term_field_attrs(eql, term, optional); fields.extend(if optional { quote! { @@ -452,8 +452,9 @@ fn render_range_query_struct(family: &DomainFamily, term: Term) -> TokenStream { /// `SearchBloomFilter`, the same JSON as `BloomFilter`, into which Stack /// Encrypt derives the empty filter for text too short for a 3-gram instead /// of refusing it. Such a value is still found by `=` and `<` through its -/// other terms; a query, and `TextMatch`, which has no other term, keep -/// `BloomFilter` and keep refusing that text. +/// other terms. `TextMatch` has no other term, so it keeps `BloomFilter` +/// and keeps refusing that text. A query's filter is `QueryBloomFilter` +/// ([`query_term_newtype`]). `QueryBloomFilter` refuses that text too. pub fn stored_term_newtype(eql: EqlVersion, domain: &Domain, term: Term) -> &'static str { if eql == EqlVersion::V4 && term == Term::Bloom && v4_optional_query_terms(domain) { "SearchBloomFilter" @@ -462,6 +463,20 @@ pub fn stored_term_newtype(eql: EqlVersion, domain: &Domain, term: Term) -> &'st } } +/// The newtype of a query struct's `term` field: the term's own +/// ([`Term::binding_newtype`]). The exception is an EQL v4 match term, whose +/// newtype is `QueryBloomFilter`, with the same JSON as `BloomFilter`. Stack +/// Encrypt derives into it the filter of the tokens a query keeps. A query +/// keeps its two-letter words only when the whole query is one two-letter +/// word. A stored value's filter contains them all. +pub fn query_term_newtype(eql: EqlVersion, term: Term) -> &'static str { + if eql == EqlVersion::V4 && term == Term::Bloom { + "QueryBloomFilter" + } else { + term.binding_newtype() + } +} + /// The Rust type of a struct field carrying `term`, in a struct of /// `family`. An EQL v4 order term is Stack Encrypt's own term over the /// family's plaintext, as [`Term::v4_format`] names it (`OreBlockTerm`, @@ -514,7 +529,7 @@ fn term_field_attrs(eql: EqlVersion, term: Term, optional: bool) -> TokenStream /// What a family module imports for its terms, in first-use order: the /// names it takes from its version's `terms` module, `Ciphertext` first /// (each stored struct's newtype, [`stored_term_newtype`], each query -/// struct's, [`Term::binding_newtype`], and a v4 order term's JSON shape), +/// struct's, [`query_term_newtype`], and a v4 order term's JSON shape), /// and the Stack Encrypt term types it names (`OreBlockTerm`, `OpeTerm`). struct FamilyTerms { terms: Vec<&'static str>, @@ -540,7 +555,7 @@ fn family_terms<'d>(eql: EqlVersion, domains: impl Iterator) } _ => { add(&mut used.terms, stored_term_newtype(eql, d, term)); - add(&mut used.terms, term.binding_newtype()); + add(&mut used.terms, query_term_newtype(eql, term)); } } } @@ -591,7 +606,7 @@ fn render_query_projections( .map(|&term| { let ident = format_ident!("{}", query_projection_ident(family, domain, term)); let fid = format_ident!("{}", term.json_key()); - let tid = term_type(eql, family, term, term.binding_newtype()); + let tid = term_type(eql, family, term, query_term_newtype(eql, term)); let ops = Term::operators_for_terms(domain.terms) .into_iter() .filter(|op| Term::extractor_for_operator(domain.terms, op) == Some(term.extractor())) @@ -1855,9 +1870,10 @@ mod tests { ); } - /// A v4 search domain's stored filter is `SearchBloomFilter`, which takes - /// the empty filter of text too short for a 3-gram; `TextMatch` and every - /// query keep `BloomFilter`, which refuses that text. v3 is untouched. + /// A v4 search domain's stored filter is `SearchBloomFilter`. That type + /// takes the empty filter of text too short for a 3-gram. `TextMatch` keeps + /// `BloomFilter`, and so refuses that text. Every query's filter is + /// `QueryBloomFilter`, built by the query rule. v3 is untouched. #[test] fn a_v4_search_domain_stores_a_filter_that_may_be_empty() { let v4 = render_family_bindings(EqlVersion::V4, family("text")); @@ -1885,18 +1901,23 @@ mod tests { ); assert_eq!( field(&v4, "TextMatchQuery").as_deref(), - Some("pub bf: BloomFilter,") + Some("pub bf: QueryBloomFilter,") ); assert_eq!( field(&v4, "TextSearchMatchQuery").as_deref(), - Some("pub bf: BloomFilter,") + Some("pub bf: QueryBloomFilter,") + ); + assert_eq!( + field(&v4, "TextSearchOreMatchQuery").as_deref(), + Some("pub bf: QueryBloomFilter,") ); assert_eq!( field(&v4, "TextSearchQuery").as_deref(), - Some("pub bf: Option,") + Some("pub bf: Option,") ); let v3 = render_family_bindings(EqlVersion::V3, family("text")); assert!(!v3.contains("SearchBloomFilter")); + assert!(!v3.contains("QueryBloomFilter")); } #[test] diff --git a/packages/eql/crates/eql-codegen/src/targets.rs b/packages/eql/crates/eql-codegen/src/targets.rs index f423f2596..378178d43 100644 --- a/packages/eql/crates/eql-codegen/src/targets.rs +++ b/packages/eql/crates/eql-codegen/src/targets.rs @@ -44,7 +44,8 @@ use quote::{format_ident, quote}; use eql_domains::{Domain, DomainFamily, Shape, Term}; use crate::bindings::{ - encryption_gap, format_rs, plaintext_of, query_projection_ident, stored_payload_domains, + encryption_gap, format_rs, plaintext_of, query_projection_ident, query_term_newtype, + stored_payload_domains, }; use crate::context::v4_optional_query_terms; use crate::render::EqlVersion; @@ -162,23 +163,30 @@ impl IndexKey { } /// The type a query twin stores the index's term in, over the type's - /// plaintext `source`: the EQL newtype of an `hm` or a `bf`, Stack - /// Encrypt's own term of an `op` or an `ob`. + /// plaintext `source`. An `hm` or a `bf` is an EQL newtype + /// ([`query_term_newtype`]). A `bf` is a `QueryBloomFilter`. An `op` or + /// an `ob` is Stack Encrypt's own term. fn twin_term_type(self, source: &syn::Path) -> TokenStream { - match self { - IndexKey::Eq => quote!(Hmac256), - IndexKey::Match => quote!(BloomFilter), - IndexKey::Ope => quote!(OpeTerm<#source>), - IndexKey::OreBlock => quote!(OreBlockTerm<#source>), + match self.term_import() { + TermImport::Newtype(name) => { + let newtype = format_ident!("{name}"); + quote!(#newtype) + } + TermImport::OrderTerm(name) => { + let term = format_ident!("{name}"); + quote!(#term<#source>) + } } } /// The name `answers.rs` imports the twin's term type by, and where - /// from. + /// from. An `hm` or a `bf` is the newtype a query contains + /// ([`query_term_newtype`]): `Hmac256`, or `QueryBloomFilter`. fn term_import(self) -> TermImport { match self { - IndexKey::Eq => TermImport::Newtype("Hmac256"), - IndexKey::Match => TermImport::Newtype("BloomFilter"), + IndexKey::Eq | IndexKey::Match => { + TermImport::Newtype(query_term_newtype(TARGET_VERSION, self.term())) + } IndexKey::Ope => TermImport::OrderTerm("OpeTerm"), IndexKey::OreBlock => TermImport::OrderTerm("OreBlockTerm"), } diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index 76a3dfdcf..6d067113c 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -382,6 +382,28 @@ async fn every_field_query_is_the_term_of_the_row_its_record_stored() { mod assertions { use super::*; + /// A match query's filter sets positions, and the stored filter of the + /// row `row` sets each of them, so the database's `matches` finds the + /// row. + pub(super) fn stored_filter_contains_the_querys( + name: &str, + needle: &str, + query: &serde_json::Value, + row: &serde_json::Value, + ) { + assert_eq!(query["i"], row["i"], "{name} {needle:?}: the same column"); + let asked = query["bf"].as_array().unwrap(); + let stored = row["bf"].as_array().unwrap(); + assert!( + !asked.is_empty(), + "{name} {needle:?}: the query sets a position: {query}" + ); + assert!( + asked.iter().all(|position| stored.contains(position)), + "{name} {needle:?}: the stored filter of {row} contains the query's {query}" + ); + } + /// Two query values for one value carry the same terms: the same JSON, /// save a block ORE `ob`, which carries a random nonce, so two /// derivations of one value differ in their bytes and compare equal. @@ -559,6 +581,141 @@ async fn a_field_reference_match_query_verifies_and_sizes_as_the_data_path_does( } } +/// A field reference's match query keeps its two-letter words only when the +/// whole query is one two-letter word, as the data path's query does. The +/// rule applies to every type with a match index: `TextMatch`, +/// `TextSearch`, and `TextSearchOre`. The twins of the last two contain the +/// equality and order terms beside the match term. +/// +/// - "Ng" is its word. The query does not find "Nguyen". +/// - "Mike Ng" and "ke Ng" are their 3-grams. Both find "Mike Nguyen". +mod given_a_two_letter_word_in_a_match_query { + use super::*; + + /// The types with a match index, each with the column its field + /// reference on `EncryptedColumns` names. + const MATCH_TYPES: [(&str, &str); 3] = [ + ("TextMatch", "text_match"), + ("TextSearch", "text_search"), + ("TextSearchOre", "text_search_ore"), + ]; + + /// The rows each query is verified against. + const PAGE: [&str; 5] = ["Ng", "Mike Ng", "Mike Nguyen", "Nguyen", "Mike"]; + + /// Each query, and which rows of [`PAGE`] it keeps. + const QUERIES: [(&str, [bool; 5]); 3] = [ + ("Ng", [true, true, false, false, false]), + ("Mike Ng", [false, true, true, false, false]), + ("ke Ng", [false, true, true, false, false]), + ]; + + /// The field reference's match query of `needle` on the type `name`, as + /// it binds, and its verdict on each row of [`PAGE`]. + async fn field_query(keyset: &Keyset<'_>, name: &str, needle: &str) -> (Vec, Vec) { + macro_rules! cut { + ($reference:expr) => {{ + let query = $reference.matches(needle).encrypt(keyset).await.unwrap(); + ( + serde_json::to_vec(&query).unwrap(), + PAGE.iter().map(|row| query.verify(row)).collect(), + ) + }}; + } + match name { + "TextMatch" => cut!(EncryptedColumns::TEXT_MATCH), + "TextSearch" => cut!(EncryptedColumns::TEXT_SEARCH), + "TextSearchOre" => cut!(EncryptedColumns::TEXT_SEARCH_ORE), + other => panic!("{other} has no match index"), + } + } + + /// A stored record whose match fields all contain "Mike Nguyen". + async fn scenario(keyset: &Keyset<'_>) -> EncryptedColumns { + Columns { + text_match: "Mike Nguyen".into(), + text_search: "Mike Nguyen".into(), + text_search_ore: "Mike Nguyen".into(), + ..columns() + } + .encrypt_into(keyset) + .await + .unwrap() + } + + #[tokio::test] + async fn the_field_query_verifies_by_the_query_rule() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + for (name, _) in MATCH_TYPES { + for (needle, want) in QUERIES { + let (_, verdicts) = field_query(&keyset, name, needle).await; + assert_eq!( + verdicts, want, + "{name} {needle:?}: verifies by the query's rule" + ); + } + } + } + + #[test] + fn the_data_path_verifies_alike() { + for (name, column) in MATCH_TYPES { + let plan = data_plan(name, column); + for (needle, want) in QUERIES { + let data = dynamic::verify( + &plan, + "value", + Op::Matches, + frame(needle), + PAGE, + &EqlTargets, + ) + .unwrap(); + assert_eq!( + data, want, + "{name} {needle:?}: the data path verifies alike" + ); + } + } + } + + #[tokio::test] + async fn the_field_query_is_the_data_paths_bytes() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + for (name, column) in MATCH_TYPES { + for (needle, _) in QUERIES { + let (typed, _) = field_query(&keyset, name, needle).await; + let (data, _) = data_term(&cipher, name, column, Op::Matches, frame(needle)).await; + assert_eq!( + typed, data, + "{name} {needle:?}: the data path sends the same filter" + ); + } + } + } + + #[tokio::test] + async fn a_partly_typed_name_finds_the_stored_full_name() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored = scenario(&keyset).await; + for (name, column) in MATCH_TYPES { + for needle in ["Mike Ng", "ke Ng"] { + let (typed, _) = field_query(&keyset, name, needle).await; + let query: serde_json::Value = serde_json::from_slice(&typed).unwrap(); + assertions::stored_filter_contains_the_querys( + name, + needle, + &query, + &stored_field(&stored, column), + ); + } + } + } +} + /// A field query refuses what the data path refuses: match text that cuts /// no token is no query, by either path. /// @@ -908,6 +1065,7 @@ async fn a_scoped_field_query_finds_a_value_stored_under_the_same_scope() { .twin() .bf .0 + .0 .iter() .all(|position| stored.name.bf.0.contains(position)), "the stored filter contains the query's" @@ -923,6 +1081,7 @@ async fn a_scoped_field_query_finds_a_value_stored_under_the_same_scope() { .twin() .bf .0 + .0 .iter() .all(|position| stored.name.bf.0.contains(position)), "under another scope the filter differs" diff --git a/packages/eql/tests/encryption/tests/v4_types.rs b/packages/eql/tests/encryption/tests/v4_types.rs index ad62e1a9e..6f48852ec 100644 --- a/packages/eql/tests/encryption/tests/v4_types.rs +++ b/packages/eql/tests/encryption/tests/v4_types.rs @@ -920,7 +920,7 @@ async fn text_match_filters_contain_their_substrings() { .await .unwrap(); assert_eq!( - positions(&query.bf).is_subset(&all), + positions(&query.bf.0).is_subset(&all), contained, "{needle:?} in Alice@Example.com" ); @@ -972,7 +972,7 @@ async fn two_letter_surnames_store_and_are_found() { .await .unwrap_or_else(|error| panic!("{surname:?} is a query: {error}")); assert_eq!( - query.bf, bare.bf, + query.bf.0, bare.bf, "{surname:?}: the query's filter is the stored one's" ); let full: text::TextMatch = format!("Mike {surname}") @@ -980,7 +980,7 @@ async fn two_letter_surnames_store_and_are_found() { .await .unwrap(); assert!( - positions(&query.bf).is_subset(&positions(&full.bf)), + positions(&query.bf.0).is_subset(&positions(&full.bf)), "{surname:?} is found in \"Mike {surname}\"" ); let longer: text::TextMatch = format!("Mike {surname}ward") @@ -988,7 +988,7 @@ async fn two_letter_surnames_store_and_are_found() { .await .unwrap(); assert!( - !positions(&query.bf).is_subset(&positions(&longer.bf)), + !positions(&query.bf.0).is_subset(&positions(&longer.bf)), "{surname:?} is not found in \"Mike {surname}ward\"" ); let named: text::TextMatch = by_name(&keyset, "TextMatch", frame(surname)).await; @@ -999,6 +999,98 @@ async fn two_letter_surnames_store_and_are_found() { } } +/// A query keeps its two-letter words only when the whole query is one +/// two-letter word. The rule applies to every path that builds a query: the +/// query twins directly (`TextMatchQuery`, `TextSearchMatchQuery`), and the +/// by-name query dispatch that a binding runs. +/// +/// - "Mike Ng" is its 3-grams alone, and finds "Mike Nguyen". +/// - A name typed in part, such as "ke Ng" or "san fr", finds its row. +/// - "Ng" alone is its word token. The query does not find "Nguyen". +/// +/// Stored values do not change. Each still contains its word tokens. +#[tokio::test] +async fn a_query_keeps_its_two_letter_words_only_when_it_cuts_no_trigram() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored = |text: &'static str| { + let keyset = &keyset; + async move { + let value: text::TextMatch = text + .to_owned() + .encrypt_into_with_context(keyset, column()) + .await + .unwrap(); + positions(&value.bf) + } + }; + for (needle, text, found) in [ + ("Ng", "Ng", true), + ("Ng", "Mike Ng", true), + ("Ng", "Mike Nguyen", false), + ("Mike Ng", "Mike Ng", true), + ("Mike Ng", "Mike Nguyen", true), + ("Mike Ng", "Mike Ngo", true), + ("Mike Ng", "Ng", false), + ("ke Ng", "Mike Ng", true), + ("san fr", "San Francisco", true), + ] { + let row = stored(text).await; + let matched: text::TextMatchQuery = needle + .to_owned() + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap(); + let search: text::TextSearchMatchQuery = needle + .to_owned() + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap(); + assert_eq!( + search.bf, matched.bf, + "{needle:?}: one filter for both query twins" + ); + let bytes = targets::query( + "TextMatch", + &stack_encrypt::target::IndexSpec::parse("match").unwrap(), + &keyset, + &label(), + frame(needle), + ) + .unwrap() + .await + .unwrap(); + let named: text::TextMatchQuery = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + named.bf, matched.bf, + "{needle:?}: the dispatch derives the same filter" + ); + assert_eq!( + positions(&matched.bf.0).is_subset(&row), + found, + "{needle:?} on {text:?}" + ); + } + // A query of 3-grams has no word token. The query's filter is the filter + // of its 3-grams. A stored value of the same text contains them beside its + // words. + let query: text::TextMatchQuery = "Mike Ng" + .to_owned() + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap(); + let sent = positions(&query.bf.0); + let whole = stored("Mike Ng").await; + assert!( + sent.is_subset(&whole) && sent != whole, + "\"Mike Ng\" sends part of the filter it stores" + ); + assert!( + !stored("Ng").await.is_subset(&sent), + "and not its word's token" + ); +} + /// Common two-letter surnames. const SURNAMES: &[&str] = &[ "Ng", "Li", "Wu", "Le", "Do", "Ho", "Yu", "Lu", "Ma", "Xu", "Hu", "Su", "Oh", "Ko", "An", "Ye", @@ -1018,7 +1110,7 @@ async fn text_match_filter_positions_are_pinned() { .await .unwrap(); // 3 tokens ("ali", "lic", "ice") at 6 positions each, de-duplicated. - assert_eq!(query.bf.0, PINNED_ALICE); + assert_eq!(query.bf.0 .0, PINNED_ALICE); } const PINNED_ALICE: [i16; 18] = [ @@ -1110,9 +1202,10 @@ async fn a_value_of_another_kind_is_refused_not_converted() { } /// Needs an EQL v4 installation. Two-letter surnames in a `TextMatch` and a -/// `TextSearch` column: `@@` with the query of the surname finds the rows -/// holding it as a word, bare or in a full name, and not a longer name it -/// begins; a full-name query needs its two-letter word whole. +/// `TextSearch` column. `@@` with the query of the surname finds the rows +/// that contain it as a whole word, such as "Ng" and "Mike Ng". The query +/// does not find a longer name that the surname begins. A full-name query +/// is its 3-grams, so it finds a longer name too. #[test] #[ignore = "requires EQL_TEST_DATABASE_URL pointing to an EQL v4 database"] fn postgres_finds_two_letter_surnames() { @@ -1202,7 +1295,8 @@ fn postgres_finds_two_letter_surnames() { for (needle, want) in [ ("ng", vec![1, 2, 6]), ("Ng", vec![1, 2, 6]), - ("Mike Ng", vec![2]), + ("Mike Ng", vec![2, 4]), + ("ke Ng", vec![2, 4]), ("Nguyen", vec![3, 4]), ("li", vec![5]), ("Wei", vec![5]), diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 62e2e3bcd..fe57fdcac 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,6 +481,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **`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 + sends. `Index::operation` still derives the term that a stored value + contains. + - `Indexes::query_operations` derives the query term of every index in + the set, in one batch. + + To upgrade: + 1. In each index you define, add `query_operation`. If the index sends + the term it stores, return the same description as `operation`. If + the index wraps another index, call that index's `query_operation`. + 2. In each set of indexes you define, add `query_operations`. Build it + from each index's `query_operation`. + + Neither method has a default, on purpose. A default that returned the + stored term would let an index that wraps a match index forward only + `operation`. That index would compile. The index's queries would then + send the stored value's tokens, and miss rows. No stored byte changes. + - **Seven `PlanError` variants that nothing raised are removed** (#1671). Only the plan builder and `plan::all` raised them, and both are gone, so no call returned them: `IdentityWithoutField`, `IndexNotDeclared`, @@ -1362,6 +1382,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **With `MatchOptions::short_words` on, a query asks for its short words + only when its whole text is shorter than one n-gram** (#1398). Before + this fix, "Mike Ng" did not find "Mike Nguyen". "san fr" did not find + "San Francisco" either. + + An n-gram is a run of n characters in a row, such as "mik" in "Mike" + under trigrams. A short word is a word shorter than one n-gram, such as + "Ng" under trigrams. A stored value contains each short word as a + whole-word token, beside its n-grams. Before this fix, a query also asked + for each of its short words as a whole word. "Nguyen" contains "ng" only + inside a longer word, so "Mike Ng" missed "Mike Nguyen". + + Now a query with an n-gram asks for its n-grams alone, as it does with + the option off. A query shorter than one n-gram asks for its short + words. Under trigrams, that is one short word: "Ng" finds "Ng" and "Mike + Ng", and not "Nguyen". Under longer n-grams it can be several words, + such as "Ng Wu" under 6-grams. + - Stored values do not change. No stored filter moves, so nothing needs + re-encrypting. + - Every query path uses the one rule, so a query's filter and its verify + agree. The paths are a field query (`Supports::prepare` and the term + it derives), `dynamic::query_term`, `dynamic::term`, `dynamic::verify`, + and `MatchQuery::verify`. + - A field query derives its term through the new `Index::query_operation` + (see Breaking). A match index returns the new `target::matching_query`. + That function builds the query's filter. Every other index returns its + `operation`. An index that wraps another forwards both methods. + - A set of indexes derives a query's terms through the new + `Indexes::query_operations`. The method calls each index's + `query_operation`, as `Indexes::operations` calls each index's + `operation`. One index, a tuple, and a `Vec` implement it. + - `target::matching_query` refuses text that keeps no token, with + `TermError::EmptyTermText`, because an empty filter would match every + row. So when you call it on its own, it refuses the text that a field + query's `prepare` refuses. `target::matching` still stores such text as + the empty filter. + - What the option reveals: one more token per short word, in every + stored value that contains one. The token is unique to the word. + Someone can tell the rows that contain "Ng" from the rows that contain + "Nguyen", and count them. A query shorter than one n-gram shows the + word tokens it asks for. A query with an n-gram sends no word token. - **The JSON path grammar is its own crate, `stack-encrypt-jsonpath`** (#1687). `JsonPath`, `Segment` and `JsonPathError` moved there unchanged, so that the derive can parse a field's declared paths at compile time @@ -1423,6 +1484,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 descriptor without it is taken to carry the answering index's term alone, as before. +- **An empty `Vec` of indexes now wipes an owned plaintext when it + refuses it** (#1398). `Indexes::operations` and + `Indexes::query_operations` refuse an empty `Vec` with + `PlanError::EmptyIndexes`. In `Owned` mode, that refusal dropped the + plaintext without wiping it. Now the refusal releases the plaintext as + an operation does. The refusal wipes an owned value, and leaves a + borrowed value with the caller. + - **`Pending::zip` and `Pending::all` wipe the plaintext they recovered before a later failure** (#1666). When one decrypt in a batch failed after its key arrived, for example with the wrong context or another 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 19c4eef5c..6b69068b9 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 @@ -208,6 +208,22 @@ cannot tell which they are producing. > differs from the stored term, and ADR-0009 makes the operator, not the > index, the thing a caller names. +> **Amended 2026-11-23 (#1398).** Do not use `KeysetCipher::match_terms` +> to build a match query when the field's match index has +> `MatchOptions::short_words` on. Build the query from the field's +> reference, or with `target::matching_query`. +> +> With short words on, `match_terms` returns what a stored value holds: +> 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". A query keeps its +> short words only when its whole text is shorter than one n-gram, such as +> "Ng" on its own. +> +> This amendment changes decision 5 above. `match_terms` is no longer the +> query path for a match index. ADR-0009's amendment of the same date gives +> the full rule. + ### 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 c55b00824..956b2d7a1 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 @@ -1325,3 +1325,63 @@ the parser, as `passthrough_with_outputs` and `outputs_with_target`. Where decision 1 and decision 7 write `.via(Ore)` and `.via(Ope)`, read: the index the field declares for the operator. + +## Amended 2026-11-23 (#1398) + +A match query no longer asks for every token of the stored value of the +same text. So each index now states the term a query sends, beside the +term a value stores. This section uses three terms: + +- An **n-gram** is a run of n characters in a row. Under trigrams, "Mike" + gives "mik" and "ike". +- A **short word** is a word shorter than one n-gram, such as "Ng" under + trigrams. +- A **token** is one item a match filter records: an n-gram, or a short + word as a whole word. + +The changes: + +- **A query keeps its short words only when its whole text is shorter than + one n-gram.** With `MatchOptions::short_words` on, a stored value + contains every n-gram and each short word as a whole word. If a query + also asked for its short words, a row would need each one as a whole + word. "Mike Ng" would then miss "Mike Nguyen". "Nguyen" contains "ng" + only inside a longer word. So a query with an n-gram asks for its + n-grams alone. A query shorter than one n-gram asks for its short words: + "Ng" under trigrams, or "Ng Wu" under 6-grams. + + The stored value does not change. The rule is in one place, the + tokenizer. Every query path goes through it: the typed verifier, the + field query, and the `dynamic` query, term, and verify paths. The + leakage is one token per short word in every stored value that contains + one. +- **`Index` has two required methods: `operation` and `query_operation`.** + `operation` derives the term a value stores. `query_operation` derives + the term a query sends, and a field query calls it. Most indexes return + the same description from both. `Match` returns + `target::matching_query`, the filter of the tokens a query keeps. + + Neither method has a default. A default of `operation` would let an + index that wraps another forward only `operation`. That index would + compile, send the stored value's tokens as its query, and miss rows. So + an index that wraps another forwards both methods. An example is + eql-bindings' `TwinIndex`. +- **`Indexes` has a required `query_operations` beside `operations`.** The + method derives each index's `query_operation` in one batch, as + `operations` derives each `operation`. One index, a tuple, and a `Vec` + implement it. +- **`target::matching_query` builds a query's filter on its own.** The + function refuses text that keeps no token, with + `TermError::EmptyTermText`, because an empty filter would match every + row. So a caller outside a field query gets the same refusal as a field + 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. +- **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 + Schema. The `EncryptTarget` of `QueryBloomFilter` derives the filter + through `matching_query`. So every way of building a query twin follows + the one rule: directly, from a field reference, or through the by-name + query dispatch. diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 90fd1b3f9..d1576ca05 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -87,7 +87,7 @@ use super::{ ValueFrame, }; use crate::op::{Limit, Stats}; -use crate::sem::{match_limit, MatchOptions, QueryTokens, TermError}; +use crate::sem::{match_limit, MatchOptions, QueryTokens, Side, TermError}; use crate::target::IndexSpec; use crate::{KeysetCipher, Pending}; use vitaminc_aead::plaintext::{Logical, Physical}; @@ -1153,7 +1153,8 @@ pub fn query_term<'a, K: 'static>( } let context = answer.field.context(); let term = |value: &ValueFrame| { - derive(cipher, value, &answer.index, context.clone()).map_err(|error| error.in_field(field)) + derive(cipher, value, &answer.index, context.clone(), Side::Query) + .map_err(|error| error.in_field(field)) }; Ok(match input { Input::One(value) => { diff --git a/packages/stack-encrypt/src/dynamic/term.rs b/packages/stack-encrypt/src/dynamic/term.rs index af96b53b7..805797eaf 100644 --- a/packages/stack-encrypt/src/dynamic/term.rs +++ b/packages/stack-encrypt/src/dynamic/term.rs @@ -50,7 +50,7 @@ use super::{Error, Reason}; use crate::json::{JsonOptions, JsonPath}; use crate::sem::{ ope, order_error, order_pending, ore, ore_block, ore_block_error, target_of, DefaultMatch, - MatchOptions, TermError, Tokenizer, + MatchOptions, Side, TermError, Tokenizer, }; use crate::target::{ chosen, CallerContext, Encryption, Index, IndexSpec, Pending, Source, WipeSource, @@ -415,7 +415,12 @@ impl TryFrom for MatchWire { } } -/// Derive one index term's frozen byte encoding. +/// Derive one index term's frozen byte encoding, as a query sends it. A +/// match term keeps the tokens a query keeps. With +/// [`short_words`](MatchOptions::short_words) on, the value's short words +/// are tokens only when its whole text is shorter than one n-gram. So the +/// term of "Mike Ng" is its trigrams alone. The record path stores the word +/// token beside them. /// /// # Examples /// @@ -485,7 +490,7 @@ where // as it is, not re-framed, so every scalar `defines` takes is one a // probe takes. prepare_probe(kind, value.lend())?; - derive(cipher, value, kind, context)? + derive(cipher, value, kind, context, Side::Query)? .await .map(TermBytes::into_bytes) .map_err(Error::Cipher) @@ -555,8 +560,10 @@ impl AsRef<[u8]> for TermBytes { } } -/// Walk `value` to its one scalar and derive `kind`'s term there. Nothing -/// is requested: a term is derived by the keyset cipher's own PRF, so the +/// Walk `value` to its one scalar and derive `kind`'s term there, for +/// `side` ([`Side`]). A stored value's term and a query's term differ only +/// for a match index with short words on. Nothing is +/// requested: a term is derived by the keyset cipher's own PRF, so the /// pending is ready when it is built. /// /// # Errors @@ -571,6 +578,7 @@ pub(super) fn derive<'a, 'c, K: 'static, P, D>( value: P, kind: &IndexSpec, context: NonEmpty, + side: Side, ) -> Result, Error> where P: Encrypt, @@ -579,7 +587,7 @@ where value .visit(OneScalar::new( |ty: Option, value: Physical<'_>| { - scalar_term(cipher, kind, ty, value, context) + scalar_term(cipher, kind, ty, value, context, side) }, )) .map_err(|refused| { @@ -601,6 +609,7 @@ fn scalar_term<'a, 'c, K: 'static, D>( ty: Option, value: Physical<'_>, context: NonEmpty, + side: Side, ) -> Result, Option> where D: IntoPrfContext<'c>, @@ -621,7 +630,7 @@ where return Err(None); }; Ok(cipher - .match_terms_under::(text, context, options.clone()) + .match_terms_under::(text, context, options.clone(), side) .map(|terms| TermBytes(terms.to_bytes()))) } IndexSpec::Ore => order_of(cipher, OrderIndex::Ore, ty, value, context).ok_or(None), @@ -924,23 +933,36 @@ impl Index for IndexSpec { fn operation<'s, K: 'static, M: WipeSource<'s, ValueFrame>>( &self, ) -> Encryption<'s, ValueFrame, TermBytes, K, CallerContext, M> { - let spec = self.clone(); - chosen( - move |source: Source<'_, ValueFrame>, cipher, cx: CallerContext| { - // A term derives under the query context: the scopes, with no - // binding. - let (query, stored) = (cx.query(), cx.stored()); - let context = match cx.validated() { - Ok(context) => CallerContext::query_nonempty(context), - Err(error) => return Pending::failed(cipher, error), - }; - match derive(cipher, source.view(), &spec, context) { - Ok(pending) => pending.under_context(query, stored), - Err(error) => Pending::failed(cipher, error.into_crate()), - } - }, - ) + spec_operation(self.clone(), Side::Stored) } + fn query_operation<'s, K: 'static, M: WipeSource<'s, ValueFrame>>( + &self, + ) -> Encryption<'s, ValueFrame, TermBytes, K, CallerContext, M> { + spec_operation(self.clone(), Side::Query) + } +} + +/// The description that derives `spec`'s term of a [`ValueFrame`] for +/// `side`: [`derive`], under the query context. +fn spec_operation<'s, K: 'static, M: WipeSource<'s, ValueFrame>>( + spec: IndexSpec, + side: Side, +) -> Encryption<'s, ValueFrame, TermBytes, K, CallerContext, M> { + chosen( + move |source: Source<'_, ValueFrame>, cipher, cx: CallerContext| { + // A term derives under the query context: the scopes, with no + // binding. + let (query, stored) = (cx.query(), cx.stored()); + let context = match cx.validated() { + Ok(context) => CallerContext::query_nonempty(context), + Err(error) => return Pending::failed(cipher, error), + }; + match derive(cipher, source.view(), &spec, context, side) { + Ok(pending) => pending.under_context(query, stored), + Err(error) => Pending::failed(cipher, error.into_crate()), + } + }, + ) } #[cfg(test)] @@ -2079,9 +2101,13 @@ mod tests { assert_ne!(wide, default, "other options derive other terms"); } - /// The data path derives a short-word index's term as the typed - /// path does, and "Ng", which cuts nothing under the default - /// options, is one token under them. + /// The data path derives a short-word index's query term by the + /// query rule. "Ng" has no token under the default options, and one + /// token with short words on. "Ng" has no trigram, so its query is + /// its word token: the filter of a stored "Ng". "Mike Ng" has + /// trigrams, so its query is its trigrams alone. That is the filter + /// the index stores without the option, not the one a stored "Mike + /// Ng" has with it. #[tokio::test] async fn short_words_drive_the_derivation() { struct ShortWords; @@ -2096,21 +2122,82 @@ mod tests { let options = ::options(); let cipher = cipher().await; let keyset = cipher.default_keyset(); - for text in ["Ng", "Mike Ng"] { - let data = term( - &keyset, - &s(text), - &IndexSpec::Match(options.clone()), - ctx("users/x"), - ) + let probe = |text: &'static str| { + let keyset = &keyset; + let index = IndexSpec::Match(options.clone()); + async move { + term(keyset, &s(text), &index, ctx("users/x")) + .await + .expect("a query") + } + }; + let stored = |text: &'static str| { + let keyset = &keyset; + async move { + keyset + .match_terms::(text, nonempty!("users/x")) + .await + .expect("stored") + .to_bytes() + } + }; + assert_eq!( + probe("Ng").await, + stored("Ng").await, + "\"Ng\" is its word token, the filter it stores" + ); + let trigrams = keyset + .match_terms::("Mike Ng", nonempty!("users/x")) .await - .expect("a short word is a query"); - let typed = keyset - .match_terms::(text, nonempty!("users/x")) - .await - .expect("typed"); - assert_eq!(data, typed.to_bytes(), "{text:?}: the typed config's bytes"); - } + .expect("stored without the option") + .to_bytes(); + assert_eq!( + probe("Mike Ng").await, + trigrams, + "\"Mike Ng\" is its trigrams alone" + ); + assert_ne!( + probe("Mike Ng").await, + stored("Mike Ng").await, + "and not the stored filter, which holds the word token too" + ); + // The index as a description: `operation` derives a stored + // value's filter, and `query_operation` a field query's filter. + // The field query's filter has the bytes `term` returns above. + let index = IndexSpec::Match(options.clone()); + let run = |query: bool| { + let keyset = &keyset; + let operation = if query { + Index::::query_operation::( + &index, + ) + } else { + Index::::operation::( + &index, + ) + }; + async move { + keyset + .run( + operation, + vf(s("Mike Ng")), + CallerContext::from(nonempty!("users/x")), + ) + .await + .expect("derives") + .into_bytes() + } + }; + assert_eq!( + run(true).await, + trigrams, + "the index's query description cuts a query" + ); + assert_eq!( + run(false).await, + stored("Mike Ng").await, + "the index's own description cuts a stored value" + ); let refused = term(&keyset, &s("Ng"), &default_match(), ctx("users/x")).await; assert!( matches!( diff --git a/packages/stack-encrypt/src/op/mod.rs b/packages/stack-encrypt/src/op/mod.rs index 9485a63f5..8a9370a49 100644 --- a/packages/stack-encrypt/src/op/mod.rs +++ b/packages/stack-encrypt/src/op/mod.rs @@ -511,8 +511,9 @@ pub trait Input: Sized + 'static { /// The index's terms for this input: one, or a pair of them. type Terms: 'static; - /// Derive the index's term for each plaintext of the input under - /// `label`, as one pending. Only a field query calls this. + /// Derive the term a query sends for each plaintext of the input + /// ([`Index::query_operation`]) under `label`, as one pending. Only a + /// field query calls this. #[doc(hidden)] fn derive<'a, 'p, I, K>( self, @@ -543,7 +544,7 @@ impl Input for S { { keyset.run( index - .operation::() + .query_operation::() .under_field(NonEmpty::from(label)), self, extend, @@ -570,14 +571,14 @@ impl Input for (S, S) { let (lo, hi) = self; let lo = keyset.run( index - .operation::() + .query_operation::() .under_field(NonEmpty::from(label.clone())), lo, extend.clone(), ); let hi = keyset.run( index - .operation::() + .query_operation::() .under_field(NonEmpty::from(label)), hi, extend, diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index 9c2f15588..c8bf0682e 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -87,15 +87,20 @@ //! filter, which shows that it is empty, separator-only or too short for //! any token. //! -//! With [`MatchOptions::short_words`] on, each word shorter than the n-gram -//! length (and at least 2 characters) adds one token: the word itself, under -//! the same PRF and a domain of its own, folded into the same filter by the -//! same `k` positions and matched by the same containment rule. That is one -//! extra token per short word and no new class of leakage. The token is -//! specific to the word, so someone who clusters tokens across rows can tell -//! the rows holding the word "Ng" from those holding "Nguyen", where before -//! only the boundary trigram `" ng"` they share was visible. No bigram of a -//! longer word is ever indexed. +//! With [`MatchOptions::short_words`] on, a stored value's filter gains one +//! token for each short word. A short word is shorter than one n-gram, and +//! at least 2 characters long. The word token is the whole word, derived +//! under the same PRF in a domain of its own. The token sets the same `k` +//! positions in the same filter, and matches by the same containment rule. +//! +//! The word token is unique to the word. Someone who clusters tokens across +//! rows can tell the rows that contain the word "Ng" from the rows that +//! contain "Nguyen". Without the option, they see only the trigram `" ng"` +//! that both share. No bigram of a longer word is indexed. +//! +//! A query sends its word tokens only when its whole text is shorter than +//! one n-gram, such as "Ng" under trigrams. A longer query, such as "Mike +//! Ng", sends its n-grams alone, as it does with the option off. //! //! This is a fresh (v2) term format: PRF inputs are framed with vitaminc's PAE //! context encoding, so terms are intentionally **not** byte-compatible with @@ -163,6 +168,7 @@ pub(crate) mod query; mod tokenize; +pub(crate) use tokenize::Side; pub use tokenize::Tokenizer; use std::fmt; @@ -718,22 +724,38 @@ pub struct MatchOptions { /// /// The word token is PRF'd under a domain of its own, so it never /// derives the bits of an n-gram of the same characters, and folds into - /// the same filter by the same `k` positions. Stored, "Ng" is one token - /// rather than the empty filter, and "Mike Ng" carries its trigrams and - /// `ng`. Queried, "Ng" is one token and is accepted, and "Mike Ng" asks - /// for its trigrams and `ng`: every short word of a query must be a - /// whole word of the row, so "Mike Ng" does not find "Mike Nguyen", - /// which it would with the option off. A query that cuts nothing at all, - /// such as one letter, is still refused - /// ([`TermError::EmptyTermText`]). + /// the same filter by the same `k` positions. A stored "Ng" is one + /// token, not the empty filter. A stored "Mike Ng" contains its trigrams + /// and `ng`. + /// + /// A query asks for its word tokens only when its whole text is shorter + /// than one n-gram. Under trigrams, that is a query of one short word. + /// Under longer n-grams it can be several words: under 6-grams, "Ng Wu" + /// asks for both. A longer query asks for its n-grams alone, as it does + /// with the option off. + /// + /// - "Ng" is accepted, and asks for the word token `ng`. The query finds + /// the rows that contain the word "Ng", such as "Ng" and "Mike Ng". + /// The query does not find "Nguyen". + /// - "Mike Ng" asks for its trigrams alone. The query finds "Mike Ng" + /// and "Mike Nguyen", so a name typed in part still finds its row. + /// - "Li Wu" also asks for its trigrams. Some of them span the space. + /// - A query with no token at all, such as one letter, is refused + /// ([`TermError::EmptyTermText`]). /// - /// **What it reveals.** One more token per short word, under the same - /// PRF, in the same filter, matched by the same containment rule, so - /// there is no new class of leakage. The token is specific to the word: - /// someone who clusters tokens across rows can tell the rows holding the - /// word "Ng" from those holding "Nguyen", where before only the boundary - /// trigram `" ng"` they share was visible. Only words shorter than an - /// n-gram get one, so no bigram of a longer word is ever indexed. + /// A query's verify checks the same tokens the query asks for, so its + /// filter and its verify agree. + /// + /// **What it reveals.** Each stored value gains one token for each short + /// word it contains. The token uses the same PRF, the same filter, and + /// the same containment rule. Only a word shorter than one n-gram gets a + /// token, so no bigram of a longer word is indexed. + /// + /// The word token is unique to the word. Someone who clusters tokens + /// across rows can tell the rows that contain the word "Ng" from the rows + /// that contain "Nguyen", and count them. Without the option, they see + /// only the trigram `" ng"` that both share. A query of short words alone + /// shows which word tokens it asks for. /// /// It takes an n-gram tokenizer of length at least 3: the /// [`Standard`](Tokenizer::Standard) tokenizer already emits whole words, @@ -806,12 +828,20 @@ 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. A filter derived directly, with -/// [`match_terms`](crate::KeysetCipher::match_terms) or a `Match` the -/// caller names, is cut under whatever configuration it is given, and -/// matches a stored filter only when that configuration is the field's. A -/// plan that is data has one match index per field, and its stored filter -/// and its query both read that index's options. +/// 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. +/// +/// `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 plan that is data has one match index per field. The plan's stored +/// filter and its query both read that index's options. pub trait MatchConfig: Send + Sync + 'static { fn options() -> MatchOptions; @@ -1165,13 +1195,21 @@ impl RangeQuery { pub struct QueryTokens(Zeroizing); impl QueryTokens { - /// The tokens of `text` under `options`' tokenizer and case folding. + /// The tokens a query of `text` keeps. `options` sets the tokenizer and + /// the case folding. The query keeps its short words only when its whole + /// text is shorter than one n-gram ([`Side::Query`]). The filter a query + /// sends is built from the same tokens. So a query verifies a row by + /// exactly the tokens it asks for. /// /// # Errors /// - /// As for [`of`](Self::of). + /// [`TermError::Normalize`] for text with no normal form. pub(crate) fn under(text: &str, options: &MatchOptions) -> Result { - Ok(Self(Zeroizing::new(tokenize::tokens(text, options)?))) + Ok(Self(Zeroizing::new(tokenize::tokens( + text, + options, + Side::Query, + )?))) } /// The tokens of a query's `text` under `options`, or why the query is @@ -1194,12 +1232,14 @@ impl QueryTokens { /// Whether `value` holds every one of these tokens, cut under the same /// `options` the tokens were: what [`MatchQuery`]'s `verify` asks, with /// the options a value rather than a type, so a match index declared as - /// data verifies by the same code. Each kind is held by its own kind: a + /// data verifies by the same code. The value is split into tokens as it + /// is stored, with every token of both kinds. Each kind is held by its + /// own kind: a /// short-word token of the query must be a short word of the value. No /// tokens verify nothing, and a value the index cannot normalize holds /// no token of any query. pub(crate) fn verify(&self, value: &str, options: &MatchOptions) -> bool { - let Ok(tokens) = tokenize::tokens(value, options) else { + let Ok(tokens) = tokenize::tokens(value, options, Side::Stored) else { return false; }; let tokens = Zeroizing::new(tokens); @@ -1272,33 +1312,44 @@ impl PrfVisitor<[u8; 32], P> for BloomVisitor { } } -/// Derive a match term. Synchronous — see [`equality`]: validation and -/// tokenization run before the PRF, the visitor folds blocks into positions. -/// The tokenizer's tokens derive under [`MATCH_DOMAIN`] and the short-word -/// tokens under [`MATCH_WORD_DOMAIN`], each bound to `context`, and both -/// fold into the one filter. +/// Derive the match term of `text` for `side` ([`Side`]): a stored value's +/// filter, or a query's. +/// +/// Synchronous, as [`equality`] is. The text is checked and split into +/// tokens before the PRF runs. The visitor then folds the PRF's blocks into +/// positions. The tokenizer's tokens derive under [`MATCH_DOMAIN`], and the +/// short-word tokens under [`MATCH_WORD_DOMAIN`]. Each is bound to +/// `context`, and both set positions in the one filter. /// -/// Text that cuts no token (empty, separator-only, or shorter than the -/// n-gram length with no short word) is the empty filter: no position set, -/// no PRF call. Stored, -/// it is a value no query matches, since a query always has at least one -/// token and the empty filter holds none of its positions. This is the -/// *stored* side's answer; a query of such text is refused before it gets -/// here ([`TermError::EmptyTermText`]). +/// Some text has no token: empty text, text of separators only, or text +/// shorter than one n-gram with no short word. +/// +/// - Stored, such text is the empty filter. No position is set. The PRF is +/// not called. No query matches it, since a query always has at least one +/// token. +/// - As a query, such text is refused ([`TermError::EmptyTermText`]), +/// because an empty filter would match every row. A field query refuses +/// it earlier, when the query is prepared. This check refuses it for +/// every other caller that builds a query's filter. fn match_term( prf: &HmacSha256Prf, text: &str, context: Context<'_>, options: MatchOptions, + side: Side, ) -> Result, TermError> { let mask = options.validate()?; // The PRF takes the tokens by value and moves each `String`'s buffer // into a `Protected`, which zeroizes it on drop: the tokens are wiped // there, not here. The `Vec`s themselves hold only their pointers. + let tokens = tokenize::tokens(text, &options, side)?; + if side == Side::Query && tokens.is_empty() { + return Err(TermError::EmptyTermText); + } let tokenize::Tokens { tokenizer, short_words, - } = tokenize::tokens(text, &options)?; + } = tokens; // Held wiped-on-drop until the PRF takes them, so a failure deriving // the tokenizer's tokens does not free the words unwiped. let mut short_words = Zeroizing::new(short_words); @@ -1340,6 +1391,29 @@ fn bloom_positions( .map_err(TermError::from_prf) } +/// The match term of `text` for `side`, through the keyset of `cipher`. The +/// term is derived now if the keyset is loaded, or else once it loads. +/// Under the local HMAC backend, the returned [`Pending`] carries no +/// requests. +fn match_pending<'a, K, O>( + cipher: &'a KeysetCipher<'_, K>, + text: &str, + context: Context<'_>, + options: MatchOptions, + side: Side, +) -> Pending<'a, MatchTerms, K> +where + O: MatchConfig, +{ + match cipher.loaded_state() { + Some(keyset) => { + let term = match_term(&keyset.prf, text, context, options, side).map_err(Error::from); + Pending::ready(cipher, term) + } + None => match_deferred(cipher, text, context, options, side), + } +} + /// The match term of `text`, through a keyset that is not loaded /// yet. The pending keeps a copy of the text, wiped on drop, and derives /// the term when it has loaded the keyset. @@ -1348,6 +1422,7 @@ fn match_deferred<'a, K, O>( text: &str, context: Context<'_>, options: MatchOptions, + side: Side, ) -> Pending<'a, MatchTerms, K> where O: MatchConfig, @@ -1355,10 +1430,35 @@ where let text = Zeroizing::new(text.to_owned()); let context = context.into_owned(); cipher.deferred(move |keyset| { - match_term(&keyset.prf, &text, context, options).map_err(Error::from) + match_term(&keyset.prf, &text, context, options, side).map_err(Error::from) }) } +/// The match term that a query of `source` sends, under `O`'s options. The +/// term is the filter of the tokens the query keeps ([`Side::Query`]). The +/// query's [`QueryTokens`] verify a row by the same tokens. +/// +/// A field query of a match index derives this term, through +/// [`matching_query`](crate::target::matching_query). That function calls +/// this one as [`Term::encrypt_from`] is called. Text that keeps no token +/// is refused ([`TermError::EmptyTermText`]). +pub(crate) fn match_query<'a, 'c, K, O>( + source: impl AsRef, + cipher: &'a KeysetCipher<'_, K>, + context: NonEmpty>, +) -> Pending<'a, MatchTerms, K> +where + O: MatchConfig, +{ + match_pending( + cipher, + source.as_ref(), + context.into_prf_context(), + O::options(), + Side::Query, + ) +} + /// A match term of any text source, generated under `O`'s options. Under /// the local HMAC backend, derived during the synchronous build — the /// returned [`Pending`] carries no requests (tokenize makes the one @@ -1379,15 +1479,13 @@ where where Self: 'a, { - let context = context.into_prf_context().into_owned(); - match cipher.loaded_state() { - Some(keyset) => { - let term = match_term(&keyset.prf, source.as_ref(), context, O::options()) - .map_err(Error::from); - Pending::ready(cipher, term) - } - None => match_deferred(cipher, source.as_ref(), context, O::options()), - } + match_pending( + cipher, + source.as_ref(), + context.into_prf_context(), + O::options(), + Side::Stored, + ) } } @@ -2023,6 +2121,17 @@ order_term! { /// 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)?`, @@ -2078,15 +2187,24 @@ impl KeysetCipher<'_, K> { /// `O`. For custom options, define a marker type implementing /// [`MatchConfig`]. /// - /// This derives the *stored* filter. Text that yields no tokens (empty - /// or separator-only text, or text shorter than the n-gram length; see - /// [`Tokenizer::Ngram`]) is the empty filter, which no query matches, - /// so a short value can be stored. A query is the other type, - /// [`MatchQuery`], and comes from a query - /// (a field reference's `matches(..)`), which refuses a query of such - /// text ([`TermError::EmptyTermText`]) because its filter would match - /// every row; this method does not know which it is deriving and - /// refuses nothing. + /// 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, @@ -2095,7 +2213,7 @@ impl KeysetCipher<'_, K> { where O: MatchConfig + MaybeSend, { - self.match_terms_under(text, descriptor, O::options()) + self.match_terms_under(text, descriptor, O::options(), Side::Stored) } /// [`equality_term`](Self::equality_term) of one scalar the caller has @@ -2123,29 +2241,25 @@ impl KeysetCipher<'_, K> { } } - /// [`match_terms`](Self::match_terms) under runtime options, for the - /// `dynamic` path, whose plan carries a match index's options as data - /// (an `IndexSpec::Match`). Not public: the typed API keeps the options - /// on the type so a stored field and its probe cannot disagree, and a - /// binding reaches this only through a plan that names the options for - /// both. - #[cfg_attr(not(feature = "dynamic"), allow(dead_code))] + /// [`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. + /// + /// 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. pub(crate) fn match_terms_under<'c, O>( &self, text: &str, descriptor: NonEmpty>, options: MatchOptions, + side: Side, ) -> Pending<'_, MatchTerms, K> where O: MatchConfig + MaybeSend, { - match self.loaded_state() { - Some(keyset) => { - let term = match_term(&keyset.prf, text, descriptor.into_prf_context(), options); - Pending::ready(self, term.map_err(Error::from)) - } - None => match_deferred(self, text, descriptor.into_prf_context(), options), - } + match_pending(self, text, descriptor.into_prf_context(), options, side) } /// Generate an order-revealing (CLLW ORE) term for a range-queryable value @@ -2408,6 +2522,197 @@ mod tests { ); } + #[test] + fn a_query_that_cuts_an_ngram_keeps_no_short_word() { + let tokens = QueryTokens::of_query("Mike Ng", &options()).expect("a query"); + assert!( + tokens.0.short_words.is_empty(), + "\"Mike Ng\" keeps its trigrams alone: {:?}", + tokens.0.short_words + ); + assert_eq!( + tokens.0.tokenizer, + ["mik", "ike", "ke ", "e n", " ng"], + "every trigram of the whole text" + ); + for row in ["Mike Ng", "Mike Nguyen", "mike ngo"] { + assert!( + tokens.verify(row, &options()), + "\"Mike Ng\" verifies {row:?}" + ); + } + assert!( + !tokens.verify("Ng", &options()), + "\"Ng\" holds none of its trigrams" + ); + } + + /// The filter a query sends, against the tokens it verifies by. + mod given_a_query_filter { + use super::*; + + fn prf() -> HmacSha256Prf { + HmacSha256Prf::new(Protected::new([7; 32])) + } + + fn context() -> Context<'static> { + Context::from_encoded(&b"users/name"[..]) + } + + /// The filter of `tokens`, each kind under its own domain, as + /// [`match_term`] folds them. + fn filter_of(prf: &HmacSha256Prf, tokens: &tokenize::Tokens) -> MatchTerms { + let mask = options().validate().expect("valid"); + let mut positions = bloom_positions( + prf, + tokens.tokenizer.clone(), + MATCH_DOMAIN, + &context(), + 3, + mask, + ) + .expect("grams"); + positions.extend( + bloom_positions( + prf, + tokens.short_words.clone(), + MATCH_WORD_DOMAIN, + &context(), + 3, + mask, + ) + .expect("words"), + ); + MatchTerms::normalised(positions) + } + + fn derive(text: &str, side: Side) -> MatchTerms { + match_term(&prf(), text, context(), options(), side).expect("derives") + } + + #[test] + fn a_query_of_ngrams_sends_the_filter_of_its_ngrams_alone() { + let query = derive("Mike Ng", Side::Query); + let without: MatchTerms = match_term( + &prf(), + "Mike Ng", + context(), + MatchOptions::default(), + Side::Stored, + ) + .expect("derives"); + assert_eq!( + query, without, + "the filter the index without the option stores" + ); + assert!( + derive("Mike Nguyen", Side::Stored).contains(&query), + "which \"Mike Nguyen\" holds" + ); + assert!( + derive("Mike Ng", Side::Stored).contains(&query) + && derive("Mike Ng", Side::Stored) != query, + "\"Mike Ng\" holds it, and stores its word beside it" + ); + } + + #[test] + fn a_query_of_one_short_word_sends_the_filter_the_word_stores() { + let query = derive("Ng", Side::Query); + assert_eq!(query, derive("Ng", Side::Stored), "one word token"); + assert!( + derive("Mike Ng", Side::Stored).contains(&query), + "held by a row holding the word" + ); + assert!( + !derive("Mike Nguyen", Side::Stored).contains(&query), + "and not by a row holding a longer word it begins" + ); + } + + /// Text of short and long words, so a query has n-grams, short + /// words, both, or neither. + fn text() -> impl Strategy { + prop::collection::vec( + prop::sample::select(vec!['a', 'n', 'g', 'é', '李', ' ', ',']), + 0..10, + ) + .prop_map(|chars| chars.into_iter().collect()) + } + + proptest! { + /// A query's filter is the filter of exactly the tokens it + /// verifies by. So no row the filter rejects would verify. A + /// query that keeps no token has no filter. + #[test] + fn the_filter_is_the_filter_of_the_tokens_it_verifies_by(query in text()) { + let prf = prf(); + let tokens = QueryTokens::under(&query, &options()).expect("normalizes"); + let derived: Result = + match_term(&prf, &query, context(), options(), Side::Query); + if tokens.0.is_empty() { + prop_assert!( + matches!(derived, Err(TermError::EmptyTermText)), + "{:?} keeps no token, and is refused: {:?}", + query, + derived + ); + } else { + prop_assert_eq!( + derived.expect("a query that keeps a token derives"), + filter_of(&prf, &tokens.0), + "the filter of {:?}", + query + ); + } + } + + /// No false negative: a row that verifies holds the query's + /// filter, whatever the two texts. + #[test] + fn a_row_that_verifies_holds_the_filter(query in text(), row in text()) { + if let Ok(tokens) = QueryTokens::of_query(&query, &options()) { + if tokens.verify(&row, &options()) { + prop_assert!( + derive(&row, Side::Stored).contains(&derive(&query, Side::Query)), + "{:?} verifies {:?} and holds its filter", + query, + row + ); + } + } + } + + /// A query with an n-gram finds every text that contains it + /// as a run of characters. So a name typed in part finds its + /// row. + #[test] + fn a_query_that_cuts_an_ngram_finds_every_text_it_is_part_of( + row in text(), + bounds in (0usize..10, 0usize..10), + ) { + let chars: Vec = row.chars().collect(); + let (start, end) = (bounds.0.min(chars.len()), bounds.1.min(chars.len())); + let query: String = chars[start.min(end)..start.max(end)].iter().collect(); + let tokens = QueryTokens::under(&query, &options()).expect("normalizes"); + if !tokens.0.tokenizer.is_empty() { + prop_assert!( + tokens.verify(&row, &options()), + "{:?} verifies {:?}", + query, + row + ); + prop_assert!( + derive(&row, Side::Stored).contains(&derive(&query, Side::Query)), + "{:?} holds the filter of {:?}", + row, + query + ); + } + } + } + } + /// A word token is framed under its own domain, so it never sets /// the bits an n-gram of the same characters sets: pinned for /// `ng`, under a fixed key and the widest filter, where the two @@ -2433,7 +2738,8 @@ mod tests { let prf = HmacSha256Prf::new(Protected::new([7; 32])); let context = Context::from_encoded(&b"users/name"[..]); let stored: MatchTerms = - match_term(&prf, "Mike Ng", context.clone(), options()).expect("derives"); + match_term(&prf, "Mike Ng", context.clone(), options(), Side::Stored) + .expect("derives"); let mask = options().validate().expect("valid"); let mut union = bloom_positions( &prf, @@ -2467,13 +2773,14 @@ mod tests { "the trigrams of the whole text and the word" ); let alone: MatchTerms = - match_term(&prf, "Ng", context.clone(), options()).expect("derives"); + match_term(&prf, "Ng", context.clone(), options(), Side::Stored).expect("derives"); assert!( !alone.positions().is_empty() && stored.contains(&alone), "\"Ng\" stores one token, which \"Mike Ng\" holds: {alone:?}" ); let without: MatchTerms = - match_term(&prf, "Ng", context, MatchOptions::default()).expect("derives"); + match_term(&prf, "Ng", context, MatchOptions::default(), Side::Stored) + .expect("derives"); assert!( without.positions().is_empty(), "without the option, \"Ng\" is the empty filter" diff --git a/packages/stack-encrypt/src/sem/tokenize.rs b/packages/stack-encrypt/src/sem/tokenize.rs index ebf2f4c8d..fcd91d3da 100644 --- a/packages/stack-encrypt/src/sem/tokenize.rs +++ b/packages/stack-encrypt/src/sem/tokenize.rs @@ -14,6 +14,10 @@ //! [`MatchOptions::short_words`] on cuts one more kind: each word too short to //! hold an n-gram, whole. The two kinds are kept apart ([`Tokens`]) because //! each is run through the PRF under a domain of its own. +//! +//! A stored value keeps both kinds. A query keeps its short words only when +//! its whole text is shorter than one n-gram ([`Side::Query`]). So "Ng" asks +//! for the word `ng`, and "Mike Ng" asks for its trigrams alone. use std::collections::HashSet; @@ -82,7 +86,39 @@ pub(crate) struct Tokens { pub(crate) short_words: Vec, } +/// What a text is split into tokens for: a value to store, or a query that +/// finds stored values. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Side { + /// A value to store. The value keeps every token of both kinds, so a + /// query of any run of its words finds it. + Stored, + /// A query. The query keeps the tokenizer's tokens, and its short words + /// only when the tokenizer found none ([`Tokens::into_query`]). + Query, +} + impl Tokens { + /// The tokens a query keeps. If the tokenizer found no token, the query + /// keeps every short word. Otherwise the query keeps the tokenizer's + /// tokens alone, and the short words are wiped. + /// + /// So a query of short words alone, such as "Ng", asks for its word + /// tokens. That query finds the rows that contain those words whole. A + /// query with an n-gram, such as "Mike Ng", asks for its n-grams, as it + /// does with the option off. That query finds every row that contains + /// them: "Mike Nguyen" as well as "Mike Ng". + /// + /// The rule changes no stored filter, since every stored value keeps its + /// word tokens. Every token a query keeps is also a token that its own + /// text stores. + fn into_query(mut self) -> Self { + if !self.tokenizer.is_empty() { + self.short_words.zeroize(); + } + self + } + /// Whether no token of either kind was cut. pub(crate) fn is_empty(&self) -> bool { self.tokenizer.is_empty() && self.short_words.is_empty() @@ -120,15 +156,27 @@ impl Default for Tokenizer { /// unassigned in Unicode 16 is refused, as equality refuses it: its NFC /// form could change when the code point is assigned. /// +/// The tokens are for `side` ([`Side`]). A stored value keeps every token. A +/// query keeps its short words only when its whole text is shorter than one +/// n-gram. +/// /// The normalized copy is held in [`Protected`](vitaminc_protected::Protected) /// and wiped on drop. -pub(crate) fn tokens(text: &str, options: &MatchOptions) -> Result { +pub(crate) fn tokens( + text: &str, + options: &MatchOptions, + side: Side, +) -> Result { let normalized = vitaminc_normalize::text(text)?; // `text` returns the UTF-8 of a `str`, so this does not fail; a failure // would be a bug there, refused rather than tokenized. let normalized = std::str::from_utf8(normalized.risky_ref()).map_err(|_| NormalizeError::Invalid)?; - Ok(tokenize(normalized, options)) + let tokens = tokenize(normalized, options); + Ok(match side { + Side::Stored => tokens, + Side::Query => tokens.into_query(), + }) } /// Split `text` into tokens under `options`' tokenizer, case folding and @@ -300,6 +348,7 @@ mod tests { downcase: false, ..MatchOptions::default() }, + Side::Stored, ) .expect("tokens") .tokenizer @@ -321,7 +370,8 @@ mod tests { &MatchOptions { tokenizer: Tokenizer::Standard, ..MatchOptions::default() - } + }, + Side::Stored, ), Err(NormalizeError::UnassignedCodePoint) ), @@ -514,7 +564,8 @@ mod tests { &MatchOptions { short_words: true, ..MatchOptions::default() - } + }, + Side::Stored, ) .expect("normalizes") .short_words, @@ -627,6 +678,44 @@ mod tests { } } + /// A query keeps every n-gram of its text. The query keeps + /// its short words only when it has no n-gram. The same + /// text, stored, contains every token the query keeps. + #[test] + fn a_query_keeps_its_short_words_only_when_it_cuts_no_ngram( + (_, text) in text(), + length in 3usize..=5, + ) { + let stored = cut(&text, length); + let query = stored.clone().into_query(); + prop_assert_eq!( + &query.tokenizer, + &stored.tokenizer, + "a query keeps every n-gram of {:?}", + text + ); + if stored.tokenizer.is_empty() { + prop_assert_eq!( + &query.short_words, + &stored.short_words, + "{:?} cuts no n-gram, so its short words are its tokens", + text + ); + } else { + prop_assert!( + query.short_words.is_empty(), + "{:?} cuts an n-gram, so it keeps no short word: {:?}", + text, + query.short_words + ); + } + prop_assert!( + stored.hold(&query), + "{:?} stored holds every token its query keeps", + text + ); + } + /// The n-grams do not depend on the option: it adds word /// tokens and moves nothing else. #[test] @@ -644,6 +733,78 @@ mod tests { } } + mod given_a_query { + use super::*; + + /// The tokens a query of `text` keeps under 3-grams, downcased, + /// with short words on, as [`tokens`] returns them. + fn query(text: &str) -> Tokens { + tokens( + text, + &MatchOptions { + short_words: true, + ..MatchOptions::default() + }, + Side::Query, + ) + .expect("normalizes") + } + + #[test] + fn a_query_of_one_short_word_is_that_word() { + let tokens = query("Ng"); + assert_eq!(tokens.short_words, vec!["ng"], "the word, folded"); + assert!( + tokens.tokenizer.is_empty(), + "two letters cut no trigram: {:?}", + tokens.tokenizer + ); + } + + #[test] + fn a_query_that_cuts_an_ngram_is_its_ngrams_alone() { + for text in ["Mike Ng", "ke Ng", "san fr", "Ng Mike", "Li Wu", "Ng "] { + let tokens = query(text); + assert!( + tokens.short_words.is_empty(), + "{text:?} keeps no short word: {:?}", + tokens.short_words + ); + assert_eq!( + tokens.tokenizer, + cut(text, 3).tokenizer, + "{text:?} keeps every trigram it cuts" + ); + } + } + + #[test] + fn a_stored_value_keeps_its_short_words_beside_its_ngrams() { + let stored = tokens( + "Mike Ng", + &MatchOptions { + short_words: true, + ..MatchOptions::default() + }, + Side::Stored, + ) + .expect("normalizes"); + assert_eq!(stored.short_words, vec!["ng"], "the word is stored"); + assert!( + stored.hold(&query("Mike Ng")) && stored.hold(&query("Ng")), + "and both queries are held" + ); + assert!( + cut("Mike Nguyen", 3).hold(&query("Mike Ng")), + "\"Mike Nguyen\" holds the trigrams of \"Mike Ng\"" + ); + assert!( + !cut("Mike Nguyen", 3).hold(&query("Ng")), + "and not the word ng" + ); + } + } + #[test] fn a_row_holds_a_query_kind_by_kind() { let row = cut("Mike Ng", 3); diff --git a/packages/stack-encrypt/src/target/index.rs b/packages/stack-encrypt/src/target/index.rs index 34dd77493..d3af06597 100644 --- a/packages/stack-encrypt/src/target/index.rs +++ b/packages/stack-encrypt/src/target/index.rs @@ -48,9 +48,11 @@ //! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); //! ``` //! -//! One term can be derived alone, with no ciphertext: [`Indexes::select`] -//! picks an index out of a set by type, and [`Index::operation`] is its -//! term alone. A field query does not use `select`: the field's +//! One term can be derived alone, with no ciphertext. [`Indexes::select`] +//! picks an index out of a set by type. That index's +//! [`Index::query_operation`] derives the term a query sends, and its +//! [`Index::operation`] the term a value stores. A field query does not use +//! `select`: the field's //! target type names the index that answers each operator //! ([`Answers`](crate::op::Answers)). //! @@ -62,7 +64,9 @@ use std::fmt; use std::marker::PhantomData; use super::context::{AeadContext, CallerContext}; -use super::operations::{ciphertext, equality, json_terms, matching, ope, open, ore, ore_block}; +use super::operations::{ + ciphertext, equality, json_terms, matching, matching_query, ope, open, ore, ore_block, +}; use super::source::{Owned, WipeSource}; use super::{ DecryptField, DecryptSource, Decryptable, Decryption, EncryptTarget, Encryption, @@ -72,7 +76,7 @@ use crate::json::{JsonOptions, JsonTerms}; use crate::op::Op; use crate::sem::{ DefaultMatch, EqualityTerm, MatchConfig, MatchOptions, MatchTerms, OpeTerm, OreBlockTerm, - OreTerm, + OreTerm, Side, }; use crate::StackCipherText; @@ -246,8 +250,9 @@ impl fmt::Display for IndexSpec { /// no `Index` for [`Match`](struct@Match), because match is defined over text. /// /// An index does not seal anything. [`indexed`] puts a ciphertext beside the -/// indexes of a field; [`operation`](Self::operation) on its own is the term -/// alone, which is the query side. +/// indexes of a field. On its own, [`operation`](Self::operation) derives the +/// term a value stores, and [`query_operation`](Self::query_operation) the +/// term a query sends. /// /// The trait is open: an index defined in another crate implements it by /// composing this module's public operations, as the four here do. @@ -271,6 +276,21 @@ pub trait Index { ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where S: 's; + /// The description that derives the term a query of `S` sends, under + /// the [`CallerContext`] it is handed when it runs. A field query derives + /// its term through this method. + /// + /// Return [`operation`](Self::operation)'s description here when the + /// index sends the term it stores, as most indexes do. A match index + /// does not: it returns [`matching_query`]. With short words on, a query + /// that sent a stored value's filter would miss rows it should find. + /// That is why this method has no default. An index that wraps another + /// must forward both methods to it. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's; } /// The equality (exact-match) index: one PRF block over the whole value. @@ -393,6 +413,15 @@ impl Index for Equality { { equality() } + /// A query sends the term this index stores. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + equality() + } } impl, O: MatchConfig + 'static> Index for Match { type Term = MatchTerms; @@ -407,6 +436,14 @@ impl, O: MatchConfig + 'static> Index for Match { { matching() } + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + matching_query() + } } impl Index for Ore where @@ -424,6 +461,15 @@ where { ore() } + /// A query sends the term this index stores. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + ore() + } } impl Index for Ope where @@ -441,6 +487,15 @@ where { ope() } + /// A query sends the term this index stores. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + ope() + } } impl Index for OreBlock where @@ -458,6 +513,15 @@ where { ore_block() } + /// A query sends the term this index stores. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + ore_block() + } } /// The JSON index's operation derives the document's terms and seals @@ -473,6 +537,13 @@ impl Index for Json { ) -> Encryption<'s, serde_json::Value, Self::Term, K, CallerContext, M> { json_terms::(self.options.clone()) } + /// The document's terms, as stored. A query takes the terms it sends + /// from them. + fn query_operation<'s, K: 'static, M: WipeSource<'s, serde_json::Value>>( + &self, + ) -> Encryption<'s, serde_json::Value, Self::Term, K, CallerContext, M> { + json_terms::(self.options.clone()) + } } /// A non-empty set of indexes over `S`: one [`Index`], or a tuple of two to @@ -504,9 +575,26 @@ pub trait Indexes { where S: 's, M: WipeSource<'s, S>; - /// The one index of type `I` in this set, for the query side, where a - /// query asks one index for one term and needs no ciphertext; its - /// [`operation`](Index::operation) is that term alone. + /// The description that derives every term a query of `S` sends. The + /// description calls each index's + /// [`query_operation`](Index::query_operation) under the one + /// [`CallerContext`] it is handed, and settles them in one batch. + /// [`operations`](Self::operations) does the same for the stored terms. + /// For a [`Match`](struct@Match) index in the set, this sends the filter + /// of the tokens the query keeps, where `operations` derives a stored + /// value's filter. There is no default, for the reason + /// [`Index::query_operation`] has none. + fn query_operations<'s, K: 'static, M>( + &self, + ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> + where + S: 's, + M: WipeSource<'s, S>; + /// The one index of type `I` in this set, for the query side. A query + /// asks one index for one term, and needs no ciphertext. The index's + /// [`query_operation`](Index::query_operation) derives the term a query + /// sends, and its [`operation`](Index::operation) the term a value + /// stores. /// /// `P` is where `I` sits (the position [`Select`] names) and is inferred; /// leave it `_`. Asking for an index the set does not hold does not @@ -591,13 +679,23 @@ macro_rules! single_index { { self.operation() } + fn query_operations<'s, K: 'static, M>( + &self, + ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> + where + S: 's, + M: WipeSource<'s, S>, + { + self.query_operation() + } } )+}; } single_index!([] Equality, [O] Match, [] Ore, [] Ope, [] OreBlock, [] Json, [] IndexSpec); -/// A tuple of indexes: each index's operation, zipped left to right, and the -/// nested pairs `zip` builds flattened back into one tuple of terms. +/// A tuple of indexes. Each index's operation, or query operation, is zipped +/// left to right. The nested pairs that `zip` builds are flattened back into +/// one tuple of terms. macro_rules! tuple_of_indexes { ($(($($name:ident $at:tt),+) => $nested:pat,)+) => {$( impl),+> Indexes for ($($name,)+) { @@ -612,14 +710,24 @@ macro_rules! tuple_of_indexes { S: 's, M: WipeSource<'s, S>, { - tuple_of_indexes!(@zip self, $($at),+) + tuple_of_indexes!(@zip self, operation, $($at),+) + .map(|$nested| ($($name,)+)) + } + fn query_operations<'s, K: 'static, M>( + &self, + ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> + where + S: 's, + M: WipeSource<'s, S>, + { + tuple_of_indexes!(@zip self, query_operation, $($at),+) .map(|$nested| ($($name,)+)) } } tuple_of_indexes!(@select [$($name),+] $($name $at),+); )+}; - (@zip $self:ident, $first:tt $(, $rest:tt)*) => { - $self.$first.operation()$(.zip($self.$rest.operation::()))* + (@zip $self:ident, $operation:ident, $first:tt $(, $rest:tt)*) => { + $self.$first.$operation()$(.zip($self.$rest.$operation::()))* }; // One `Select` impl per position, each over the whole tuple. (@select [$($all:ident),+] $name:ident $at:tt $(, $rest:ident $rest_at:tt)*) => { @@ -652,7 +760,8 @@ mod tuples { /// A `Vec` cannot be refused for being empty at compile time as `()` is, so /// an empty one is refused when it runs, with /// [`PlanError::EmptyIndexes`](crate::PlanError::EmptyIndexes), before any -/// key is requested: a field declared indexed derives at least one term. +/// key is requested: a field declared indexed derives at least one term. In +/// [`Owned`] mode, the refusal wipes the value it is handed. /// [`select`](Indexes::select) is not available on a `Vec`; a binding /// answers a query by index key, through its own `Index` impl. impl> Indexes for Vec { @@ -665,18 +774,55 @@ impl> Indexes for Vec { S: 's, M: WipeSource<'s, S>, { - let mut indexes = self.iter(); - let Some(first) = indexes.next() else { - return Encryption::failed(crate::PlanError::EmptyIndexes.into()); - }; - indexes.fold(first.operation().map(|term| vec![term]), |terms, index| { + each_index(self, Side::Stored) + } + fn query_operations<'s, K: 'static, M>( + &self, + ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> + where + S: 's, + M: WipeSource<'s, S>, + { + each_index(self, Side::Query) + } +} + +/// The description that derives the term of each of `indexes` for `side`, +/// in order, zipped into one batch: the stored terms, or a query's. An empty +/// list is refused with +/// [`PlanError::EmptyIndexes`](crate::PlanError::EmptyIndexes). The refusal +/// releases the plaintext as an operation would ([`WipeSource`]). +fn each_index<'s, S: 's, I: Index, K: 'static, M: WipeSource<'s, S>>( + indexes: &[I], + side: Side, +) -> Encryption<'s, S, Vec, K, CallerContext, M> { + let mut indexes = indexes.iter(); + let Some(first) = indexes.next() else { + return Encryption::failed_wiping(crate::PlanError::EmptyIndexes.into()); + }; + indexes.fold( + term_for(first, side).map(|term| vec![term]), + |terms, index| { terms - .zip(index.operation::()) + .zip(term_for::(index, side)) .map(|(mut terms, term)| { terms.push(term); terms }) - }) + }, + ) +} + +/// `index`'s description for `side`: the term it stores +/// ([`operation`](Index::operation)) or the term a query sends +/// ([`query_operation`](Index::query_operation)). +fn term_for<'s, S: 's, I: Index, K: 'static, M: WipeSource<'s, S>>( + index: &I, + side: Side, +) -> Encryption<'s, S, I::Term, K, CallerContext, M> { + match side { + Side::Stored => index.operation(), + Side::Query => index.query_operation(), } } diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index c9356d16d..e3aa7ce03 100644 --- a/packages/stack-encrypt/src/target/mod.rs +++ b/packages/stack-encrypt/src/target/mod.rs @@ -198,8 +198,8 @@ pub use input::{ #[cfg(feature = "dynamic")] pub(crate) use operations::{chosen, inspect}; pub use operations::{ - ciphertext, equality, json_document, json_terms, matching, ope, open, ore, ore_block, - passthrough, scalar_ciphertext, DecryptField, Decryptable, Decryption, Encryption, + ciphertext, equality, json_document, json_terms, matching, matching_query, ope, open, ore, + ore_block, passthrough, scalar_ciphertext, DecryptField, Decryptable, Decryption, Encryption, }; pub(crate) use pending::KeysetSelector; pub use pending::{CipherRef, Pending, PendingFuture}; diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 49dde0018..4510d6901 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -181,6 +181,24 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> mode: PhantomData, } } + /// Reject the declaration as [`failed`](Self::failed) does, and release + /// the plaintext it is handed through [`WipeSource`]. In [`Owned`] mode + /// the value is wiped. A borrow is left with the caller. Use this when a + /// description refuses before any operation has taken its plaintext, so + /// the refusal does not free the value without wiping it. + pub(crate) fn failed_wiping(error: Error) -> Self + where + M: WipeSource<'s, S>, + { + Self { + build: Box::new(move |source, cipher, _| { + M::wipe(source); + Pending::failed(cipher, error) + }), + shapes: Vec::new(), + mode: PhantomData, + } + } /// Reject this declaration as [`failed`](Self::failed) does, but keep /// the contexts of its leaves. [`contexts`](Self::contexts) then still /// shows each field the declaration names, and running it yields @@ -1131,9 +1149,11 @@ where /// Every term reads the plaintext in place, so it runs in either mode /// without a copy. `$lend` is how a borrow of `S` becomes the source its /// scheme reads. In [`Owned`] mode a `wipe` term hands the value to its -/// scheme, which wipes it. A `view` term (match) reads a borrow in either -/// mode, and then wipes a value it was handed. Either kind wipes a value it -/// was handed when the context is refused ([`WipeSource`]). +/// scheme, and the scheme wipes it. A `view` term (match) reads a borrow in +/// either mode through `$derive`. The term calls `$derive` as +/// `Term::encrypt_from` is called, and then wipes a value it was handed. +/// Either kind wipes a value it was handed when the context is refused +/// ([`WipeSource`]). macro_rules! term_operation { ( $(#[$doc:meta])* @@ -1177,7 +1197,7 @@ macro_rules! term_operation { }; ( $(#[$doc:meta])* - $function:ident, $output:ty, view, [$($generics:tt)*], [$($bounds:tt)*] + $function:ident, $output:ty, view($derive:expr), [$($generics:tt)*], [$($bounds:tt)*] ) => { $(#[$doc])* pub fn $function<'s, S, K: 'static, M: WipeSource<'s, S>, $($generics)*>( @@ -1193,7 +1213,7 @@ macro_rules! term_operation { let guarded = Guarded::::new(source); let (query, stored) = (cx.query(), cx.stored()); match cx.validated() { - Ok(ctx) => <$output as Term<&S, K, _>>::encrypt_from( + Ok(ctx) => ($derive)( guarded.source().view(), cipher, CallerContext::query_nonempty(ctx), @@ -1215,9 +1235,36 @@ term_operation!( equality, crate::sem::EqualityTerm, wipe(EncryptRef::lend), [], [S: crate::Encrypt + EncryptRef] ); term_operation!( - /// The match term of any text `S` under the context the tree hands it, - /// tokenised and hashed as `O` declares. - matching, crate::sem::MatchTerms, view, [O: crate::sem::MatchConfig + 'static], [S: AsRef] + /// The match term of any text `S`, under the context the tree hands it, + /// tokenised and hashed as `O` declares. The term is a stored value's + /// filter, with every token of the text. A query's filter comes from + /// [`matching_query`]. + matching, crate::sem::MatchTerms, + view( as Term<&S, K, _>>::encrypt_from), + [O: crate::sem::MatchConfig + 'static], [S: AsRef] +); +term_operation!( + /// The match term that a query of the text `S` sends, under the context + /// the tree hands it. The term is the filter of the tokens the query + /// keeps. A stored filter contains it when the row contains those + /// tokens. A field query of a match index derives this term + /// ([`Index::query_operation`](super::Index::query_operation)). + /// + /// With [`short_words`](crate::sem::MatchOptions::short_words) on, a + /// query keeps its short words only when its whole text is shorter than + /// one n-gram. "Ng" asks for the word `ng`. "Mike Ng" asks for its + /// trigrams alone, so it finds "Mike Nguyen" as well as "Mike Ng". With + /// the option off, this is [`matching`]'s term, for any text that has a + /// token. + /// + /// Text with no token is refused + /// ([`TermError::EmptyTermText`](crate::sem::TermError::EmptyTermText)), + /// since its empty filter would match every row. [`matching`] stores + /// such text as the empty filter. A field query refuses it earlier, when + /// it is prepared ([`Supports::prepare`](crate::op::Supports::prepare)). + matching_query, crate::sem::MatchTerms, + view(crate::sem::match_query), + [O: crate::sem::MatchConfig + 'static], [S: AsRef] ); term_operation!( /// The order-revealing term of `S` under the context the tree hands it. diff --git a/packages/stack-encrypt/tests/index.rs b/packages/stack-encrypt/tests/index.rs index 9856ca012..67b099a4a 100644 --- a/packages/stack-encrypt/tests/index.rs +++ b/packages/stack-encrypt/tests/index.rs @@ -493,6 +493,292 @@ mod given_a_set_of_indexes { } } +/// A set of indexes derives a query's terms through each index's own +/// `query_operation` (`Indexes::query_operations`). A match index's term is +/// the filter of the tokens the query keeps. Every other index's term is the +/// one it stores. The same holds for one index, a tuple, and a `Vec`. +mod given_a_set_holding_a_match_index_with_short_words { + use super::*; + + /// 3-grams with short-word tokens. So a query with an n-gram derives a + /// filter other than the one the same text stores. + struct ShortWords; + impl MatchConfig for ShortWords { + fn options() -> MatchOptions { + MatchOptions { + short_words: true, + ..MatchOptions::default() + } + } + } + + /// The text. The query has n-grams, so it keeps its 3-grams alone and + /// drops the short word "Ng". A stored value contains the word too. + const TEXT: &str = "Mike Ng"; + + /// A keyset over the fake key source, and the stored and query filters + /// the match index derives for [`TEXT`] alone. + async fn scenario() -> ( + stack_encrypt::StackCipher, + MatchTerms, + MatchTerms, + ) { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let index = Match::::new(); + let text = TEXT.to_owned(); + let stored = keyset + .run( + Index::::operation::<_, Borrowed>(&index), + &text, + caller(), + ) + .await + .unwrap(); + let queried = keyset + .run( + Index::::query_operation::<_, Borrowed>(&index), + &text, + caller(), + ) + .await + .unwrap(); + assertions::differ(&stored, &queried); + (cipher, stored, queried) + } + + #[tokio::test] + async fn one_index_derives_its_query_filter() { + let (cipher, stored, queried) = scenario().await; + let keyset = cipher.default_keyset(); + let index = Match::::new(); + let text = TEXT.to_owned(); + let query: MatchTerms = keyset + .run( + Indexes::::query_operations::<_, Borrowed>(&index), + &text, + caller(), + ) + .await + .unwrap(); + assertions::same_filter("one index's query", &query, &queried); + let store: MatchTerms = keyset + .run( + Indexes::::operations::<_, Borrowed>(&index), + &text, + caller(), + ) + .await + .unwrap(); + assertions::same_filter("one index's stored terms", &store, &stored); + } + + #[tokio::test] + async fn a_tuple_derives_the_query_filter_beside_the_stored_equality_term() { + let (cipher, stored, queried) = scenario().await; + let keyset = cipher.default_keyset(); + let indexes = (Equality, Match::::new()); + let text = TEXT.to_owned(); + let (query_eq, query_match): (EqualityTerm, MatchTerms) = keyset + .run( + Indexes::::query_operations::<_, Borrowed>(&indexes), + &text, + caller(), + ) + .await + .unwrap(); + let (stored_eq, stored_match): (EqualityTerm, MatchTerms) = keyset + .run( + Indexes::::operations::<_, Borrowed>(&indexes), + &text, + caller(), + ) + .await + .unwrap(); + assertions::same_filter("the tuple's query", &query_match, &queried); + assertions::same_filter("the tuple's stored terms", &stored_match, &stored); + assert_eq!( + query_eq, stored_eq, + "the equality index sends the term it stores" + ); + } + + #[tokio::test] + async fn a_vec_derives_each_query_filter_in_order() { + let (cipher, stored, queried) = scenario().await; + let keyset = cipher.default_keyset(); + let indexes = vec![Match::::new(), Match::::new()]; + let text = TEXT.to_owned(); + let query: Vec> = keyset + .run( + Indexes::::query_operations::<_, Borrowed>(&indexes), + &text, + caller(), + ) + .await + .unwrap(); + assert_eq!(query.len(), 2, "one query term per index"); + for term in &query { + assertions::same_filter("the vec's query", term, &queried); + } + let store: Vec> = keyset + .run( + Indexes::::operations::<_, Borrowed>(&indexes), + &text, + caller(), + ) + .await + .unwrap(); + assert_eq!(store.len(), 2, "one stored term per index"); + for term in &store { + assertions::same_filter("the vec's stored terms", term, &stored); + } + } + + #[tokio::test] + async fn an_empty_vec_is_refused_before_any_key_request() { + let (cipher, generates, _) = counting_cipher().await; + let keyset = cipher.default_keyset(); + let none: Vec> = Vec::new(); + let refused: Result>, _> = keyset + .run( + Indexes::::query_operations::<_, Borrowed>(&none), + &TEXT.to_owned(), + caller(), + ) + .await; + assert!( + matches!( + refused, + Err(Error::Plan(stack_encrypt::PlanError::EmptyIndexes)) + ), + "an empty set derives no query: {refused:?}" + ); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "no key request for an empty set" + ); + } + + mod assertions { + use super::*; + + /// The stored and query filters of one text differ. So this shows a + /// set that derived the stored filter for a query. + pub(super) fn differ(stored: &MatchTerms, queried: &MatchTerms) { + assert_ne!( + stored.positions(), + queried.positions(), + "{TEXT:?}: a stored value holds the word token, a query its 3-grams alone" + ); + } + + /// Two filters set the same positions. + pub(super) fn same_filter( + what: &str, + actual: &MatchTerms, + expected: &MatchTerms, + ) { + assert_eq!( + actual.positions(), + expected.positions(), + "{what}: the filter the match index derives on its own" + ); + } + } +} + +/// An empty `Vec` of indexes handed a plaintext by value. The refusal is the +/// operation that releases the plaintext, so the refusal wipes it, for a +/// stored value and for a query alike. +mod given_an_owned_plaintext_and_an_empty_vec_of_indexes { + use super::*; + use std::sync::atomic::AtomicUsize; + use std::sync::Arc; + use zeroize::Zeroize; + + /// Text that counts the times it is wiped. + struct Counted { + text: String, + wipes: Arc, + } + impl AsRef for Counted { + fn as_ref(&self) -> &str { + &self.text + } + } + impl Zeroize for Counted { + fn zeroize(&mut self) { + self.text.zeroize(); + let _ = self.wipes.fetch_add(1, Ordering::SeqCst); + } + } + + /// The text, its wipe counter, and an empty set of match indexes. + fn scenario() -> (Counted, Arc, Vec) { + let wipes = Arc::new(AtomicUsize::new(0)); + let text = Counted { + text: "Mike Ng".to_owned(), + wipes: wipes.clone(), + }; + (text, wipes, Vec::new()) + } + + #[tokio::test] + async fn the_stored_terms_refusal_wipes_the_value() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let (text, wipes, none) = scenario(); + let refused: Result, _> = keyset + .run( + Indexes::::operations::<_, Owned>(&none), + text, + caller(), + ) + .await; + assertions::refused_and_wiped(&refused, &wipes); + } + + #[tokio::test] + async fn the_query_terms_refusal_wipes_the_value() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let (text, wipes, none) = scenario(); + let refused: Result, _> = keyset + .run( + Indexes::::query_operations::<_, Owned>(&none), + text, + caller(), + ) + .await; + assertions::refused_and_wiped(&refused, &wipes); + } + + mod assertions { + use super::*; + + /// Refused as an empty set, with the value wiped exactly once. + pub(super) fn refused_and_wiped( + refused: &Result, Error>, + wipes: &AtomicUsize, + ) { + assert!( + matches!( + refused, + Err(Error::Plan(stack_encrypt::PlanError::EmptyIndexes)) + ), + "an empty set derives nothing: {refused:?}" + ); + assert_eq!( + wipes.load(Ordering::SeqCst), + 1, + "the refusal wipes the owned value once" + ); + } + } +} + mod given_a_passthrough { use super::*; diff --git a/packages/stack-encrypt/tests/match_short_words.rs b/packages/stack-encrypt/tests/match_short_words.rs index 5995c9083..45775dd61 100644 --- a/packages/stack-encrypt/tests/match_short_words.rs +++ b/packages/stack-encrypt/tests/match_short_words.rs @@ -4,11 +4,16 @@ //! //! - **Round trip.** "Ng" stored is found by the query "Ng"; "Mike Ng" is //! found by "Ng" and by "Mike Ng"; "Nguyen" is not found by "Ng". +//! - **Queries.** A query keeps its short words only when its whole text is +//! shorter than one n-gram. "Ng" is its word token. "Mike Ng" is its +//! trigrams alone, so it finds "Mike Nguyen", as it does with the option +//! off. The filter and `verify` agree. //! - **Identity.** The option is part of the index, which is the field's //! type: a field is stored and queried under the options its type //! declares, and options the index cannot use are refused on both sides. -//! - **Containment.** For random text, the stored filter holds the filter of -//! any run of its whole words. +//! - **Containment.** For random text, the stored filter contains the filter +//! of any run of its whole words. The stored filter also contains the +//! filter of any run of its characters that has an n-gram. //! - **Calibration.** A one-word query sets as many bits as a one-trigram //! query, and a row's chance of matching either falsely is the same. @@ -132,27 +137,80 @@ mod given_short_words { } } + /// A query with an n-gram asks for its n-grams alone. So a short word in + /// it need not be a whole word of the row. A name typed in part finds + /// its row, as it does with the option off. A query of one short + /// word is that word, whole. The filter and `verify` agree on every row. #[tokio::test] - async fn a_query_of_words_and_ngrams_needs_every_short_word_whole() { + async fn a_query_keeps_its_short_words_only_when_it_cuts_no_ngram() { let cipher = stack_cipher().await; let keyset = cipher.default_keyset(); - let mike_ng = query(&keyset, "Mike Ng").await.expect("a query"); - let stored = store(&keyset, "Mike Ng").await; - assert!(stored.matches(&mike_ng), "\"Mike Ng\" finds itself"); - assert!(mike_ng.verify("mike ng"), "case folded"); - let longer = store(&keyset, "Mike Nguyen").await; - assert!( - !mike_ng.verify("Mike Nguyen"), - "the query's short word must be a whole word of the row" - ); - assert!( - !longer.matches(&mike_ng), - "and the filter says so: \"Mike Nguyen\" has no word token ng" + for (asked, text, found) in [ + ("Ng", "Ng", true), + ("Ng", "Mike Ng", true), + ("Ng", "Mike Nguyen", false), + ("Mike Ng", "Mike Ng", true), + ("Mike Ng", "mike ng", true), + ("Mike Ng", "Mike Nguyen", true), + ("Mike Ng", "Mike Ngo", true), + ("Mike Ng", "Ng", false), + ("Mike Ng", "Mike Smith", false), + ("ke Ng", "Mike Ng", true), + ("san fr", "San Francisco", true), + ("Li Wu", "Li Wu", true), + ("Li Wu", "Li Wuhan", true), + ("Li Wu", "Wu Li", false), + ] { + let query = query(&keyset, asked) + .await + .unwrap_or_else(|error| panic!("{asked:?} is a query: {error}")); + let stored = store(&keyset, text).await; + // The filter alone. A row without the tokens could have their + // bits by chance. Under the test key and these rows, none does. + assert_eq!( + stored.matches(&query), + found, + "the filter of {asked:?} on {text:?}" + ); + assert_eq!( + query.verify(text), + found, + "verify agrees with the filter of {asked:?} on {text:?}" + ); + } + } + + /// A person whose name is under the default match index, under the + /// same label as [`EncryptedPerson`]'s. + #[derive(EncryptTarget)] + #[stash(struct = Person, scope = "people")] + struct PlainPerson { + name: Encrypted, + } + + /// A query with an n-gram sends the filter that the index stores for the + /// same text without the option: its n-grams, and no word. + #[tokio::test] + async fn a_query_of_ngrams_is_the_filter_the_index_without_the_option_stores() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let asked = query(&keyset, "Mike Ng").await.expect("a query"); + let plain: PlainPerson = Person { + name: "Mike Ng".into(), + } + .encrypt_into(&keyset) + .await + .expect("stores"); + let trigrams = plain.name.terms; + assert_eq!( + asked.positions(), + trigrams.positions(), + "\"Mike Ng\" sends its trigrams alone" ); - let mike = query(&keyset, "Mike").await.expect("a query"); - assert!( - longer.matches(&mike) && stored.matches(&mike), - "a query of trigrams alone finds both" + assert_ne!( + asked.positions(), + store(&keyset, "Mike Ng").await.positions(), + "not the stored filter, which holds the word token too" ); } @@ -174,6 +232,95 @@ mod given_short_words { ); } + /// `matching_query` run on its own, as a binding or an index defined + /// elsewhere runs it. `matching_query` refuses text with no token, as a + /// field query does, because the empty filter would match every row. + /// `matching` stores such text as the empty filter. + mod given_the_query_cut_alone { + use super::*; + use stack_encrypt::sem::DefaultMatch; + use stack_encrypt::target::{matching, matching_query, Borrowed, CallerContext}; + + fn caller() -> CallerContext { + CallerContext::from(nonempty!("people/name")) + } + + async fn derive_query( + keyset: &Keyset<'_>, + text: &str, + ) -> Result, Error> { + keyset + .run( + matching_query::<_, _, Borrowed, O>(), + &text.to_owned(), + caller(), + ) + .await + } + + #[tokio::test] + async fn text_that_cuts_no_token_is_refused() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + for text in ["", "a", "Ng", " "] { + assertions::refused_as_empty( + text, + derive_query::(&keyset, text).await, + ); + } + for text in ["", "N", "n "] { + assertions::refused_as_empty(text, derive_query::(&keyset, text).await); + } + } + + #[tokio::test] + async fn the_stored_cut_of_that_text_is_the_empty_filter() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let stored: MatchTerms = keyset + .run( + matching::<_, _, Borrowed, DefaultMatch>(), + &"Ng".to_owned(), + caller(), + ) + .await + .expect("a stored value of short text derives"); + assert!( + stored.positions().is_empty(), + "\"Ng\" stores the empty filter under the default index: {:?}", + stored.positions() + ); + } + + #[tokio::test] + async fn text_that_cuts_a_token_derives_its_filter() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let queried = derive_query::(&keyset, "Ng") + .await + .expect("a short word is a token of the short-word index"); + assert!( + !queried.positions().is_empty(), + "the word token sets positions" + ); + } + + mod assertions { + use super::*; + + pub(super) fn refused_as_empty( + text: &str, + derived: Result, Error>, + ) { + assert!( + matches!(derived, Err(Error::Term(TermError::EmptyTermText))), + "{text:?} cuts no token, and its query is refused: {:?}", + derived.map(|terms| terms.positions().to_vec()) + ); + } + } + } + /// A person with one name under each index: the short-word index on /// `name`, the default on `alias`. #[derive(Clone, Zeroize)] @@ -350,6 +497,44 @@ mod given_random_text { Ok(()) })?; } + + /// A query of any run of a text's characters that has an n-gram + /// finds the text, by filter and by `verify`. The run can start or + /// end inside a word. So with short words on, a query typed in part + /// finds its row, as does a partial name. + #[test] + fn a_run_of_characters_that_cuts_an_ngram_finds_its_text( + words in prop::collection::vec(word(), 1..8), + separators in prop::collection::vec(separator(), 8), + run in (0usize..40, 0usize..40), + ) { + let mut text = String::new(); + for (i, word) in words.iter().enumerate() { + if i > 0 { + text.push(separators[i - 1]); + } + text.push_str(word); + } + let chars: Vec = text.chars().collect(); + let (first, last) = (run.0 % chars.len(), run.1 % chars.len()); + let asked: String = chars[first.min(last)..=first.max(last)].iter().collect(); + prop_assume!(asked.chars().count() >= 3, "a run too short for a trigram"); + + runtime().block_on(async { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let stored = store(&keyset, &text).await; + let query = query(&keyset, &asked) + .await + .map_err(|error| TestCaseError::fail(format!("{asked:?}: {error}")))?; + prop_assert!( + stored.matches(&query), + "{text:?} holds the filter of {asked:?}" + ); + prop_assert!(query.verify(&text), "{text:?} verifies {asked:?}"); + Ok(()) + })?; + } } } diff --git a/packages/stack-encrypt/tests/op.rs b/packages/stack-encrypt/tests/op.rs index 83e1e6a00..09d55a5b9 100644 --- a/packages/stack-encrypt/tests/op.rs +++ b/packages/stack-encrypt/tests/op.rs @@ -465,6 +465,11 @@ impl Index for Labelled { ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) } + fn query_operation<'s, K: 'static, M: WipeSource<'s, String>>( + &self, + ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { + Index::::query_operation(&Equality) + } } impl op::Supports for Labelled { @@ -520,6 +525,11 @@ impl Index for Unextendable { ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) } + fn query_operation<'s, K: 'static, M: WipeSource<'s, String>>( + &self, + ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { + Index::::query_operation(&Equality) + } } impl op::Supports for Unextendable { diff --git a/packages/stack-encrypt/tests/ui/execution_callback.stderr b/packages/stack-encrypt/tests/ui/execution_callback.stderr index 7b6f890c4..82e8940b0 100644 --- a/packages/stack-encrypt/tests/ui/execution_callback.stderr +++ b/packages/stack-encrypt/tests/ui/execution_callback.stderr @@ -30,5 +30,12 @@ help: you might have meant to use an associated function to build this type 7 - stack_encrypt::Pending::failed(cipher, stack_encrypt::Error::Aead) 8 - }), 9 - }; +5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::failed_wiping(_); + | +5 - let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption { +6 - build: Box::new(|_, cipher, _| { +7 - stack_encrypt::Pending::failed(cipher, stack_encrypt::Error::Aead) +8 - }), +9 - }; 5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::from_build(_, _); | diff --git a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs index e80a69f0d..4d408118e 100644 --- a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs +++ b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs @@ -18,6 +18,11 @@ impl Index for Shortcut { ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) } + fn query_operation<'s, K: 'static, M: WipeSource<'s, String>>( + &self, + ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { + Index::::query_operation(&Equality) + } } impl op::Supports for Shortcut { diff --git a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.stderr b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.stderr index 248900eee..e43a477c0 100644 --- a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.stderr +++ b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.stderr @@ -1,7 +1,7 @@ error[E0277]: `EqualityTerm` cannot answer `stack_encrypt::op::Matches` - --> tests/ui/op_inexact_operator_needs_probabilistic.rs:24:18 + --> tests/ui/op_inexact_operator_needs_probabilistic.rs:29:18 | -24 | type Query = EqualityTerm; +29 | type Query = EqualityTerm; | ^^^^^^^^^^^^ this query term does not meet the operator's requirement | = help: the trait `stack_encrypt::op::Probabilistic` is not implemented for `EqualityTerm`