From f1b0cd2274ff99a8738177adb7a2e9a5dffea5c9 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 20:41:34 +1100 Subject: [PATCH 1/3] fix(eql-bindings): TextMatch stores the empty filter for text that cuts no token A match filter was built by two rules. For text that cuts no token, such as an empty string or one letter, TextSearch and TextSearchOre stored the empty filter and TextMatch refused the value. The rule depended on which other terms the type had. Now every type stores the empty filter, which is what Stack Encrypt derives for a stored value. A match query of such text is still refused, and no query finds a stored empty filter, so no query changes. SearchBloomFilter existed only to allow the empty filter, and no release has it. It is removed, and the three types store a BloomFilter. The query visitor now makes its own check for a filter with no positions: it relied on the stored visitor's refusal before. A Go program got ErrTerm when it stored such text in a TextMatch field. The value is now stored, and the Go changelog says so. Refs #2040 --- .changeset/eql-v4-match-short-words.md | 2 +- .../eql-v4-text-search-optional-terms.md | 2 +- ...-three-encodings-and-eql-v4-by-producer.md | 6 +- languages/golang/CHANGELOG.md | 11 +++ languages/golang/cmd/stashgen/README.md | 4 +- languages/golang/encrypt/README.md | 11 +-- languages/golang/encrypt/eql_v4_test.go | 39 ++++++++++ .../golang/encrypt/eql_v4_text_search_test.go | 4 +- packages/eql/crates/eql-bindings/CHANGELOG.md | 21 +++--- packages/eql/crates/eql-bindings/README.md | 22 +++--- .../eql/crates/eql-bindings/src/encryption.rs | 74 ++++--------------- .../eql/crates/eql-bindings/src/v4/mod.rs | 57 ++------------ .../eql/crates/eql-bindings/src/v4/text.rs | 8 +- .../eql/crates/eql-codegen/src/bindings.rs | 37 +++------- .../tests/encryption/tests/v4_text_search.rs | 42 +++++++---- .../eql/tests/encryption/tests/v4_types.rs | 26 +++++-- 16 files changed, 167 insertions(+), 199 deletions(-) diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index a2bea966e3..d81a06d2dc 100644 --- a/.changeset/eql-v4-match-short-words.md +++ b/.changeset/eql-v4-match-short-words.md @@ -23,7 +23,7 @@ Every query path follows this rule, so a query's filter and its verify agree. Th 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. +Text with no token at all, such as one letter or nothing, is stored with the empty filter in all three types. No `@@` query finds that filter. A query of such text is refused. **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. diff --git a/.changeset/eql-v4-text-search-optional-terms.md b/.changeset/eql-v4-text-search-optional-terms.md index e59f4e40f2..a06f788c08 100644 --- a/.changeset/eql-v4-text-search-optional-terms.md +++ b/.changeset/eql-v4-text-search-optional-terms.md @@ -2,4 +2,4 @@ '@cipherstash/eql': minor --- -**An EQL v4 text search query carries only the terms its operator reads.** `eql_v4.query_text_search` and `eql_v4.query_text_search_ore` now require at least one of their terms (`hm`, `op` or `ob`, `bf`) instead of all of them, so `col = $1` and `col < $1` work on text too short to cut a 3-gram, which has no match term. Each extractor over such a query raises (`invalid_parameter_value`) wherever it reads the operand when the query lacks the term it reads, or holds it as JSON `null` or an empty array, naming the domain, the term and the operators that compare it: `=` without `hm`, `<` without `op`, `@@` without `bf`. So a missing term raises rather than matching no row silently, or every row; the raise is at evaluation, so a generic plan that never reaches the predicate returns no row and no error. Stored `eql_v4_text_search` values still carry every term. This change leaves the `eql_v3` domains as they were. With it, **Stack Encrypt produces `TextSearch`** (`eql-bindings`, `stack-encrypt` feature): `TextSearchQuery`'s terms are `Option`s, built per index through `TextSearchEqualityQuery`, `TextSearchOrderQuery` and `TextSearchMatchQuery`, and the stored value carries every term: text too short for a 3-gram stores the empty filter (`"bf": []`, the new `v4::terms::SearchBloomFilter` field type), so `=` and `<` find it and no `@@` query does, where `TextMatch` still refuses it. `TextSearchQuery`'s `Option` terms and `TextSearch`'s `SearchBloomFilter` change the fields of the unreleased `v4` module only; no published `eql-bindings` has it. See [U-001](../../docs/upgrading/v3.1.md#u-001-a-text-search-query-carries-only-the-terms-its-operator-reads) for what a hand-built query must carry, the raise, and the rollback. +**An EQL v4 text search query carries only the terms its operator reads.** `eql_v4.query_text_search` and `eql_v4.query_text_search_ore` now require at least one of their terms (`hm`, `op` or `ob`, `bf`) instead of all of them, so `col = $1` and `col < $1` work on text too short to cut a 3-gram, which has no match term. Each extractor over such a query raises (`invalid_parameter_value`) wherever it reads the operand when the query lacks the term it reads, or holds it as JSON `null` or an empty array, naming the domain, the term and the operators that compare it: `=` without `hm`, `<` without `op`, `@@` without `bf`. So a missing term raises rather than matching no row silently, or every row; the raise is at evaluation, so a generic plan that never reaches the predicate returns no row and no error. Stored `eql_v4_text_search` values still carry every term. This change leaves the `eql_v3` domains as they were. With it, **Stack Encrypt produces `TextSearch`** (`eql-bindings`, `stack-encrypt` feature): `TextSearchQuery`'s terms are `Option`s, built per index through `TextSearchEqualityQuery`, `TextSearchOrderQuery` and `TextSearchMatchQuery`, and the stored value carries every term: text too short for a 3-gram stores the empty filter (`"bf": []`), as it does in `TextMatch`, so `=` and `<` find it and no `@@` query does. `TextSearchQuery`'s `Option` terms change the fields of the unreleased `v4` module only; no published `eql-bindings` has it. See [U-001](../../docs/upgrading/v3.1.md#u-001-a-text-search-query-carries-only-the-terms-its-operator-reads) for what a hand-built query must carry, the raise, and the rollback. diff --git a/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md index f7fa7aa0fd..2601e532ac 100644 --- a/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md +++ b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md @@ -471,8 +471,10 @@ without loss, and refuses it otherwise. `a.name @@ b.name`, or `matches(col, )`) keeps the shared guard, so two stored empty filters match each other there, as they do in v3. No producer builds that predicate. A match - query of such text is refused, as it is for `TextMatch`, whose stored - value still refuses it too. The v3 domains are cipherstash-client's format + query of such text is refused, as it is for `TextMatch`. A stored + `TextMatch` value of such text has the empty filter too (amended + 2026-12-05): a match filter is built the same way in every type. Before + the amendment, `TextMatch` refused to store such text. The v3 domains are cipherstash-client's format and keep requiring every term, byte for byte, so here the v4 SQL differs from the v3 SQL. The one source holds both forms between version-block directive lines (`-- {{#v3}}` … `-- {{/v3}}`, `-- {{#v4}}` … `-- {{/v4}}`), which the renderer keeps for their own diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 171f448e84..861a42c729 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -15,6 +15,17 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Changed +- **A `TextMatch` field stores text that cuts no token.** Such text is an + empty string, one letter, or separators alone. Before, `Encrypt` refused + it with `ErrTerm`. Now the value is stored with an empty match filter, as + a `TextSearch` field and a plain `match` index store it. So a match filter + is built the same way in every type. + - No `Matches` query finds a value with an empty filter. A `Matches` query + of such text is still refused with `ErrTerm`. + - The empty filter tells anyone who can read the column that the value + cuts no token. + - A program that relied on the refusal to reject short text has to check + the text itself. - **Tokens are refreshed in the background, before they expire** (#1962). An access-key or device-session `auth.Strategy` now runs a goroutine that refreshes its token between 90 seconds and two minutes before the token diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 66228b8291..208558b8c3 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -437,8 +437,8 @@ The ordered date, timestamp and numeric types answer the four comparisons, as do 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 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. +A `TextMatch` field stores text that cuts no token, such as an empty string or one letter, with an empty match filter. No `Matches` query finds that value, and a `Matches` query of such text is refused. +A `TextSearch` field stores such text the same way. Its `Eq`, `Lt`, `Lte`, `Gt` and `Gte` queries find the value, and take such text too. Its `Matches` query refuses such text. 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. `encrypt_into` with any other type is refused with the type's name and the reason it is not produced yet. Separate columns work today for four indexes: `equality`, `match`, `ore` and `ope`. diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index e9721c470c..6f42317fc2 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -413,7 +413,7 @@ filter: a valid value that no query matches, so an optional or short value can live under `match`. The empty filter tells anyone who can read the column that the value is one of those. A match *query* of such text is refused with `ErrTerm`, because an empty filter as a query would match every row. An EQL -`TextMatch` field is stricter, as "EQL columns" below says. +`TextMatch` field follows the same rule. Terms are byte-equal to the ones the Rust crate derives, so a term from `users.Fields.Email.Eq` compares against a stored term written from any @@ -683,10 +683,11 @@ 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 -`Matches` query does. A `TextSearch` query carries only the term its +Some text cuts no token, such as an empty string or one letter. A +`TextMatch` field stores such text with an empty match filter. No `Matches` +query finds that value, and a `Matches` query of such text is refused. A +`TextSearch` field stores such text the same way. Its `Eq`, `Lt`, `Lte`, +`Gt` and `Gte` queries find the value through its other terms. A `TextSearch` query carries only the term its operator reads, so `Eq` and `Lt` on one-letter text work and `Matches` on it is refused; EQL v4 raises if a query lacks the term its operator compares. The number equality types compare as diff --git a/languages/golang/encrypt/eql_v4_test.go b/languages/golang/encrypt/eql_v4_test.go index b1f7c5470f..2cd208f475 100644 --- a/languages/golang/encrypt/eql_v4_test.go +++ b/languages/golang/encrypt/eql_v4_test.go @@ -115,6 +115,45 @@ func TestV4FieldsSealToTheirEQLTypesAndOpenBack(t *testing.T) { } } +// A TextMatch field stores text that cuts no match token (one letter, an +// empty string, or separators alone) with the empty filter, as a +// TextSearch field does: a match filter is built the same way in every +// type. The value opens to the text that went in. A Matches query of such +// text is refused (TestV4QueriesMatchTheRustFixture). +func TestV4TextMatchStoresTextThatCutsNoToken(t *testing.T) { + c := deterministicEQLClient(t) + ctx := context.Background() + cipher := c.DefaultKeyset() + + short := []testusers.Profile{ + {ID: 1, Name: "A", Email: "a@example.com"}, + {ID: 2, Name: "", Email: "b@example.com"}, + {ID: 3, Name: " ", Email: "c@example.com"}, + } + encrypted, err := testusers.EncryptProfile(ctx, cipher, short) + if err != nil { + t.Fatalf("storing text that cuts no token in a TextMatch: %v", err) + } + for i, e := range encrypted { + keys, terms := keysAndTerms(t, e.Name) + if keys != "bf,c,i,v" { + t.Errorf("stored keys for %q %s, want bf,c,i,v", short[i].Name, keys) + } + if string(terms["bf"]) != "[]" { + t.Errorf("stored filter for %q is %s, want []", short[i].Name, terms["bf"]) + } + } + decrypted, err := testusers.DecryptProfile(ctx, cipher, encrypted) + if err != nil { + t.Fatal(err) + } + for i := range short { + if decrypted[i] != short[i] { + t.Errorf("row %d: %+v, want %+v", i, decrypted[i], short[i]) + } + } +} + // bloom is the set of filter positions in a TextMatch value or query. func bloom(t *testing.T, value []byte) map[int]bool { t.Helper() diff --git a/languages/golang/encrypt/eql_v4_text_search_test.go b/languages/golang/encrypt/eql_v4_text_search_test.go index 8bdac8f963..db14e2cfda 100644 --- a/languages/golang/encrypt/eql_v4_text_search_test.go +++ b/languages/golang/encrypt/eql_v4_text_search_test.go @@ -132,8 +132,8 @@ func TestV4TextSearchStoresEveryTermAndQueriesCarryOne(t *testing.T) { t.Errorf(`the query "ng"'s bf %s is not the stored "Ng"'s %s`, q["bf"], ngTerms["bf"]) } // Storing such text, an empty string included, keeps every term, the - // match term as the empty filter (where TextMatch refuses the text): Eq - // and Lt find the row through hm and op, and no Matches query does. + // match term as the empty filter (as TextMatch stores it): Eq and Lt + // find the row through hm and op, and no Matches query does. short, err := testusers.EncryptEntry(ctx, cipher, []testusers.Entry{{ID: 2, Name: "A"}, {ID: 3, Name: ""}}) if err != nil { t.Fatalf("storing short text in a TextSearch: %v", err) diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 29085ffb46..9a1868b160 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -388,16 +388,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `BETWEEN`. - **`TextSearch` is producible** (`stack-encrypt` feature), from `String`. The stored value carries `TextEq`'s `hm`, `TextOrd`'s `op` and - `TextMatch`'s `bf`. Text too short for a 3-gram (an empty string, a - two-letter code) is stored with the empty filter, `"bf": []`, where - `TextMatch` refuses it: `=` and `<` find the row through `hm` and `op`, - and no `@@` query does (a `@@` between two stored values is not a query, - and two stored empty filters match each other there, as in v3). Its `bf` - field is the new - `v4::terms::SearchBloomFilter` (as is `TextSearchOre`'s), whose JSON and - JSON Schema are `BloomFilter`'s and which takes the empty filter; - `TextMatch` and every query keep `BloomFilter`, which refuses it. Its - query is built per index, through + `TextMatch`'s `bf`. Some text cuts no match token, such as an empty + string or one letter. Such text is stored with the empty filter, + `"bf": []`, as `TextMatch` stores it. `=` and `<` find the row through + `hm` and `op`, and no `@@` query does. (A `@@` between two stored values + is not a query, and two stored empty filters match each other there, as + in v3.) The `bf` field of `TextSearch`, `TextSearchOre` and `TextMatch` is + one type, `BloomFilter`. The query of `TextSearch` is built per index, + through `TextSearchEqualityQuery`, `TextSearchOrderQuery` or `TextSearchMatchQuery` (each `EncryptTarget` and `Into`), so it carries only the term its operator reads: @@ -504,8 +502,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `pub hm: Option`, and likewise `op`/`ob` and `bf`: code that builds one of these structs wraps each term in `Some`, code that reads one handles `None`, and a JSON operand missing a term now deserializes - where it was refused. `TextSearch` and `TextSearchOre`'s `bf` is - `SearchBloomFilter`, not `BloomFilter` (`.0` reaches the `BloomFilter`). + where it was refused. No published release of this crate has the `v4` module (3.0.6 does not), so this breaks only code built against unreleased sources; the v3 twins are unchanged, as cipherstash-client's query carries every term. diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 412c6aecfa..3cbabbf929 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -212,16 +212,20 @@ 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 -other order finds nothing until #1171 is fixed. Text that cuts no token -(empty strings, one letter) cannot be stored in a `TextMatch` column, and a -`TextMatchQuery` for it is refused too: one filter type builds both, and an -empty filter as a query would match every row. +other order finds nothing until #1171 is fixed. + +Some text cuts no token, such as an empty string or one letter. Every match +type stores such text with the empty filter, `"bf": []`: `TextMatch`, +`TextSearch` and `TextSearchOre`. No `@@` query finds an empty filter, +because a query's filter is never empty. A `TextMatchQuery` of such text is +refused: an empty filter as a query would match every row. The empty filter +tells anyone who can read the column that the value cuts no token. (A `@@` +between two stored values, which no producer builds, is not a query: two +stored empty filters match each other there, as in v3.) + `TextSearch` stores all three terms (`TextEq`'s `hm`, `TextOrd`'s `op` and -`TextMatch`'s `bf`). Text that cuts no token is stored with the empty -filter (`"bf": []`, the `SearchBloomFilter` field type): `=` and `<` find it -through `hm` and `op`, and no `@@` query does, because a query's filter is -never empty. (A `@@` between two stored values, which no producer builds, is -not a query: two stored empty filters match each other there, as in v3.) Its query carries only the term its operator reads: build it +`TextMatch`'s `bf`). `=` and `<` find text that cuts no token through `hm` +and `op`. Its query carries only the term its operator reads: build it through `TextSearchEqualityQuery` (`=`, `<>`), `TextSearchOrderQuery` (`<`, `<=`, `>`, `>=`) or `TextSearchMatchQuery` (`@@`) and convert into `TextSearchQuery`, and the by-name dispatch picks the one for the index that diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 7df390c539..6ea2b5652b 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::{QueryBloomFilter, SearchBloomFilter}, + v4::terms::QueryBloomFilter, Identifier, }; @@ -409,31 +409,25 @@ 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 built under +/// native match terms built under [`EqlMatch`]: the stored filter of +/// `TextMatch`, `TextSearch` and `TextSearchOre`. Every stored filter and +/// every query filter is built under /// [`EqlMatch`], so they agree on every token a query keeps. A query can /// keep fewer tokens than the same text stores. A query's filter is a /// [`QueryBloomFilter`] ([`QueryMatchVisitor`]). Matching /// cipherstash-client's parameters is not a goal, because cipherstash-client /// never writes an `eql_v4` column. /// -/// Text that cuts no token (empty, separator-only, or shorter than a 3-gram -/// with no two-letter word, such as one letter) is refused with -/// [`TermError::EmptyTermText`]. Stack Encrypt stores such a value as the -/// empty filter, but a `TextMatch` value with an empty filter is a row no -/// operator can find. A query's filter is refused for such text too, -/// because it must never be empty. A search domain's stored filter is a -/// [`SearchBloomFilter`]. That filter can be empty -/// ([`SearchMatchVisitor`]), since `=` and `<` find the value through its -/// other terms. +/// Some text cuts no token: empty text, text of separators only, or text +/// shorter than a 3-gram with no two-letter word, such as one letter. Such +/// text is stored as the empty filter, as Stack Encrypt stores it, in every +/// type. No `@@` query finds an empty filter, because a query's filter is +/// never empty ([`QueryMatchVisitor`]). #[doc(hidden)] pub struct MatchVisitor; impl Visitor for MatchVisitor { type Value = BloomFilter; fn matching(self, terms: MatchTerms) -> Result { - if terms.positions().is_empty() { - return Err(Error::Term(TermError::EmptyTermText)); - } bloom_filter(terms.positions()) } } @@ -487,55 +481,19 @@ impl DecryptField for BloomFilter { } } -/// Builds a stored search value's filter: [`MatchVisitor`]'s filter, except -/// that text which cuts no token stores the empty filter instead of being -/// refused (see [`SearchBloomFilter`]). -#[doc(hidden)] -pub struct SearchMatchVisitor; -impl Visitor for SearchMatchVisitor { - type Value = SearchBloomFilter; - fn matching(self, terms: MatchTerms) -> Result { - if terms.positions().is_empty() { - return Ok(SearchBloomFilter(BloomFilter(Vec::new()))); - } - MatchVisitor.matching(terms).map(SearchBloomFilter) - } -} -impl Transcode for SearchBloomFilter { - type Visitor = SearchMatchVisitor; - fn visitor() -> Self::Visitor { - SearchMatchVisitor - } -} -impl + Zeroize> EncryptTarget for SearchBloomFilter { - type ContextInput = RequiredContext; - fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> - where - S: 's, - { - // The annotation names the match configuration, as for `BloomFilter`. - let terms: Encryption<'s, S, MatchTerms, K, CallerContext> = target::matching(); - terms.accepting().transcode() - } -} -impl Decryptable for SearchBloomFilter { - const DECRYPTABLE: bool = false; -} -impl DecryptField for SearchBloomFilter { - fn decryption_field(self, _: Ctx) -> Option> { - None - } -} - /// 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. +/// [`QueryBloomFilter`]). Text with no token is refused with +/// [`TermError::EmptyTermText`]: an empty filter is contained by every +/// stored filter, so a query with one would return every row. #[doc(hidden)] pub struct QueryMatchVisitor; impl Visitor for QueryMatchVisitor { type Value = QueryBloomFilter; fn matching(self, terms: MatchTerms) -> Result { - MatchVisitor.matching(terms).map(QueryBloomFilter) + if terms.positions().is_empty() { + return Err(Error::Term(TermError::EmptyTermText)); + } + bloom_filter(terms.positions()).map(QueryBloomFilter) } } impl Transcode for QueryBloomFilter { diff --git a/packages/eql/crates/eql-bindings/src/v4/mod.rs b/packages/eql/crates/eql-bindings/src/v4/mod.rs index 5a8a48a2e2..e808ebfef0 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -38,9 +38,8 @@ //! 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. 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. +//! (`OreBlock256`, `OpeCllw`) are not among them. One v4 term has no use +//! in v3: [`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`. @@ -88,8 +87,7 @@ pub use inventory::{all, all_query, all_range_query}; /// 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); +/// - [`QueryBloomFilter`](terms::QueryBloomFilter); /// - the JSON of the order terms, [`OreBlockHex`](terms::OreBlockHex), /// and [`OpeHex`](terms::OpeHex), whose fields contain Stack Encrypt's /// terms. @@ -101,48 +99,6 @@ pub mod terms { use serde::{Deserialize, Serialize}; use ts_rs::TS; - /// The `bf` term of a stored search value (`TextSearch`, - /// `TextSearchOre`): a [`BloomFilter`] that may be empty. - /// - /// Text that cuts no match token (empty, separator-only, or shorter than - /// three characters with no two-letter word, such as one letter) has no - /// match tokens. A search column stores it with - /// the empty filter, Stack Encrypt's answer for a stored value, so `=` - /// and `<` still find it through its `hm` and `op`, and no `@@` query - /// does: EQL's `matches` finds a stored filter only when it contains the - /// 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`], `TextMatch`'s stored filter, still refuses such - /// text, since `TextMatch` has no other term to find it by. - /// [`QueryBloomFilter`], the filter of every query, refuses it too. The - /// JSON and JSON Schema are [`BloomFilter`]'s. Only what Stack Encrypt - /// derives into it differs. - #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TS)] - #[serde(transparent)] - pub struct SearchBloomFilter(pub BloomFilter); - - /// [`BloomFilter`]'s schema, under its name: the wire format is one. - impl JsonSchema for SearchBloomFilter { - 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: SearchBloomFilter) -> Self { - filter.0 - } - } - /// The `bf` term of a match query: a [`BloomFilter`] of the tokens the /// query keeps. `QueryBloomFilter` is the `bf` of `TextMatchQuery`, /// `TextSearchMatchQuery`, `TextSearchOreMatchQuery`, `TextSearchQuery`, @@ -163,9 +119,10 @@ pub mod terms { /// A query sends no token that a stored value of its own text lacks. So /// the rule changes no stored filter. /// - /// Text with no token is refused, as for [`BloomFilter`]: a query's - /// filter is never empty. Such text is empty, separators only, or one - /// letter. The JSON and JSON Schema are [`BloomFilter`]'s. Only what + /// Text with no token is refused: a query's filter is never empty. Such + /// text is empty, separators only, or one letter. A stored + /// [`BloomFilter`] of such text is the empty filter, which no query + /// finds. 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)] diff --git a/packages/eql/crates/eql-bindings/src/v4/text.rs b/packages/eql/crates/eql-bindings/src/v4/text.rs index 6b56e206e3..520836dc81 100644 --- a/packages/eql/crates/eql-bindings/src/v4/text.rs +++ b/packages/eql/crates/eql-bindings/src/v4/text.rs @@ -1,8 +1,6 @@ // @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, QueryBloomFilter, SearchBloomFilter, -}; +use crate::v4::terms::{BloomFilter, Ciphertext, Hmac256, OpeHex, OreBlockHex, QueryBloomFilter}; use crate::v4::{DomainType, SchemaVersion}; use crate::Identifier; use schemars::{schema_for, JsonSchema, Schema}; @@ -356,7 +354,7 @@ pub struct TextSearchOre { #[ts(as = "OreBlockHex")] #[schemars(with = "OreBlockHex")] pub ob: OreBlockTerm, - pub bf: SearchBloomFilter, + pub bf: BloomFilter, } impl DomainType for TextSearchOre { fn sql_domain_static() -> &'static str { @@ -411,7 +409,7 @@ pub struct TextSearch { #[ts(as = "OpeHex")] #[schemars(with = "OpeHex")] pub op: OpeTerm, - pub bf: SearchBloomFilter, + pub bf: BloomFilter, } impl DomainType for TextSearch { fn sql_domain_static() -> &'static str { diff --git a/packages/eql/crates/eql-codegen/src/bindings.rs b/packages/eql/crates/eql-codegen/src/bindings.rs index 24edfeabab..2dfbbde7a5 100644 --- a/packages/eql/crates/eql-codegen/src/bindings.rs +++ b/packages/eql/crates/eql-codegen/src/bindings.rs @@ -200,7 +200,7 @@ fn render_struct(eql: EqlVersion, family: &DomainFamily, domain: &Domain) -> Tok fields.extend(quote! { pub c: Ciphertext, }); for term in Term::payload_terms(domain.terms) { let fid = format_ident!("{}", term.json_key()); - let ty = term_type(eql, family, term, stored_term_newtype(eql, domain, term)); + let ty = term_type(eql, family, term, term.binding_newtype()); let attrs = term_field_attrs(eql, term, false); fields.extend(quote! { #attrs pub #fid: #ty, }); } @@ -447,23 +447,6 @@ fn render_range_query_struct(family: &DomainFamily, term: Term) -> TokenStream { } } -/// The newtype of a stored struct's `term` field. The term's own -/// ([`Term::binding_newtype`]), except the match term of an EQL v4 search -/// domain (one whose query terms are optional, [`v4_optional_query_terms`]): -/// `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` 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" - } else { - term.binding_newtype() - } -} - /// 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 @@ -529,7 +512,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 +/// (each stored struct's newtype, [`Term::binding_newtype`], each query /// 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 { @@ -555,7 +538,7 @@ fn family_terms<'d>(eql: EqlVersion, domains: impl Iterator) add(&mut used.sem, format.rust_type); } _ => { - 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)); } } @@ -1877,12 +1860,11 @@ mod tests { ); } - /// 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. + /// Every v4 stored filter is `BloomFilter`, whatever other terms the + /// type has. 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() { + fn every_v4_stored_filter_is_one_type() { let v4 = render_family_bindings(EqlVersion::V4, family("text")); let field = |out: &str, name: &str| { let start = out @@ -1896,11 +1878,11 @@ mod tests { }; assert_eq!( field(&v4, "TextSearch").as_deref(), - Some("pub bf: SearchBloomFilter,") + Some("pub bf: BloomFilter,") ); assert_eq!( field(&v4, "TextSearchOre").as_deref(), - Some("pub bf: SearchBloomFilter,") + Some("pub bf: BloomFilter,") ); assert_eq!( field(&v4, "TextMatch").as_deref(), @@ -1923,7 +1905,6 @@ mod tests { Some("pub bf: Option,") ); let v3 = render_family_bindings(EqlVersion::V3, family("text")); - assert!(!v3.contains("SearchBloomFilter")); assert!(!v3.contains("QueryBloomFilter")); } diff --git a/packages/eql/tests/encryption/tests/v4_text_search.rs b/packages/eql/tests/encryption/tests/v4_text_search.rs index af9e9dff35..85c5697d13 100644 --- a/packages/eql/tests/encryption/tests/v4_text_search.rs +++ b/packages/eql/tests/encryption/tests/v4_text_search.rs @@ -5,8 +5,8 @@ //! A stored value carries all three terms, each the one the single-index //! type stores (`TextEq`'s `hm`, `TextOrd`'s `op`, `TextMatch`'s `bf`). //! Text that cuts no match token (one letter, or none: a two-letter word is -//! a token of its own) stores the empty filter, where `TextMatch` refuses -//! it, so `=` and `<` find it and no `@@` query does. A query is built +//! a token of its own) stores the empty filter, as it does in `TextMatch`, +//! so `=` and `<` find it and no `@@` query does. A query is built //! through the projection of the index that answers its operator, so `=` and //! `<` on such text work and a match query on it is refused. Against an EQL //! v4 database: a query with any one term is a `query_text_search`, one with @@ -116,10 +116,11 @@ async fn a_stored_value_carries_the_three_single_index_terms() { /// Text that cuts no match token (one letter, or none) has no filter. /// `TextSearch` stores /// it with the empty filter and the same `hm` and `op` as `TextEq` and -/// `TextOrd`, so `=` and `<` find it and no match query does. `TextMatch`, -/// which has no other term to find it by, still refuses it. +/// `TextOrd`, so `=` and `<` find it and no match query does. `TextMatch` +/// stores the same empty filter: a filter is built the same way in every +/// type. #[tokio::test] -async fn short_text_stores_the_empty_filter_where_text_match_refuses_it() { +async fn short_text_stores_the_empty_filter_in_every_match_type() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); for text in ["A", "", " "] { @@ -151,16 +152,25 @@ async fn short_text_stores_the_empty_filter_where_text_match_refuses_it() { "{text:?}" ); - let refused = targets::encrypt("TextMatch", &keyset, &label(), frame(text).frame()) - .unwrap() - .await - .unwrap_err(); - assert!( - matches!( - refused, - stack_encrypt::Error::Term(TermError::EmptyTermText) - ), - "TextMatch {text:?}: {refused:?}" + let matched = stored(&keyset, "TextMatch", text).await; + assert_eq!(keys(&matched), ["bf", "c", "i", "v"], "TextMatch {text:?}"); + assert_eq!( + matched["bf"], search["bf"], + "TextMatch stores the filter TextSearch stores for {text:?}" + ); + let opened = targets::decrypt( + "TextMatch", + &cipher, + &label(), + matched.to_string().as_bytes(), + ) + .unwrap() + .await + .unwrap(); + assert_eq!( + opened.frame().as_bytes(), + frame(text).frame().as_bytes(), + "TextMatch {text:?} opens to the text that was stored" ); } } @@ -293,7 +303,7 @@ async fn the_typed_projections_are_what_the_dispatch_writes() { .encrypt_into_with_context(&keyset, column()) .await .unwrap(); - assert!(short.bf.0 .0.is_empty()); + assert!(short.bf.0.is_empty()); assert_eq!( serde_json::to_value(&short.bf).unwrap(), serde_json::json!([]) diff --git a/packages/eql/tests/encryption/tests/v4_types.rs b/packages/eql/tests/encryption/tests/v4_types.rs index abb52e389a..5c7d66c293 100644 --- a/packages/eql/tests/encryption/tests/v4_types.rs +++ b/packages/eql/tests/encryption/tests/v4_types.rs @@ -935,16 +935,21 @@ async fn text_match_filters_contain_their_substrings() { let named: text::TextMatch = by_name(&keyset, "TextMatch", frame("Alice@Example.com")).await; assert_eq!(named.bf, stored.bf); - // Text that cuts no token (one letter, or none) has no filter. - // eql-bindings refuses it for a stored value as well as a query: one - // filter type builds both, and an empty filter as a query would match - // every row. A two-letter word is a token of its own, so it stores. + // Text that cuts no token (one letter, or none) has no filter. A + // stored value keeps the empty filter, which no query finds. A query of + // such text is refused: an empty filter as a query would match every + // row. A two-letter word is a token of its own, so its filter is not + // empty. for short in ["a", "", " "] { - let stored: Result = short + let stored: text::TextMatch = short .to_owned() .encrypt_into_with_context(&keyset, column()) - .await; - assert!(stored.is_err(), "{short:?} cuts no token"); + .await + .unwrap(); + assert!( + stored.bf.0.is_empty(), + "{short:?} cuts no token, so its stored filter is empty" + ); let query: Result = short .to_owned() .encrypt_into_with_context(&keyset, column()) @@ -1210,7 +1215,8 @@ async fn a_value_of_another_kind_is_refused_not_converted() { /// `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. +/// is its 3-grams, so it finds a longer name too. No query finds the two +/// rows whose text cuts no token, in either column. #[test] #[ignore = "requires EQL_TEST_DATABASE_URL pointing to an EQL v4 database"] fn postgres_finds_two_letter_surnames() { @@ -1240,6 +1246,10 @@ fn postgres_finds_two_letter_surnames() { (4, "Mike Nguyen"), (5, "Li Wei"), (6, "NG, Anna"), + // Text that cuts no token: both columns store the empty filter, + // which each domain's CHECK accepts, and no query below finds it. + (7, "A"), + (8, ""), ]; for (id, name) in names { let (matched, search) = runtime.block_on(async { From 6845026ed9535ddbebcb91a152ddc1eeb70ed5ac Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 20:47:35 +1100 Subject: [PATCH 2/3] docs(eql-bindings): say which queries find no empty filter The docs said that no @@ query finds an empty filter. That is true of a query eql-bindings builds, because it refuses a query with no token. A query_text_match operand built by hand with an empty filter does find the TextMatch values that store one: the search query domains raise on such an operand, and query_text_match does not. The stashgen README still called a TextMatch field stricter than a match index. The Go changelog entry describes a break, so it moves under Breaking. --- .changeset/eql-v4-match-short-words.md | 2 +- languages/golang/CHANGELOG.md | 22 +++++++++---------- languages/golang/cmd/stashgen/README.md | 2 +- packages/eql/crates/eql-bindings/README.md | 18 ++++++++++----- .../eql/crates/eql-bindings/src/encryption.rs | 13 +++++++---- .../eql/crates/eql-bindings/src/v4/mod.rs | 7 +++--- 6 files changed, 38 insertions(+), 26 deletions(-) diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index d81a06d2dc..5625f4141b 100644 --- a/.changeset/eql-v4-match-short-words.md +++ b/.changeset/eql-v4-match-short-words.md @@ -23,7 +23,7 @@ Every query path follows this rule, so a query's filter and its verify agree. Th 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 stored with the empty filter in all three types. No `@@` query finds that filter. A query of such text is refused. +Text with no token at all, such as one letter or nothing, is stored with the empty filter in all three types. A query of such text is refused, so no query that `eql-bindings` builds finds that filter. A `query_text_match` operand built by hand with `"bf": []` does find a `TextMatch` value with the empty filter, and no other value. **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. diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 861a42c729..e01894e199 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -15,17 +15,6 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Changed -- **A `TextMatch` field stores text that cuts no token.** Such text is an - empty string, one letter, or separators alone. Before, `Encrypt` refused - it with `ErrTerm`. Now the value is stored with an empty match filter, as - a `TextSearch` field and a plain `match` index store it. So a match filter - is built the same way in every type. - - No `Matches` query finds a value with an empty filter. A `Matches` query - of such text is still refused with `ErrTerm`. - - The empty filter tells anyone who can read the column that the value - cuts no token. - - A program that relied on the refusal to reject short text has to check - the text itself. - **Tokens are refreshed in the background, before they expire** (#1962). An access-key or device-session `auth.Strategy` now runs a goroutine that refreshes its token between 90 seconds and two minutes before the token @@ -90,6 +79,17 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Breaking +- **A `TextMatch` field stores text that cuts no token.** Such text is an + empty string, one letter, or separators alone. Before, `Encrypt` refused + it with `ErrTerm`. Now the value is stored with an empty match filter, as + a `TextSearch` field and a plain `match` index store it. So a match filter + is built the same way in every type. + - A program that relied on the refusal to reject short text has to check + the text itself. + - No `Matches` query finds a value with an empty filter. A `Matches` query + of such text is still refused with `ErrTerm`. + - The empty filter tells anyone who can read the column that the value + cuts no token. - **vitaminc's Go packages `vcvalue` and `vcffi` are now `encrypt/value` and `encrypt/frame`.** `encrypt.Date`, `Decimal`, `Int128` and `Uint128` are still aliases, now of the types in `encrypt/value`. Code that names diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 208558b8c3..0313932b10 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -105,7 +105,7 @@ A query on such a type derives its term under the context the cipher names, so i The index names are `equality`, `match`, `ore`, `ope` and `json`. A `match` index stores text with no token (an empty string, separator-only text, or text shorter than the n-gram length of 3 characters) as the empty filter, which no query matches, so an optional or short value can live under `match`; the empty filter tells a reader of the column that the value is one of those. A match query of such text is refused, because an empty filter as a query would match every row. -An EQL `TextMatch` field is stricter: see below. +An EQL `TextMatch` field follows the same rule: see below. An index takes its options in parentheses after its name, separated by commas: `index=equality;match(k=3)`. This build refuses an index with options: a query term is derived with the default options only, so a stored term with other options would never match one. These words are the same as the Rust API's words for the same behaviour, with two that only Go has. diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 3cbabbf929..cc9845a974 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -216,12 +216,18 @@ other order finds nothing until #1171 is fixed. Some text cuts no token, such as an empty string or one letter. Every match type stores such text with the empty filter, `"bf": []`: `TextMatch`, -`TextSearch` and `TextSearchOre`. No `@@` query finds an empty filter, -because a query's filter is never empty. A `TextMatchQuery` of such text is -refused: an empty filter as a query would match every row. The empty filter -tells anyone who can read the column that the value cuts no token. (A `@@` -between two stored values, which no producer builds, is not a query: two -stored empty filters match each other there, as in v3.) +`TextSearch` and `TextSearchOre`. A query of such text is refused, so a +query's filter is never empty, and no query that this crate builds finds an +empty filter. The empty filter tells anyone who can read the column that the +value cuts no token. + +EQL's SQL treats an empty filter in two more ways: + +- A `query_text_match` operand built by hand with `"bf": []` finds the + `TextMatch` values that have the empty filter, and no other value. The + search query domains raise on such an operand. +- A `@@` between two stored values is not a query. No producer builds + one. Two stored empty filters match each other there, as in v3. `TextSearch` stores all three terms (`TextEq`'s `hm`, `TextOrd`'s `op` and `TextMatch`'s `bf`). `=` and `<` find text that cuts no token through `hm` diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 6ea2b5652b..1d6beb41ce 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -421,8 +421,13 @@ impl MatchConfig for EqlMatch { /// Some text cuts no token: empty text, text of separators only, or text /// shorter than a 3-gram with no two-letter word, such as one letter. Such /// text is stored as the empty filter, as Stack Encrypt stores it, in every -/// type. No `@@` query finds an empty filter, because a query's filter is -/// never empty ([`QueryMatchVisitor`]). +/// type. No query that this crate builds finds an empty filter, because +/// such a query's filter is never empty ([`QueryMatchVisitor`]). +/// +/// A `query_text_match` operand built by hand with `"bf": []` does find a +/// `TextMatch` value with the empty filter, and no other value. EQL v4's +/// search query domains raise on such an operand. `query_text_match` does +/// not. #[doc(hidden)] pub struct MatchVisitor; impl Visitor for MatchVisitor { @@ -483,8 +488,8 @@ impl DecryptField for BloomFilter { /// Builds a query's filter from the tokens the query keeps (see /// [`QueryBloomFilter`]). Text with no token is refused with -/// [`TermError::EmptyTermText`]: an empty filter is contained by every -/// stored filter, so a query with one would return every row. +/// [`TermError::EmptyTermText`], so a query's filter is never empty: every +/// stored filter contains the empty filter. #[doc(hidden)] pub struct QueryMatchVisitor; impl Visitor for QueryMatchVisitor { diff --git a/packages/eql/crates/eql-bindings/src/v4/mod.rs b/packages/eql/crates/eql-bindings/src/v4/mod.rs index e808ebfef0..b064abddfc 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -121,9 +121,10 @@ pub mod terms { /// /// Text with no token is refused: a query's filter is never empty. Such /// text is empty, separators only, or one letter. A stored - /// [`BloomFilter`] of such text is the empty filter, which no query - /// finds. The JSON and JSON Schema are [`BloomFilter`]'s. Only what - /// Stack Encrypt derives into it differs. + /// [`BloomFilter`] of such text is the empty filter. No + /// `QueryBloomFilter` that Stack Encrypt derives finds it. 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); From b32334b3fa61c7c68906e046ad132cbbd8c2ab5a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 21:01:07 +1100 Subject: [PATCH 3/3] fix(eql): a v4 match query with an empty filter is refused A TextMatch column can now store the empty filter. An eql_v4.query_text_match operand built by hand with an empty bf was accepted, and would have found exactly those stored values. The search query domains already raise on such an operand. The match extractor over query_text_match now reads its bf through require_query_term, as the search domains' extractors do. So a match query's filter is never empty, in any type and from any producer. The eql_v3 extractor is unchanged. Refs #2040 --- .changeset/eql-v4-match-filter-one-rule.md | 12 ++++++ .changeset/eql-v4-match-short-words.md | 2 +- ...-three-encodings-and-eql-v4-by-producer.md | 4 +- packages/eql/crates/eql-bindings/README.md | 22 +++++----- .../eql/crates/eql-bindings/src/encryption.rs | 11 ++--- .../eql/crates/eql-bindings/src/v4/mod.rs | 8 ++-- .../eql/crates/eql-codegen/src/context.rs | 38 ++++++++++++---- .../eql/crates/eql-codegen/src/generate.rs | 43 +++++++++++++++++-- packages/eql/src/v3/scalars/functions.sql | 4 ++ .../text/query_text_match_functions.sql | 9 ++++ .../eql/tests/encryption/tests/v4_types.rs | 35 ++++++++++++++- 11 files changed, 149 insertions(+), 39 deletions(-) create mode 100644 .changeset/eql-v4-match-filter-one-rule.md diff --git a/.changeset/eql-v4-match-filter-one-rule.md b/.changeset/eql-v4-match-filter-one-rule.md new file mode 100644 index 0000000000..fa18bc0e44 --- /dev/null +++ b/.changeset/eql-v4-match-filter-one-rule.md @@ -0,0 +1,12 @@ +--- +'@cipherstash/eql': minor +--- + +**In EQL v4, a match filter follows one rule in every type.** The types are `TextMatch`, `TextSearch` and `TextSearchOre`. Some text cuts no match token: an empty string, one letter, or separators alone. + +- **Stored values.** `eql-bindings` now stores such text in `TextMatch` with the empty filter, `"bf": []`, as it does in the two search types. Before, `TextMatch` refused the value. The three types store one filter type, `v4::terms::BloomFilter`. The type `v4::terms::SearchBloomFilter` is removed. No release has it. +- **Queries.** `eql_v4.match_term` over an `eql_v4.query_text_match` operand now raises (`invalid_parameter_value`) when the operand's `bf` is missing, JSON `null` or an empty array. The search query domains already raise this way. So `col @@ $1` raises on such an operand, where it could match the stored values with an empty filter. `eql-bindings` never builds such an operand: it refuses a query of text that cuts no token. + +No `@@` query finds a stored empty filter. The empty filter tells anyone who can read the column that the value cuts no token. + +The `eql_v3` functions do not change. Only the unreleased `v4` module and the EQL v4 SQL change. diff --git a/.changeset/eql-v4-match-short-words.md b/.changeset/eql-v4-match-short-words.md index 5625f4141b..d81a06d2dc 100644 --- a/.changeset/eql-v4-match-short-words.md +++ b/.changeset/eql-v4-match-short-words.md @@ -23,7 +23,7 @@ Every query path follows this rule, so a query's filter and its verify agree. Th 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 stored with the empty filter in all three types. A query of such text is refused, so no query that `eql-bindings` builds finds that filter. A `query_text_match` operand built by hand with `"bf": []` does find a `TextMatch` value with the empty filter, and no other value. +Text with no token at all, such as one letter or nothing, is stored with the empty filter in all three types. No `@@` query finds that filter. A query of such text is refused. **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. diff --git a/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md index 2601e532ac..edcfc497a6 100644 --- a/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md +++ b/docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md @@ -474,7 +474,9 @@ without loss, and refuses it otherwise. query of such text is refused, as it is for `TextMatch`. A stored `TextMatch` value of such text has the empty filter too (amended 2026-12-05): a match filter is built the same way in every type. Before - the amendment, `TextMatch` refused to store such text. The v3 domains are cipherstash-client's format + the amendment, `TextMatch` refused to store such text. The extractor + over `eql_v4.query_text_match` refuses `"bf": []` too, from the same + date, so no match query has an empty filter. The v3 domains are cipherstash-client's format and keep requiring every term, byte for byte, so here the v4 SQL differs from the v3 SQL. The one source holds both forms between version-block directive lines (`-- {{#v3}}` … `-- {{/v3}}`, `-- {{#v4}}` … `-- {{/v4}}`), which the renderer keeps for their own diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index cc9845a974..85aac18630 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -216,18 +216,16 @@ other order finds nothing until #1171 is fixed. Some text cuts no token, such as an empty string or one letter. Every match type stores such text with the empty filter, `"bf": []`: `TextMatch`, -`TextSearch` and `TextSearchOre`. A query of such text is refused, so a -query's filter is never empty, and no query that this crate builds finds an -empty filter. The empty filter tells anyone who can read the column that the -value cuts no token. - -EQL's SQL treats an empty filter in two more ways: - -- A `query_text_match` operand built by hand with `"bf": []` finds the - `TextMatch` values that have the empty filter, and no other value. The - search query domains raise on such an operand. -- A `@@` between two stored values is not a query. No producer builds - one. Two stored empty filters match each other there, as in v3. +`TextSearch` and `TextSearchOre`. No `@@` query finds an empty filter, +because a query's filter is never empty: + +- This crate refuses a query of such text. +- EQL v4's SQL raises on a query operand whose `bf` is empty, in every + match query domain. So an operand built by hand is refused too. + +The empty filter tells anyone who can read the column that the value cuts +no token. A `@@` between two stored values is not a query, and no producer +builds one. Two stored empty filters match each other there, as in v3. `TextSearch` stores all three terms (`TextEq`'s `hm`, `TextOrd`'s `op` and `TextMatch`'s `bf`). `=` and `<` find text that cuts no token through `hm` diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 1d6beb41ce..88c3818c80 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -421,13 +421,10 @@ impl MatchConfig for EqlMatch { /// Some text cuts no token: empty text, text of separators only, or text /// shorter than a 3-gram with no two-letter word, such as one letter. Such /// text is stored as the empty filter, as Stack Encrypt stores it, in every -/// type. No query that this crate builds finds an empty filter, because -/// such a query's filter is never empty ([`QueryMatchVisitor`]). -/// -/// A `query_text_match` operand built by hand with `"bf": []` does find a -/// `TextMatch` value with the empty filter, and no other value. EQL v4's -/// search query domains raise on such an operand. `query_text_match` does -/// not. +/// type. No `@@` query finds an empty filter, because a query's filter is +/// never empty. This crate refuses a query of such text +/// ([`QueryMatchVisitor`]), and EQL v4's SQL raises on a query operand +/// whose `bf` is empty. #[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 b064abddfc..84041908f2 100644 --- a/packages/eql/crates/eql-bindings/src/v4/mod.rs +++ b/packages/eql/crates/eql-bindings/src/v4/mod.rs @@ -121,10 +121,10 @@ pub mod terms { /// /// Text with no token is refused: a query's filter is never empty. Such /// text is empty, separators only, or one letter. A stored - /// [`BloomFilter`] of such text is the empty filter. No - /// `QueryBloomFilter` that Stack Encrypt derives finds it. The JSON and - /// JSON Schema are [`BloomFilter`]'s. Only what Stack Encrypt derives - /// into it differs. + /// [`BloomFilter`] of such text is the empty filter, which no query + /// finds: EQL v4's SQL also raises on a query operand whose `bf` is + /// empty. 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/context.rs b/packages/eql/crates/eql-codegen/src/context.rs index 8b15a278e8..df8bec34d4 100644 --- a/packages/eql/crates/eql-codegen/src/context.rs +++ b/packages/eql/crates/eql-codegen/src/context.rs @@ -98,10 +98,28 @@ pub fn v4_optional_query_terms(domain: &Domain) -> bool { domain.terms.contains(&Term::Bloom) && Term::payload_terms(domain.terms).len() > 1 } -/// The term an extractor over a query operand reads, for an operand whose -/// terms are optional in EQL v4 ([`v4_optional_query_terms`]): the extractor -/// raises, naming the term and the operators that read it, when the operand -/// carries none, rather than answer `NULL` and match no row. +/// Whether the EQL v4 extractor of `term` over `domain`'s query operand +/// raises when the operand has no such term, or has it as `null` or as an +/// empty array. Two kinds of extractor do: +/// +/// - Every extractor over an operand whose terms are optional +/// ([`v4_optional_query_terms`]). A missing term would otherwise read as +/// `NULL` and match no row. +/// - The match extractor over every operand, `query_text_match` included. A +/// match query's filter is never empty, in any type. An empty filter is +/// the filter of text that cuts no match token. A stored filter of such +/// text is empty too, so a query with an empty filter would find the +/// stored values that no match query should find. +/// +/// EQL v4 only: an `eql_v3` extractor reads its term as before. +pub fn v4_query_term_raises(domain: &Domain, term: Term) -> bool { + v4_optional_query_terms(domain) || term == Term::Bloom +} + +/// The term an extractor over a query operand reads, for an extractor that +/// raises in EQL v4 ([`v4_query_term_raises`]): the extractor raises, naming +/// the term and the operators that read it, when the operand carries none, +/// rather than answer `NULL` and match no row. #[derive(serde::Serialize)] pub struct RequiredTerm { /// sql_str-escaped JSON key, e.g. `hm`. @@ -114,9 +132,10 @@ pub struct RequiredTerm { } /// The [`RequiredTerm`] for `term`'s extractor over `domain`'s query operand -/// `query_dom`, or `None` when the operand's terms are not optional. +/// `query_dom`, or `None` when the extractor does not raise in EQL v4 +/// ([`v4_query_term_raises`]). pub fn required_term(domain: &Domain, term: Term, query_dom: &str) -> Option { - if !v4_optional_query_terms(domain) { + if !v4_query_term_raises(domain, term) { return None; } // The operators this extractor answers on this domain: an operator two @@ -343,8 +362,9 @@ pub enum FnEntry { ret: String, // e.g. eql_v3_internal.hmac_256 (selection STAYS in Rust) extractor: String, // e.g. eq_term ctor: String, // e.g. hmac_256 (called as {{ internal_schema }}.{{ ctor }}) - // Set on an extractor over a query operand whose terms are optional - // in EQL v4: the v4 body raises when the term is absent. + // Set on an extractor over a query operand that raises in EQL v4 + // (`v4_query_term_raises`): the v4 body raises when the term is + // absent or empty. required: Option, }, Wrapper { @@ -393,7 +413,7 @@ pub fn extractor_entry(term: Term) -> FnEntry { } /// [`extractor_entry`] over a query operand: in EQL v4 it raises when the -/// operand lacks the term, if the operand's terms are optional there +/// operand lacks the term, if the extractor is one that raises there /// ([`required_term`]). pub fn query_extractor_entry(domain: &Domain, term: Term, query_dom: &str) -> FnEntry { extractor_entry_requiring(term, required_term(domain, term, query_dom)) diff --git a/packages/eql/crates/eql-codegen/src/generate.rs b/packages/eql/crates/eql-codegen/src/generate.rs index 99b72bf136..7448102c11 100644 --- a/packages/eql/crates/eql-codegen/src/generate.rs +++ b/packages/eql/crates/eql-codegen/src/generate.rs @@ -328,7 +328,7 @@ pub fn render_query_functions_file( use crate::consts::sql_str; use crate::context::{ domain_name, environment, mismatch_blocker_entry, query_domain_name, query_extractor_entry, - v4_optional_query_terms, wrapper_entry, FunctionsContext, SqlParam, + v4_query_term_raises, wrapper_entry, FunctionsContext, SqlParam, }; let name = domain.full_name(family_name); let query_name = domain.query_name(family_name); @@ -409,9 +409,11 @@ pub fn render_query_functions_file( query_types_path(family_name), scalar_path(family_name, &format!("{name}_functions.sql")), ]; - // The v4 extractors over an operand with optional terms raise through the - // shared helper there. - if v4_optional_query_terms(domain) { + // A v4 extractor that raises does so through the shared helper there. + if Term::payload_terms(domain.terms) + .into_iter() + .any(|term| v4_query_term_raises(domain, term)) + { requires.push(V3_SCALARS_BLOCKER.to_string()); } let ctx = FunctionsContext { @@ -2920,6 +2922,39 @@ mod tests { assert!(!eq.contains("require_query_term") && !eq.contains("{{#v")); } + /// A match query's filter is never empty in EQL v4, in any type: the + /// extractor over `query_text_match` raises on an operand whose `bf` is + /// missing or empty, as the search domains' extractors do. An empty + /// filter would find the stored values that no match query should find. + /// v3's extractor reads the term as before. + #[test] + fn a_v4_match_query_raises_without_a_filter() { + use crate::render::{render_str, EqlVersion}; + let text = spec("text"); + let functions = super::render_query_functions_file( + "text", + domain(text, "match"), + &super::cross_pair_domains(text, domain(text, "match")), + ); + let f3 = render_str(&functions, EqlVersion::V3).unwrap(); + let f4 = render_str(&functions, EqlVersion::V4).unwrap(); + assert!( + !f3.contains("require_query_term"), + "the v3 extractor reads the filter as before: {f3}" + ); + assert!( + f3.contains("AS $$ SELECT eql_v3_internal.bloom_filter(a::jsonb) $$;"), + "the v3 extractor reads the filter as before: {f3}" + ); + let body = + "SELECT eql_v4_internal.bloom_filter(eql_v4_internal.require_query_term(a::jsonb, \ + 'eql_v4.query_text_match', 'bf', '@@'))"; + assert!( + f4.contains(body), + "the v4 extractor raises without a filter: {body} in {f4}" + ); + } + #[test] fn only_the_search_domains_have_optional_v4_query_terms() { let optional: Vec = CATALOG diff --git a/packages/eql/src/v3/scalars/functions.sql b/packages/eql/src/v3/scalars/functions.sql index 70476face8..8116bf8ed6 100644 --- a/packages/eql/src/v3/scalars/functions.sql +++ b/packages/eql/src/v3/scalars/functions.sql @@ -69,6 +69,10 @@ $$ LANGUAGE plpgsql; --! missing term raises here rather than reading as NULL, which would compare --! as no row. --! +--! The match extractor over {{prefix}}.query_text_match reads its `bf` +--! through this helper too, so a match query's filter is never empty in any +--! domain. +--! --! A term whose value is JSON `null` is missing, and so is an empty array: a --! `bf` with no positions is the filter of text that cuts no match token (one --! letter, or none), which a stored filter of the same text would contain, so diff --git a/packages/eql/src/v3/scalars/text/query_text_match_functions.sql b/packages/eql/src/v3/scalars/text/query_text_match_functions.sql index 19dddc204b..e9c93c95bf 100644 --- a/packages/eql/src/v3/scalars/text/query_text_match_functions.sql +++ b/packages/eql/src/v3/scalars/text/query_text_match_functions.sql @@ -2,6 +2,7 @@ -- REQUIRE: src/v3/schema.sql -- REQUIRE: src/v3/scalars/text/query_text_types.sql -- REQUIRE: src/v3/scalars/text/text_match_functions.sql +-- REQUIRE: src/v3/scalars/functions.sql --! @file encrypted_domain/text/query_text_match_functions.sql --! @brief Functions for {{prefix}}.query_text_match. @@ -9,10 +10,18 @@ --! @brief Index extractor for {{prefix}}.query_text_match. --! @param a {{prefix}}.query_text_match --! @return {{prefix}}_internal.bloom_filter +-- {{#v4}} +--! @throws When the operand carries no `bf` term, the term @@ compare. +-- {{/v4}} CREATE FUNCTION {{prefix}}.match_term(a {{prefix}}.query_text_match) RETURNS {{prefix}}_internal.bloom_filter LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE +-- {{#v3}} AS $$ SELECT {{prefix}}_internal.bloom_filter(a::jsonb) $$; +-- {{/v3}} +-- {{#v4}} +AS $$ SELECT {{prefix}}_internal.bloom_filter({{prefix}}_internal.require_query_term(a::jsonb, '{{prefix}}.query_text_match', 'bf', '@@')) $$; +-- {{/v4}} --! @brief Operator wrapper for {{prefix}}.query_text_match. --! @param a public.{{prefix}}_text_match diff --git a/packages/eql/tests/encryption/tests/v4_types.rs b/packages/eql/tests/encryption/tests/v4_types.rs index 5c7d66c293..f0f256ea2a 100644 --- a/packages/eql/tests/encryption/tests/v4_types.rs +++ b/packages/eql/tests/encryption/tests/v4_types.rs @@ -1216,7 +1216,8 @@ async fn a_value_of_another_kind_is_refused_not_converted() { /// 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. No query finds the two -/// rows whose text cuts no token, in either column. +/// rows whose text cuts no token, in either column, and a `TextMatch` query +/// built by hand with an empty filter is refused. #[test] #[ignore = "requires EQL_TEST_DATABASE_URL pointing to an EQL v4 database"] fn postgres_finds_two_letter_surnames() { @@ -1320,6 +1321,38 @@ fn postgres_finds_two_letter_surnames() { assert_eq!(matched, want, "TextMatch @@ {needle:?}"); assert_eq!(search, want, "TextSearch @@ {needle:?}"); } + + // An operand built by hand with an empty filter is refused. Stack + // Encrypt never builds one. Without the refusal, the operand would find + // rows 7 and 8, which no match query should find. + let mut empty = runtime.block_on(async { + let query: text::TextMatchQuery = "Nguyen" + .to_owned() + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap(); + serde_json::to_value(&query).unwrap() + }); + empty["bf"] = serde_json::json!([]); + let error = db + .query( + "SELECT id FROM v4_surnames WHERE name @@ $1::text::jsonb::eql_v4.query_text_match", + &[&empty.to_string()], + ) + .expect_err("a match query with an empty filter is refused"); + assert_eq!( + error.code().map(postgres::error::SqlState::code), + Some("22023"), + "an empty filter is an invalid parameter value: {error}" + ); + let message = error + .as_db_error() + .map(|e| e.message().to_owned()) + .unwrap_or_default(); + assert!( + message.contains("eql_v4.query_text_match value has no \"bf\" term"), + "the message names the domain and the term: {message}" + ); } /// Needs an EQL v4 installation; uses fresh real ciphertext with a fake key