From 9be6a47c067f8fb898554a48b78ce35300cd8430 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 00:46:09 +1100 Subject: [PATCH 1/4] fix(stack-encrypt,eql-bindings): cut a query's short words only when it cuts no n-gram With MatchOptions::short_words on, a query that held a short word also asked for that word's token beside its n-grams, so the word had to be a whole word of the row. "Mike Ng" no longer found "Mike Nguyen", and "san fr" no longer found "San Francisco", which breaks typeahead and partial names on EQL v4 text columns. A query now keeps its short words only when it cuts no n-gram, which is when the whole query is one short word. "Ng" is still its word token and finds "Ng" and "Mike Ng" but not "Nguyen"; "Mike Ng" is its trigrams alone. The stored side is unchanged, so no stored filter moves. The rule lives once, in tokenize (Tokens::into_query, selected by Side::Query), and every query derivation cuts through it: - QueryTokens::under, so the typed verifier, dynamic::verify and the query preparation all keep the same tokens; - match_term takes a Side; a new target::matching_query operation derives a query's filter, and Index::query_operation (defaulting to operation) is what a field query now derives through. Match overrides it, IndexSpec overrides it, and a set of indexes derives its query terms through the new Indexes::query_operations, each index's query_operation (one index, a tuple and a Vec); - eql-bindings' TwinIndex forwards query_operation to the indexes whose terms its twin carries, so matches on TextMatch, TextSearch and TextSearchOre sends the query's filter, and every other operator the term its index stores; - the dynamic derive takes a Side: query_term and the term probe cut a query, the record path a stored value; - eql-bindings' v4 query twins carry a new QueryBloomFilter (BloomFilter's JSON and schema), whose EncryptTarget derives through matching_query, so TextMatchQuery and TextSearch(Ore)MatchQuery built directly or by the by-name query dispatch follow the rule. eql-codegen emits it for every v4 query twin's bf, and for the bf term of the twins' QueryTwin impls. typed_queries.rs holds a field reference's matches on TextMatch, TextSearch and TextSearchOre to the data path's bytes and verdicts, and checks that "Mike Ng" and "ke Ng" find a stored "Mike Nguyen". Docs, the pending EQL changeset and the CHANGELOGs state the new rule and the leakage: one unique token per short word in every stored value that holds one. Closes #1398 --- .changeset/eql-v4-match-short-words.md | 4 +- languages/golang/CHANGELOG.md | 11 + languages/golang/cmd/stashgen/README.md | 2 +- languages/golang/encrypt/README.md | 12 +- languages/golang/encrypt/eql_v4_test.go | 9 + packages/eql/crates/eql-bindings/CHANGELOG.md | 20 + packages/eql/crates/eql-bindings/README.md | 13 +- .../eql/crates/eql-bindings/src/encryption.rs | 65 +++- .../eql-bindings/src/encryption/query.rs | 24 +- .../eql/crates/eql-bindings/src/v4/answers.rs | 14 +- .../eql/crates/eql-bindings/src/v4/mod.rs | 55 ++- .../eql/crates/eql-bindings/src/v4/text.rs | 14 +- .../eql/crates/eql-codegen/src/bindings.rs | 38 +- .../eql/crates/eql-codegen/src/targets.rs | 28 +- .../tests/encryption/tests/typed_queries.rs | 157 ++++++++ .../eql/tests/encryption/tests/v4_types.rs | 103 ++++- packages/stack-encrypt/CHANGELOG.md | 28 ++ packages/stack-encrypt/src/dynamic/query.rs | 5 +- packages/stack-encrypt/src/dynamic/term.rs | 165 ++++++-- packages/stack-encrypt/src/op/mod.rs | 11 +- packages/stack-encrypt/src/sem/mod.rs | 362 +++++++++++++++--- packages/stack-encrypt/src/sem/tokenize.rs | 165 +++++++- packages/stack-encrypt/src/target/index.rs | 104 ++++- packages/stack-encrypt/src/target/mod.rs | 4 +- .../stack-encrypt/src/target/operations.rs | 35 +- packages/stack-encrypt/tests/index.rs | 197 ++++++++++ .../stack-encrypt/tests/match_short_words.rs | 133 ++++++- 27 files changed, 1565 insertions(+), 213 deletions(-) diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index 858f489def..d41798cecf 100644 --- a/.changeset/eql-v4-match-short-words.md +++ b/.changeset/eql-v4-match-short-words.md @@ -2,10 +2,10 @@ '@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 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 keeps its two-letter words only when it cuts no 3-gram, which is when the whole query is one two-letter word: "Mike Ng" is its 3-grams alone and finds "Mike Ng" and "Mike Nguyen", as it would without the word tokens, so a name typed in part ("ke Ng", "san fr") still finds its row. Every query path follows this rule (a field reference's `matches`, the query twins' `EncryptTarget`, the by-name query dispatch a binding runs, and `verify`), so a filter and its verify agree. A query twin's filter is the new `v4::terms::QueryBloomFilter` field type (`TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, and the `bf` of `TextSearchQuery` and `TextSearchOreQuery`), with `BloomFilter`'s JSON and JSON Schema; it changes fields of the unreleased `v4` module only. 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. **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.** One more token per two-letter word in every stored value that holds one, under the same PRF, in the same filter, by the same containment rule. The token is unique 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, and can count them. A query of one two-letter word shows which word it asks for; a longer query sends no word token. No bigram of a longer word is indexed. 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 0c70e9a5d4..6574e4a75c 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -152,6 +152,17 @@ 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). A query that held a two-letter word + also asked for that word whole, so "Mike Ng" did not find "Mike Nguyen". + Now a query keeps its two-letter words only when it cuts no 3-gram, + which is when the whole query is one two-letter word. "Mike Ng" is its + 3-grams alone and finds "Mike Ng" and "Mike Nguyen", and "ke Ng" finds + "Mike Ng". "Ng" is still its word token, and finds "Ng" and "Mike Ng" and + not "Nguyen". `Verify` keeps the same rows 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 8c6c392f86..077f3b824c 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 whole, so a two-letter surname such as "Ng" is stored and found by the query "ng". A query keeps its two-letter words only when it cuts no 3-gram, so "Mike Ng" is 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 f90e23a747..8d5061bfe9 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -664,10 +664,14 @@ 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 query keeps its two-letter words only when it cuts no 3-gram, which is +when the whole query is one two-letter word: "Mike Ng" is its 3-grams alone, +so it finds "Mike Ng" and "Mike Nguyen", and a name typed in part, such as +"ke Ng", finds its row. The word token is one more token per two-letter word +in every stored value that holds one, unique to the word: someone who +clusters tokens across rows can tell the rows holding "Ng" from those +holding "Nguyen", and count them, where before only the trigram they share +was visible. 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 fbc6d7814e..d17821ca94 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 that cuts a 3-gram 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 01ff964aca..394edff730 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -224,6 +224,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **A match query keeps its two-letter words only when it cuts no + 3-gram** (#1398, `stack-encrypt` feature). `EqlMatch` indexes each + two-letter word whole, and a query holding one also asked for that + word, so "Mike Ng" did not find "Mike Nguyen". Now a query that cuts a + 3-gram is its 3-grams alone: "Mike Ng" finds "Mike Ng" and "Mike + Nguyen", and "ke Ng" and "san fr" find the names they are part of. A + query of one two-letter word is that word's token: "Ng" finds "Ng" and + "Mike Ng", and not "Nguyen". Stored values do not change. + - The `bf` of every v4 query twin is the new `v4::terms::QueryBloomFilter` + (`TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, + and `TextSearchQuery` and `TextSearchOreQuery`, whose `bf` is an + `Option`). Its JSON and JSON Schema are + `BloomFilter`'s, and `From for BloomFilter` unwraps + it. Its `EncryptTarget` derives the query's filter, so a query twin + built directly, by a field reference's `matches`, or by the by-name + query dispatch follows the one rule. + - `TwinIndex` forwards Stack Encrypt's `Index::query_operation` to the + indexes whose terms its twin carries (`Indexes::query_operations`), so + `matches` on `TextMatch`, `TextSearch` and `TextSearchOre` sends the + query's filter, and every other operator 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 d781e2d628..9f4e1efa51 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -190,10 +190,15 @@ bound: `BETWEEN` needs EQL v4's range query domains and is not produced yet. (`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 +searchable: `@@` with "ng" finds "Ng" and "Mike Ng", not "Nguyen" (words +split on space, comma, semicolon, colon and exclamation mark). A query keeps +its two-letter words only when it cuts no 3-gram, which is when the whole +query is one two-letter word: "Mike Ng" is its 3-grams alone, so it finds +"Mike Ng" and "Mike Nguyen", and "san fr" finds "San Francisco". A query's +filter is a `QueryBloomFilter`, with `BloomFilter`'s JSON. The word token is +one more token per two-letter word in every stored value that holds one, +unique to the word, so rows holding "Ng" can be told from rows holding +"Nguyen". A query is not a plain substring test. 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 c3ed40c1e3..080eeda1a2 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, }; @@ -367,13 +367,17 @@ impl DecryptField for Hmac256 { /// 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. +/// "Mike Ng", "Ng, Mike"), not "Nguyen". A query keeps its word token only +/// when it is one two-letter word: a query that cuts a 3-gram is its +/// 3-grams alone, so "Mike Ng" finds "Mike Ng" and "Mike Nguyen", and "san +/// fr" finds "San Francisco" ([`QueryBloomFilter`]). What it reveals: one +/// more token per two-letter word in every stored value that holds one, +/// under the same PRF (in a domain of its own), in the same filter, by the +/// same containment rule. The token is unique 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. +/// +/// [`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 @@ -516,6 +520,51 @@ impl DecryptField for SearchBloomFilter { } } +/// Builds a query's filter: [`MatchVisitor`]'s filter, so text that cuts no +/// token is refused, over the tokens a query keeps (see +/// [`QueryBloomFilter`]). +#[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 cut of the text: its two-letter words only when it cuts + // no 3-gram. 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 [`BloomFilter`]'s: a query + /// twin holding a `bf` is the 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 06e24a50e8..bf1e357e31 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 `I`'s own query is. 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 @@ -545,14 +556,15 @@ 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 +/// over the tokens the query keeps (its two-letter words only when it cuts +/// no 3-gram, [`QueryBloomFilter`]), and the query keeps those 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. impl Supports for TwinIndex, Q> where - Q: QueryTwin + MaybeSend + 'static, + Q: QueryTwin + MaybeSend + 'static, Q::Plaintext: AsRef + Zeroize + 'static, { type Query = MatchTwin; @@ -573,7 +585,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 9bb121f1a5..cca59ec25f 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 e4a19ce22f..cdabdba7f8 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. The two v4 terms v3 has +//! no use for are [`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 @@ -84,8 +85,9 @@ 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 +/// shared; [`SearchBloomFilter`](terms::SearchBloomFilter) and +/// [`QueryBloomFilter`](terms::QueryBloomFilter); and the JSON of the order +/// terms, [`OreBlockHex`](terms::OreBlockHex) and /// [`OpeHex`](terms::OpeHex), whose fields hold Stack Encrypt's terms. pub mod terms { pub use super::term_formats::{OpeHex, OreBlockHex}; @@ -135,6 +137,49 @@ pub mod terms { filter.0 } } + + /// The `bf` term of a match query (`TextMatchQuery`, + /// `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, and the `bf` of + /// `TextSearchQuery` and `TextSearchOreQuery`): a [`BloomFilter`] over the + /// tokens a query keeps. + /// + /// A stored value's filter holds every token its text cuts: its + /// 3-grams, and each two-letter word whole. A query keeps its two-letter + /// words only when it cuts no 3-gram. So the query "ng" is the word + /// token `ng`, and finds the rows holding the word "Ng" ("Ng", "Mike + /// Ng"), not "Nguyen"; the query "Mike Ng" is its 3-grams alone, and + /// finds "Mike Ng" and "Mike Nguyen", as does "ke Ng"; "san fr" finds + /// "San Francisco". A query sends no token a stored value of its own + /// text lacks, so the rule moves no stored filter. + /// + /// Text that cuts no token (empty, separator-only, or one letter) is + /// refused, as for [`BloomFilter`]: a query's filter is never empty. The + /// JSON is [`BloomFilter`]'s, and so is the JSON Schema; 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 a5d645235f..c4b7165bfe 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 528ed013df..49c63634f1 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! { @@ -462,6 +462,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`]), except an EQL v4 match term: +/// `QueryBloomFilter`, the same JSON as `BloomFilter`, into which Stack +/// Encrypt derives the filter of the tokens a query keeps (its two-letter +/// words only when it cuts no 3-gram), where a stored value's filter holds +/// 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 +528,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 +554,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 +605,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())) @@ -1856,8 +1870,9 @@ 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. + /// the empty filter of text too short for a 3-gram; `TextMatch` keeps + /// `BloomFilter`, which refuses that text; every query's is + /// `QueryBloomFilter`, cut by the query's 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 +1900,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 f423f2596a..f4ca3a5bbd 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 + /// plaintext `source`: the EQL newtype of an `hm` or a `bf` + /// ([`query_term_newtype`], so a `bf` is a `QueryBloomFilter`), Stack /// Encrypt's own term of an `op` or an `ob`. 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 carries + /// ([`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 76a3dfdcf4..74e78d121a 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,139 @@ async fn a_field_reference_match_query_verifies_and_sizes_as_the_data_path_does( } } +/// A field reference's match query keeps a query's two-letter words only +/// when it cuts no 3-gram, as the data path's does, on every type with a +/// match index: `TextMatch`, and `TextSearch` and `TextSearchOre`, whose +/// twins carry the equality and order terms beside the match term. "Ng" is +/// its word and does not find "Nguyen"; "Mike Ng" and "ke Ng" are their +/// 3-grams and 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 record whose match fields all hold "Mike Nguyen", stored. + 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 +1063,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 +1079,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 ad62e1a9e4..0ac3c8bc34 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,94 @@ async fn two_letter_surnames_store_and_are_found() { } } +/// A query keeps its two-letter words only when it cuts no 3-gram, on every +/// path that builds one: the query twins directly (`TextMatchQuery`, +/// `TextSearchMatchQuery`) and the by-name query dispatch a binding runs. +/// So "Mike Ng" is its 3-grams alone and finds "Mike Nguyen", a name typed +/// in part ("ke Ng", "san fr") finds its row, and "Ng" alone is its word +/// token and does not find "Nguyen". Stored values are unchanged: each +/// still carries 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 carries no word token: it is the filter of its + // 3-grams, which a stored value of the same text holds 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 +1106,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] = [ @@ -1112,7 +1200,7 @@ 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. +/// 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 +1290,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 62e2e3bcd8..67d8a633f5 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1362,6 +1362,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **With `MatchOptions::short_words` on, a query keeps its short words only + when it cuts no n-gram** (#1398). A query that held a short word cut that + word's token beside its n-grams, so the word had to be a whole word of + the row: "Mike Ng" no longer found "Mike Nguyen", and "san fr" no longer + found "San Francisco". Now a query that cuts an n-gram sends its n-grams + alone, as it does with the option off, and finds those rows again. A + query that cuts no n-gram, which is a query of one short word, is that + word's token: "Ng" finds "Ng" and "Mike Ng", and not "Nguyen". + - The stored side does not change: a stored value keeps its word tokens, + so no stored filter moves and nothing needs re-encrypting. + - Every query path cuts a query by the one rule, so a filter and its + verify agree: a field query (`Supports::prepare` and the term it + derives), `dynamic::query_term`, `dynamic::term`, `dynamic::verify`, and + `MatchQuery::verify`. + - A field query now derives its term through the new + `Index::query_operation`, which by default is `Index::operation`. A + match index overrides it with the new `target::matching_query`, the + query's filter. An index that wraps another forwards both methods. + - A set of indexes derives a query's terms through the new + `Indexes::query_operations`, each index's `query_operation`, as + `Indexes::operations` derives the stored terms through each index's + `operation`. One index, a tuple and a `Vec` implement it; by default it + is `Indexes::operations`, so a set defined elsewhere that holds a match + index overrides it. + - What it reveals: one more token per short word in every stored value + that holds one, unique to the word, so rows holding "Ng" can be told + from rows holding "Nguyen" and counted. A query of one short word + shows the word token it asks for; a longer query 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 diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 90fd1b3f97..d1576ca052 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 af96b53b74..ef150df68c 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,11 @@ 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 is cut as a query is: with +/// [`short_words`](MatchOptions::short_words) on, a value's short words are +/// tokens only when it cuts no n-gram, so the probe of "Mike Ng" is its +/// trigrams alone, where the record path stores its word token beside them. /// /// # Examples /// @@ -485,7 +489,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 +559,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`: a stored value's term, or the term a query sends, which differ +/// only for a match index with short words ([`Side`]). 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 +577,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 +586,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 +608,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 +629,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 +932,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 +2100,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's rule, and "Ng", which cuts nothing under the default + /// options, is one token under them. A probe is a query: "Ng" cuts + /// no trigram, so it is its word token, the filter "Ng" stores; + /// "Mike Ng" cuts trigrams, so it is its trigrams alone, the filter + /// the index without the option stores, and not the one "Mike Ng" + /// stores under it. #[tokio::test] async fn short_words_drive_the_derivation() { struct ShortWords; @@ -2096,21 +2121,81 @@ 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` is the stored side, + // `query_operation` a field query's, the probe's bytes. + 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 9485a63f58..8a9370a498 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 9c2f155881..8da5c62e5b 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -88,14 +88,16 @@ //! 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. +//! length (and at least 2 characters) adds one token to a stored value's +//! filter: 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 more token per short word, and the +//! token is unique 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 ever indexed. A query sends its word tokens +//! only when it cuts no n-gram ("Ng"); a query that cuts one ("Mike Ng") +//! sends its n-grams alone, as it would 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 +165,7 @@ pub(crate) mod query; mod tokenize; +pub(crate) use tokenize::Side; pub use tokenize::Tokenizer; use std::fmt; @@ -720,20 +723,28 @@ pub struct MatchOptions { /// 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`]). + /// `ng`. /// - /// **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: + /// A query keeps its word tokens only when it cuts no n-gram, which is + /// when the whole query is one short word. "Ng" is one word token and is + /// accepted: it finds the rows holding the word "Ng" ("Ng", "Mike Ng"), + /// and not "Nguyen". "Mike Ng" cuts trigrams, so it asks for its + /// trigrams alone, as with the option off: it finds "Mike Ng", and "Mike + /// Nguyen" too, so a name typed in part still finds its row. So does + /// "Li Wu": its trigrams cross the space. A query that cuts nothing at + /// all, such as one letter, is still refused + /// ([`TermError::EmptyTermText`]). A query is verified by the tokens it + /// asks for, so its filter and its verify agree. + /// + /// **What it reveals.** One more token per short word in every stored + /// value that holds one, under the same PRF, in the same filter, matched + /// by the same containment rule. The token is unique 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. + /// trigram `" ng"` they share was visible, and can count how many rows + /// hold it. A query of short words alone shows which word tokens it asks + /// for. Only words shorter than an n-gram get one, so no bigram of a + /// longer word is ever indexed. /// /// It takes an n-gram tokenizer of length at least 3: the /// [`Standard`](Tokenizer::Standard) tokenizer already emits whole words, @@ -1165,13 +1176,20 @@ 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 under `options`' tokenizer and + /// case folding: its short words only when it cuts no n-gram + /// ([`Side::Query`]). The filter a query sends is derived from the same + /// cut, so a query verifies 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 +1212,13 @@ 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 cut 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,11 +1291,12 @@ 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 a match term of `text` cut for `side` ([`Side`]): a stored +/// value's filter or a query's. 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. /// /// 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, @@ -1290,6 +1310,7 @@ fn match_term( 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 @@ -1298,7 +1319,7 @@ fn match_term( let tokenize::Tokens { tokenizer, short_words, - } = tokenize::tokens(text, &options)?; + } = tokenize::tokens(text, &options, side)?; // 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 +1361,29 @@ fn bloom_positions( .map_err(TermError::from_prf) } +/// The match term of `text` cut for `side`, through the keyset `cipher` +/// holds: derived now when the keyset is loaded, else when it has loaded. +/// 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 +1392,7 @@ fn match_deferred<'a, K, O>( text: &str, context: Context<'_>, options: MatchOptions, + side: Side, ) -> Pending<'a, MatchTerms, K> where O: MatchConfig, @@ -1355,10 +1400,32 @@ 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 a query of `source` sends under `O`'s options: the +/// filter of the tokens the query keeps ([`Side::Query`]), the tokens its +/// [`QueryTokens`] verify a row by. What a field query of a match index +/// derives ([`matching_query`](crate::target::matching_query)), called as +/// [`Term::encrypt_from`] is. +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 +1446,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, + ) } } @@ -2085,8 +2150,9 @@ impl KeysetCipher<'_, K> { /// [`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. + /// every row, and keeps a query's short words only when it cuts no + /// n-gram ([`MatchOptions::short_words`]); this method derives the + /// stored filter and refuses nothing. pub fn match_terms<'c, O>( &self, text: &str, @@ -2095,7 +2161,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 +2189,24 @@ 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 and cut for + /// `side`, for the `dynamic` path, whose plan carries a match index's + /// options as data (an `IndexSpec::Match`) and which derives a stored + /// value's filter and a query's alike. 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. 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 +2469,185 @@ 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 cuts n-grams, 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. + #[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"); + prop_assert_eq!( + derive(&query, Side::Query), + 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 finds the text it was cut from, and any text it + /// is a run of characters of when it cuts an n-gram: 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 +2673,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 +2708,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 ebf2f4c8da..1c65d4e3e2 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 +//! it cuts no 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,36 @@ pub(crate) struct Tokens { pub(crate) short_words: Vec, } +/// Which side of a match a text is cut for: a value to store, or a query +/// to find stored values by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Side { + /// A value to store: every token of both kinds, so that any query of a + /// run of its words finds it. + Stored, + /// A query: the tokenizer's tokens, and the short words only when the + /// tokenizer cut none ([`Tokens::into_query`]). + Query, +} + impl Tokens { + /// The tokens a query keeps of the tokens its text cuts: all of them + /// when the tokenizer cut none, else the tokenizer's alone, the short + /// words wiped. + /// + /// So a query of short words alone ("Ng") is its word tokens, and finds + /// the rows that hold those words whole. A query that cuts an n-gram + /// ("Mike Ng") is its n-grams, as with the option off, and finds the rows + /// that hold them: "Mike Nguyen" as well as "Mike Ng". Every stored + /// value keeps its word tokens, so the rule moves no stored filter, and + /// every token a query keeps is still a token 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 +153,26 @@ 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 cut for `side`: a stored value keeps every token, and a +/// query its short words only when it cuts no n-gram ([`Side`]). +/// /// 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 +344,7 @@ mod tests { downcase: false, ..MatchOptions::default() }, + Side::Stored, ) .expect("tokens") .tokenizer @@ -321,7 +366,8 @@ mod tests { &MatchOptions { tokenizer: Tokenizer::Standard, ..MatchOptions::default() - } + }, + Side::Stored, ), Err(NormalizeError::UnassignedCodePoint) ), @@ -514,7 +560,8 @@ mod tests { &MatchOptions { short_words: true, ..MatchOptions::default() - } + }, + Side::Stored, ) .expect("normalizes") .short_words, @@ -627,6 +674,44 @@ mod tests { } } + /// A query keeps the n-grams its text cuts, and its short + /// words only when it cuts none of them; whichever it + /// keeps, the same text stored holds them. + #[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 +729,78 @@ mod tests { } } + mod given_a_query { + use super::*; + + /// The tokens a query of `text` keeps under 3-grams, downcased, + /// with the short-word filter on, as [`tokens`] cuts 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 34dd774931..e25d6d35a5 100644 --- a/packages/stack-encrypt/src/target/index.rs +++ b/packages/stack-encrypt/src/target/index.rs @@ -62,7 +62,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, @@ -247,7 +249,8 @@ impl fmt::Display for IndexSpec { /// /// 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. +/// alone, and [`query_operation`](Self::query_operation) is 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 +274,20 @@ 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: what a field query + /// derives. By default [`operation`](Self::operation)'s, since most + /// indexes send what they store. A match index cuts a query differently + /// from a stored value ([`matching_query`]), so it overrides this. An + /// index that wraps another forwards both. + fn query_operation<'s, K: 'static, M: WipeSource<'s, S>>( + &self, + ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> + where + S: 's, + { + self.operation() + } } /// The equality (exact-match) index: one PRF block over the whole value. @@ -407,6 +424,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 @@ -504,6 +529,28 @@ pub trait Indexes { where S: 's, M: WipeSource<'s, S>; + /// The description that derives every term a query of `S` sends, each + /// index's [`query_operation`](Index::query_operation), under the one + /// [`CallerContext`] it is handed and settled in one batch, as + /// [`operations`](Self::operations) settles the stored terms. A set + /// that holds a [`Match`](struct@Match) index sends the filter of the + /// tokens the query keeps, where [`operations`](Self::operations) + /// derives a stored value's. + /// + /// By default [`operations`](Self::operations)'s, since most indexes + /// send what they store. Every set in this crate derives each index's + /// query term; a set defined elsewhere that holds a + /// [`Match`](struct@Match) index overrides this, as an index that wraps + /// another forwards [`Index::query_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.operations() + } /// 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. @@ -591,13 +638,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), zipped +/// left to right, and the nested pairs `zip` builds flattened back into one +/// tuple of terms. macro_rules! tuple_of_indexes { ($(($($name:ident $at:tt),+) => $nested:pat,)+) => {$( impl),+> Indexes for ($($name,)+) { @@ -612,14 +669,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)*) => { @@ -678,6 +745,29 @@ impl> Indexes for Vec { }) }) } + fn query_operations<'s, K: 'static, M>( + &self, + ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> + where + 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.query_operation().map(|term| vec![term]), + |terms, index| { + terms + .zip(index.query_operation::()) + .map(|(mut terms, term)| { + terms.push(term); + terms + }) + }, + ) + } } /// One value, sealed, with the terms of its indexes beside it: what diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index c9356d16d9..e3aa7ce038 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 49dde00189..01a87c0627 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -1132,8 +1132,9 @@ where /// 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`]). +/// mode through `$derive`, called as `Term::encrypt_from` is, 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 +1178,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 +1194,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), @@ -1216,8 +1217,30 @@ term_operation!( ); 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] + /// tokenised and hashed as `O` declares: a stored value's filter, which + /// holds every token the text cuts. + matching, crate::sem::MatchTerms, + view( as Term<&S, K, _>>::encrypt_from), + [O: crate::sem::MatchConfig + 'static], [S: AsRef] +); +term_operation!( + /// The match term a query of the text `S` sends, under the context the + /// tree hands it: the filter of the tokens the query keeps, which a + /// stored filter holds when the row holds them. With + /// [`short_words`](crate::sem::MatchOptions::short_words) on, a query's + /// short words are tokens of the filter only when it cuts no n-gram: + /// "Ng" asks for the word `ng`, and "Mike Ng" for its trigrams alone, so + /// it finds "Mike Nguyen" as well as "Mike Ng". With the option off it + /// is [`matching`]'s term. + /// + /// What a field query of a match index derives + /// ([`Index::query_operation`](super::Index::query_operation)). It + /// refuses nothing [`matching`] does not: a query is prepared first + /// ([`Supports::prepare`](crate::op::Supports::prepare)), which refuses + /// text that cuts no token. + 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 9856ca0122..e5c618e401 100644 --- a/packages/stack-encrypt/tests/index.rs +++ b/packages/stack-encrypt/tests/index.rs @@ -493,6 +493,203 @@ mod given_a_set_of_indexes { } } +/// A set of indexes derives a query's terms through each index's own query +/// derivation (`Indexes::query_operations`): a match index's term is the +/// filter of the tokens the query keeps, and every other index's is the +/// term it stores. One index, a tuple and a `Vec` alike. +mod given_a_set_holding_a_match_index_with_short_words { + use super::*; + + /// 3-grams with short-word tokens, so a query that cuts 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: "Ng" is a short word of a query that cuts n-grams, so the + /// query keeps its 3-grams alone, where a stored value holds 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 a set that + /// derived the stored filter for a query would show. + 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" + ); + } + } +} + 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 5995c9083d..c5d5141594 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 it cuts no +//! n-gram: "Ng" is its word token, and "Mike Ng" 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. +//! any run of its whole words, and of any run of its characters that cuts +//! 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,81 @@ mod given_short_words { } } + /// A query that cuts 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 hold their + // bits by chance, but 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 that cuts an n-gram sends the filter the index without the + /// option stores for the same text: 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" ); } @@ -350,6 +409,44 @@ mod given_random_text { Ok(()) })?; } + + /// A query of any run of a text's characters that cuts an n-gram + /// finds the text, filter and `verify` alike, whether or not the + /// run starts or ends inside a word: typeahead and partial names + /// find their rows with short words on. + #[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(()) + })?; + } } } From 98694cc9f1d0b7c8821d33a9667e759b9bd4bf46 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 02:49:06 +1100 Subject: [PATCH 2/4] fix(stack-encrypt,eql-bindings): address review on query match cuts An empty Vec of indexes refused with EmptyIndexes through Encryption::failed, which ignores its source, so in Owned mode the refusal freed the plaintext unwiped. Both Vec::operations and Vec::query_operations now share one fold (each_index, keyed by Side), and its empty branch refuses through a new crate-private Encryption::failed_wiping, which hands the source to WipeSource::wipe first. Two owned wipe-counter tests in tests/index.rs pin it. Index::query_operation and Indexes::query_operations lose their defaults. With a default of the stored term, a wrapper over a short-words Match that forwarded only operation compiled and sent the stored cut, missing "Mike Nguyen" for "Mike Ng". Every built-in index now states its query term, and the CHANGELOG records the breaking change for indexes defined elsewhere. target::matching_query run on its own refuses text that keeps no token with TermError::EmptyTermText (in sem::match_term, for Side::Query), as a field query's prepare does, rather than deriving an empty filter that matches every row. Docs: the Index and Indexes docs point a query at query_operation; the KeysetCipher, MatchConfig, MatchVisitor, SearchBloomFilter and stored_term_newtype docs say match_terms and BloomFilter are the stored cut and QueryBloomFilter the query's; ADR-0004 decision 5 gets a caveat and ADR-0009 an amendment for the query cut. --- .../eql/crates/eql-bindings/src/encryption.rs | 20 ++- .../eql/crates/eql-bindings/src/v4/mod.rs | 9 +- .../eql/crates/eql-codegen/src/bindings.rs | 5 +- packages/stack-encrypt/CHANGELOG.md | 33 +++- ...t-threaded-through-the-declaration-tree.md | 8 + ...and-a-query-term-is-not-the-stored-term.md | 38 +++++ packages/stack-encrypt/src/sem/mod.rs | 66 ++++++-- packages/stack-encrypt/src/target/index.rs | 156 ++++++++++++------ .../stack-encrypt/src/target/operations.rs | 31 +++- packages/stack-encrypt/tests/index.rs | 90 ++++++++++ .../stack-encrypt/tests/match_short_words.rs | 89 ++++++++++ packages/stack-encrypt/tests/op.rs | 10 ++ .../tests/ui/execution_callback.stderr | 7 + ...op_inexact_operator_needs_probabilistic.rs | 5 + ...nexact_operator_needs_probabilistic.stderr | 4 +- 15 files changed, 474 insertions(+), 97 deletions(-) diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 080eeda1a2..2ce43bce3f 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -405,20 +405,22 @@ 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 cut under +/// [`EqlMatch`], so they agree on every token a query keeps; a query keeps +/// fewer tokens than the same text stores, and its filter is +/// [`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, since +/// it must never be empty. A search domain's stored filter, which `=` and +/// `<` find through its other terms, is [`SearchBloomFilter`] and takes the +/// empty filter ([`SearchMatchVisitor`]). #[doc(hidden)] pub struct MatchVisitor; impl Visitor for MatchVisitor { diff --git a/packages/eql/crates/eql-bindings/src/v4/mod.rs b/packages/eql/crates/eql-bindings/src/v4/mod.rs index cdabdba7f8..031a722b08 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -109,10 +109,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, and so does + /// [`QueryBloomFilter`], the filter of every query. The JSON is + /// [`BloomFilter`]'s, and so is the JSON Schema; only what Stack Encrypt + /// derives into it differs. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] #[serde(transparent)] pub struct SearchBloomFilter(pub BloomFilter); diff --git a/packages/eql/crates/eql-codegen/src/bindings.rs b/packages/eql/crates/eql-codegen/src/bindings.rs index 49c63634f1..44494b0af4 100644 --- a/packages/eql/crates/eql-codegen/src/bindings.rs +++ b/packages/eql/crates/eql-codegen/src/bindings.rs @@ -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`, which has no other term, keeps `BloomFilter` +/// and keeps refusing that text; a query's filter is `QueryBloomFilter` +/// ([`query_term_newtype`]), which refuses it 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" diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 67d8a633f5..7f6ac000a7 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,6 +481,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **`Index` and `Indexes` each gain a required method** (#1398). + `Index::query_operation` derives the term a query of the index sends, and + `Indexes::query_operations` derives each index's query term in one batch. + A field query derives through them. Neither has a default: a default of + the stored term would let an index that wraps a match index forward only + `operation` and send the stored cut, which misses rows. To upgrade, an + index defined outside this crate adds `query_operation`, returning the + same description as `operation` when it sends what it stores, and + forwarding to the wrapped index's `query_operation` when it wraps one. A + set of indexes defined outside this crate adds `query_operations`, built + from each index's `query_operation`. 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`, @@ -1377,15 +1389,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 derives), `dynamic::query_term`, `dynamic::term`, `dynamic::verify`, and `MatchQuery::verify`. - A field query now derives its term through the new - `Index::query_operation`, which by default is `Index::operation`. A - match index overrides it with the new `target::matching_query`, the - query's filter. An index that wraps another forwards both methods. + `Index::query_operation` (see Breaking). A match index's is the new + `target::matching_query`, the query's filter; every other index's is + 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`, each index's `query_operation`, as `Indexes::operations` derives the stored terms through each index's - `operation`. One index, a tuple and a `Vec` implement it; by default it - is `Indexes::operations`, so a set defined elsewhere that holds a match - index overrides it. + `operation`. One index, a tuple and a `Vec` implement it. + - `target::matching_query` refuses text that keeps no token + (`TermError::EmptyTermText`), since its empty filter would match every + row: run on its own, it refuses what a field query's `prepare` does. + `target::matching` still stores such text as the empty filter. - What it reveals: one more token per short word in every stored value that holds one, unique to the word, so rows holding "Ng" can be told from rows holding "Nguyen" and counted. A query of one short word @@ -1451,6 +1465,13 @@ 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 wipes an owned plaintext when it refuses + it** (#1398). `Indexes::operations` and `Indexes::query_operations` on an + empty `Vec` refuse with `PlanError::EmptyIndexes`, and in `Owned` mode + the refusal dropped the plaintext without wiping it. The refusal now lets + go of it as an operation does: an owned value is wiped, and a borrow is + left 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 19c4eef5cf..de74030e58 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,14 @@ 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).** `match_terms` is no longer a match +> query's path when `MatchOptions::short_words` is on. It derives a stored +> value's filter, and a query keeps its short words only when it cuts no +> n-gram, so the `match_terms` filter of "Mike Ng" asks for the word `ng` +> and misses "Mike Nguyen". A match query comes from the field's reference, +> or from `target::matching_query`. ADR-0009's amendment of the same date +> has the 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 c55b00824a..e47987e01b 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,41 @@ 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 is now cut differently from the value it would store, so an +index states the term a query sends beside the term it stores. + +- **A query keeps its short words only when it cuts no n-gram.** With + `MatchOptions::short_words` on, a stored value holds every n-gram and + each short word whole. A query that also asked for its short words would + need the word whole in the row, so "Mike Ng" would miss "Mike Nguyen". A + query that cuts an n-gram is its n-grams alone; a query of one short word + ("Ng") is that word's token. The stored side does not change. The rule + lives once, in the tokenizer, and every query path cuts 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 holds one. +- **`Index` has two required methods, `operation` and + `query_operation`.** `operation` derives the term a value stores, and + `query_operation` the term a query sends. A field query derives through + `query_operation`. Most indexes return the same description from both. + `Match` returns `target::matching_query` from `query_operation`, the + filter of the tokens a query keeps. Neither method has a default: with a + default of `operation`, a wrapper that forwarded only `operation` would + compile and send the stored cut, which misses rows. So an index that + wraps another, such as eql-bindings' `TwinIndex`, forwards both. +- **`Indexes` has `query_operations` beside `operations`,** also required. + It derives each index's `query_operation` in one batch, for one index, a + tuple and a `Vec`, as `operations` derives each `operation`. +- **`target::matching_query` is the query cut on its own.** It refuses text + that keeps no token (`TermError::EmptyTermText`), whose empty filter + would match every row, so a caller that runs it outside a field query + gets the refusal a field query's `prepare` gives. `matching` stores such + text as the empty filter. `KeysetCipher::match_terms` derives the stored + filter, so with short words on it is not a query's path. +- **EQL v4's query twins carry `QueryBloomFilter`,** `BloomFilter`'s JSON + and schema, whose `EncryptTarget` derives through `matching_query`. So a + query twin built directly, from a field reference, or by the by-name + query dispatch follows the one rule. diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index 8da5c62e5b..770431573a 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -820,9 +820,13 @@ impl MatchOptions { /// 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. +/// matches a stored filter only when that configuration is the field's. +/// `match_terms` and `Match`'s [`operation`](crate::target::Index::operation) +/// cut a stored value; with [`MatchOptions::short_words`] on, a query is +/// cut by [`matching_query`](crate::target::matching_query), which keeps +/// its short words only when it cuts no n-gram. A plan that is data has one +/// match index per field, and its stored filter and its query both read +/// that index's options. pub trait MatchConfig: Send + Sync + 'static { fn options() -> MatchOptions; @@ -1299,12 +1303,13 @@ impl PrfVisitor<[u8; 32], P> for BloomVisitor { /// and both fold into 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`]). +/// n-gram length with no short word) is the empty filter when stored: no +/// position set, no PRF call, and a value no query matches, since a query +/// always has at least one token and the empty filter holds none of its +/// positions. A query of such text is refused +/// ([`TermError::EmptyTermText`]), because its empty filter would match +/// every row. A field query refuses it earlier, when it is prepared; this +/// refuses it for every other caller of the query cut. fn match_term( prf: &HmacSha256Prf, text: &str, @@ -1316,10 +1321,14 @@ fn match_term( // 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, side)?; + } = 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); @@ -1408,7 +1417,8 @@ where /// filter of the tokens the query keeps ([`Side::Query`]), the tokens its /// [`QueryTokens`] verify a row by. What a field query of a match index /// derives ([`matching_query`](crate::target::matching_query)), called as -/// [`Term::encrypt_from`] is. +/// [`Term::encrypt_from`] is. 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>, @@ -2088,6 +2098,14 @@ order_term! { /// identical either way; what differs is whether anything holds the two in /// agreement. /// +/// [`match_terms`](Self::match_terms) is the exception: it derives a stored +/// value's filter, which is a query's only while +/// [`MatchOptions::short_words`] is off. With the option on, a query keeps +/// its short words only when it cuts no n-gram, so the filter of "Mike Ng" +/// from `match_terms` asks for the word `ng` and misses "Mike Nguyen". A +/// match query comes from the field's reference (`matches(..)`), or from +/// [`matching_query`](crate::target::matching_query) run on its own. +/// /// The descriptor is a context /// as the target-directed leaves take it — a [`NonEmpty`]: /// `nonempty!("users").with("email")`, `NonEmpty::new(column)?`, @@ -2589,17 +2607,29 @@ mod tests { proptest! { /// A query's filter is the filter of exactly the tokens it - /// verifies by, so no row the filter rejects would verify. + /// 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"); - prop_assert_eq!( - derive(&query, Side::Query), - filter_of(&prf, &tokens.0), - "the filter of {:?}", - query - ); + 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 diff --git a/packages/stack-encrypt/src/target/index.rs b/packages/stack-encrypt/src/target/index.rs index e25d6d35a5..7ee1f0ab79 100644 --- a/packages/stack-encrypt/src/target/index.rs +++ b/packages/stack-encrypt/src/target/index.rs @@ -49,8 +49,9 @@ //! ``` //! //! 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 +//! picks an index out of a set by type, [`Index::query_operation`] is the +//! term a query of it sends, and [`Index::operation`] the term it stores. A +//! field query does not use `select`: the field's //! target type names the index that answers each operator //! ([`Answers`](crate::op::Answers)). //! @@ -74,7 +75,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; @@ -276,18 +277,19 @@ pub trait Index { S: 's; /// The description that derives the term a query of `S` sends, under /// the [`CallerContext`] it is handed when it runs: what a field query - /// derives. By default [`operation`](Self::operation)'s, since most - /// indexes send what they store. A match index cuts a query differently - /// from a stored value ([`matching_query`]), so it overrides this. An - /// index that wraps another forwards both. + /// derives. + /// + /// Most indexes send the term they store, and return + /// [`operation`](Self::operation)'s description here. A match index + /// cuts a query differently from a stored value ([`matching_query`]): + /// with short words on, a query that sent the stored cut would miss rows + /// it should find. So there is no default, and an index that wraps + /// another forwards 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, - { - self.operation() - } + S: 's; } /// The equality (exact-match) index: one PRF block over the whole value. @@ -410,6 +412,15 @@ impl Index for Equality { { equality() } + /// The term it stores: a query sends the same term. + 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; @@ -449,6 +460,15 @@ where { ore() } + /// The term it stores: a query sends the same term. + 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 @@ -466,6 +486,15 @@ where { ope() } + /// The term it stores: a query sends the same term. + 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 @@ -483,6 +512,15 @@ where { ore_block() } + /// The term it stores: a query sends the same term. + 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 @@ -498,6 +536,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 reads the terms it sends + /// out of 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 @@ -535,25 +580,19 @@ pub trait Indexes { /// [`operations`](Self::operations) settles the stored terms. A set /// that holds a [`Match`](struct@Match) index sends the filter of the /// tokens the query keeps, where [`operations`](Self::operations) - /// derives a stored value's. - /// - /// By default [`operations`](Self::operations)'s, since most indexes - /// send what they store. Every set in this crate derives each index's - /// query term; a set defined elsewhere that holds a - /// [`Match`](struct@Match) index overrides this, as an index that wraps - /// another forwards [`Index::query_operation`]. + /// derives a stored value's. 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>, - { - self.operations() - } + 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. + /// [`query_operation`](Index::query_operation) is 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 @@ -719,7 +758,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 { @@ -732,18 +772,7 @@ 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| { - terms - .zip(index.operation::()) - .map(|(mut terms, term)| { - terms.push(term); - terms - }) - }) + each_index(self, Side::Stored) } fn query_operations<'s, K: 'static, M>( &self, @@ -752,21 +781,46 @@ 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.query_operation().map(|term| vec![term]), - |terms, index| { - terms - .zip(index.query_operation::()) - .map(|(mut terms, term)| { - terms.push(term); - terms - }) - }, - ) + each_index(self, Side::Query) + } +} + +/// The description that derives each of `indexes`' terms 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), and the +/// refusal lets go of 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(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/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 01a87c0627..2fb0cb1a48 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -181,6 +181,25 @@ 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 let go + /// of the plaintext it is handed through [`WipeSource`]: in + /// [`Owned`] mode the value is wiped, and a borrow is left + /// with the caller. A description that refuses before any operation has + /// taken its plaintext uses this, so the refusal does not free the value + /// unwiped. + 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 @@ -1231,13 +1250,15 @@ term_operation!( /// short words are tokens of the filter only when it cuts no n-gram: /// "Ng" asks for the word `ng`, and "Mike Ng" for its trigrams alone, so /// it finds "Mike Nguyen" as well as "Mike Ng". With the option off it - /// is [`matching`]'s term. + /// is [`matching`]'s term of any text that cuts a token. /// /// What a field query of a match index derives - /// ([`Index::query_operation`](super::Index::query_operation)). It - /// refuses nothing [`matching`] does not: a query is prepared first - /// ([`Supports::prepare`](crate::op::Supports::prepare)), which refuses - /// text that cuts no token. + /// ([`Index::query_operation`](super::Index::query_operation)). Text + /// that cuts 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] diff --git a/packages/stack-encrypt/tests/index.rs b/packages/stack-encrypt/tests/index.rs index e5c618e401..b8f8a86276 100644 --- a/packages/stack-encrypt/tests/index.rs +++ b/packages/stack-encrypt/tests/index.rs @@ -690,6 +690,96 @@ mod given_a_set_holding_a_match_index_with_short_words { } } +/// An empty `Vec` of indexes handed a plaintext by value: the refusal is the +/// operation that lets go of it, so it 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 c5d5141594..572e36aa92 100644 --- a/packages/stack-encrypt/tests/match_short_words.rs +++ b/packages/stack-encrypt/tests/match_short_words.rs @@ -233,6 +233,95 @@ mod given_short_words { ); } + /// The query cut run on its own, as a binding or an index defined + /// elsewhere runs it, refuses text that cuts no token as a field query + /// does: its empty filter would match every row. The stored cut keeps + /// 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)] diff --git a/packages/stack-encrypt/tests/op.rs b/packages/stack-encrypt/tests/op.rs index 83e1e6a00e..09d55a5b90 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 7b6f890c45..82e8940b00 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 e80a69f0d7..4d408118ec 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 248900eee4..e43a477c07 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` From 931be62bed2f2e0873c40e668bd870c0d7b24d7b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 03:40:04 +1100 Subject: [PATCH 3/4] docs(stack-encrypt): a query keeps its words when it is shorter than the n-gram The docs said a query cuts no n-gram only when it is one short word. That holds for trigrams, but the n-gram length is an option: under 6-grams "Ng Wu" cuts no n-gram and asks for both its words. Say what the condition is instead. The EQL and Go docs keep "one two-letter word", because both use 3-grams. --- packages/stack-encrypt/CHANGELOG.md | 11 +++++++---- ...e-index-and-a-query-term-is-not-the-stored-term.md | 5 +++-- packages/stack-encrypt/src/sem/mod.rs | 6 ++++-- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7f6ac000a7..e46b3aa8ea 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1380,8 +1380,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the row: "Mike Ng" no longer found "Mike Nguyen", and "san fr" no longer found "San Francisco". Now a query that cuts an n-gram sends its n-grams alone, as it does with the option off, and finds those rows again. A - query that cuts no n-gram, which is a query of one short word, is that - word's token: "Ng" finds "Ng" and "Mike Ng", and not "Nguyen". + query that cuts no n-gram (its whole text is shorter than the n-gram + length) asks for its word tokens: "Ng" finds "Ng" and "Mike Ng", and not + "Nguyen". With trigrams that is one short word; with longer n-grams it + can be several words, such as "Ng Wu" under 6-grams. - The stored side does not change: a stored value keeps its word tokens, so no stored filter moves and nothing needs re-encrypting. - Every query path cuts a query by the one rule, so a filter and its @@ -1402,8 +1404,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `target::matching` still stores such text as the empty filter. - What it reveals: one more token per short word in every stored value that holds one, unique to the word, so rows holding "Ng" can be told - from rows holding "Nguyen" and counted. A query of one short word - shows the word token it asks for; a longer query sends no word token. + from rows holding "Nguyen" and counted. A query shorter than the + n-gram length shows the word tokens it asks for; a query that cuts 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 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 e47987e01b..9ff56f3583 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 @@ -1335,8 +1335,9 @@ index states the term a query sends beside the term it stores. `MatchOptions::short_words` on, a stored value holds every n-gram and each short word whole. A query that also asked for its short words would need the word whole in the row, so "Mike Ng" would miss "Mike Nguyen". A - query that cuts an n-gram is its n-grams alone; a query of one short word - ("Ng") is that word's token. The stored side does not change. The rule + query that cuts an n-gram is its n-grams alone; a query that cuts none, + because its whole text is shorter than the n-gram length ("Ng" under + trigrams, "Ng Wu" under 6-grams), is its word tokens. The stored side does not change. The rule lives once, in the tokenizer, and every query path cuts 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 diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index 770431573a..fdf7a880a8 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -726,8 +726,10 @@ pub struct MatchOptions { /// `ng`. /// /// A query keeps its word tokens only when it cuts no n-gram, which is - /// when the whole query is one short word. "Ng" is one word token and is - /// accepted: it finds the rows holding the word "Ng" ("Ng", "Mike Ng"), + /// when the whole query is shorter than the n-gram length. With trigrams + /// that is one short word; with longer n-grams it can be several, so + /// under 6-grams "Ng Wu" asks for both its words. "Ng" is one word token + /// and is accepted: it finds the rows holding the word "Ng" ("Ng", "Mike Ng"), /// and not "Nguyen". "Mike Ng" cuts trigrams, so it asks for its /// trigrams alone, as with the option off: it finds "Mike Ng", and "Mike /// Nguyen" too, so a name typed in part still finds its row. So does From b0d2a9d6b99d42586d5fe0b163b0715be8201c9d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 12:31:23 +1100 Subject: [PATCH 4/4] docs(stack-encrypt,eql-bindings): rewrite the short-word query docs in plain language The docs this branch added or changed were hard to follow. They used "cut" for several ideas, packed several facts into each sentence, and mixed the value an app stores with the query it sends. Each passage now leads with what the reader must do or must not do, then gives the reason, with "Mike Ng" and "Mike Nguyen" as the example. "n-gram", "short word" and "token" are defined where they first appear. The rule is stated one way everywhere: a query keeps its short words only when its whole text is shorter than one n-gram. In the EQL and Go docs that is a query of one two-letter word. The rewrite covers the rustdoc and comments in stack-encrypt, eql-bindings and eql-codegen, the ADR-0004 and ADR-0009 amendments, the stack-encrypt, eql-bindings and Go changelogs, the changeset, and the eql-bindings and Go READMEs. Every fact is kept, including the leakage note, the upgrade steps for the new required methods, and why query_operation has no default. Rustdoc and Go docs no longer describe what was visible before the option; they say what is visible without it. No code changes. --- .changeset/eql-v4-match-short-words.md | 29 ++- languages/golang/CHANGELOG.md | 27 +- languages/golang/cmd/stashgen/README.md | 2 +- languages/golang/encrypt/README.md | 28 +- languages/golang/encrypt/eql_v4_test.go | 4 +- packages/eql/crates/eql-bindings/CHANGELOG.md | 47 ++-- packages/eql/crates/eql-bindings/README.md | 36 ++- .../eql/crates/eql-bindings/src/encryption.rs | 57 +++-- .../eql-bindings/src/encryption/query.rs | 19 +- .../eql/crates/eql-bindings/src/v4/mod.rs | 65 +++-- .../eql/crates/eql-codegen/src/bindings.rs | 26 +- .../eql/crates/eql-codegen/src/targets.rs | 8 +- .../tests/encryption/tests/typed_queries.rs | 16 +- .../eql/tests/encryption/tests/v4_types.rs | 29 ++- packages/stack-encrypt/CHANGELOG.md | 115 +++++---- ...t-threaded-through-the-declaration-tree.md | 22 +- ...and-a-query-term-is-not-the-stored-term.md | 93 ++++--- packages/stack-encrypt/src/dynamic/term.rs | 30 ++- packages/stack-encrypt/src/sem/mod.rs | 239 ++++++++++-------- packages/stack-encrypt/src/sem/tokenize.rs | 50 ++-- packages/stack-encrypt/src/target/index.rs | 80 +++--- .../stack-encrypt/src/target/operations.rs | 59 +++-- packages/stack-encrypt/tests/index.rs | 27 +- .../stack-encrypt/tests/match_short_words.rs | 45 ++-- 24 files changed, 661 insertions(+), 492 deletions(-) diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index d41798cecf..a2bea966e3 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 keeps its two-letter words only when it cuts no 3-gram, which is when the whole query is one two-letter word: "Mike Ng" is its 3-grams alone and finds "Mike Ng" and "Mike Nguyen", as it would without the word tokens, so a name typed in part ("ke Ng", "san fr") still finds its row. Every query path follows this rule (a field reference's `matches`, the query twins' `EncryptTarget`, the by-name query dispatch a binding runs, and `verify`), so a filter and its verify agree. A query twin's filter is the new `v4::terms::QueryBloomFilter` field type (`TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, and the `bf` of `TextSearchQuery` and `TextSearchOreQuery`), with `BloomFilter`'s JSON and JSON Schema; it changes fields of the unreleased `v4` module only. 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 in every stored value that holds one, under the same PRF, in the same filter, by the same containment rule. The token is unique 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, and can count them. A query of one two-letter word shows which word it asks for; a longer query sends no word token. 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 6574e4a75c..358b43c1b0 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -153,15 +153,24 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. 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). A query that held a two-letter word - also asked for that word whole, so "Mike Ng" did not find "Mike Nguyen". - Now a query keeps its two-letter words only when it cuts no 3-gram, - which is when the whole query is one two-letter word. "Mike Ng" is its - 3-grams alone and finds "Mike Ng" and "Mike Nguyen", and "ke Ng" finds - "Mike Ng". "Ng" is still its word token, and finds "Ng" and "Mike Ng" and - not "Nguyen". `Verify` keeps the same rows the filter selects. Stored - values do not change, so nothing needs re-encrypting. +- **`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 diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 077f3b824c..5c4b1800a4 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 keeps its two-letter words only when it cuts no 3-gram, so "Mike Ng" is its 3-grams alone and finds "Mike Nguyen" too. +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 8d5061bfe9..e88e10efd8 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -661,17 +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 keeps its two-letter words only when it cuts no 3-gram, which is -when the whole query is one two-letter word: "Mike Ng" is its 3-grams alone, -so it finds "Mike Ng" and "Mike Nguyen", and a name typed in part, such as -"ke Ng", finds its row. The word token is one more token per two-letter word -in every stored value that holds one, unique to the word: someone who -clusters tokens across rows can tell the rows holding "Ng" from those -holding "Nguyen", and count them, 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 d17821ca94..ccd402cc76 100644 --- a/languages/golang/encrypt/eql_v4_test.go +++ b/languages/golang/encrypt/eql_v4_test.go @@ -297,8 +297,8 @@ 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 that cuts a 3-gram keeps no two-letter word, so a name typed - // in part finds the longer name too. + // 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) diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 394edff730..cfd46a5c83 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -224,26 +224,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **A match query keeps its two-letter words only when it cuts no - 3-gram** (#1398, `stack-encrypt` feature). `EqlMatch` indexes each - two-letter word whole, and a query holding one also asked for that - word, so "Mike Ng" did not find "Mike Nguyen". Now a query that cuts a - 3-gram is its 3-grams alone: "Mike Ng" finds "Mike Ng" and "Mike - Nguyen", and "ke Ng" and "san fr" find the names they are part of. A - query of one two-letter word is that word's token: "Ng" finds "Ng" and - "Mike Ng", and not "Nguyen". Stored values do not change. - - The `bf` of every v4 query twin is the new `v4::terms::QueryBloomFilter` - (`TextMatchQuery`, `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, - and `TextSearchQuery` and `TextSearchOreQuery`, whose `bf` is an - `Option`). Its JSON and JSON Schema are - `BloomFilter`'s, and `From for BloomFilter` unwraps - it. Its `EncryptTarget` derives the query's filter, so a query twin - built directly, by a field reference's `matches`, or by the by-name - query dispatch follows the one rule. +- **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 carries (`Indexes::query_operations`), so - `matches` on `TextMatch`, `TextSearch` and `TextSearchOre` sends the - query's filter, and every other operator the term its index stores. + 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 9f4e1efa51..4ea64bec46 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -186,19 +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" (words -split on space, comma, semicolon, colon and exclamation mark). A query keeps -its two-letter words only when it cuts no 3-gram, which is when the whole -query is one two-letter word: "Mike Ng" is its 3-grams alone, so it finds -"Mike Ng" and "Mike Nguyen", and "san fr" finds "San Francisco". A query's -filter is a `QueryBloomFilter`, with `BloomFilter`'s JSON. The word token is -one more token per two-letter word in every stored value that holds one, -unique to the word, so rows holding "Ng" can be told from rows holding -"Nguyen". 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 2ce43bce3f..7df390c539 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -365,17 +365,21 @@ 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 keeps its word token only -/// when it is one two-letter word: a query that cuts a 3-gram is its -/// 3-grams alone, so "Mike Ng" finds "Mike Ng" and "Mike Nguyen", and "san -/// fr" finds "San Francisco" ([`QueryBloomFilter`]). What it reveals: one -/// more token per two-letter word in every stored value that holds one, -/// under the same PRF (in a domain of its own), in the same filter, by the -/// same containment rule. The token is unique 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 /// @@ -406,9 +410,9 @@ impl MatchConfig for EqlMatch { /// Builds EQL's bloom filter, the set bit positions as `smallint`s, from the /// native match terms built under [`EqlMatch`]: `TextMatch`'s stored -/// filter. Every stored filter and every query filter is cut under -/// [`EqlMatch`], so they agree on every token a query keeps; a query keeps -/// fewer tokens than the same text stores, and its filter is +/// 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. @@ -417,10 +421,11 @@ impl MatchConfig for EqlMatch { /// with no two-letter word, such as one letter) is refused with /// [`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, since -/// it must never be empty. A search domain's stored filter, which `=` and -/// `<` find through its other terms, is [`SearchBloomFilter`] and takes the -/// empty filter ([`SearchMatchVisitor`]). +/// 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 { @@ -522,9 +527,9 @@ impl DecryptField for SearchBloomFilter { } } -/// Builds a query's filter: [`MatchVisitor`]'s filter, so text that cuts no -/// token is refused, over the tokens a query keeps (see -/// [`QueryBloomFilter`]). +/// 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 { @@ -545,15 +550,15 @@ impl + Zeroize> EncryptTarget for QueryBloomFilter { where S: 's, { - // A query's cut of the text: its two-letter words only when it cuts - // no 3-gram. The annotation names the match configuration, as for - // `BloomFilter`. + // 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 [`BloomFilter`]'s: a query - /// twin holding a `bf` is the query of that index. + /// 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())] } diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index bf1e357e31..fdaf9e1537 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -348,8 +348,8 @@ 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`. 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 `I`'s own query is. +/// ([`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 { @@ -555,13 +555,14 @@ 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 tokens the query keeps (its two-letter words only when it cuts -/// no 3-gram, [`QueryBloomFilter`]), and the query keeps those 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, diff --git a/packages/eql/crates/eql-bindings/src/v4/mod.rs b/packages/eql/crates/eql-bindings/src/v4/mod.rs index 031a722b08..d33ffffa6b 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -38,10 +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 two v4 terms v3 has -//! no use for are [`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 +//! (`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 @@ -84,11 +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 -/// [`QueryBloomFilter`](terms::QueryBloomFilter); 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}; @@ -110,9 +113,9 @@ pub mod terms { /// match projection refuses such text, and the SQL refuses `"bf": []`). /// /// [`BloomFilter`], `TextMatch`'s stored filter, still refuses such - /// text, since `TextMatch` has no other term to find it by, and so does - /// [`QueryBloomFilter`], the filter of every query. The JSON is - /// [`BloomFilter`]'s, and so is the JSON Schema; only what Stack Encrypt + /// 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)] @@ -139,24 +142,30 @@ pub mod terms { } } - /// The `bf` term of a match query (`TextMatchQuery`, - /// `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, and the `bf` of - /// `TextSearchQuery` and `TextSearchOreQuery`): a [`BloomFilter`] over the - /// tokens a query keeps. + /// 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 stored value's filter holds every token its text cuts: its - /// 3-grams, and each two-letter word whole. A query keeps its two-letter - /// words only when it cuts no 3-gram. So the query "ng" is the word - /// token `ng`, and finds the rows holding the word "Ng" ("Ng", "Mike - /// Ng"), not "Nguyen"; the query "Mike Ng" is its 3-grams alone, and - /// finds "Mike Ng" and "Mike Nguyen", as does "ke Ng"; "san fr" finds - /// "San Francisco". A query sends no token a stored value of its own - /// text lacks, so the rule moves no stored filter. + /// A query sends no token that a stored value of its own text lacks. So + /// the rule changes no stored filter. /// - /// Text that cuts no token (empty, separator-only, or one letter) is - /// refused, as for [`BloomFilter`]: a query's filter is never empty. The - /// JSON is [`BloomFilter`]'s, and so is the JSON Schema; only what Stack - /// Encrypt derives into it differs. + /// 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); diff --git a/packages/eql/crates/eql-codegen/src/bindings.rs b/packages/eql/crates/eql-codegen/src/bindings.rs index 44494b0af4..1b0d38972a 100644 --- a/packages/eql/crates/eql-codegen/src/bindings.rs +++ b/packages/eql/crates/eql-codegen/src/bindings.rs @@ -452,9 +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. `TextMatch`, which has no other term, keeps `BloomFilter` -/// and keeps refusing that text; a query's filter is `QueryBloomFilter` -/// ([`query_term_newtype`]), which refuses it too. +/// 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" @@ -463,12 +463,12 @@ 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`]), except an EQL v4 match term: -/// `QueryBloomFilter`, the same JSON as `BloomFilter`, into which Stack -/// Encrypt derives the filter of the tokens a query keeps (its two-letter -/// words only when it cuts no 3-gram), where a stored value's filter holds -/// them all. +/// 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" @@ -1870,10 +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` keeps - /// `BloomFilter`, which refuses that text; every query's is - /// `QueryBloomFilter`, cut by the query's rule. 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")); diff --git a/packages/eql/crates/eql-codegen/src/targets.rs b/packages/eql/crates/eql-codegen/src/targets.rs index f4ca3a5bbd..378178d430 100644 --- a/packages/eql/crates/eql-codegen/src/targets.rs +++ b/packages/eql/crates/eql-codegen/src/targets.rs @@ -163,9 +163,9 @@ 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` - /// ([`query_term_newtype`], so a `bf` is a `QueryBloomFilter`), 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.term_import() { TermImport::Newtype(name) => { @@ -180,7 +180,7 @@ impl IndexKey { } /// The name `answers.rs` imports the twin's term type by, and where - /// from. An `hm` or a `bf` is the newtype a query carries + /// 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 { diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index 74e78d121a..6d067113cc 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -581,12 +581,14 @@ async fn a_field_reference_match_query_verifies_and_sizes_as_the_data_path_does( } } -/// A field reference's match query keeps a query's two-letter words only -/// when it cuts no 3-gram, as the data path's does, on every type with a -/// match index: `TextMatch`, and `TextSearch` and `TextSearchOre`, whose -/// twins carry the equality and order terms beside the match term. "Ng" is -/// its word and does not find "Nguyen"; "Mike Ng" and "ke Ng" are their -/// 3-grams and find "Mike Nguyen". +/// 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::*; @@ -628,7 +630,7 @@ mod given_a_two_letter_word_in_a_match_query { } } - /// A record whose match fields all hold "Mike Nguyen", stored. + /// A stored record whose match fields all contain "Mike Nguyen". async fn scenario(keyset: &Keyset<'_>) -> EncryptedColumns { Columns { text_match: "Mike Nguyen".into(), diff --git a/packages/eql/tests/encryption/tests/v4_types.rs b/packages/eql/tests/encryption/tests/v4_types.rs index 0ac3c8bc34..6f48852ec3 100644 --- a/packages/eql/tests/encryption/tests/v4_types.rs +++ b/packages/eql/tests/encryption/tests/v4_types.rs @@ -999,13 +999,16 @@ async fn two_letter_surnames_store_and_are_found() { } } -/// A query keeps its two-letter words only when it cuts no 3-gram, on every -/// path that builds one: the query twins directly (`TextMatchQuery`, -/// `TextSearchMatchQuery`) and the by-name query dispatch a binding runs. -/// So "Mike Ng" is its 3-grams alone and finds "Mike Nguyen", a name typed -/// in part ("ke Ng", "san fr") finds its row, and "Ng" alone is its word -/// token and does not find "Nguyen". Stored values are unchanged: each -/// still carries its word tokens. +/// 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; @@ -1068,8 +1071,9 @@ async fn a_query_keeps_its_two_letter_words_only_when_it_cuts_no_trigram() { "{needle:?} on {text:?}" ); } - // A query of 3-grams carries no word token: it is the filter of its - // 3-grams, which a stored value of the same text holds beside its words. + // 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()) @@ -1198,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 is its 3-grams, so it finds a longer name too. +/// `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() { diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index e46b3aa8ea..fe57fdcac2 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -481,17 +481,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking -- **`Index` and `Indexes` each gain a required method** (#1398). - `Index::query_operation` derives the term a query of the index sends, and - `Indexes::query_operations` derives each index's query term in one batch. - A field query derives through them. Neither has a default: a default of - the stored term would let an index that wraps a match index forward only - `operation` and send the stored cut, which misses rows. To upgrade, an - index defined outside this crate adds `query_operation`, returning the - same description as `operation` when it sends what it stores, and - forwarding to the wrapped index's `query_operation` when it wraps one. A - set of indexes defined outside this crate adds `query_operations`, built - from each index's `query_operation`. No stored byte changes. +- **`Index` and `Indexes` each gain a required method** (#1398). A field + query now derives its terms through these methods. + - `Index::query_operation` derives the term that a query of the index + 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, @@ -1374,39 +1382,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **With `MatchOptions::short_words` on, a query keeps its short words only - when it cuts no n-gram** (#1398). A query that held a short word cut that - word's token beside its n-grams, so the word had to be a whole word of - the row: "Mike Ng" no longer found "Mike Nguyen", and "san fr" no longer - found "San Francisco". Now a query that cuts an n-gram sends its n-grams - alone, as it does with the option off, and finds those rows again. A - query that cuts no n-gram (its whole text is shorter than the n-gram - length) asks for its word tokens: "Ng" finds "Ng" and "Mike Ng", and not - "Nguyen". With trigrams that is one short word; with longer n-grams it - can be several words, such as "Ng Wu" under 6-grams. - - The stored side does not change: a stored value keeps its word tokens, - so no stored filter moves and nothing needs re-encrypting. - - Every query path cuts a query by the one rule, so a filter and its - verify agree: a field query (`Supports::prepare` and the term it - derives), `dynamic::query_term`, `dynamic::term`, `dynamic::verify`, and - `MatchQuery::verify`. - - A field query now derives its term through the new - `Index::query_operation` (see Breaking). A match index's is the new - `target::matching_query`, the query's filter; every other index's is - its `operation`. An index that wraps another forwards both methods. +- **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`, each index's `query_operation`, as - `Indexes::operations` derives the stored terms through each index's - `operation`. One index, a tuple and a `Vec` implement it. - - `target::matching_query` refuses text that keeps no token - (`TermError::EmptyTermText`), since its empty filter would match every - row: run on its own, it refuses what a field query's `prepare` does. - `target::matching` still stores such text as the empty filter. - - What it reveals: one more token per short word in every stored value - that holds one, unique to the word, so rows holding "Ng" can be told - from rows holding "Nguyen" and counted. A query shorter than the - n-gram length shows the word tokens it asks for; a query that cuts an - n-gram sends no word token. + `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 @@ -1468,12 +1484,13 @@ 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 wipes an owned plaintext when it refuses - it** (#1398). `Indexes::operations` and `Indexes::query_operations` on an - empty `Vec` refuse with `PlanError::EmptyIndexes`, and in `Owned` mode - the refusal dropped the plaintext without wiping it. The refusal now lets - go of it as an operation does: an owned value is wiped, and a borrow is - left with the caller. +- **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 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 de74030e58..6b69068b92 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,13 +208,21 @@ 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).** `match_terms` is no longer a match -> query's path when `MatchOptions::short_words` is on. It derives a stored -> value's filter, and a query keeps its short words only when it cuts no -> n-gram, so the `match_terms` filter of "Mike Ng" asks for the word `ng` -> and misses "Mike Nguyen". A match query comes from the field's reference, -> or from `target::matching_query`. ADR-0009's amendment of the same date -> has the rule. +> **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 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 9ff56f3583..956b2d7a1d 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 @@ -1328,39 +1328,60 @@ index the field declares for the operator. ## Amended 2026-11-23 (#1398) -A match query is now cut differently from the value it would store, so an -index states the term a query sends beside the term it stores. - -- **A query keeps its short words only when it cuts no n-gram.** With - `MatchOptions::short_words` on, a stored value holds every n-gram and - each short word whole. A query that also asked for its short words would - need the word whole in the row, so "Mike Ng" would miss "Mike Nguyen". A - query that cuts an n-gram is its n-grams alone; a query that cuts none, - because its whole text is shorter than the n-gram length ("Ng" under - trigrams, "Ng Wu" under 6-grams), is its word tokens. The stored side does not change. The rule - lives once, in the tokenizer, and every query path cuts 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 holds one. -- **`Index` has two required methods, `operation` and - `query_operation`.** `operation` derives the term a value stores, and - `query_operation` the term a query sends. A field query derives through - `query_operation`. Most indexes return the same description from both. - `Match` returns `target::matching_query` from `query_operation`, the - filter of the tokens a query keeps. Neither method has a default: with a - default of `operation`, a wrapper that forwarded only `operation` would - compile and send the stored cut, which misses rows. So an index that - wraps another, such as eql-bindings' `TwinIndex`, forwards both. -- **`Indexes` has `query_operations` beside `operations`,** also required. - It derives each index's `query_operation` in one batch, for one index, a - tuple and a `Vec`, as `operations` derives each `operation`. -- **`target::matching_query` is the query cut on its own.** It refuses text - that keeps no token (`TermError::EmptyTermText`), whose empty filter - would match every row, so a caller that runs it outside a field query - gets the refusal a field query's `prepare` gives. `matching` stores such - text as the empty filter. `KeysetCipher::match_terms` derives the stored - filter, so with short words on it is not a query's path. -- **EQL v4's query twins carry `QueryBloomFilter`,** `BloomFilter`'s JSON - and schema, whose `EncryptTarget` derives through `matching_query`. So a - query twin built directly, from a field reference, or by the by-name - query dispatch follows the one rule. +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/term.rs b/packages/stack-encrypt/src/dynamic/term.rs index ef150df68c..805797eafa 100644 --- a/packages/stack-encrypt/src/dynamic/term.rs +++ b/packages/stack-encrypt/src/dynamic/term.rs @@ -416,10 +416,11 @@ impl TryFrom for MatchWire { } /// Derive one index term's frozen byte encoding, as a query sends it. A -/// match term is cut as a query is: with -/// [`short_words`](MatchOptions::short_words) on, a value's short words are -/// tokens only when it cuts no n-gram, so the probe of "Mike Ng" is its -/// trigrams alone, where the record path stores its word token beside them. +/// 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 /// @@ -560,8 +561,8 @@ impl AsRef<[u8]> for TermBytes { } /// Walk `value` to its one scalar and derive `kind`'s term there, for -/// `side`: a stored value's term, or the term a query sends, which differ -/// only for a match index with short words ([`Side`]). Nothing is +/// `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. /// @@ -2101,12 +2102,12 @@ mod tests { } /// The data path derives a short-word index's query term by the - /// query's rule, and "Ng", which cuts nothing under the default - /// options, is one token under them. A probe is a query: "Ng" cuts - /// no trigram, so it is its word token, the filter "Ng" stores; - /// "Mike Ng" cuts trigrams, so it is its trigrams alone, the filter - /// the index without the option stores, and not the one "Mike Ng" - /// stores under it. + /// 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; @@ -2160,8 +2161,9 @@ mod tests { stored("Mike Ng").await, "and not the stored filter, which holds the word token too" ); - // The index as a description: `operation` is the stored side, - // `query_operation` a field query's, the probe's bytes. + // 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; diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index fdf7a880a8..c8bf0682e2 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -87,17 +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 to a stored value's -//! filter: 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 more token per short word, and the -//! token is unique 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 ever indexed. A query sends its word tokens -//! only when it cuts no n-gram ("Ng"); a query that cuts one ("Mike Ng") -//! sends its n-grams alone, as it would with the option off. +//! 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 @@ -721,32 +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`. + /// 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`]). /// - /// A query keeps its word tokens only when it cuts no n-gram, which is - /// when the whole query is shorter than the n-gram length. With trigrams - /// that is one short word; with longer n-grams it can be several, so - /// under 6-grams "Ng Wu" asks for both its words. "Ng" is one word token - /// and is accepted: it finds the rows holding the word "Ng" ("Ng", "Mike Ng"), - /// and not "Nguyen". "Mike Ng" cuts trigrams, so it asks for its - /// trigrams alone, as with the option off: it finds "Mike Ng", and "Mike - /// Nguyen" too, so a name typed in part still finds its row. So does - /// "Li Wu": its trigrams cross the space. A query that cuts nothing at - /// all, such as one letter, is still refused - /// ([`TermError::EmptyTermText`]). A query is verified by the tokens it - /// asks for, so its filter and its verify agree. + /// A query's verify checks the same tokens the query asks for, so its + /// filter and its verify agree. /// - /// **What it reveals.** One more token per short word in every stored - /// value that holds one, under the same PRF, in the same filter, matched - /// by the same containment rule. The token is unique 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, and can count how many rows - /// hold it. A query of short words alone shows which word tokens it asks - /// for. Only words shorter than an n-gram get one, so no bigram of a - /// longer word is ever indexed. + /// **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, @@ -819,16 +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 +/// 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) -/// cut a stored value; with [`MatchOptions::short_words`] on, a query is -/// cut by [`matching_query`](crate::target::matching_query), which keeps -/// its short words only when it cuts no n-gram. A plan that is data has one -/// match index per field, and its stored filter and its query both read -/// that index's options. +/// 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; @@ -1182,10 +1195,11 @@ impl RangeQuery { pub struct QueryTokens(Zeroizing); impl QueryTokens { - /// The tokens a query of `text` keeps under `options`' tokenizer and - /// case folding: its short words only when it cuts no n-gram - /// ([`Side::Query`]). The filter a query sends is derived from the same - /// cut, so a query verifies by exactly the tokens it asks for. + /// 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 /// @@ -1218,8 +1232,9 @@ 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. The value is cut as it is stored, - /// with every token of both kinds. 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. @@ -1297,21 +1312,25 @@ impl PrfVisitor<[u8; 32], P> for BloomVisitor { } } -/// Derive a match term of `text` cut for `side` ([`Side`]): a stored -/// value's filter or a query's. 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. /// -/// Text that cuts no token (empty, separator-only, or shorter than the -/// n-gram length with no short word) is the empty filter when stored: no -/// position set, no PRF call, and a value no query matches, since a query -/// always has at least one token and the empty filter holds none of its -/// positions. A query of such text is refused -/// ([`TermError::EmptyTermText`]), because its empty filter would match -/// every row. A field query refuses it earlier, when it is prepared; this -/// refuses it for every other caller of the query cut. +/// 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. +/// +/// 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, @@ -1372,9 +1391,9 @@ fn bloom_positions( .map_err(TermError::from_prf) } -/// The match term of `text` cut for `side`, through the keyset `cipher` -/// holds: derived now when the keyset is loaded, else when it has loaded. -/// Under the local HMAC backend the returned [`Pending`] carries no +/// 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>, @@ -1415,12 +1434,14 @@ where }) } -/// The match term a query of `source` sends under `O`'s options: the -/// filter of the tokens the query keeps ([`Side::Query`]), the tokens its -/// [`QueryTokens`] verify a row by. What a field query of a match index -/// derives ([`matching_query`](crate::target::matching_query)), called as -/// [`Term::encrypt_from`] is. Text that keeps no token is refused -/// ([`TermError::EmptyTermText`]). +/// 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>, @@ -2100,13 +2121,16 @@ order_term! { /// identical either way; what differs is whether anything holds the two in /// agreement. /// -/// [`match_terms`](Self::match_terms) is the exception: it derives a stored -/// value's filter, which is a query's only while -/// [`MatchOptions::short_words`] is off. With the option on, a query keeps -/// its short words only when it cuts no n-gram, so the filter of "Mike Ng" -/// from `match_terms` asks for the word `ng` and misses "Mike Nguyen". A -/// match query comes from the field's reference (`matches(..)`), or from -/// [`matching_query`](crate::target::matching_query) run on its own. +/// Do not use [`match_terms`](Self::match_terms) to build a match query when +/// [`MatchOptions::short_words`] is on. `match_terms` is the exception to +/// the rule above, because it derives a stored value's filter. That filter +/// is also a query's filter only while the option is off. +/// +/// 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`]: @@ -2163,16 +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, and keeps a query's short words only when it cuts no - /// n-gram ([`MatchOptions::short_words`]); this method derives the - /// stored filter 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, @@ -2209,13 +2241,14 @@ impl KeysetCipher<'_, K> { } } - /// [`match_terms`](Self::match_terms) under runtime options and cut for - /// `side`, for the `dynamic` path, whose plan carries a match index's - /// options as data (an `IndexSpec::Match`) and which derives a stored - /// value's filter and a query's alike. 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. + /// [`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, @@ -2597,8 +2630,8 @@ mod tests { ); } - /// Text of short and long words, so a query cuts n-grams, words, - /// both or neither. + /// 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', 'é', '李', ' ', ',']), @@ -2609,8 +2642,8 @@ mod tests { 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. + /// 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(); @@ -2650,9 +2683,9 @@ mod tests { } } - /// A query finds the text it was cut from, and any text it - /// is a run of characters of when it cuts an n-gram: a name - /// typed in part finds its 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(), diff --git a/packages/stack-encrypt/src/sem/tokenize.rs b/packages/stack-encrypt/src/sem/tokenize.rs index 1c65d4e3e2..fcd91d3da4 100644 --- a/packages/stack-encrypt/src/sem/tokenize.rs +++ b/packages/stack-encrypt/src/sem/tokenize.rs @@ -16,8 +16,8 @@ //! 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 -//! it cuts no n-gram ([`Side::Query`]), so "Ng" asks for the word `ng` and -//! "Mike Ng" asks for its trigrams alone. +//! 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; @@ -86,29 +86,32 @@ pub(crate) struct Tokens { pub(crate) short_words: Vec, } -/// Which side of a match a text is cut for: a value to store, or a query -/// to find stored values by. +/// 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: every token of both kinds, so that any query of a - /// run of its words finds it. + /// 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 tokenizer's tokens, and the short words only when the - /// tokenizer cut none ([`Tokens::into_query`]). + /// 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 of the tokens its text cuts: all of them - /// when the tokenizer cut none, else the tokenizer's alone, the short - /// words wiped. + /// 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 ("Ng") is its word tokens, and finds - /// the rows that hold those words whole. A query that cuts an n-gram - /// ("Mike Ng") is its n-grams, as with the option off, and finds the rows - /// that hold them: "Mike Nguyen" as well as "Mike Ng". Every stored - /// value keeps its word tokens, so the rule moves no stored filter, and - /// every token a query keeps is still a token its own text stores. + /// 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(); @@ -153,8 +156,9 @@ 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 cut for `side`: a stored value keeps every token, and a -/// query its short words only when it cuts no n-gram ([`Side`]). +/// 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. @@ -674,9 +678,9 @@ mod tests { } } - /// A query keeps the n-grams its text cuts, and its short - /// words only when it cuts none of them; whichever it - /// keeps, the same text stored holds them. + /// 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(), @@ -733,7 +737,7 @@ mod tests { use super::*; /// The tokens a query of `text` keeps under 3-grams, downcased, - /// with the short-word filter on, as [`tokens`] cuts them. + /// with short words on, as [`tokens`] returns them. fn query(text: &str) -> Tokens { tokens( text, diff --git a/packages/stack-encrypt/src/target/index.rs b/packages/stack-encrypt/src/target/index.rs index 7ee1f0ab79..d3af06597e 100644 --- a/packages/stack-encrypt/src/target/index.rs +++ b/packages/stack-encrypt/src/target/index.rs @@ -48,10 +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, [`Index::query_operation`] is the -//! term a query of it sends, and [`Index::operation`] the term it stores. 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)). //! @@ -249,9 +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, and [`query_operation`](Self::query_operation) is the term a query -/// sends. +/// 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. @@ -276,15 +277,15 @@ pub trait Index { where S: 's; /// The description that derives the term a query of `S` sends, under - /// the [`CallerContext`] it is handed when it runs: what a field query - /// derives. + /// the [`CallerContext`] it is handed when it runs. A field query derives + /// its term through this method. /// - /// Most indexes send the term they store, and return - /// [`operation`](Self::operation)'s description here. A match index - /// cuts a query differently from a stored value ([`matching_query`]): - /// with short words on, a query that sent the stored cut would miss rows - /// it should find. So there is no default, and an index that wraps - /// another forwards both methods to it. + /// 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> @@ -412,7 +413,7 @@ impl Index for Equality { { equality() } - /// The term it stores: a query sends the same term. + /// 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> @@ -460,7 +461,7 @@ where { ore() } - /// The term it stores: a query sends the same term. + /// 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> @@ -486,7 +487,7 @@ where { ope() } - /// The term it stores: a query sends the same term. + /// 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> @@ -512,7 +513,7 @@ where { ore_block() } - /// The term it stores: a query sends the same term. + /// 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> @@ -536,8 +537,8 @@ 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 reads the terms it sends - /// out of them. + /// 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> { @@ -574,13 +575,14 @@ pub trait Indexes { where S: 's, M: WipeSource<'s, S>; - /// The description that derives every term a query of `S` sends, each - /// index's [`query_operation`](Index::query_operation), under the one - /// [`CallerContext`] it is handed and settled in one batch, as - /// [`operations`](Self::operations) settles the stored terms. A set - /// that holds a [`Match`](struct@Match) index sends the filter of the - /// tokens the query keeps, where [`operations`](Self::operations) - /// derives a stored value's. There is no default, for the reason + /// 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, @@ -588,9 +590,9 @@ 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 - /// [`query_operation`](Index::query_operation) is the term a query + /// 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. /// @@ -691,9 +693,9 @@ macro_rules! single_index { } single_index!([] Equality, [O] Match, [] Ore, [] Ope, [] OreBlock, [] Json, [] IndexSpec); -/// A tuple of indexes: each index's operation (or query 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,)+) { @@ -759,7 +761,7 @@ mod tuples { /// 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. In -/// [`Owned`] mode the refusal wipes the value it is handed. +/// [`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 { @@ -785,11 +787,11 @@ impl> Indexes for Vec { } } -/// The description that derives each of `indexes`' terms for `side`, in -/// order, zipped into one batch: the stored terms or a query's. An empty +/// 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), and the -/// refusal lets go of the plaintext as an operation would ([`WipeSource`]). +/// [`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, diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 2fb0cb1a48..4510d6901c 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -181,12 +181,11 @@ 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 let go - /// of the plaintext it is handed through [`WipeSource`]: in - /// [`Owned`] mode the value is wiped, and a borrow is left - /// with the caller. A description that refuses before any operation has - /// taken its plaintext uses this, so the refusal does not free the value - /// unwiped. + /// 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>, @@ -1150,10 +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 through `$derive`, called as `Term::encrypt_from` is, 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])* @@ -1235,30 +1235,33 @@ 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: a stored value's filter, which - /// holds every token the text cuts. + /// 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 a query of the text `S` sends, under the context the - /// tree hands it: the filter of the tokens the query keeps, which a - /// stored filter holds when the row holds them. With - /// [`short_words`](crate::sem::MatchOptions::short_words) on, a query's - /// short words are tokens of the filter only when it cuts no n-gram: - /// "Ng" asks for the word `ng`, and "Mike Ng" for its trigrams alone, so - /// it finds "Mike Nguyen" as well as "Mike Ng". With the option off it - /// is [`matching`]'s term of any text that cuts a token. - /// - /// What a field query of a match index derives - /// ([`Index::query_operation`](super::Index::query_operation)). Text - /// that cuts no token is refused + /// 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)). + /// 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] diff --git a/packages/stack-encrypt/tests/index.rs b/packages/stack-encrypt/tests/index.rs index b8f8a86276..67b099a4ad 100644 --- a/packages/stack-encrypt/tests/index.rs +++ b/packages/stack-encrypt/tests/index.rs @@ -493,15 +493,15 @@ mod given_a_set_of_indexes { } } -/// A set of indexes derives a query's terms through each index's own query -/// derivation (`Indexes::query_operations`): a match index's term is the -/// filter of the tokens the query keeps, and every other index's is the -/// term it stores. One index, a tuple and a `Vec` alike. +/// 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 that cuts an n-gram - /// derives a filter other than the one the same text stores. + /// 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 { @@ -512,9 +512,8 @@ mod given_a_set_holding_a_match_index_with_short_words { } } - /// The text: "Ng" is a short word of a query that cuts n-grams, so the - /// query keeps its 3-grams alone, where a stored value holds the word - /// too. + /// 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 @@ -665,8 +664,8 @@ mod given_a_set_holding_a_match_index_with_short_words { mod assertions { use super::*; - /// The stored and query filters of one text differ, so a set that - /// derived the stored filter for a query would show. + /// 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(), @@ -690,9 +689,9 @@ mod given_a_set_holding_a_match_index_with_short_words { } } -/// An empty `Vec` of indexes handed a plaintext by value: the refusal is the -/// operation that lets go of it, so it wipes it, for a stored value and for a -/// query alike. +/// 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; diff --git a/packages/stack-encrypt/tests/match_short_words.rs b/packages/stack-encrypt/tests/match_short_words.rs index 572e36aa92..45775dd61c 100644 --- a/packages/stack-encrypt/tests/match_short_words.rs +++ b/packages/stack-encrypt/tests/match_short_words.rs @@ -4,16 +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 it cuts no -//! n-gram: "Ng" is its word token, and "Mike Ng" its trigrams alone, so it -//! finds "Mike Nguyen" as it does with the option off. The filter and -//! `verify` agree. +//! - **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, and of any run of its characters that cuts -//! an n-gram. +//! - **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. @@ -137,9 +137,9 @@ mod given_short_words { } } - /// A query that cuts 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 + /// 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_keeps_its_short_words_only_when_it_cuts_no_ngram() { @@ -165,9 +165,8 @@ mod given_short_words { .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 hold their - // bits by chance, but under the test key and these rows none - // does. + // 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, @@ -189,8 +188,8 @@ mod given_short_words { name: Encrypted, } - /// A query that cuts an n-gram sends the filter the index without the - /// option stores for the same text: its n-grams, and no word. + /// 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; @@ -233,10 +232,10 @@ mod given_short_words { ); } - /// The query cut run on its own, as a binding or an index defined - /// elsewhere runs it, refuses text that cuts no token as a field query - /// does: its empty filter would match every row. The stored cut keeps - /// such text as the empty filter. + /// `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; @@ -499,10 +498,10 @@ mod given_random_text { })?; } - /// A query of any run of a text's characters that cuts an n-gram - /// finds the text, filter and `verify` alike, whether or not the - /// run starts or ends inside a word: typeahead and partial names - /// find their rows with short words on. + /// 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),