From 6ec6982116897ed89786a85ab4abee66a94f779a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 00:19:33 +1100 Subject: [PATCH 1/4] feat(eql-bindings): answer order queries from a field reference A field reference of an ordered EQL v4 type (IntegerOrd, DateOrdOre, TextOrd and the rest) had no op::Answers impls, so a Rust program could range-query such a field only through a data plan. eql-codegen now generates the impls for every producible type with a query twin, by the rule the data path answers a field that names the type: eq through the equality index, lt, lte, gt and gte through the type's order index (OPE or block ORE), matches through the match index. Every ordered type answers the orderings, TextOrd* answer eq too, and TextSearch and TextSearchOre answer eq, the orderings and matches. The twins differ in the terms they need, and no SQL or stored form changes. An ordered type other than text has a one-term twin (op or ob). eql_v4.query_text_ord requires hm and op together, so TwinIndex takes a third type parameter, the indexes whose terms the twin carries (defaulting to the answering index), and a TextOrd query derives the terms of (Equality, Ope) for its one value through stack-encrypt's Indexes, as the data path's run of the twin's own plan does. A text search twin's terms are optional, so QueryTwin is implemented once per term and its query carries the answering index's term alone, as the data path's projection does. No type answers between, which the data path answers on no EQL type. typed_queries.rs now holds every type's operators to the data path's with no gap, and every query's bytes to the data path's (a block ORE term, which carries a random nonce, compares equal instead). typed_order_queries.rs stores rows through a record and checks that a field reference's query and the data path's each find exactly the rows the plaintexts say, in Rust and, against an EQL v4 database, through the SQL operators; it joins the test:encryption:postgres suites. Closes #1668 --- .../2026-10-24-stack-encrypt-api-plan.md | 16 +- packages/eql/crates/eql-bindings/CHANGELOG.md | 30 + packages/eql/crates/eql-bindings/README.md | 27 +- .../eql-bindings/src/encryption/query.rs | 248 +++- .../eql/crates/eql-bindings/src/v4/answers.rs | 1026 ++++++++++++++++- .../eql/crates/eql-codegen/src/targets.rs | 631 ++++++---- packages/eql/mise.toml | 4 +- .../eql/tests/encryption/tests/common/mod.rs | 45 + .../encryption/tests/typed_order_queries.rs | 475 ++++++++ .../tests/encryption/tests/typed_queries.rs | 659 ++++++++--- 10 files changed, 2773 insertions(+), 388 deletions(-) create mode 100644 packages/eql/tests/encryption/tests/typed_order_queries.rs diff --git a/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 640137bfda..34d94f7c5a 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1587,15 +1587,25 @@ Base64. `DecryptSource`. - A query from a field reference works for the equality and match types, with the record's scope. A data plan's query for an EQL type - takes a scope too. The order types do not implement `Answers` yet, so - a field reference cannot query them (#1668). + takes a scope too. + - In #1668, a field reference queries the order types too: `lt`, `lte`, + `gt` and `gte` on every ordered type, `eq` as well on `TextOrd`, and + the orderings and `matches` on text search. A twin that requires + several terms (`TextOrdQuery`'s `hm` and `op`) gets all of them for the + one value; a twin whose terms are optional gets the answering index's + term alone, as the data plan's does. No SQL or stored form changes. + Each query is the data plan's for the same value, and each finds the + rows the other finds + (`packages/eql/tests/encryption/tests/typed_queries.rs`, + `typed_order_queries.rs`). `between` is not answered from a field + reference, as the data plan answers it on no EQL type. - A data plan that names an EQL type takes a scope and a binding too. `TargetResolver` receives them after the field's label, and `TargetError::Extended` is removed. Under the same scope and binding, a data plan and a derived record write the same terms, and each opens the other's values. A Go struct with an `encrypt_into` field seals through `cipher.Scope(..).Bind(..)`. -- **Tracked in.** Issue #1658 is open. Pull request #1659, open, closes it. Issue #1668 is open for order queries from a field reference. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. +- **Tracked in.** Issue #1658 is open. Pull request #1659, open, closes it. Issue #1668 is for order queries from a field reference. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. - **Finished when** these are all true: - a Rust record with EQL fields encrypts, decrypts, and queries through the new API, including order queries; diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 5af8e98297..b13c4108a5 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -27,6 +27,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the `JsonTreeToken` to send. The call also returns the key that decrypts what the query returns. - The stored format and the SQL do not change. + `JsonSubtreeKey` of its parent's path, and opens + (`DecryptSource`) to the child's value. It is checked + against the parent as Stack Encrypt's `JsonSubtreeKey::open_child` + checks it. A child with members of its own does not open alone: read it + through `JsonTreeSubtree`. The stored format and the SQL do not change. +- **Order queries from a field reference** (#1668). The field reference of a + field typed with an ordered EQL v4 type has `lt`, `lte`, `gt` and `gte`: + `EncryptedMember::AGE.gt(30).encrypt(&keyset)` returns the type's query + twin (`IntegerOrdQuery`, `DateOrdOreQuery`, …). This covers every + producible `…Ord`, `…OrdOpe` and `…OrdOre` type. `TextOrd`, `TextOrdOpe` + and `TextOrdOre` answer `eq` too. `TextSearch` and `TextSearchOre` answer + `eq`, the orderings and `matches`. Each query is the one a data plan + derives for a field that names the type, for the same operator and value, + and binds as the twin's query domain. A block ORE term carries a random + nonce, so its bytes differ between derivations, and it compares equal. + - A twin that requires several terms carries all of them whatever the + operator: a `TextOrd` query derives both its `hm` and its `op` for the + one value, since `eql_v4.query_text_ord` requires both. A text search + twin's terms are optional, so its query carries only the term of the + index that answers the operator. No EQL SQL and no stored form changes. + - `TwinIndex` takes a third type parameter, the indexes whose terms the + twin carries. It defaults to the answering index, so + `TwinIndex` is unchanged. `TextOrd` answers + `op::Lt` through `TwinIndex`. + - `QueryTwin` is implemented for an order term (`OpeTerm`, + `OreBlockTerm`), for a pair `(Hmac256, OpeTerm)` or + `(Hmac256, OreBlockTerm)`, and, for a twin whose terms are + optional, once per term. + - No type answers `between` from a field reference, as a data plan + answers no `between` on an EQL type. - **A `JsonTreeDocument` field is queried from its field reference** (#1459, #1687). As a field of a derived record, a `JsonTreeDocument` (and an diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index ba27ffd57e..9534e96a47 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -429,6 +429,9 @@ async fn main() -> Result<(), Box> { | `SmallintEq`, `IntegerEq`, `BigintEq`, `RealEq`, `DoubleEq` | `eq` | `op::Eq` | `SmallintEqQuery`, `IntegerEqQuery`, `BigintEqQuery`, `RealEqQuery`, `DoubleEqQuery` | | `DateEq`, `TimestampEq`, `NumericEq` | `eq` | `op::Eq` | `DateEqQuery`, `TimestampEqQuery`, `NumericEqQuery` (from `v4::plaintext::Date`, `Timestamp`, `Decimal`) | | `TextMatch` | `matches` | `op::Matches` | `MatchTwin` | +| `SmallintOrd`, `IntegerOrd`, `BigintOrd`, `RealOrd`, `DoubleOrd`, `DateOrd`, `TimestampOrd`, `NumericOrd`, and each `…OrdOpe` and `…OrdOre` | `lt`, `lte`, `gt`, `gte` | `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte` | the type's twin: `IntegerOrdQuery`, `IntegerOrdOreQuery`, … | +| `TextOrd`, `TextOrdOpe`, `TextOrdOre` | `eq`, `lt`, `lte`, `gt`, `gte` | `op::Eq` and the orderings | `TextOrdQuery`, `TextOrdOpeQuery`, `TextOrdOreQuery` | +| `TextSearch`, `TextSearchOre` | `eq`, `lt`, `lte`, `gt`, `gte`, `matches` | `op::Eq`, the orderings and `op::Matches` | `TextSearchQuery`, `TextSearchOreQuery`, and a `MatchTwin` of one for `matches` | `MatchTwin` serializes as the twin and adds `verify` and `target_limit` under `EqlMatch`: a filter can match a row that does not hold the query's @@ -436,11 +439,18 @@ text, so keep only the decrypted rows that verify. An exact query has no `verify`. An operator a type does not answer does not compile: `.lt(..)` on a `TextEq` field, or `.matches(..)` on an `IntegerEq` field. A field reference names its field's type and no index, so a query cannot send another index's term, -such as the bare `Equality` term, which the type's SQL does not take. The -ordered types (`IntegerOrd`, `TextOrd`, …) and the text search types answer -nothing from a field reference yet: their twins need an order term, or several terms -at once, and a field query sends one index's term. Query them through -the data path (`stack_encrypt::dynamic::query_term`) for now. +such as the bare `Equality` term, which the type's SQL does not take. No +type answers `between` from a field reference, as no data plan answers it +for an EQL type. + +A twin carries what its query domain requires. The twin of an ordered +type other than text carries its one order term (`op` or `ob`). A +`TextOrd` twin carries both +its `hm` and its order term whatever the operator, because +`eql_v4.query_text_ord` requires both, so a field query derives the two +terms for the one value. A text search twin's terms are optional, so its +query carries only the term of the index that answers the operator: `hm` +for `eq`, `op` or `ob` for an ordering, `bf` for `matches`. The query is derived under the field reference's label: the record's scope, then the field's name (or its `identity`). That is the column the field stores in @@ -542,6 +552,13 @@ async fn main() -> Result<(), Box> { .await?; assert_eq!(query.hm, stored.email.hm); + // An order query: an `IntegerOrdQuery`, bound as + // WHERE age > $1::eql_v4.query_integer_ord. + let older = EncryptedMember::AGE.gt(30).encrypt(&keyset).await?; + assert_eq!(older.i, stored.age.i); + // Its order term sorts below the stored age of 36. + assert!(older.op < stored.age.op); + let opened = Member::decrypt_from(stored, &keyset).await?; assert_eq!(opened.email, "alice@example.com"); Ok(()) diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 3570ca5a29..61bde437f4 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -23,18 +23,28 @@ //! | `TimestampEq` | `eq` | [`op::Eq`](struct@op::Eq) | `TimestampEqQuery` | //! | `NumericEq` | `eq` | [`op::Eq`](struct@op::Eq) | `NumericEqQuery` | //! | `TextMatch` | `matches` | [`op::Matches`](struct@op::Matches) | [`MatchTwin`](MatchTwin) | +//! | `SmallintOrd`, `IntegerOrd`, `BigintOrd`, `RealOrd`, `DoubleOrd`, `DateOrd`, `TimestampOrd`, `NumericOrd`, and each `…OrdOpe` and `…OrdOre` | `lt`, `lte`, `gt`, `gte` | [`op::Lt`], [`op::Lte`], [`op::Gt`], [`op::Gte`] | `IntegerOrdQuery`, … | +//! | `TextOrd`, `TextOrdOpe`, `TextOrdOre` | `eq`, `lt`, `lte`, `gt`, `gte` | [`op::Eq`](struct@op::Eq) and the orderings | `TextOrdQuery`, `TextOrdOpeQuery`, `TextOrdOreQuery` | +//! | `TextSearch`, `TextSearchOre` | `eq`, `lt`, `lte`, `gt`, `gte`, `matches` | [`op::Eq`](struct@op::Eq), the orderings and [`op::Matches`](struct@op::Matches) | `TextSearchQuery`, `TextSearchOreQuery`; [`MatchTwin`] of one for `matches` | //! //! eql-codegen writes those impls from the catalog, by the rule Stack //! Encrypt's data path answers an EQL type's operators with: `Eq` through -//! the equality index, `Matches` through the match index. Each type is also -//! an [`op::LabelledTarget`], which is what lets its field reference be queried. The -//! ordered types (`IntegerOrd`, `TextOrdOre` and the rest) and the text -//! search types answer nothing from a field reference yet: their twins need an order -//! term, or several terms at once, and a field query sends one index's -//! term. Query them through the data path -//! (`stack_encrypt::dynamic::query_term`). An operator a type does not -//! answer does not compile. A field reference names its field's type and no index, -//! so a query cannot send another index's term in place of the type's twin. +//! the equality index, `Matches` through the match index, and the orderings +//! through the type's order index (OPE or block ORE). Each type is also an +//! [`op::LabelledTarget`], which is what lets its field reference be +//! queried. An operator a type does not answer does not compile: no EQL +//! type answers [`op::Between`] from a field reference, as the data path +//! answers no `between` on an EQL type. A field reference names its +//! field's type and no index, so a query cannot send another index's term +//! in place of the type's twin. +//! +//! The twin carries what the type's query domain requires, as the data +//! path's does. The twin of an ordered type other than text carries its one +//! order term. A `TextOrd` twin carries the equality term and the order term whatever the +//! operator, since `eql_v4.query_text_ord` requires both: the query derives +//! the two terms for the one value. A text search twin's terms are +//! optional, so its query carries the term of the index that answers the +//! operator alone. //! //! The query is derived under the field reference's label: the record's scope, then //! the field's name (or its `identity`). That is the column the field @@ -144,6 +154,64 @@ //! //! let _ = EncryptedUser::AGE.matches("42"); //! ``` +//! An `IntegerOrd` field answers the orderings: +//! ``` +//! use eql_bindings::v4::integer::IntegerOrd; +//! use stack_encrypt::EncryptTarget; +//! use zeroize::Zeroize; +//! +//! #[derive(Zeroize)] +//! struct User { +//! age: i32, +//! } +//! +//! #[derive(EncryptTarget)] +//! #[stash(struct = User, scope = "users")] +//! struct EncryptedUser { +//! age: IntegerOrd, +//! } +//! +//! let _ = EncryptedUser::AGE.gt(30i32); +//! let _ = EncryptedUser::AGE.lte(65i32); +//! ``` +//! and no `eq`, since `IntegerOrd` carries no equality term: +//! ```compile_fail +//! use eql_bindings::v4::integer::IntegerOrd; +//! use stack_encrypt::EncryptTarget; +//! use zeroize::Zeroize; +//! +//! #[derive(Zeroize)] +//! struct User { +//! age: i32, +//! } +//! +//! #[derive(EncryptTarget)] +//! #[stash(struct = User, scope = "users")] +//! struct EncryptedUser { +//! age: IntegerOrd, +//! } +//! +//! let _ = EncryptedUser::AGE.eq(42i32); +//! ``` +//! nor `between`, which no EQL type answers from a field reference: +//! ```compile_fail +//! use eql_bindings::v4::integer::IntegerOrd; +//! use stack_encrypt::EncryptTarget; +//! use zeroize::Zeroize; +//! +//! #[derive(Zeroize)] +//! struct User { +//! age: i32, +//! } +//! +//! #[derive(EncryptTarget)] +//! #[stash(struct = User, scope = "users")] +//! struct EncryptedUser { +//! age: IntegerOrd, +//! } +//! +//! let _ = EncryptedUser::AGE.between(18i32, 65i32); +//! ``` //! The index a type answers through is a [`TwinIndex`]. It answers for its //! twin's own plaintext only ([`QueryTwin::Plaintext`]): `TextEqQuery`'s //! for a `String`, @@ -182,80 +250,102 @@ use serde::{Serialize, Serializer}; use stack_encrypt::kms::MaybeSend; use stack_encrypt::op::{self, Limit, Probabilistic, QueryTerm, QueryToken, Stats, Supports}; use stack_encrypt::sem::{EqualityTerm, MatchQuery, MatchTerms, QueryTokens}; -use stack_encrypt::target::{CallerContext, Encryption, Index, IndexSpec, WipeSource}; -use stack_encrypt::{Encrypt, EncryptRef, Equality, Error, Label, Match, NonEmpty}; +use stack_encrypt::target::{CallerContext, Encryption, Index, IndexSpec, Indexes, WipeSource}; +use stack_encrypt::{Encrypt, EncryptRef, Equality, Error, Label, Match, NonEmpty, Orderable}; use zeroize::Zeroize; use super::{bloom_filter, hmac256, EqlMatch}; use crate::v3::terms::{BloomFilter, Hmac256}; use crate::Identifier; -/// An EQL v4 query twin, assembled from the column it queries and the one -/// term its type's index derived for the query's value. eql-codegen -/// implements it for the twin of every type that answers an operator -/// ([`TextEqQuery`] from an [`Hmac256`], [`TextMatchQuery`] from a -/// [`BloomFilter`]), with the version every v4 value carries. +/// An EQL v4 query twin, assembled from the column it queries and the +/// terms `T` its type's indexes derived for the query's value, as EQL +/// 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 +/// [`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 +/// `TextSearchQuery`, implements it once per term, each assembling that +/// term alone. /// /// [`TextEqQuery`]: crate::v4::text::TextEqQuery /// [`TextMatchQuery`]: crate::v4::text::TextMatchQuery +/// [`TextOrdQuery`]: crate::v4::text::TextOrdQuery pub trait QueryTwin: Sized { /// The plaintext the twin's type is produced from: `String` for /// `TextEqQuery`, `i32` for `IntegerEqQuery`. A [`TwinIndex`] answers /// for this plaintext only, so no query can send one type's twin for /// another type's value. type Plaintext; - /// The twin of `term`, derived under `column`. - fn assemble(column: Identifier, term: T) -> Self; + /// The twin of `terms`, derived under `column`. + fn assemble(column: Identifier, terms: T) -> Self; } /// The index an EQL v4 type answers an operator through: Stack Encrypt's -/// index `I`, whose query term is sent as the type's query twin `Q`. +/// index `I`, whose query is sent as the type's query twin `Q`, built from +/// the terms of the indexes `D`. +/// +/// `D` is the indexes whose terms the twin carries. It is `I` alone for a +/// twin that carries one term (`TextEqQuery`, `IntegerOrdQuery`) or whose +/// terms are optional (`TextSearchQuery`), and every index of the type, in +/// catalog order, for a twin that carries them all whatever the operator: +/// `TextOrd` answers [`op::Lt`] through +/// `TwinIndex`, and [`op::Eq`](struct@op::Eq) through +/// `TwinIndex`. /// -/// It derives exactly what `I` derives, under the label of the field's -/// field reference and any scope the query carries, and checks and refuses what `I` -/// refuses, as well as a label that names no column; it then writes the -/// term into the twin, with the column the label names. It answers for the -/// twin's own plaintext +/// It derives the terms of `D`, under the label of the field's field +/// reference and any scope the query carries, and checks and refuses what +/// `I` refuses, as well as a label that names no column; it then writes the +/// terms into the twin, with the column the label names. It is declared as +/// `I` is ([`Index::spec`]). It answers for the twin's own plaintext /// ([`QueryTwin::Plaintext`]) only. `TextEq` answers [`op::Eq`](struct@op::Eq) through -/// `TwinIndex`, and `TextMatch` answers +/// `TwinIndex`, `IntegerOrd` answers [`op::Gt`] +/// through `TwinIndex`, and `TextMatch` answers /// [`op::Matches`](struct@op::Matches) through /// `TwinIndex, TextMatchQuery>`. -pub struct TwinIndex { +pub struct TwinIndex { index: I, + terms: D, twin: PhantomData Q>, } -impl Default for TwinIndex { +impl Default for TwinIndex { fn default() -> Self { Self { index: I::default(), + terms: D::default(), twin: PhantomData, } } } -impl Clone for TwinIndex { +impl Clone for TwinIndex { fn clone(&self) -> Self { Self { index: self.index.clone(), + terms: self.terms.clone(), twin: PhantomData, } } } -impl fmt::Debug for TwinIndex { +impl fmt::Debug for TwinIndex { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TwinIndex") .field("index", &self.index) + .field("terms", &self.terms) .field("twin", &std::any::type_name::()) .finish() } } -/// The index `I`, unchanged: the same spec, so it is declared as `I` is, -/// and the same derivation, so its term is `I`'s. -impl, Q> Index for TwinIndex { - type Term = I::Term; +/// 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`. +impl, Q, D: Indexes> Index for TwinIndex { + type Term = D::Terms; fn spec(&self) -> IndexSpec { self.index.spec() } @@ -265,7 +355,7 @@ impl, Q> Index for TwinIndex { where S: 's, { - self.index.operation() + self.terms.operations() } } @@ -350,6 +440,96 @@ where } } +/// Equality on a twin that carries an order term beside its `hm` +/// (`TextOrdQuery`, from `(Equality, O)`): the HMAC the equality index +/// derives, hex encoded as the stored value's is, and the term the order +/// index `O` derives for the same value, under the same context, +/// since the type's query domain requires both. Refuses what the equality +/// index refuses, as the data path does for `=`. Only for the plaintext +/// the twin's type is produced from. +impl Supports for TwinIndex +where + O: Index

, + Q: QueryTwin<(Hmac256, O::Term), Plaintext = P> + QueryTerm + MaybeSend + 'static, + P: Encrypt + EncryptRef + Zeroize + 'static, +{ + type Query = Q; + type Verifier = (); + fn prepare(&self, value: &P) -> Result<(), Error> { + Supports::::prepare(&self.index, value) + } + fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { + check_column(label) + } + fn query((): (), (equality, order): (EqualityTerm, O::Term), token: QueryToken) -> Q { + Q::assemble(column(&token), (hmac256(&equality), order)) + } +} + +// The orderings, through an order index `O` (OPE or block ORE): on a twin +// that carries `O`'s term alone (`IntegerOrdQuery` from an `OpeTerm`), +// and on one that carries an `hm` beside it (`TextOrdQuery`, from +// `(Equality, O)`), as the pair's equality impl does. The term is the one +// `O` sends for the operator, which is what it stores, so the twin compares +// against the stored value's term under the same column. Refuses what `O` +// refuses for the operator. Only for the plaintext the twin's type is +// produced from. +macro_rules! twin_orderings { + ($($operator:ident),+ $(,)?) => {$( + #[doc = concat!("`op::", stringify!($operator), "` on a twin that carries the order index's term alone.")] + impl Supports for TwinIndex + where + O: Supports + Indexes

, + Q: QueryTwin<>::Terms, Plaintext = P> + QueryTerm + MaybeSend + 'static, + P: Orderable + Zeroize + 'static, + { + type Query = Q; + type Verifier = (); + fn prepare(&self, value: &P) -> Result<(), Error> { + Supports::::prepare(&self.index, value) + } + fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { + check_column(label) + } + fn query( + (): (), + order: >::Terms, + token: QueryToken, + ) -> Q { + Q::assemble(column(&token), order) + } + } + + #[doc = concat!("`op::", stringify!($operator), "` on a twin that carries an `hm` beside the order index's term.")] + impl Supports for TwinIndex + where + O: Supports + Index

, + Q: QueryTwin<(Hmac256, >::Term), Plaintext = P> + + QueryTerm + + MaybeSend + + 'static, + P: Orderable + Encrypt + EncryptRef + Zeroize + 'static, + { + type Query = Q; + type Verifier = (); + fn prepare(&self, value: &P) -> Result<(), Error> { + Supports::::prepare(&self.index, value) + } + fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { + check_column(label) + } + fn query( + (): (), + (equality, order): (EqualityTerm, >::Term), + token: QueryToken, + ) -> Q { + Q::assemble(column(&token), (hmac256(&equality), order)) + } + } + )+}; +} +twin_orderings!(Lt, Lte, Gt, Gte); + /// Text match: the twin's `bf` is the filter EQL's match index derives /// over the query's text, and the query keeps that text's tokens to /// [`verify`](Probabilistic::verify) each decrypted row, as Stack Encrypt's diff --git a/packages/eql/crates/eql-bindings/src/v4/answers.rs b/packages/eql/crates/eql-bindings/src/v4/answers.rs index 8731ffbdf0..9bb121f1a5 100644 --- a/packages/eql/crates/eql-bindings/src/v4/answers.rs +++ b/packages/eql/crates/eql-bindings/src/v4/answers.rs @@ -6,8 +6,8 @@ use crate::v4::terms::{BloomFilter, Hmac256}; use crate::v4::SchemaVersion; use crate::Identifier; use stack_encrypt::op; -use stack_encrypt::Equality; -use stack_encrypt::Match; +use stack_encrypt::sem::{OpeTerm, OreBlockTerm}; +use stack_encrypt::{Equality, Match, Ope, OreBlock}; /// The operators each EQL type answers in Stack Encrypt's typed /// query (`op::Answers`), by the wire names /// `stack_encrypt::dynamic::Op` gives them, in catalog order: @@ -18,15 +18,47 @@ use stack_encrypt::Match; #[doc(hidden)] pub const ANSWERS: &[(&str, &[&str])] = &[ ("IntegerEq", &["eq"]), + ("IntegerOrdOre", &["lt", "lte", "gt", "gte"]), + ("IntegerOrd", &["lt", "lte", "gt", "gte"]), + ("IntegerOrdOpe", &["lt", "lte", "gt", "gte"]), ("SmallintEq", &["eq"]), + ("SmallintOrdOre", &["lt", "lte", "gt", "gte"]), + ("SmallintOrd", &["lt", "lte", "gt", "gte"]), + ("SmallintOrdOpe", &["lt", "lte", "gt", "gte"]), ("BigintEq", &["eq"]), + ("BigintOrdOre", &["lt", "lte", "gt", "gte"]), + ("BigintOrd", &["lt", "lte", "gt", "gte"]), + ("BigintOrdOpe", &["lt", "lte", "gt", "gte"]), ("DateEq", &["eq"]), + ("DateOrdOre", &["lt", "lte", "gt", "gte"]), + ("DateOrd", &["lt", "lte", "gt", "gte"]), + ("DateOrdOpe", &["lt", "lte", "gt", "gte"]), ("TimestampEq", &["eq"]), + ("TimestampOrdOre", &["lt", "lte", "gt", "gte"]), + ("TimestampOrd", &["lt", "lte", "gt", "gte"]), + ("TimestampOrdOpe", &["lt", "lte", "gt", "gte"]), ("NumericEq", &["eq"]), + ("NumericOrdOre", &["lt", "lte", "gt", "gte"]), + ("NumericOrd", &["lt", "lte", "gt", "gte"]), + ("NumericOrdOpe", &["lt", "lte", "gt", "gte"]), ("TextEq", &["eq"]), ("TextMatch", &["matches"]), + ("TextOrdOre", &["eq", "lt", "lte", "gt", "gte"]), + ("TextOrd", &["eq", "lt", "lte", "gt", "gte"]), + ("TextOrdOpe", &["eq", "lt", "lte", "gt", "gte"]), + ( + "TextSearchOre", + &["eq", "lt", "lte", "gt", "gte", "matches"], + ), + ("TextSearch", &["eq", "lt", "lte", "gt", "gte", "matches"]), ("RealEq", &["eq"]), + ("RealOrdOre", &["lt", "lte", "gt", "gte"]), + ("RealOrd", &["lt", "lte", "gt", "gte"]), + ("RealOrdOpe", &["lt", "lte", "gt", "gte"]), ("DoubleEq", &["eq"]), + ("DoubleOrdOre", &["lt", "lte", "gt", "gte"]), + ("DoubleOrd", &["lt", "lte", "gt", "gte"]), + ("DoubleOrdOpe", &["lt", "lte", "gt", "gte"]), ]; /// `IntegerEq` 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::integer::IntegerEq {} @@ -47,6 +79,99 @@ impl op::QueryTerm for super::integer::IntegerEqQuery {} impl op::Answers for super::integer::IntegerEq { type Via = TwinIndex; } +/// `IntegerOrdOre` 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::integer::IntegerOrdOre {} +/// `IntegerOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::integer::IntegerOrdOreQuery { + type Plaintext = i32; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `IntegerOrdOreQuery` is exact: the query term of `IntegerOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::integer::IntegerOrdOreQuery {} +/// `IntegerOrdOre` answers `op::Lt` through its block ORE index. The query term is `IntegerOrdOreQuery`, bound as `eql_v4.query_integer_ord_ore`. +impl op::Answers for super::integer::IntegerOrdOre { + type Via = TwinIndex; +} +/// `IntegerOrdOre` answers `op::Lte` through its block ORE index. The query term is `IntegerOrdOreQuery`, bound as `eql_v4.query_integer_ord_ore`. +impl op::Answers for super::integer::IntegerOrdOre { + type Via = TwinIndex; +} +/// `IntegerOrdOre` answers `op::Gt` through its block ORE index. The query term is `IntegerOrdOreQuery`, bound as `eql_v4.query_integer_ord_ore`. +impl op::Answers for super::integer::IntegerOrdOre { + type Via = TwinIndex; +} +/// `IntegerOrdOre` answers `op::Gte` through its block ORE index. The query term is `IntegerOrdOreQuery`, bound as `eql_v4.query_integer_ord_ore`. +impl op::Answers for super::integer::IntegerOrdOre { + type Via = TwinIndex; +} +/// `IntegerOrd` 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::integer::IntegerOrd {} +/// `IntegerOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::integer::IntegerOrdQuery { + type Plaintext = i32; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `IntegerOrdQuery` is exact: the query term of `IntegerOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::integer::IntegerOrdQuery {} +/// `IntegerOrd` answers `op::Lt` through its OPE index. The query term is `IntegerOrdQuery`, bound as `eql_v4.query_integer_ord`. +impl op::Answers for super::integer::IntegerOrd { + type Via = TwinIndex; +} +/// `IntegerOrd` answers `op::Lte` through its OPE index. The query term is `IntegerOrdQuery`, bound as `eql_v4.query_integer_ord`. +impl op::Answers for super::integer::IntegerOrd { + type Via = TwinIndex; +} +/// `IntegerOrd` answers `op::Gt` through its OPE index. The query term is `IntegerOrdQuery`, bound as `eql_v4.query_integer_ord`. +impl op::Answers for super::integer::IntegerOrd { + type Via = TwinIndex; +} +/// `IntegerOrd` answers `op::Gte` through its OPE index. The query term is `IntegerOrdQuery`, bound as `eql_v4.query_integer_ord`. +impl op::Answers for super::integer::IntegerOrd { + type Via = TwinIndex; +} +/// `IntegerOrdOpe` 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::integer::IntegerOrdOpe {} +/// `IntegerOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::integer::IntegerOrdOpeQuery { + type Plaintext = i32; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `IntegerOrdOpeQuery` is exact: the query term of `IntegerOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::integer::IntegerOrdOpeQuery {} +/// `IntegerOrdOpe` answers `op::Lt` through its OPE index. The query term is `IntegerOrdOpeQuery`, bound as `eql_v4.query_integer_ord_ope`. +impl op::Answers for super::integer::IntegerOrdOpe { + type Via = TwinIndex; +} +/// `IntegerOrdOpe` answers `op::Lte` through its OPE index. The query term is `IntegerOrdOpeQuery`, bound as `eql_v4.query_integer_ord_ope`. +impl op::Answers for super::integer::IntegerOrdOpe { + type Via = TwinIndex; +} +/// `IntegerOrdOpe` answers `op::Gt` through its OPE index. The query term is `IntegerOrdOpeQuery`, bound as `eql_v4.query_integer_ord_ope`. +impl op::Answers for super::integer::IntegerOrdOpe { + type Via = TwinIndex; +} +/// `IntegerOrdOpe` answers `op::Gte` through its OPE index. The query term is `IntegerOrdOpeQuery`, bound as `eql_v4.query_integer_ord_ope`. +impl op::Answers for super::integer::IntegerOrdOpe { + type Via = TwinIndex; +} /// `SmallintEq` 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::smallint::SmallintEq {} /// `SmallintEqQuery` from the column it queries and its `hm` term, at version 4. @@ -66,6 +191,99 @@ impl op::QueryTerm for super::smallint::SmallintEqQuery {} impl op::Answers for super::smallint::SmallintEq { type Via = TwinIndex; } +/// `SmallintOrdOre` 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::smallint::SmallintOrdOre {} +/// `SmallintOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::smallint::SmallintOrdOreQuery { + type Plaintext = i16; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `SmallintOrdOreQuery` is exact: the query term of `SmallintOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::smallint::SmallintOrdOreQuery {} +/// `SmallintOrdOre` answers `op::Lt` through its block ORE index. The query term is `SmallintOrdOreQuery`, bound as `eql_v4.query_smallint_ord_ore`. +impl op::Answers for super::smallint::SmallintOrdOre { + type Via = TwinIndex; +} +/// `SmallintOrdOre` answers `op::Lte` through its block ORE index. The query term is `SmallintOrdOreQuery`, bound as `eql_v4.query_smallint_ord_ore`. +impl op::Answers for super::smallint::SmallintOrdOre { + type Via = TwinIndex; +} +/// `SmallintOrdOre` answers `op::Gt` through its block ORE index. The query term is `SmallintOrdOreQuery`, bound as `eql_v4.query_smallint_ord_ore`. +impl op::Answers for super::smallint::SmallintOrdOre { + type Via = TwinIndex; +} +/// `SmallintOrdOre` answers `op::Gte` through its block ORE index. The query term is `SmallintOrdOreQuery`, bound as `eql_v4.query_smallint_ord_ore`. +impl op::Answers for super::smallint::SmallintOrdOre { + type Via = TwinIndex; +} +/// `SmallintOrd` 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::smallint::SmallintOrd {} +/// `SmallintOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::smallint::SmallintOrdQuery { + type Plaintext = i16; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `SmallintOrdQuery` is exact: the query term of `SmallintOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::smallint::SmallintOrdQuery {} +/// `SmallintOrd` answers `op::Lt` through its OPE index. The query term is `SmallintOrdQuery`, bound as `eql_v4.query_smallint_ord`. +impl op::Answers for super::smallint::SmallintOrd { + type Via = TwinIndex; +} +/// `SmallintOrd` answers `op::Lte` through its OPE index. The query term is `SmallintOrdQuery`, bound as `eql_v4.query_smallint_ord`. +impl op::Answers for super::smallint::SmallintOrd { + type Via = TwinIndex; +} +/// `SmallintOrd` answers `op::Gt` through its OPE index. The query term is `SmallintOrdQuery`, bound as `eql_v4.query_smallint_ord`. +impl op::Answers for super::smallint::SmallintOrd { + type Via = TwinIndex; +} +/// `SmallintOrd` answers `op::Gte` through its OPE index. The query term is `SmallintOrdQuery`, bound as `eql_v4.query_smallint_ord`. +impl op::Answers for super::smallint::SmallintOrd { + type Via = TwinIndex; +} +/// `SmallintOrdOpe` 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::smallint::SmallintOrdOpe {} +/// `SmallintOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::smallint::SmallintOrdOpeQuery { + type Plaintext = i16; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `SmallintOrdOpeQuery` is exact: the query term of `SmallintOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::smallint::SmallintOrdOpeQuery {} +/// `SmallintOrdOpe` answers `op::Lt` through its OPE index. The query term is `SmallintOrdOpeQuery`, bound as `eql_v4.query_smallint_ord_ope`. +impl op::Answers for super::smallint::SmallintOrdOpe { + type Via = TwinIndex; +} +/// `SmallintOrdOpe` answers `op::Lte` through its OPE index. The query term is `SmallintOrdOpeQuery`, bound as `eql_v4.query_smallint_ord_ope`. +impl op::Answers for super::smallint::SmallintOrdOpe { + type Via = TwinIndex; +} +/// `SmallintOrdOpe` answers `op::Gt` through its OPE index. The query term is `SmallintOrdOpeQuery`, bound as `eql_v4.query_smallint_ord_ope`. +impl op::Answers for super::smallint::SmallintOrdOpe { + type Via = TwinIndex; +} +/// `SmallintOrdOpe` answers `op::Gte` through its OPE index. The query term is `SmallintOrdOpeQuery`, bound as `eql_v4.query_smallint_ord_ope`. +impl op::Answers for super::smallint::SmallintOrdOpe { + type Via = TwinIndex; +} /// `BigintEq` 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::bigint::BigintEq {} /// `BigintEqQuery` from the column it queries and its `hm` term, at version 4. @@ -85,6 +303,99 @@ impl op::QueryTerm for super::bigint::BigintEqQuery {} impl op::Answers for super::bigint::BigintEq { type Via = TwinIndex; } +/// `BigintOrdOre` 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::bigint::BigintOrdOre {} +/// `BigintOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::bigint::BigintOrdOreQuery { + type Plaintext = i64; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `BigintOrdOreQuery` is exact: the query term of `BigintOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::bigint::BigintOrdOreQuery {} +/// `BigintOrdOre` answers `op::Lt` through its block ORE index. The query term is `BigintOrdOreQuery`, bound as `eql_v4.query_bigint_ord_ore`. +impl op::Answers for super::bigint::BigintOrdOre { + type Via = TwinIndex; +} +/// `BigintOrdOre` answers `op::Lte` through its block ORE index. The query term is `BigintOrdOreQuery`, bound as `eql_v4.query_bigint_ord_ore`. +impl op::Answers for super::bigint::BigintOrdOre { + type Via = TwinIndex; +} +/// `BigintOrdOre` answers `op::Gt` through its block ORE index. The query term is `BigintOrdOreQuery`, bound as `eql_v4.query_bigint_ord_ore`. +impl op::Answers for super::bigint::BigintOrdOre { + type Via = TwinIndex; +} +/// `BigintOrdOre` answers `op::Gte` through its block ORE index. The query term is `BigintOrdOreQuery`, bound as `eql_v4.query_bigint_ord_ore`. +impl op::Answers for super::bigint::BigintOrdOre { + type Via = TwinIndex; +} +/// `BigintOrd` 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::bigint::BigintOrd {} +/// `BigintOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::bigint::BigintOrdQuery { + type Plaintext = i64; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `BigintOrdQuery` is exact: the query term of `BigintOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::bigint::BigintOrdQuery {} +/// `BigintOrd` answers `op::Lt` through its OPE index. The query term is `BigintOrdQuery`, bound as `eql_v4.query_bigint_ord`. +impl op::Answers for super::bigint::BigintOrd { + type Via = TwinIndex; +} +/// `BigintOrd` answers `op::Lte` through its OPE index. The query term is `BigintOrdQuery`, bound as `eql_v4.query_bigint_ord`. +impl op::Answers for super::bigint::BigintOrd { + type Via = TwinIndex; +} +/// `BigintOrd` answers `op::Gt` through its OPE index. The query term is `BigintOrdQuery`, bound as `eql_v4.query_bigint_ord`. +impl op::Answers for super::bigint::BigintOrd { + type Via = TwinIndex; +} +/// `BigintOrd` answers `op::Gte` through its OPE index. The query term is `BigintOrdQuery`, bound as `eql_v4.query_bigint_ord`. +impl op::Answers for super::bigint::BigintOrd { + type Via = TwinIndex; +} +/// `BigintOrdOpe` 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::bigint::BigintOrdOpe {} +/// `BigintOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::bigint::BigintOrdOpeQuery { + type Plaintext = i64; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `BigintOrdOpeQuery` is exact: the query term of `BigintOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::bigint::BigintOrdOpeQuery {} +/// `BigintOrdOpe` answers `op::Lt` through its OPE index. The query term is `BigintOrdOpeQuery`, bound as `eql_v4.query_bigint_ord_ope`. +impl op::Answers for super::bigint::BigintOrdOpe { + type Via = TwinIndex; +} +/// `BigintOrdOpe` answers `op::Lte` through its OPE index. The query term is `BigintOrdOpeQuery`, bound as `eql_v4.query_bigint_ord_ope`. +impl op::Answers for super::bigint::BigintOrdOpe { + type Via = TwinIndex; +} +/// `BigintOrdOpe` answers `op::Gt` through its OPE index. The query term is `BigintOrdOpeQuery`, bound as `eql_v4.query_bigint_ord_ope`. +impl op::Answers for super::bigint::BigintOrdOpe { + type Via = TwinIndex; +} +/// `BigintOrdOpe` answers `op::Gte` through its OPE index. The query term is `BigintOrdOpeQuery`, bound as `eql_v4.query_bigint_ord_ope`. +impl op::Answers for super::bigint::BigintOrdOpe { + type Via = TwinIndex; +} /// `DateEq` 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::date::DateEq {} /// `DateEqQuery` from the column it queries and its `hm` term, at version 4. @@ -104,6 +415,99 @@ impl op::QueryTerm for super::date::DateEqQuery {} impl op::Answers for super::date::DateEq { type Via = TwinIndex; } +/// `DateOrdOre` 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::date::DateOrdOre {} +/// `DateOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::date::DateOrdOreQuery { + type Plaintext = crate::v4::plaintext::Date; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `DateOrdOreQuery` is exact: the query term of `DateOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::date::DateOrdOreQuery {} +/// `DateOrdOre` answers `op::Lt` through its block ORE index. The query term is `DateOrdOreQuery`, bound as `eql_v4.query_date_ord_ore`. +impl op::Answers for super::date::DateOrdOre { + type Via = TwinIndex; +} +/// `DateOrdOre` answers `op::Lte` through its block ORE index. The query term is `DateOrdOreQuery`, bound as `eql_v4.query_date_ord_ore`. +impl op::Answers for super::date::DateOrdOre { + type Via = TwinIndex; +} +/// `DateOrdOre` answers `op::Gt` through its block ORE index. The query term is `DateOrdOreQuery`, bound as `eql_v4.query_date_ord_ore`. +impl op::Answers for super::date::DateOrdOre { + type Via = TwinIndex; +} +/// `DateOrdOre` answers `op::Gte` through its block ORE index. The query term is `DateOrdOreQuery`, bound as `eql_v4.query_date_ord_ore`. +impl op::Answers for super::date::DateOrdOre { + type Via = TwinIndex; +} +/// `DateOrd` 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::date::DateOrd {} +/// `DateOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::date::DateOrdQuery { + type Plaintext = crate::v4::plaintext::Date; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `DateOrdQuery` is exact: the query term of `DateOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::date::DateOrdQuery {} +/// `DateOrd` answers `op::Lt` through its OPE index. The query term is `DateOrdQuery`, bound as `eql_v4.query_date_ord`. +impl op::Answers for super::date::DateOrd { + type Via = TwinIndex; +} +/// `DateOrd` answers `op::Lte` through its OPE index. The query term is `DateOrdQuery`, bound as `eql_v4.query_date_ord`. +impl op::Answers for super::date::DateOrd { + type Via = TwinIndex; +} +/// `DateOrd` answers `op::Gt` through its OPE index. The query term is `DateOrdQuery`, bound as `eql_v4.query_date_ord`. +impl op::Answers for super::date::DateOrd { + type Via = TwinIndex; +} +/// `DateOrd` answers `op::Gte` through its OPE index. The query term is `DateOrdQuery`, bound as `eql_v4.query_date_ord`. +impl op::Answers for super::date::DateOrd { + type Via = TwinIndex; +} +/// `DateOrdOpe` 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::date::DateOrdOpe {} +/// `DateOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::date::DateOrdOpeQuery { + type Plaintext = crate::v4::plaintext::Date; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `DateOrdOpeQuery` is exact: the query term of `DateOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::date::DateOrdOpeQuery {} +/// `DateOrdOpe` answers `op::Lt` through its OPE index. The query term is `DateOrdOpeQuery`, bound as `eql_v4.query_date_ord_ope`. +impl op::Answers for super::date::DateOrdOpe { + type Via = TwinIndex; +} +/// `DateOrdOpe` answers `op::Lte` through its OPE index. The query term is `DateOrdOpeQuery`, bound as `eql_v4.query_date_ord_ope`. +impl op::Answers for super::date::DateOrdOpe { + type Via = TwinIndex; +} +/// `DateOrdOpe` answers `op::Gt` through its OPE index. The query term is `DateOrdOpeQuery`, bound as `eql_v4.query_date_ord_ope`. +impl op::Answers for super::date::DateOrdOpe { + type Via = TwinIndex; +} +/// `DateOrdOpe` answers `op::Gte` through its OPE index. The query term is `DateOrdOpeQuery`, bound as `eql_v4.query_date_ord_ope`. +impl op::Answers for super::date::DateOrdOpe { + type Via = TwinIndex; +} /// `TimestampEq` 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::timestamp::TimestampEq {} /// `TimestampEqQuery` from the column it queries and its `hm` term, at version 4. @@ -123,6 +527,103 @@ impl op::QueryTerm for super::timestamp::TimestampEqQuery {} impl op::Answers for super::timestamp::TimestampEq { type Via = TwinIndex; } +/// `TimestampOrdOre` 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::timestamp::TimestampOrdOre {} +/// `TimestampOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> + for super::timestamp::TimestampOrdOreQuery +{ + type Plaintext = crate::v4::plaintext::Timestamp; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `TimestampOrdOreQuery` is exact: the query term of `TimestampOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::timestamp::TimestampOrdOreQuery {} +/// `TimestampOrdOre` answers `op::Lt` through its block ORE index. The query term is `TimestampOrdOreQuery`, bound as `eql_v4.query_timestamp_ord_ore`. +impl op::Answers for super::timestamp::TimestampOrdOre { + type Via = TwinIndex; +} +/// `TimestampOrdOre` answers `op::Lte` through its block ORE index. The query term is `TimestampOrdOreQuery`, bound as `eql_v4.query_timestamp_ord_ore`. +impl op::Answers for super::timestamp::TimestampOrdOre { + type Via = TwinIndex; +} +/// `TimestampOrdOre` answers `op::Gt` through its block ORE index. The query term is `TimestampOrdOreQuery`, bound as `eql_v4.query_timestamp_ord_ore`. +impl op::Answers for super::timestamp::TimestampOrdOre { + type Via = TwinIndex; +} +/// `TimestampOrdOre` answers `op::Gte` through its block ORE index. The query term is `TimestampOrdOreQuery`, bound as `eql_v4.query_timestamp_ord_ore`. +impl op::Answers for super::timestamp::TimestampOrdOre { + type Via = TwinIndex; +} +/// `TimestampOrd` 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::timestamp::TimestampOrd {} +/// `TimestampOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::timestamp::TimestampOrdQuery { + type Plaintext = crate::v4::plaintext::Timestamp; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `TimestampOrdQuery` is exact: the query term of `TimestampOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::timestamp::TimestampOrdQuery {} +/// `TimestampOrd` answers `op::Lt` through its OPE index. The query term is `TimestampOrdQuery`, bound as `eql_v4.query_timestamp_ord`. +impl op::Answers for super::timestamp::TimestampOrd { + type Via = TwinIndex; +} +/// `TimestampOrd` answers `op::Lte` through its OPE index. The query term is `TimestampOrdQuery`, bound as `eql_v4.query_timestamp_ord`. +impl op::Answers for super::timestamp::TimestampOrd { + type Via = TwinIndex; +} +/// `TimestampOrd` answers `op::Gt` through its OPE index. The query term is `TimestampOrdQuery`, bound as `eql_v4.query_timestamp_ord`. +impl op::Answers for super::timestamp::TimestampOrd { + type Via = TwinIndex; +} +/// `TimestampOrd` answers `op::Gte` through its OPE index. The query term is `TimestampOrdQuery`, bound as `eql_v4.query_timestamp_ord`. +impl op::Answers for super::timestamp::TimestampOrd { + type Via = TwinIndex; +} +/// `TimestampOrdOpe` 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::timestamp::TimestampOrdOpe {} +/// `TimestampOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> + for super::timestamp::TimestampOrdOpeQuery +{ + type Plaintext = crate::v4::plaintext::Timestamp; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `TimestampOrdOpeQuery` is exact: the query term of `TimestampOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::timestamp::TimestampOrdOpeQuery {} +/// `TimestampOrdOpe` answers `op::Lt` through its OPE index. The query term is `TimestampOrdOpeQuery`, bound as `eql_v4.query_timestamp_ord_ope`. +impl op::Answers for super::timestamp::TimestampOrdOpe { + type Via = TwinIndex; +} +/// `TimestampOrdOpe` answers `op::Lte` through its OPE index. The query term is `TimestampOrdOpeQuery`, bound as `eql_v4.query_timestamp_ord_ope`. +impl op::Answers for super::timestamp::TimestampOrdOpe { + type Via = TwinIndex; +} +/// `TimestampOrdOpe` answers `op::Gt` through its OPE index. The query term is `TimestampOrdOpeQuery`, bound as `eql_v4.query_timestamp_ord_ope`. +impl op::Answers for super::timestamp::TimestampOrdOpe { + type Via = TwinIndex; +} +/// `TimestampOrdOpe` answers `op::Gte` through its OPE index. The query term is `TimestampOrdOpeQuery`, bound as `eql_v4.query_timestamp_ord_ope`. +impl op::Answers for super::timestamp::TimestampOrdOpe { + type Via = TwinIndex; +} /// `NumericEq` 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::numeric::NumericEq {} /// `NumericEqQuery` from the column it queries and its `hm` term, at version 4. @@ -142,6 +643,99 @@ impl op::QueryTerm for super::numeric::NumericEqQuery {} impl op::Answers for super::numeric::NumericEq { type Via = TwinIndex; } +/// `NumericOrdOre` 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::numeric::NumericOrdOre {} +/// `NumericOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::numeric::NumericOrdOreQuery { + type Plaintext = crate::v4::plaintext::Decimal; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `NumericOrdOreQuery` is exact: the query term of `NumericOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::numeric::NumericOrdOreQuery {} +/// `NumericOrdOre` answers `op::Lt` through its block ORE index. The query term is `NumericOrdOreQuery`, bound as `eql_v4.query_numeric_ord_ore`. +impl op::Answers for super::numeric::NumericOrdOre { + type Via = TwinIndex; +} +/// `NumericOrdOre` answers `op::Lte` through its block ORE index. The query term is `NumericOrdOreQuery`, bound as `eql_v4.query_numeric_ord_ore`. +impl op::Answers for super::numeric::NumericOrdOre { + type Via = TwinIndex; +} +/// `NumericOrdOre` answers `op::Gt` through its block ORE index. The query term is `NumericOrdOreQuery`, bound as `eql_v4.query_numeric_ord_ore`. +impl op::Answers for super::numeric::NumericOrdOre { + type Via = TwinIndex; +} +/// `NumericOrdOre` answers `op::Gte` through its block ORE index. The query term is `NumericOrdOreQuery`, bound as `eql_v4.query_numeric_ord_ore`. +impl op::Answers for super::numeric::NumericOrdOre { + type Via = TwinIndex; +} +/// `NumericOrd` 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::numeric::NumericOrd {} +/// `NumericOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::numeric::NumericOrdQuery { + type Plaintext = crate::v4::plaintext::Decimal; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `NumericOrdQuery` is exact: the query term of `NumericOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::numeric::NumericOrdQuery {} +/// `NumericOrd` answers `op::Lt` through its OPE index. The query term is `NumericOrdQuery`, bound as `eql_v4.query_numeric_ord`. +impl op::Answers for super::numeric::NumericOrd { + type Via = TwinIndex; +} +/// `NumericOrd` answers `op::Lte` through its OPE index. The query term is `NumericOrdQuery`, bound as `eql_v4.query_numeric_ord`. +impl op::Answers for super::numeric::NumericOrd { + type Via = TwinIndex; +} +/// `NumericOrd` answers `op::Gt` through its OPE index. The query term is `NumericOrdQuery`, bound as `eql_v4.query_numeric_ord`. +impl op::Answers for super::numeric::NumericOrd { + type Via = TwinIndex; +} +/// `NumericOrd` answers `op::Gte` through its OPE index. The query term is `NumericOrdQuery`, bound as `eql_v4.query_numeric_ord`. +impl op::Answers for super::numeric::NumericOrd { + type Via = TwinIndex; +} +/// `NumericOrdOpe` 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::numeric::NumericOrdOpe {} +/// `NumericOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::numeric::NumericOrdOpeQuery { + type Plaintext = crate::v4::plaintext::Decimal; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `NumericOrdOpeQuery` is exact: the query term of `NumericOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::numeric::NumericOrdOpeQuery {} +/// `NumericOrdOpe` answers `op::Lt` through its OPE index. The query term is `NumericOrdOpeQuery`, bound as `eql_v4.query_numeric_ord_ope`. +impl op::Answers for super::numeric::NumericOrdOpe { + type Via = TwinIndex; +} +/// `NumericOrdOpe` answers `op::Lte` through its OPE index. The query term is `NumericOrdOpeQuery`, bound as `eql_v4.query_numeric_ord_ope`. +impl op::Answers for super::numeric::NumericOrdOpe { + type Via = TwinIndex; +} +/// `NumericOrdOpe` answers `op::Gt` through its OPE index. The query term is `NumericOrdOpeQuery`, bound as `eql_v4.query_numeric_ord_ope`. +impl op::Answers for super::numeric::NumericOrdOpe { + type Via = TwinIndex; +} +/// `NumericOrdOpe` answers `op::Gte` through its OPE index. The query term is `NumericOrdOpeQuery`, bound as `eql_v4.query_numeric_ord_ope`. +impl op::Answers for super::numeric::NumericOrdOpe { + type Via = TwinIndex; +} /// `TextEq` 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::TextEq {} /// `TextEqQuery` from the column it queries and its `hm` term, at version 4. @@ -178,6 +772,248 @@ impl QueryTwin for super::text::TextMatchQuery { impl op::Answers for super::text::TextMatch { type Via = TwinIndex, super::text::TextMatchQuery>; } +/// `TextOrdOre` 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::TextOrdOre {} +/// `TextOrdOreQuery` from the column it queries and its `hm` and `ob` terms, at version 4. +impl QueryTwin<(Hmac256, OreBlockTerm)> for super::text::TextOrdOreQuery { + type Plaintext = String; + fn assemble(i: Identifier, (hm, ob): (Hmac256, OreBlockTerm)) -> Self { + Self { + v: SchemaVersion::default(), + i, + hm, + ob, + } + } +} +/// `TextOrdOreQuery` is exact: the query term of `TextOrdOre`'s `op::Eq`, `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::text::TextOrdOreQuery {} +/// `TextOrdOre` answers `op::Eq` through its equality index. The query term is `TextOrdOreQuery`, bound as `eql_v4.query_text_ord_ore`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOre { + type Via = TwinIndex; +} +/// `TextOrdOre` answers `op::Lt` through its block ORE index. The query term is `TextOrdOreQuery`, bound as `eql_v4.query_text_ord_ore`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOre { + type Via = TwinIndex; +} +/// `TextOrdOre` answers `op::Lte` through its block ORE index. The query term is `TextOrdOreQuery`, bound as `eql_v4.query_text_ord_ore`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOre { + type Via = TwinIndex; +} +/// `TextOrdOre` answers `op::Gt` through its block ORE index. The query term is `TextOrdOreQuery`, bound as `eql_v4.query_text_ord_ore`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOre { + type Via = TwinIndex; +} +/// `TextOrdOre` answers `op::Gte` through its block ORE index. The query term is `TextOrdOreQuery`, bound as `eql_v4.query_text_ord_ore`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOre { + type Via = TwinIndex; +} +/// `TextOrd` 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::TextOrd {} +/// `TextOrdQuery` from the column it queries and its `hm` and `op` terms, at version 4. +impl QueryTwin<(Hmac256, OpeTerm)> for super::text::TextOrdQuery { + type Plaintext = String; + fn assemble(i: Identifier, (hm, op): (Hmac256, OpeTerm)) -> Self { + Self { + v: SchemaVersion::default(), + i, + hm, + op, + } + } +} +/// `TextOrdQuery` is exact: the query term of `TextOrd`'s `op::Eq`, `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::text::TextOrdQuery {} +/// `TextOrd` answers `op::Eq` through its equality index. The query term is `TextOrdQuery`, bound as `eql_v4.query_text_ord`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrd { + type Via = TwinIndex; +} +/// `TextOrd` answers `op::Lt` through its OPE index. The query term is `TextOrdQuery`, bound as `eql_v4.query_text_ord`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrd { + type Via = TwinIndex; +} +/// `TextOrd` answers `op::Lte` through its OPE index. The query term is `TextOrdQuery`, bound as `eql_v4.query_text_ord`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrd { + type Via = TwinIndex; +} +/// `TextOrd` answers `op::Gt` through its OPE index. The query term is `TextOrdQuery`, bound as `eql_v4.query_text_ord`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrd { + type Via = TwinIndex; +} +/// `TextOrd` answers `op::Gte` through its OPE index. The query term is `TextOrdQuery`, bound as `eql_v4.query_text_ord`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrd { + type Via = TwinIndex; +} +/// `TextOrdOpe` 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::TextOrdOpe {} +/// `TextOrdOpeQuery` from the column it queries and its `hm` and `op` terms, at version 4. +impl QueryTwin<(Hmac256, OpeTerm)> for super::text::TextOrdOpeQuery { + type Plaintext = String; + fn assemble(i: Identifier, (hm, op): (Hmac256, OpeTerm)) -> Self { + Self { + v: SchemaVersion::default(), + i, + hm, + op, + } + } +} +/// `TextOrdOpeQuery` is exact: the query term of `TextOrdOpe`'s `op::Eq`, `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::text::TextOrdOpeQuery {} +/// `TextOrdOpe` answers `op::Eq` through its equality index. The query term is `TextOrdOpeQuery`, bound as `eql_v4.query_text_ord_ope`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOpe { + type Via = TwinIndex; +} +/// `TextOrdOpe` answers `op::Lt` through its OPE index. The query term is `TextOrdOpeQuery`, bound as `eql_v4.query_text_ord_ope`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOpe { + type Via = TwinIndex; +} +/// `TextOrdOpe` answers `op::Lte` through its OPE index. The query term is `TextOrdOpeQuery`, bound as `eql_v4.query_text_ord_ope`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOpe { + type Via = TwinIndex; +} +/// `TextOrdOpe` answers `op::Gt` through its OPE index. The query term is `TextOrdOpeQuery`, bound as `eql_v4.query_text_ord_ope`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOpe { + type Via = TwinIndex; +} +/// `TextOrdOpe` answers `op::Gte` through its OPE index. The query term is `TextOrdOpeQuery`, bound as `eql_v4.query_text_ord_ope`, which carries the terms of all its indexes. +impl op::Answers for super::text::TextOrdOpe { + type Via = TwinIndex; +} +/// `TextSearchOre` 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::TextSearchOre {} +/// `TextSearchOreQuery` from the column it queries and its `hm` term alone, at version 4: the query through its equality index. +impl QueryTwin for super::text::TextSearchOreQuery { + type Plaintext = String; + fn assemble(i: Identifier, hm: Hmac256) -> Self { + Self { + v: SchemaVersion::default(), + i, + hm: Some(hm), + ob: None, + bf: None, + } + } +} +/// `TextSearchOreQuery` from the column it queries and its `ob` term alone, at version 4: the query through its block ORE index. +impl QueryTwin> for super::text::TextSearchOreQuery { + type Plaintext = String; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob: Some(ob), + hm: None, + bf: None, + } + } +} +/// `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 { + type Plaintext = String; + fn assemble(i: Identifier, bf: BloomFilter) -> Self { + Self { + v: SchemaVersion::default(), + i, + bf: Some(bf), + hm: None, + ob: None, + } + } +} +/// `TextSearchOreQuery` is exact: the query term of `TextSearchOre`'s `op::Eq`, `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::text::TextSearchOreQuery {} +/// `TextSearchOre` answers `op::Eq` through its equality index. The query term is `TextSearchOreQuery`, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex; +} +/// `TextSearchOre` answers `op::Lt` through its block ORE index. The query term is `TextSearchOreQuery`, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex; +} +/// `TextSearchOre` answers `op::Lte` through its block ORE index. The query term is `TextSearchOreQuery`, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex; +} +/// `TextSearchOre` answers `op::Gt` through its block ORE index. The query term is `TextSearchOreQuery`, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex; +} +/// `TextSearchOre` answers `op::Gte` through its block ORE index. The query term is `TextSearchOreQuery`, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex; +} +/// `TextSearchOre` answers `op::Matches` through its match index, under `EqlMatch`. The query term is a `MatchTwin`: the twin, bound as `eql_v4.query_text_search_ore`, which carries that index's term alone, and the tokens that verify a row. +impl op::Answers for super::text::TextSearchOre { + type Via = TwinIndex, super::text::TextSearchOreQuery>; +} +/// `TextSearch` 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::TextSearch {} +/// `TextSearchQuery` from the column it queries and its `hm` term alone, at version 4: the query through its equality index. +impl QueryTwin for super::text::TextSearchQuery { + type Plaintext = String; + fn assemble(i: Identifier, hm: Hmac256) -> Self { + Self { + v: SchemaVersion::default(), + i, + hm: Some(hm), + op: None, + bf: None, + } + } +} +/// `TextSearchQuery` from the column it queries and its `op` term alone, at version 4: the query through its OPE index. +impl QueryTwin> for super::text::TextSearchQuery { + type Plaintext = String; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op: Some(op), + hm: None, + bf: None, + } + } +} +/// `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 { + type Plaintext = String; + fn assemble(i: Identifier, bf: BloomFilter) -> Self { + Self { + v: SchemaVersion::default(), + i, + bf: Some(bf), + hm: None, + op: None, + } + } +} +/// `TextSearchQuery` is exact: the query term of `TextSearch`'s `op::Eq`, `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::text::TextSearchQuery {} +/// `TextSearch` answers `op::Eq` through its equality index. The query term is `TextSearchQuery`, bound as `eql_v4.query_text_search`, which carries that index's term alone. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex; +} +/// `TextSearch` answers `op::Lt` through its OPE index. The query term is `TextSearchQuery`, bound as `eql_v4.query_text_search`, which carries that index's term alone. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex; +} +/// `TextSearch` answers `op::Lte` through its OPE index. The query term is `TextSearchQuery`, bound as `eql_v4.query_text_search`, which carries that index's term alone. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex; +} +/// `TextSearch` answers `op::Gt` through its OPE index. The query term is `TextSearchQuery`, bound as `eql_v4.query_text_search`, which carries that index's term alone. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex; +} +/// `TextSearch` answers `op::Gte` through its OPE index. The query term is `TextSearchQuery`, bound as `eql_v4.query_text_search`, which carries that index's term alone. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex; +} +/// `TextSearch` answers `op::Matches` through its match index, under `EqlMatch`. The query term is a `MatchTwin`: the twin, bound as `eql_v4.query_text_search`, which carries that index's term alone, and the tokens that verify a row. +impl op::Answers for super::text::TextSearch { + type Via = TwinIndex, super::text::TextSearchQuery>; +} /// `RealEq` 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::real::RealEq {} /// `RealEqQuery` from the column it queries and its `hm` term, at version 4. @@ -197,6 +1033,99 @@ impl op::QueryTerm for super::real::RealEqQuery {} impl op::Answers for super::real::RealEq { type Via = TwinIndex; } +/// `RealOrdOre` 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::real::RealOrdOre {} +/// `RealOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::real::RealOrdOreQuery { + type Plaintext = f32; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `RealOrdOreQuery` is exact: the query term of `RealOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::real::RealOrdOreQuery {} +/// `RealOrdOre` answers `op::Lt` through its block ORE index. The query term is `RealOrdOreQuery`, bound as `eql_v4.query_real_ord_ore`. +impl op::Answers for super::real::RealOrdOre { + type Via = TwinIndex; +} +/// `RealOrdOre` answers `op::Lte` through its block ORE index. The query term is `RealOrdOreQuery`, bound as `eql_v4.query_real_ord_ore`. +impl op::Answers for super::real::RealOrdOre { + type Via = TwinIndex; +} +/// `RealOrdOre` answers `op::Gt` through its block ORE index. The query term is `RealOrdOreQuery`, bound as `eql_v4.query_real_ord_ore`. +impl op::Answers for super::real::RealOrdOre { + type Via = TwinIndex; +} +/// `RealOrdOre` answers `op::Gte` through its block ORE index. The query term is `RealOrdOreQuery`, bound as `eql_v4.query_real_ord_ore`. +impl op::Answers for super::real::RealOrdOre { + type Via = TwinIndex; +} +/// `RealOrd` 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::real::RealOrd {} +/// `RealOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::real::RealOrdQuery { + type Plaintext = f32; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `RealOrdQuery` is exact: the query term of `RealOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::real::RealOrdQuery {} +/// `RealOrd` answers `op::Lt` through its OPE index. The query term is `RealOrdQuery`, bound as `eql_v4.query_real_ord`. +impl op::Answers for super::real::RealOrd { + type Via = TwinIndex; +} +/// `RealOrd` answers `op::Lte` through its OPE index. The query term is `RealOrdQuery`, bound as `eql_v4.query_real_ord`. +impl op::Answers for super::real::RealOrd { + type Via = TwinIndex; +} +/// `RealOrd` answers `op::Gt` through its OPE index. The query term is `RealOrdQuery`, bound as `eql_v4.query_real_ord`. +impl op::Answers for super::real::RealOrd { + type Via = TwinIndex; +} +/// `RealOrd` answers `op::Gte` through its OPE index. The query term is `RealOrdQuery`, bound as `eql_v4.query_real_ord`. +impl op::Answers for super::real::RealOrd { + type Via = TwinIndex; +} +/// `RealOrdOpe` 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::real::RealOrdOpe {} +/// `RealOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::real::RealOrdOpeQuery { + type Plaintext = f32; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `RealOrdOpeQuery` is exact: the query term of `RealOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::real::RealOrdOpeQuery {} +/// `RealOrdOpe` answers `op::Lt` through its OPE index. The query term is `RealOrdOpeQuery`, bound as `eql_v4.query_real_ord_ope`. +impl op::Answers for super::real::RealOrdOpe { + type Via = TwinIndex; +} +/// `RealOrdOpe` answers `op::Lte` through its OPE index. The query term is `RealOrdOpeQuery`, bound as `eql_v4.query_real_ord_ope`. +impl op::Answers for super::real::RealOrdOpe { + type Via = TwinIndex; +} +/// `RealOrdOpe` answers `op::Gt` through its OPE index. The query term is `RealOrdOpeQuery`, bound as `eql_v4.query_real_ord_ope`. +impl op::Answers for super::real::RealOrdOpe { + type Via = TwinIndex; +} +/// `RealOrdOpe` answers `op::Gte` through its OPE index. The query term is `RealOrdOpeQuery`, bound as `eql_v4.query_real_ord_ope`. +impl op::Answers for super::real::RealOrdOpe { + type Via = TwinIndex; +} /// `DoubleEq` 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::double::DoubleEq {} /// `DoubleEqQuery` from the column it queries and its `hm` term, at version 4. @@ -216,3 +1145,96 @@ impl op::QueryTerm for super::double::DoubleEqQuery {} impl op::Answers for super::double::DoubleEq { type Via = TwinIndex; } +/// `DoubleOrdOre` 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::double::DoubleOrdOre {} +/// `DoubleOrdOreQuery` from the column it queries and its `ob` term, at version 4. +impl QueryTwin> for super::double::DoubleOrdOreQuery { + type Plaintext = f64; + fn assemble(i: Identifier, ob: OreBlockTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + ob, + } + } +} +/// `DoubleOrdOreQuery` is exact: the query term of `DoubleOrdOre`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::double::DoubleOrdOreQuery {} +/// `DoubleOrdOre` answers `op::Lt` through its block ORE index. The query term is `DoubleOrdOreQuery`, bound as `eql_v4.query_double_ord_ore`. +impl op::Answers for super::double::DoubleOrdOre { + type Via = TwinIndex; +} +/// `DoubleOrdOre` answers `op::Lte` through its block ORE index. The query term is `DoubleOrdOreQuery`, bound as `eql_v4.query_double_ord_ore`. +impl op::Answers for super::double::DoubleOrdOre { + type Via = TwinIndex; +} +/// `DoubleOrdOre` answers `op::Gt` through its block ORE index. The query term is `DoubleOrdOreQuery`, bound as `eql_v4.query_double_ord_ore`. +impl op::Answers for super::double::DoubleOrdOre { + type Via = TwinIndex; +} +/// `DoubleOrdOre` answers `op::Gte` through its block ORE index. The query term is `DoubleOrdOreQuery`, bound as `eql_v4.query_double_ord_ore`. +impl op::Answers for super::double::DoubleOrdOre { + type Via = TwinIndex; +} +/// `DoubleOrd` 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::double::DoubleOrd {} +/// `DoubleOrdQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::double::DoubleOrdQuery { + type Plaintext = f64; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `DoubleOrdQuery` is exact: the query term of `DoubleOrd`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::double::DoubleOrdQuery {} +/// `DoubleOrd` answers `op::Lt` through its OPE index. The query term is `DoubleOrdQuery`, bound as `eql_v4.query_double_ord`. +impl op::Answers for super::double::DoubleOrd { + type Via = TwinIndex; +} +/// `DoubleOrd` answers `op::Lte` through its OPE index. The query term is `DoubleOrdQuery`, bound as `eql_v4.query_double_ord`. +impl op::Answers for super::double::DoubleOrd { + type Via = TwinIndex; +} +/// `DoubleOrd` answers `op::Gt` through its OPE index. The query term is `DoubleOrdQuery`, bound as `eql_v4.query_double_ord`. +impl op::Answers for super::double::DoubleOrd { + type Via = TwinIndex; +} +/// `DoubleOrd` answers `op::Gte` through its OPE index. The query term is `DoubleOrdQuery`, bound as `eql_v4.query_double_ord`. +impl op::Answers for super::double::DoubleOrd { + type Via = TwinIndex; +} +/// `DoubleOrdOpe` 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::double::DoubleOrdOpe {} +/// `DoubleOrdOpeQuery` from the column it queries and its `op` term, at version 4. +impl QueryTwin> for super::double::DoubleOrdOpeQuery { + type Plaintext = f64; + fn assemble(i: Identifier, op: OpeTerm) -> Self { + Self { + v: SchemaVersion::default(), + i, + op, + } + } +} +/// `DoubleOrdOpeQuery` is exact: the query term of `DoubleOrdOpe`'s `op::Lt`, `op::Lte`, `op::Gt`, `op::Gte`. +impl op::QueryTerm for super::double::DoubleOrdOpeQuery {} +/// `DoubleOrdOpe` answers `op::Lt` through its OPE index. The query term is `DoubleOrdOpeQuery`, bound as `eql_v4.query_double_ord_ope`. +impl op::Answers for super::double::DoubleOrdOpe { + type Via = TwinIndex; +} +/// `DoubleOrdOpe` answers `op::Lte` through its OPE index. The query term is `DoubleOrdOpeQuery`, bound as `eql_v4.query_double_ord_ope`. +impl op::Answers for super::double::DoubleOrdOpe { + type Via = TwinIndex; +} +/// `DoubleOrdOpe` answers `op::Gt` through its OPE index. The query term is `DoubleOrdOpeQuery`, bound as `eql_v4.query_double_ord_ope`. +impl op::Answers for super::double::DoubleOrdOpe { + type Via = TwinIndex; +} +/// `DoubleOrdOpe` answers `op::Gte` through its OPE index. The query term is `DoubleOrdOpeQuery`, bound as `eql_v4.query_double_ord_ope`. +impl op::Answers for super::double::DoubleOrdOpe { + type Via = TwinIndex; +} diff --git a/packages/eql/crates/eql-codegen/src/targets.rs b/packages/eql/crates/eql-codegen/src/targets.rs index 08fb6d127d..3d37b67732 100644 --- a/packages/eql/crates/eql-codegen/src/targets.rs +++ b/packages/eql/crates/eql-codegen/src/targets.rs @@ -24,10 +24,11 @@ //! alone: it implements `op::Answers` for each, with the type's query twin as //! the query term, and lists them in `ANSWERS` so the encryption tests can //! hold them to the operators the engine's data path answers for the same -//! type. A producible type whose twin carries an order index, or more than -//! one index, answers nothing there yet ([`typed_gap`]): a typed query sends one -//! index's term as the twin, and those twins need an order term, or several -//! terms at once. +//! type: every producible type with a twin answers there what it answers +//! through a data plan. A twin that requires several terms (`TextOrdQuery`'s +//! `hm` and `op`) is assembled from all of them whatever the operator, and a +//! twin whose terms are optional (`TextSearchQuery`) from the answering +//! index's term alone, as the data path builds each. //! //! The reasons a type is not producible: eql-bindings names no Rust //! plaintext type for the family, and the JSON index is a new engine @@ -70,11 +71,22 @@ pub fn index_key(term: Term) -> &'static str { } /// An operator a producible EQL type answers in a Stack Encrypt typed -/// query: what the generated file implements `op::Answers` for. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// query: what the generated file implements `op::Answers` for. Declared in +/// the order `stack_encrypt::dynamic::Op::ALL` lists them, which is the +/// order the data path lists a type's operators in, so sorting a type's +/// answers gives the data path's list. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum Answer { /// `op::Eq`, through the equality index. Eq, + /// `op::Lt`, through the type's order index. + Lt, + /// `op::Lte`, through the type's order index. + Lte, + /// `op::Gt`, through the type's order index. + Gt, + /// `op::Gte`, through the type's order index. + Gte, /// `op::Matches`, through the match index under EQL's configuration. Matches, } @@ -84,66 +96,111 @@ impl Answer { pub(crate) fn name(self) -> &'static str { match self { Answer::Eq => "eq", + Answer::Lt => "lt", + Answer::Lte => "lte", + Answer::Gt => "gt", + Answer::Gte => "gte", Answer::Matches => "matches", } } - /// The catalog term the operator's index derives: the one term the - /// query twin carries, under its JSON key. - pub(crate) fn term(self) -> Term { + /// The operator's type in `stack_encrypt::op`. + pub(crate) fn operator(self) -> &'static str { match self { - Answer::Eq => Term::Hm, - Answer::Matches => Term::Bloom, + Answer::Eq => "Eq", + Answer::Lt => "Lt", + Answer::Lte => "Lte", + Answer::Gt => "Gt", + Answer::Gte => "Gte", + Answer::Matches => "Matches", } } + + /// Whether the server's answer is the answer, so the twin itself is the + /// query term: every operator but `Matches`, whose query is a + /// `MatchTwin` that verifies rows. + pub(crate) fn is_exact(self) -> bool { + self != Answer::Matches + } + + /// The operators the index under `key` ([`index_key`]) answers: the + /// engine's declarations (`Equality::OPERATORS`, `Ope::OPERATORS`, …) + /// less `between`, which the data path answers for no EQL type. + /// + /// # Panics + /// + /// On an index key the generator does not know: a new catalog term must + /// say what a typed query does with it. + fn of_index(type_name: &str, key: &str) -> &'static [Answer] { + match key { + "eq" => &[Answer::Eq], + "match" => &[Answer::Matches], + "ope" | "ore_block" => &[Answer::Lt, Answer::Lte, Answer::Gt, Answer::Gte], + other => panic!( + "{type_name}: a typed query has no rule for the {other} index; extend \ + eql-codegen's Answer::of_index" + ), + } + } + + /// The key of the index among `indexes` that answers this operator. + fn index<'i>(self, indexes: &[&'i str]) -> &'i str { + indexes + .iter() + .copied() + .find(|key| Answer::of_index("", key).contains(&self)) + .expect("an answer comes from one of the type's indexes") + } } -/// Why a typed query has no answer yet for a type carrying these -/// indexes, by [`index_key`] name, or `None` when it answers: a query twin -/// is assembled from the one term its type's index derived, so a twin that -/// needs an order term (`"ore"`, `"ore_block"` or `"ope"`), or more than one term, is not -/// built by it. The reason is the generator's, for its tests and docs; the -/// generated file simply leaves the type out. -pub(crate) fn typed_gap(indexes: &[&str]) -> Option<&'static str> { - if indexes - .iter() - .any(|key| matches!(*key, "ore" | "ore_block" | "ope")) - { - Some("its twin carries an order term, which a typed query does not derive yet") - } else if indexes.len() > 1 { - Some("its twin carries more than one term, which a typed query does not assemble yet") - } else { - None +/// The catalog term an index derives, by its [`index_key`]: the inverse of +/// that function. +fn term_of_key(key: &str) -> Term { + match key { + "eq" => Term::Hm, + "match" => Term::Bloom, + "ore_block" => Term::Ore, + "ope" => Term::Ope, + other => panic!("no catalog term rides under the {other} index"), } } /// The operators a producible type with a query twin answers, given the /// indexes it carries by [`index_key`] name, the same input the engine's -/// table reads: `Eq` for the `"eq"` index and `Matches` for the `"match"` -/// index, as `Op::answered_by` answers a field that names the type -/// (`TargetDescriptor::operators`). Empty for a type a typed query has no -/// answer for yet ([`typed_gap`]). The encryption tests compare the two, -/// type by type, and hold the gap to exactly those types. +/// table reads: `Eq` for the `"eq"` index, `Matches` for the `"match"` +/// index and the orderings (`Lt`, `Lte`, `Gt`, `Gte`) for the `"ope"` or +/// `"ore_block"` index, as `Op::answered_by` answers a field that names the +/// type (`TargetDescriptor::operators`), in its order. No `Between`: the +/// data path answers no `between` on an EQL type. The encryption tests +/// compare the two, type by type. +/// +/// `optional_terms` says whether the twin's terms are optional in EQL v4, +/// so its query carries the answering index's term alone; otherwise the +/// twin carries every index's term whatever the operator. /// /// # Panics /// -/// On an index key the generator does not know: a new catalog term must say -/// what a typed query does with it. -pub(crate) fn answers_for_indexes(name: &str, indexes: &[&str]) -> Vec { - if typed_gap(indexes).is_some() { - return Vec::new(); +/// On an index key the generator does not know, and on a twin that carries +/// a match term beside another term that it requires: its `matches` query +/// would carry them all, and a typed query has no rule to assemble a +/// verifying query from several terms. +pub(crate) fn answers_for_indexes( + name: &str, + indexes: &[&str], + optional_terms: bool, +) -> Vec { + if indexes.len() > 1 && indexes.contains(&"match") && !optional_terms { + panic!( + "{name}: its twin requires a match term beside another term; a typed query \ + assembles a match twin from the match term alone" + ); } - indexes + let mut answers: Vec = indexes .iter() - .map(|key| match *key { - "eq" => Answer::Eq, - "match" => Answer::Matches, - other => panic!( - "{name}: a typed query has no rule for the {other} index; extend \ - eql-codegen's answers_for_indexes and typed_gap" - ), - }) - .collect() + .flat_map(|key| Answer::of_index(name, key).iter().copied()) + .collect(); + answers.sort_unstable(); + answers } /// The plaintext a family's domains are produced from: see @@ -264,8 +321,9 @@ fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { }; let name = domain.rust_struct_name(family.name); let reason = target_gap(family, domain); + let optional_terms = v4_optional_query_terms(domain); let answers = if reason.is_none() && query.is_some() { - answers_for_indexes(&name, &indexes) + answers_for_indexes(&name, &indexes, optional_terms) } else { Vec::new() }; @@ -281,7 +339,7 @@ fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { ), indexes, query, - projections: if v4_optional_query_terms(domain) { + projections: if optional_terms { Term::payload_terms(domain.terms) .into_iter() .map(|term| { @@ -300,13 +358,51 @@ fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { } } -/// A typed query's impls for one type that answers an operator: -/// its query twin's assembly from the one term it carries, `QueryTerm` on -/// the twin when an exact operator returns it as is, and one `op::Answers` -/// per operator, through Stack Encrypt's index for it, sent as the twin. +/// Stack Encrypt's index type for an index key, as `answers.rs` names it. +fn index_type(key: &str) -> TokenStream { + match key { + "eq" => quote!(Equality), + "match" => quote!(Match), + "ope" => quote!(Ope), + "ore_block" => quote!(OreBlock), + other => panic!("no Stack Encrypt index for the {other} index"), + } +} + +/// The type a query twin stores the term of an index in, over the type's +/// plaintext `source`: the EQL newtype of an `hm` or a `bf`, Stack +/// Encrypt's own term of an `op` or an `ob`. +fn twin_term_type(key: &str, source: &syn::Path) -> TokenStream { + match key { + "eq" => quote!(Hmac256), + "match" => quote!(BloomFilter), + "ope" => quote!(OpeTerm<#source>), + "ore_block" => quote!(OreBlockTerm<#source>), + other => panic!("no query twin term for the {other} index"), + } +} + +/// How an index is named in the generated docs. +fn index_doc(key: &str) -> &'static str { + match key { + "eq" => "equality", + "match" => "match", + "ope" => "OPE", + "ore_block" => "block ORE", + other => panic!("no name for the {other} index"), + } +} + +/// A typed query's impls for one type that answers an operator: its query +/// twin's assembly from the terms it carries (every index's, or for a twin +/// whose terms are optional, one assembly per index from that index's term +/// alone), `QueryTerm` on the twin when an exact operator returns it as is, +/// and one `op::Answers` per operator, through Stack Encrypt's index for it, +/// sent as the twin. fn answer_impls(r: &Row) -> TokenStream { let module = format_ident!("{}", r.family); let ty = format_ident!("{}", r.name); + let name = &r.name; let (twin_name, twin_domain) = r .query .as_ref() @@ -314,63 +410,119 @@ fn answer_impls(r: &Row) -> TokenStream { let twin = format_ident!("{twin_name}"); let (_, rust) = plaintext_of(r.family).expect("a producible family has a specified plaintext"); let source: syn::Path = syn::parse_str(rust).expect("a family's Rust plaintext is a type path"); - // `answers_for_indexes` admits one index, so every operator's term is - // the same. - let term = r.answers[0].term(); - let field = format_ident!("{}", term.json_key()); - let newtype = format_ident!("{}", term.binding_newtype()); - let assemble_doc = format!( - " `{twin_name}` from the column it queries and its `{}` term, at version 4.", - term.json_key() - ); + let field = |key: &str| format_ident!("{}", term_of_key(key).json_key()); + let optional_terms = !r.projections.is_empty(); let labelled_doc = format!( - " `{}` is sealed under the column a two-segment label names, so a field of this \ - type is queried under its field reference's label.", - r.name + " `{name}` is sealed under the column a two-segment label names, so a field of this \ + type is queried under its field reference's label." ); let mut out = quote! { #[doc = #labelled_doc] impl op::LabelledTarget for super::#module::#ty {} - #[doc = #assemble_doc] - impl QueryTwin<#newtype> for super::#module::#twin { - type Plaintext = #source; - fn assemble(i: Identifier, #field: #newtype) -> Self { - Self { v: SchemaVersion::default(), i, #field } - } + }; + if optional_terms { + // One assembly per index, each setting that index's term alone. + for key in &r.indexes { + let set = field(key); + let term = twin_term_type(key, &source); + let unset = r.indexes.iter().filter(|k| *k != key).map(|k| field(k)); + let doc = format!( + " `{twin_name}` from the column it queries and its `{set}` term alone, at \ + version 4: the query through its {} index.", + index_doc(key) + ); + out.extend(quote! { + #[doc = #doc] + impl QueryTwin<#term> for super::#module::#twin { + type Plaintext = #source; + fn assemble(i: Identifier, #set: #term) -> Self { + Self { v: SchemaVersion::default(), i, #set: Some(#set), #(#unset: None),* } + } + } + }); } + } else { + let fields: Vec<_> = r.indexes.iter().map(|key| field(key)).collect(); + let terms: Vec<_> = r + .indexes + .iter() + .map(|key| twin_term_type(key, &source)) + .collect(); + let named: Vec = fields.iter().map(|f| format!("`{f}`")).collect(); + let doc = format!( + " `{twin_name}` from the column it queries and its {} {}, at version 4.", + named.join(" and "), + if named.len() == 1 { "term" } else { "terms" } + ); + let (pattern, input) = match (fields.as_slice(), terms.as_slice()) { + ([one], [term]) => (quote!(#one), quote!(#term)), + _ => (quote!((#(#fields),*)), quote!((#(#terms),*))), + }; + out.extend(quote! { + #[doc = #doc] + impl QueryTwin<#input> for super::#module::#twin { + type Plaintext = #source; + fn assemble(i: Identifier, #pattern: #input) -> Self { + Self { v: SchemaVersion::default(), i, #(#fields),* } + } + } + }); + } + let exact: Vec = r + .answers + .iter() + .filter(|answer| answer.is_exact()) + .map(|answer| format!("`op::{}`", answer.operator())) + .collect(); + if !exact.is_empty() { + let term_doc = format!( + " `{twin_name}` is exact: the query term of `{name}`'s {}.", + exact.join(", ") + ); + out.extend(quote! { + #[doc = #term_doc] + impl op::QueryTerm for super::#module::#twin {} + }); + } + // A twin that requires every term derives them all, whichever index + // answers; one whose terms are optional derives the answering index's. + let derived = (!optional_terms && r.indexes.len() > 1).then(|| { + let all = r.indexes.iter().map(|key| index_type(key)); + quote!(, (#(#all),*)) + }); + let carries = if derived.is_some() { + ", which carries the terms of all its indexes" + } else if optional_terms { + ", which carries that index's term alone" + } else { + "" }; for answer in &r.answers { - let name = &r.name; - let (op, via, doc) = match answer { - Answer::Eq => { - let term_doc = - format!(" `{twin_name}` is exact: the query term of `{name}`'s `op::Eq`."); - out.extend(quote! { - #[doc = #term_doc] - impl op::QueryTerm for super::#module::#twin {} - }); - ( - quote!(op::Eq), - quote!(TwinIndex), - format!( - " `{name}` answers `op::Eq` through its equality index. The query \ - term is `{twin_name}`, bound as `{twin_domain}`." - ), - ) - } + let key = answer.index(&r.indexes); + let index = index_type(key); + let op = format_ident!("{}", answer.operator()); + let (via, doc) = match answer { Answer::Matches => ( - quote!(op::Matches), - quote!(TwinIndex, super::#module::#twin>), + quote!(TwinIndex<#index, super::#module::#twin>), format!( " `{name}` answers `op::Matches` through its match index, under \ `EqlMatch`. The query term is a `MatchTwin<{twin_name}>`: the twin, \ - bound as `{twin_domain}`, and the tokens that verify a row." + bound as `{twin_domain}`{carries}, and the tokens that verify a row." + ), + ), + exact => ( + quote!(TwinIndex<#index, super::#module::#twin #derived>), + format!( + " `{name}` answers `op::{}` through its {} index. The query term is \ + `{twin_name}`, bound as `{twin_domain}`{carries}.", + exact.operator(), + index_doc(key) ), ), }; out.extend(quote! { #[doc = #doc] - impl op::Answers<#op, #source> for super::#module::#ty { + impl op::Answers for super::#module::#ty { type Via = #via; } }); @@ -635,7 +787,7 @@ pub fn render_answers_rs() -> String { /// feature) is built on. fn render_answers_from(rows: &[Row]) -> String { // A typed query: per type that answers an operator, its twin's - // assembly from the one term it carries, and one `op::Answers` impl per + // assembly from the terms it carries, and one `op::Answers` impl per // operator, through Stack Encrypt's index for it, sent as the twin. let answering: Vec<&Row> = rows.iter().filter(|r| !r.answers.is_empty()).collect(); let answer_impls: TokenStream = answering.iter().map(|r| answer_impls(r)).collect(); @@ -647,38 +799,43 @@ fn render_answers_from(rows: &[Row]) -> String { quote!((#name, &[#(#ops),*]),) }) .collect(); - let answers_any = |wanted: Answer| answering.iter().any(|r| r.answers.contains(&wanted)); + // Every index an answering type carries is named in its impls: as the + // index an operator answers through, in the indexes a twin's terms are + // derived by, and as the type of the term the twin stores. + let carries = |key: &str| answering.iter().any(|r| r.indexes.contains(&key)); let mut answer_imports = TokenStream::new(); if !answering.is_empty() { - let mut newtypes: Vec<&str> = answering - .iter() - .flat_map(|r| { - r.answers - .iter() - .map(|answer| answer.term().binding_newtype()) - }) - .collect(); - newtypes.sort_unstable(); - newtypes.dedup(); - let newtypes = newtypes.iter().map(|n| format_ident!("{n}")); + let pick = |names: &[(&str, &'static str)]| -> Vec { + names + .iter() + .filter(|(key, _)| carries(key)) + .map(|(_, name)| format_ident!("{name}")) + .collect() + }; + let newtypes = pick(&[("match", "BloomFilter"), ("eq", "Hmac256")]); + let indexes = pick(&[ + ("eq", "Equality"), + ("match", "Match"), + ("ope", "Ope"), + ("ore_block", "OreBlock"), + ]); + let order_terms = pick(&[("ope", "OpeTerm"), ("ore_block", "OreBlockTerm")]); answer_imports.extend(quote! { use crate::encryption::query::{QueryTwin, TwinIndex}; use crate::Identifier; use crate::v4::terms::{#(#newtypes),*}; use crate::v4::SchemaVersion; use stack_encrypt::op; + use stack_encrypt::{#(#indexes),*}; }); - } - if answers_any(Answer::Eq) { - answer_imports.extend(quote!( - use stack_encrypt::Equality; - )); - } - if answers_any(Answer::Matches) { - answer_imports.extend(quote! { - use crate::encryption::EqlMatch; - use stack_encrypt::Match; - }); + if !order_terms.is_empty() { + answer_imports.extend(quote!(use stack_encrypt::sem::{#(#order_terms),*};)); + } + if carries("match") { + answer_imports.extend(quote!( + use crate::encryption::EqlMatch; + )); + } } let mod_doc = @@ -945,11 +1102,12 @@ mod tests { /// A type answers operators in a typed query exactly when the /// engine produces it and it has a query twin, and then by the engine's - /// rule over its indexes: `Eq` for the equality index, `Matches` for - /// the match index. Spelled out per type, so the table reads without - /// the rule. + /// rule over its indexes: `Eq` for the equality index, the orderings for + /// an order index, `Matches` for the match index, in the data path's + /// order. Spelled out per type, so the table reads without the rule. #[test] fn a_producible_type_with_a_twin_answers_what_its_indexes_answer() { + const ORDERINGS: &[&str] = &["lt", "lte", "gt", "gte"]; for row in rows() { let answers: Vec<&str> = row.answers.iter().map(|a| a.name()).collect(); // A document's operators are the JSON index's, answered @@ -958,19 +1116,20 @@ mod tests { assert!(answers.is_empty(), "{}: answers nothing", row.name); continue; } - if let Some(gap) = typed_gap(&row.indexes) { - assert!(answers.is_empty(), "{}: {gap}", row.name); - continue; + let mut expected: Vec<&str> = Vec::new(); + if row.indexes.contains(&"eq") { + expected.push("eq"); } - let expected: Vec<&str> = row + if row .indexes .iter() - .map(|key| match *key { - "eq" => "eq", - "match" => "matches", - other => panic!("{}: no answer for the {other} index", row.name), - }) - .collect(); + .any(|key| matches!(*key, "ope" | "ore_block")) + { + expected.extend(ORDERINGS); + } + if row.indexes.contains(&"match") { + expected.push("matches"); + } assert_eq!(answers, expected, "{}", row.name); } let answered: Vec<(String, Vec<&str>)> = rows() @@ -979,90 +1138,124 @@ mod tests { .map(|r| (r.name, r.answers.iter().map(|a| a.name()).collect())) .collect(); let spelled = |name: &str, ops: &[&'static str]| (name.to_owned(), ops.to_vec()); - assert_eq!( - answered, - vec![ - spelled("IntegerEq", &["eq"]), - spelled("SmallintEq", &["eq"]), - spelled("BigintEq", &["eq"]), - spelled("DateEq", &["eq"]), - spelled("TimestampEq", &["eq"]), - spelled("NumericEq", &["eq"]), - spelled("TextEq", &["eq"]), - spelled("TextMatch", &["matches"]), - spelled("RealEq", &["eq"]), - spelled("DoubleEq", &["eq"]), - ] - ); - } - - /// The rule over indexes: `eq` answers `Eq` and `match` answers - /// `Matches`; each operator's twin term is its index's. - #[test] - fn answers_for_indexes_maps_each_index_to_its_operator() { - assert_eq!(answers_for_indexes("T", &[]), Vec::::new()); - assert_eq!(answers_for_indexes("T", &["eq"]), vec![Answer::Eq]); - assert_eq!(answers_for_indexes("T", &["match"]), vec![Answer::Matches]); - assert_eq!(index_key(Answer::Eq.term()), "eq"); - assert_eq!(index_key(Answer::Matches.term()), "match"); - assert_eq!(Answer::Eq.name(), "eq"); - assert_eq!(Answer::Matches.name(), "matches"); + const ORDERED_TEXT: &[&str] = &["eq", "lt", "lte", "gt", "gte"]; + const SEARCH: &[&str] = &["eq", "lt", "lte", "gt", "gte", "matches"]; + let mut expected = Vec::new(); + for family in [ + "Integer", + "Smallint", + "Bigint", + "Date", + "Timestamp", + "Numeric", + "Text", + "Real", + "Double", + ] { + expected.push(spelled(&format!("{family}Eq"), &["eq"])); + if family == "Text" { + expected.push(spelled("TextMatch", &["matches"])); + } + let ordered = if family == "Text" { + ORDERED_TEXT + } else { + ORDERINGS + }; + for suffix in ["OrdOre", "Ord", "OrdOpe"] { + expected.push(spelled(&format!("{family}{suffix}"), ordered)); + } + if family == "Text" { + expected.push(spelled("TextSearchOre", SEARCH)); + expected.push(spelled("TextSearch", SEARCH)); + } + } + assert_eq!(answered, expected); } - /// A producible type whose twin carries an order index, or more than - /// one index, has no typed answer yet: the generator leaves it out of - /// a typed query and says why. + /// The rule over indexes: `eq` answers `Eq`, `match` answers `Matches`, + /// and an order index (`ope` or `ore_block`) the four orderings, in the + /// order `Op::ALL` lists them, whatever the order of the indexes. #[test] - fn an_order_index_or_several_indexes_answer_nothing_yet() { - for (name, indexes) in [ - ("IntegerOrd", &["ope"][..]), - ("IntegerOrdOre", &["ore"]), - ("TextOrd", &["eq", "ope"]), - ("TextSearch", &["eq", "ope", "match"]), - ] { - let gap = typed_gap(indexes).unwrap_or_else(|| panic!("{name} has a typed gap")); - assert!(gap.contains("order term"), "{name}: {gap}"); - assert_eq!( - answers_for_indexes(name, indexes), - Vec::::new(), - "{name}" - ); - } - let gap = typed_gap(&["eq", "match"]).expect("several terms are a gap"); - assert!(gap.contains("more than one term"), "{gap}"); + fn answers_for_indexes_maps_each_index_to_its_operators() { + use Answer::*; + assert_eq!(answers_for_indexes("T", &[], false), Vec::::new()); + assert_eq!(answers_for_indexes("T", &["eq"], false), vec![Eq]); + assert_eq!(answers_for_indexes("T", &["match"], false), vec![Matches]); + assert_eq!( + answers_for_indexes("T", &["ope"], false), + vec![Lt, Lte, Gt, Gte] + ); + assert_eq!( + answers_for_indexes("T", &["ore_block"], false), + vec![Lt, Lte, Gt, Gte] + ); assert_eq!( - answers_for_indexes("T", &["eq", "match"]), - Vec::::new() + answers_for_indexes("T", &["ope", "eq"], false), + vec![Eq, Lt, Lte, Gt, Gte] ); - assert_eq!(typed_gap(&[]), None); - assert_eq!(typed_gap(&["eq"]), None); - assert_eq!(typed_gap(&["match"]), None); + assert_eq!( + answers_for_indexes("T", &["match", "ore_block", "eq"], true), + vec![Eq, Lt, Lte, Gt, Gte, Matches] + ); + let names: Vec<&str> = [Eq, Lt, Lte, Gt, Gte, Matches] + .iter() + .map(|a| a.name()) + .collect(); + assert_eq!(names, ["eq", "lt", "lte", "gt", "gte", "matches"]); + let operators: Vec<&str> = [Eq, Lt, Lte, Gt, Gte, Matches] + .iter() + .map(|a| a.operator()) + .collect(); + assert_eq!(operators, ["Eq", "Lt", "Lte", "Gt", "Gte", "Matches"]); + assert!(!Matches.is_exact(), "a match query verifies its rows"); + assert!([Eq, Lt, Lte, Gt, Gte].iter().all(|a| a.is_exact())); + for (key, answer) in [ + ("eq", Eq), + ("ope", Lt), + ("ore_block", Gte), + ("match", Matches), + ] { + assert_eq!(answer.index(&["match", key]), key, "{answer:?}"); + assert_eq!(index_key(term_of_key(key)), key, "{key}"); + } } #[test] #[should_panic(expected = "no rule for the json index")] fn an_unknown_index_stops_the_generator() { - answers_for_indexes("SteVecDocument", &["json"]); + answers_for_indexes("SteVecDocument", &["json"], false); + } + + /// A twin that requires a match term beside another stops the + /// generator: its `matches` query would have to carry every term, and a + /// typed query assembles a match twin from the match term alone. + #[test] + #[should_panic(expected = "requires a match term beside another term")] + fn a_twin_requiring_a_match_term_and_another_stops_the_generator() { + answers_for_indexes("TextEqMatch", &["eq", "match"], false); } /// The rendered file implements `op::Answers` once per answered /// operator, through the index the operator names, sent as the type's - /// twin; marks an exact twin a `QueryTerm`; and lists every answering - /// type in `ANSWERS`. + /// twin; derives every index's term for a twin that requires them all; + /// assembles a twin once, or once per index when its terms are + /// optional; marks an exact twin a `QueryTerm`; and lists every + /// answering type in `ANSWERS`. #[test] fn rendered_answers_are_one_impl_per_operator_and_one_table_row_per_type() { let tight: String = render_answers_rs().split_whitespace().collect(); let mut answered = 0; + let mut impls_total = 0; for row in rows() { let module = row.family; let name = &row.name; let Some((twin, _)) = &row.query else { continue; }; - let answers_impl = |op: &str| format!("implop::Answers 1 { + let all: Vec = row + .indexes + .iter() + .map(|key| index_type(key).to_string().replace(' ', "")) + .collect(); + format!(",({})", all.join(",")) + } else { + String::new() + }; for answer in &row.answers { - let (op, via) = match answer { - Answer::Eq => ( - "Eq", - format!("TwinIndex;"), - ), - Answer::Matches => ( - "Matches", - format!("TwinIndex,super::{module}::{twin}>;"), - ), + let op = answer.operator(); + let index = index_type(answer.index(&row.indexes)) + .to_string() + .replace(' ', ""); + let derived = if answer.is_exact() { + derived.as_str() + } else { + "" }; - assert!(tight.contains(&answers_impl(op)), "{name}: op::{op}"); + let via = format!( + "implop::Answersforsuper::{module}::{name}{{typeVia=\ + TwinIndex<{index},super::{module}::{twin}{derived}>;", + plaintext_of(row.family).unwrap().1.replace(' ', "") + ); assert!(tight.contains(&via), "{name}: {via}"); } - let exact = row.answers.contains(&Answer::Eq); + let exact = row.answers.iter().any(|a| a.is_exact()); assert_eq!( tight.contains(&format!("implop::QueryTermforsuper::{module}::{twin}{{}}")), exact, "{name}: QueryTerm exactly on an exact twin" ); + let assemblies = if optional { row.indexes.len() } else { 1 }; assert_eq!( tight .matches(&format!("forsuper::{module}::{twin}{{typePlaintext=")) .count(), - 1, - "{name}: one assembly" + assemblies, + "{name}: one assembly, or one per index of optional terms" ); assert_eq!( tight @@ -1114,9 +1324,22 @@ mod tests { "{name}: labelled" ); } - assert_eq!(answered, 10); - assert_eq!(tight.matches("implop::Answers<").count(), 10); - assert_eq!(tight.matches("implop::LabelledTarget").count(), 10); + assert_eq!(answered, 39, "every producible type with a twin answers"); + assert_eq!(tight.matches("implop::Answers<").count(), impls_total); + assert_eq!(tight.matches("implop::LabelledTarget").count(), 39); + assert!( + tight.contains( + "implQueryTwin<(Hmac256,OpeTerm)>forsuper::text::TextOrdQuery{\ + typePlaintext=String;fnassemble(i:Identifier,(hm,op):(Hmac256,OpeTerm))" + ), + "TextOrdQuery is assembled from both its terms" + ); + assert!( + tight.contains( + "fnassemble(i:Identifier,ob:OreBlockTerm)->Self{Self{v:SchemaVersion::default(),i,ob:Some(ob),hm:None,bf:None,}}" + ), + "TextSearchOreQuery is assembled from its `ob` alone for an ordering" + ); } /// A producible type with no query twin — the storage-only `Text` — diff --git a/packages/eql/mise.toml b/packages/eql/mise.toml index 79bea8ab09..f75aaefce2 100644 --- a/packages/eql/mise.toml +++ b/packages/eql/mise.toml @@ -322,7 +322,7 @@ cargo clippy --locked -p eql-bindings --features stack-encrypt --all-targets -- """ [tasks."test:encryption:postgres"] -description = "Install the EQL v4 bundle built from the tree into the database EQL_TEST_DATABASE_URL names and run the PostgreSQL tests against it: stack-encrypt values (fresh encryption, fake KMS), the range query domains and eql_v4.between, and the JSON tree family" +description = "Install the EQL v4 bundle built from the tree into the database EQL_TEST_DATABASE_URL names and run the PostgreSQL tests against it: stack-encrypt values (fresh encryption, fake KMS), the range query domains and eql_v4.between, order queries from a field reference, and the JSON tree family" # `build` writes release/cipherstash-encrypt-v4.sql from the SQL in the tree. The # copy under crates/eql-bindings/sql is the RELEASED bundle, rewritten only by # the lockstep version bump, so a test that installs it cannot see a SQL edit @@ -340,7 +340,7 @@ psql "$EQL_TEST_DATABASE_URL" -v ON_ERROR_STOP=1 -f release/cipherstash-encrypt- # `--ignored` selects by attribute, and cargo exits 0 on an empty selection, so # a test that loses its `#[ignore]` or is renamed would leave this task passing # on nothing. List what the filter selects before running it. -for suite in text_eq v4_types v4_order v4_date_time_numeric v4_range v4_text_search v4_ore_block json_tree; do +for suite in text_eq v4_types v4_order v4_date_time_numeric v4_range v4_text_search v4_ore_block typed_order_queries json_tree; do listing=$(cargo test --locked -p eql-encryption-tests --test "$suite" -- --ignored --list | sed -n 's/: test$//p') [ -n "$listing" ] || { echo "error: '--ignored' selects no test in $suite; the PostgreSQL test has gone missing." >&2; exit 1; } # `--show-output`: a passing test's output is otherwise captured, and the diff --git a/packages/eql/tests/encryption/tests/common/mod.rs b/packages/eql/tests/encryption/tests/common/mod.rs index 64db54f1c5..e44484392a 100644 --- a/packages/eql/tests/encryption/tests/common/mod.rs +++ b/packages/eql/tests/encryption/tests/common/mod.rs @@ -126,3 +126,48 @@ pub fn decimal_of(mantissa: i128, scale: u32) -> eql_bindings::v4::plaintext::De mantissa, scale, )) } + +/// The order of two block ORE `ob` terms of the type `name`, by ore-rs's +/// comparator, which EQL v4's comparator agrees with +/// (tests/v4_ore_block.rs). +#[allow(dead_code)] +pub fn ob_order(name: &str, a: &serde_json::Value, b: &serde_json::Value) -> std::cmp::Ordering { + fn compare(a: &[u8], b: &[u8]) -> std::cmp::Ordering { + let a = stack_encrypt::sem::OreBlockTerm::::try_from(a).unwrap(); + let b = stack_encrypt::sem::OreBlockTerm::::try_from(b).unwrap(); + a.compare(&b).expect("terms of one index compare") + } + let unhex = |term: &serde_json::Value| -> Vec { + let hex = term.as_str().expect("an `ob` term is one hex string"); + (0..hex.len()) + .step_by(2) + .map(|at| u8::from_str_radix(&hex[at..at + 2], 16).unwrap()) + .collect() + }; + let (a, b) = (unhex(a), unhex(b)); + let family = [ + "Integer", + "Smallint", + "Bigint", + "Date", + "Timestamp", + "Numeric", + "Text", + "Real", + "Double", + ] + .into_iter() + .find(|family| name.starts_with(family)) + .unwrap_or_else(|| panic!("{name}: no family")); + match family { + "Integer" => compare::(&a, &b), + "Smallint" => compare::(&a, &b), + "Bigint" => compare::(&a, &b), + "Date" => compare::(&a, &b), + "Timestamp" => compare::(&a, &b), + "Numeric" => compare::(&a, &b), + "Text" => compare::(&a, &b), + "Real" => compare::(&a, &b), + _ => compare::(&a, &b), + } +} diff --git a/packages/eql/tests/encryption/tests/typed_order_queries.rs b/packages/eql/tests/encryption/tests/typed_order_queries.rs new file mode 100644 index 0000000000..8f14f00564 --- /dev/null +++ b/packages/eql/tests/encryption/tests/typed_order_queries.rs @@ -0,0 +1,475 @@ +//! A field reference's order query on an ordered EQL v4 type finds the +//! rows the data path's query for the same value finds +//! (`stack_encrypt::dynamic::query_term`, which the Go SDK runs), and those +//! are the rows the plaintexts say. +//! +//! One column for each way a twin carries its terms: an order term alone +//! (`IntegerOrd` OPE, `IntegerOrdOre` block ORE), an equality term beside +//! it (`TextOrd`, `TextOrdOre`), and the answering index's term alone, for +//! a twin whose terms are optional (`TextSearch`, `TextSearchOre`). +//! tests/typed_queries.rs holds every ordered type's query to the data +//! path's, term by term. Here each query is compared against rows a record +//! stored: in Rust, by the comparison EQL v4 makes (an OPE term's bytes, +//! ore-rs's comparator for a block ORE term, an `hm`'s equality), and, +//! against an EQL v4 database, by the SQL operators themselves. + +mod common; + +use eql_bindings::encryption::EqlTargets; +use eql_bindings::v4::integer::{IntegerOrd, IntegerOrdOre}; +use eql_bindings::v4::text::{TextOrd, TextOrdOre, TextSearch, TextSearchOre}; +use eql_bindings::v4::DomainType; +use serde::Serialize; +use stack_encrypt::dynamic::{self, record, FieldPlan, Op, Operand, ValueFrame}; +use stack_encrypt::{ContextPiece, EncryptInto, EncryptTarget, NonEmpty, StackCipher}; +use std::cmp::Ordering; +use zeroize::Zeroize; + +type Cipher = StackCipher; + +/// One row's plaintexts: a value for each ordered column. +#[derive(Zeroize)] +struct Ranking { + level: i32, + level_ore: i32, + title: String, + title_ore: String, + name: String, + name_ore: String, +} + +/// The table `rankings`, with a column of each shape of ordered twin. +#[derive(EncryptTarget)] +#[stash(struct = Ranking, scope = "rankings")] +struct EncryptedRanking { + level: IntegerOrd, + level_ore: IntegerOrdOre, + title: TextOrd, + title_ore: TextOrdOre, + name: TextSearch, + name_ore: TextSearchOre, +} + +/// The integers the rows hold, ascending, and the texts, ascending by +/// their fold. +const LEVELS: [i32; 5] = [-200, -1, 0, 7, 1_000_000]; +const TEXTS: [&str; 5] = ["Alpha", "bravo", "Charlie", "delta", "Echo"]; + +/// The row at `at`: each column holds the `at`th value, so the rows ascend +/// in every column. +fn ranking(at: usize) -> Ranking { + Ranking { + level: LEVELS[at], + level_ore: LEVELS[at], + title: TEXTS[at].to_owned(), + title_ore: TEXTS[at].to_owned(), + name: TEXTS[at].to_owned(), + name_ore: TEXTS[at].to_owned(), + } +} + +/// The row whose values every query below asks for: the middle one, so +/// each ordering finds rows on both sides. +const ASKED: usize = 2; + +/// One column: its field name, the EQL type it names, and its stored and +/// query domains. +struct Column { + field: &'static str, + name: &'static str, + domain: &'static str, + query_domain: &'static str, +} + +const fn column( + field: &'static str, + name: &'static str, + domain: &'static str, + query_domain: &'static str, +) -> Column { + Column { + field, + name, + domain, + query_domain, + } +} + +/// Every column, and the operators each answers from a field reference. +fn columns() -> [(Column, &'static [&'static str]); 6] { + const ORDERINGS: &[&str] = &["lt", "lte", "gt", "gte"]; + const TEXT: &[&str] = &["eq", "lt", "lte", "gt", "gte"]; + [ + ( + column( + "level", + "IntegerOrd", + IntegerOrd::sql_domain_static(), + eql_bindings::v4::integer::IntegerOrdQuery::sql_domain_static(), + ), + ORDERINGS, + ), + ( + column( + "level_ore", + "IntegerOrdOre", + IntegerOrdOre::sql_domain_static(), + eql_bindings::v4::integer::IntegerOrdOreQuery::sql_domain_static(), + ), + ORDERINGS, + ), + ( + column( + "title", + "TextOrd", + TextOrd::sql_domain_static(), + eql_bindings::v4::text::TextOrdQuery::sql_domain_static(), + ), + TEXT, + ), + ( + column( + "title_ore", + "TextOrdOre", + TextOrdOre::sql_domain_static(), + eql_bindings::v4::text::TextOrdOreQuery::sql_domain_static(), + ), + TEXT, + ), + ( + column( + "name", + "TextSearch", + TextSearch::sql_domain_static(), + eql_bindings::v4::text::TextSearchQuery::sql_domain_static(), + ), + TEXT, + ), + ( + column( + "name_ore", + "TextSearchOre", + TextSearchOre::sql_domain_static(), + eql_bindings::v4::text::TextSearchOreQuery::sql_domain_static(), + ), + TEXT, + ), + ] +} + +/// The JSON a query binds. +fn json(query: &Q) -> serde_json::Value { + serde_json::to_value(query).unwrap() +} + +/// The field reference's query on `column` for `operator`, for the value +/// of the [asked](ASKED) row. +async fn typed(keyset: &Keyset<'_>, field: &str, operator: &str) -> serde_json::Value { + let row = || ranking(ASKED); + macro_rules! query { + ($reference:expr, $value:ident, [$($op:ident),+]) => { + match operator { + $(stringify!($op) => json(&$reference.$op(row().$value).encrypt(keyset).await.unwrap()),)+ + other => panic!("{field} answers no `{other}`"), + } + }; + } + match field { + "level" => query!(EncryptedRanking::LEVEL, level, [lt, lte, gt, gte]), + "level_ore" => query!(EncryptedRanking::LEVEL_ORE, level_ore, [lt, lte, gt, gte]), + "title" => query!(EncryptedRanking::TITLE, title, [eq, lt, lte, gt, gte]), + "title_ore" => query!( + EncryptedRanking::TITLE_ORE, + title_ore, + [eq, lt, lte, gt, gte] + ), + "name" => query!(EncryptedRanking::NAME, name, [eq, lt, lte, gt, gte]), + "name_ore" => query!(EncryptedRanking::NAME_ORE, name_ore, [eq, lt, lte, gt, gte]), + other => panic!("no column {other}"), + } +} + +type Keyset<'k> = stack_encrypt::KeysetCipher<'k, common::RecordingKeySource>; + +/// The data path's query on `column` for `operator`, for the value of the +/// [asked](ASKED) row: a data plan with one field under +/// `rankings/`, naming the column's type. +async fn data(cipher: &Cipher, column: &Column, operator: &str) -> serde_json::Value { + let context = NonEmpty::new(ContextPiece::List(vec![ + ContextPiece::Text("rankings".into()), + ContextPiece::Text(column.field.to_owned().into()), + ])) + .unwrap(); + let plan = record::Plan::new_with( + vec![FieldPlan::with_target("value", context, column.name).unwrap()], + &EqlTargets, + ) + .unwrap(); + let input: ValueFrame = if column.name.starts_with("Integer") { + ValueFrame::of(LEVELS[ASKED]).unwrap() + } else { + ValueFrame::of(TEXTS[ASKED]).unwrap() + }; + let term = dynamic::query_term( + &cipher.default_keyset(), + &plan, + "value", + Op::parse(operator).unwrap(), + input, + &EqlTargets, + ) + .unwrap() + .await + .unwrap(); + assert_eq!( + term.domain(), + Some(column.query_domain), + "{} {operator}: the data path binds the twin's domain", + column.name + ); + let Operand::One(bytes) = term.operand() else { + panic!("{}: a one-value query has one operand", column.name); + }; + serde_json::from_slice(bytes).unwrap() +} + +/// The rows the plaintexts say `operator` finds against the asked row: the +/// rows ascend in every column, so it is their position against +/// [`ASKED`]. +fn expected(operator: &str) -> Vec { + (0..LEVELS.len()) + .filter(|at| match operator { + "eq" => *at == ASKED, + "lt" => *at < ASKED, + "lte" => *at <= ASKED, + "gt" => *at > ASKED, + "gte" => *at >= ASKED, + other => panic!("no operator {other}"), + }) + .collect() +} + +/// The rows of `stored` that `query` finds for `operator`, by the +/// comparison EQL v4 makes of their terms: `=` compares the `hm`, an +/// ordering compares the `op` as bytes (its hex is lowercase, so the +/// strings order as the bytes do) or the `ob` by ore-rs's comparator. +fn finds( + name: &str, + operator: &str, + query: &serde_json::Value, + stored: &[serde_json::Value], +) -> Vec { + stored + .iter() + .enumerate() + .filter(|(_, row)| { + if operator == "eq" { + return row["hm"] == query["hm"]; + } + let order = match query.get("op") { + Some(op) => row["op"].as_str().unwrap().cmp(op.as_str().unwrap()), + None => common::ob_order(name, &row["ob"], &query["ob"]), + }; + match operator { + "lt" => order == Ordering::Less, + "lte" => order != Ordering::Greater, + "gt" => order == Ordering::Greater, + "gte" => order != Ordering::Less, + other => panic!("no operator {other}"), + } + }) + .map(|(at, _)| at) + .collect() +} + +/// The rows a record stored, as JSON, by column. +struct Scenario { + cipher: Cipher, + rows: Vec>, +} + +async fn scenario() -> Scenario { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let mut rows = Vec::new(); + for at in 0..LEVELS.len() { + let stored: EncryptedRanking = ranking(at).encrypt_into(&keyset).await.unwrap(); + let row = serde_json::json!({ + "level": stored.level, + "level_ore": stored.level_ore, + "title": stored.title, + "title_ore": stored.title_ore, + "name": stored.name, + "name_ore": stored.name_ore, + }); + let serde_json::Value::Object(row) = row else { + unreachable!("a row is an object") + }; + rows.push(row); + } + Scenario { cipher, rows } +} + +mod given_rows_a_record_stored { + use super::*; + + /// For every column and operator, the field reference's query and the + /// data path's each find exactly the rows the plaintexts say. + #[tokio::test] + async fn each_query_finds_the_rows_the_plaintexts_say() { + let scenario = scenario().await; + let keyset = scenario.cipher.default_keyset(); + for (column, operators) in columns() { + let stored: Vec = scenario + .rows + .iter() + .map(|row| row[column.field].clone()) + .collect(); + for operator in operators { + let typed = typed(&keyset, column.field, operator).await; + let data = data(&scenario.cipher, &column, operator).await; + assertions::finds_the_rows( + column.name, + operator, + "field reference", + &typed, + &stored, + ); + assertions::finds_the_rows(column.name, operator, "data path", &data, &stored); + } + } + } + + /// Needs an EQL v4 installation. The rows are inserted into their + /// domains, and each SQL operator, given the field reference's query + /// or the data path's, cast to the type's query domain, selects + /// exactly the rows the plaintexts say. + #[test] + #[ignore = "requires EQL_TEST_DATABASE_URL pointing to an EQL v4 database"] + fn postgres_selects_the_same_rows_for_each_query() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let (scenario, queries) = runtime.block_on(async { + let scenario = scenario().await; + let keyset = scenario.cipher.default_keyset(); + let mut queries = Vec::new(); + for (column, operators) in columns() { + for operator in operators { + let typed = typed(&keyset, column.field, operator).await; + let data = data(&scenario.cipher, &column, operator).await; + queries.push((column.field, *operator, typed, data)); + } + } + (scenario, queries) + }); + + let mut db = postgres::Client::connect( + &std::env::var("EQL_TEST_DATABASE_URL").expect("EQL_TEST_DATABASE_URL"), + postgres::NoTls, + ) + .unwrap(); + let declared: Vec = columns() + .iter() + .map(|(column, _)| format!("{} {}", column.field, column.domain)) + .collect(); + db.batch_execute(&format!( + "CREATE TEMP TABLE typed_rankings (id int PRIMARY KEY, {});", + declared.join(", ") + )) + .unwrap(); + for (id, row) in scenario.rows.iter().enumerate() { + let values: Vec = columns() + .iter() + .map(|(column, _)| row[column.field].to_string()) + .collect(); + let casts: Vec = columns() + .iter() + .enumerate() + .map(|(at, (column, _))| format!("${}::text::jsonb::{}", at + 2, column.domain)) + .collect(); + let id = i32::try_from(id).unwrap(); + let mut params: Vec<&(dyn postgres::types::ToSql + Sync)> = vec![&id]; + params.extend( + values + .iter() + .map(|v| v as &(dyn postgres::types::ToSql + Sync)), + ); + db.execute( + &format!( + "INSERT INTO typed_rankings VALUES ($1, {})", + casts.join(", ") + ), + ¶ms, + ) + .unwrap(); + } + + for (field, operator, typed, data) in queries { + let column = columns() + .into_iter() + .find(|(column, _)| column.field == field) + .unwrap() + .0; + let sql_operator = match operator { + "eq" => "=", + "lt" => "<", + "lte" => "<=", + "gt" => ">", + "gte" => ">=", + other => panic!("no operator {other}"), + }; + let sql = format!( + "SELECT id FROM typed_rankings WHERE {field} {sql_operator} \ + $1::text::jsonb::{} ORDER BY id", + column.query_domain + ); + let select = |db: &mut postgres::Client, query: &serde_json::Value| -> Vec { + db.query(&sql, &[&query.to_string()]) + .unwrap_or_else(|error| panic!("{sql}: {error}")) + .iter() + .map(|row| usize::try_from(row.get::<_, i32>(0)).unwrap()) + .collect() + }; + let expected = expected(operator); + assert_eq!( + select(&mut db, &typed), + expected, + "{} {operator}: the field reference's query selects the plaintexts' rows", + column.name + ); + assert_eq!( + select(&mut db, &data), + expected, + "{} {operator}: the data path's query selects the same rows", + column.name + ); + } + } +} + +mod assertions { + use super::*; + + /// `query` finds exactly the rows the plaintexts say among `stored`, + /// and finds some, or misses some, so the comparison is not vacuous. + pub(super) fn finds_the_rows( + name: &str, + operator: &str, + path: &str, + query: &serde_json::Value, + stored: &[serde_json::Value], + ) { + let expected = expected(operator); + assert!( + !expected.is_empty() && expected.len() < stored.len(), + "{name} {operator}: the rows split" + ); + assert_eq!( + finds(name, operator, query, stored), + expected, + "{name} {operator}: the {path}'s query finds the rows the plaintexts say" + ); + } +} diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index a3ff25b286..47a4c2c748 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -19,7 +19,7 @@ use eql_bindings::v4::answers::ANSWERS; use eql_bindings::v4::plaintext::{Date, Decimal, Timestamp}; use eql_bindings::v4::text::{TextEq, TextMatch, TextMatchQuery}; use eql_bindings::v4::{ - bigint, date, double, integer, numeric, real, smallint, timestamp, DomainType, + bigint, date, double, integer, numeric, real, smallint, text, timestamp, DomainType, }; use eql_bindings::Identifier; use serde::Serialize; @@ -28,6 +28,7 @@ use stack_encrypt::op::{Probabilistic, Stats}; use stack_encrypt::target::Scope; use stack_encrypt::{ContextPiece, Encrypt, Error, KeysetCipher, NonEmpty, StackCipher}; use stack_encrypt::{DecryptSource, EncryptInto, EncryptTarget}; +use std::cmp::Ordering; use zeroize::Zeroize; type Cipher = StackCipher; @@ -88,16 +89,45 @@ fn typed_bytes(query: &Q) -> (Vec, String) { /// named after its type, and the name is its column. #[derive(Zeroize)] struct Columns { - text_eq: String, integer_eq: i32, + integer_ord_ore: i32, + integer_ord: i32, + integer_ord_ope: i32, smallint_eq: i16, + smallint_ord_ore: i16, + smallint_ord: i16, + smallint_ord_ope: i16, + bigint_eq: i64, + bigint_ord_ore: i64, + bigint_ord: i64, + bigint_ord_ope: i64, date_eq: Date, + date_ord_ore: Date, + date_ord: Date, + date_ord_ope: Date, timestamp_eq: Timestamp, + timestamp_ord_ore: Timestamp, + timestamp_ord: Timestamp, + timestamp_ord_ope: Timestamp, numeric_eq: Decimal, - bigint_eq: i64, + numeric_ord_ore: Decimal, + numeric_ord: Decimal, + numeric_ord_ope: Decimal, + text_eq: String, + text_match: String, + text_ord_ore: String, + text_ord: String, + text_ord_ope: String, + text_search_ore: String, + text_search: String, real_eq: f32, + real_ord_ore: f32, + real_ord: f32, + real_ord_ope: f32, double_eq: f64, - text_match: String, + double_ord_ore: f64, + double_ord: f64, + double_ord_ope: f64, } /// A record with a field of each EQL type that answers an operator, in the @@ -105,16 +135,45 @@ struct Columns { #[derive(EncryptTarget)] #[stash(struct = Columns, scope = "users")] struct EncryptedColumns { - text_eq: TextEq, integer_eq: integer::IntegerEq, + integer_ord_ore: integer::IntegerOrdOre, + integer_ord: integer::IntegerOrd, + integer_ord_ope: integer::IntegerOrdOpe, smallint_eq: smallint::SmallintEq, + smallint_ord_ore: smallint::SmallintOrdOre, + smallint_ord: smallint::SmallintOrd, + smallint_ord_ope: smallint::SmallintOrdOpe, + bigint_eq: bigint::BigintEq, + bigint_ord_ore: bigint::BigintOrdOre, + bigint_ord: bigint::BigintOrd, + bigint_ord_ope: bigint::BigintOrdOpe, date_eq: date::DateEq, + date_ord_ore: date::DateOrdOre, + date_ord: date::DateOrd, + date_ord_ope: date::DateOrdOpe, timestamp_eq: timestamp::TimestampEq, + timestamp_ord_ore: timestamp::TimestampOrdOre, + timestamp_ord: timestamp::TimestampOrd, + timestamp_ord_ope: timestamp::TimestampOrdOpe, numeric_eq: numeric::NumericEq, - bigint_eq: bigint::BigintEq, + numeric_ord_ore: numeric::NumericOrdOre, + numeric_ord: numeric::NumericOrd, + numeric_ord_ope: numeric::NumericOrdOpe, + text_eq: text::TextEq, + text_match: text::TextMatch, + text_ord_ore: text::TextOrdOre, + text_ord: text::TextOrd, + text_ord_ope: text::TextOrdOpe, + text_search_ore: text::TextSearchOre, + text_search: text::TextSearch, real_eq: real::RealEq, + real_ord_ore: real::RealOrdOre, + real_ord: real::RealOrd, + real_ord_ope: real::RealOrdOpe, double_eq: double::DoubleEq, - text_match: TextMatch, + double_ord_ore: double::DoubleOrdOre, + double_ord: double::DoubleOrd, + double_ord_ope: double::DoubleOrdOpe, } /// The row each query below asks for. The float values are the ones whose @@ -122,17 +181,93 @@ struct EncryptedColumns { /// nanoseconds below a microsecond, which both paths truncate alike. fn columns() -> Columns { Columns { - text_eq: "bob@example.com".into(), integer_eq: -42, + integer_ord_ore: -42, + integer_ord: -42, + integer_ord_ope: -42, smallint_eq: -7, + smallint_ord_ore: -7, + smallint_ord: -7, + smallint_ord_ope: -7, + bigint_eq: i64::MIN + 1, + bigint_ord_ore: i64::MIN + 1, + bigint_ord: i64::MIN + 1, + bigint_ord_ope: i64::MIN + 1, date_eq: common::date_of_days(19_000), + date_ord_ore: common::date_of_days(19_000), + date_ord: common::date_of_days(19_000), + date_ord_ope: common::date_of_days(19_000), timestamp_eq: common::timestamp_of(1_700_000_000, 123_456_789), + timestamp_ord_ore: common::timestamp_of(1_700_000_000, 123_456_789), + timestamp_ord: common::timestamp_of(1_700_000_000, 123_456_789), + timestamp_ord_ope: common::timestamp_of(1_700_000_000, 123_456_789), numeric_eq: common::decimal_of(-1_234_567, 4), - bigint_eq: i64::MIN + 1, + numeric_ord_ore: common::decimal_of(-1_234_567, 4), + numeric_ord: common::decimal_of(-1_234_567, 4), + numeric_ord_ope: common::decimal_of(-1_234_567, 4), + text_eq: "bob@example.com".into(), + text_match: "alice".into(), + text_ord_ore: "bob@example.com".into(), + text_ord: "bob@example.com".into(), + text_ord_ope: "bob@example.com".into(), + text_search_ore: "alice smith".into(), + text_search: "alice smith".into(), real_eq: -0.0, + real_ord_ore: -0.0, + real_ord: -0.0, + real_ord_ope: -0.0, double_eq: f64::NAN, - text_match: "alice".into(), + double_ord_ore: f64::NAN, + double_ord: f64::NAN, + double_ord_ope: f64::NAN, + } +} + +/// The stored value of the field `column` of `stored`, as JSON. +fn stored_field(stored: &EncryptedColumns, column: &str) -> serde_json::Value { + match column { + "integer_eq" => serde_json::to_value(&stored.integer_eq), + "integer_ord_ore" => serde_json::to_value(&stored.integer_ord_ore), + "integer_ord" => serde_json::to_value(&stored.integer_ord), + "integer_ord_ope" => serde_json::to_value(&stored.integer_ord_ope), + "smallint_eq" => serde_json::to_value(&stored.smallint_eq), + "smallint_ord_ore" => serde_json::to_value(&stored.smallint_ord_ore), + "smallint_ord" => serde_json::to_value(&stored.smallint_ord), + "smallint_ord_ope" => serde_json::to_value(&stored.smallint_ord_ope), + "bigint_eq" => serde_json::to_value(&stored.bigint_eq), + "bigint_ord_ore" => serde_json::to_value(&stored.bigint_ord_ore), + "bigint_ord" => serde_json::to_value(&stored.bigint_ord), + "bigint_ord_ope" => serde_json::to_value(&stored.bigint_ord_ope), + "date_eq" => serde_json::to_value(&stored.date_eq), + "date_ord_ore" => serde_json::to_value(&stored.date_ord_ore), + "date_ord" => serde_json::to_value(&stored.date_ord), + "date_ord_ope" => serde_json::to_value(&stored.date_ord_ope), + "timestamp_eq" => serde_json::to_value(&stored.timestamp_eq), + "timestamp_ord_ore" => serde_json::to_value(&stored.timestamp_ord_ore), + "timestamp_ord" => serde_json::to_value(&stored.timestamp_ord), + "timestamp_ord_ope" => serde_json::to_value(&stored.timestamp_ord_ope), + "numeric_eq" => serde_json::to_value(&stored.numeric_eq), + "numeric_ord_ore" => serde_json::to_value(&stored.numeric_ord_ore), + "numeric_ord" => serde_json::to_value(&stored.numeric_ord), + "numeric_ord_ope" => serde_json::to_value(&stored.numeric_ord_ope), + "text_eq" => serde_json::to_value(&stored.text_eq), + "text_match" => serde_json::to_value(&stored.text_match), + "text_ord_ore" => serde_json::to_value(&stored.text_ord_ore), + "text_ord" => serde_json::to_value(&stored.text_ord), + "text_ord_ope" => serde_json::to_value(&stored.text_ord_ope), + "text_search_ore" => serde_json::to_value(&stored.text_search_ore), + "text_search" => serde_json::to_value(&stored.text_search), + "real_eq" => serde_json::to_value(&stored.real_eq), + "real_ord_ore" => serde_json::to_value(&stored.real_ord_ore), + "real_ord" => serde_json::to_value(&stored.real_ord), + "real_ord_ope" => serde_json::to_value(&stored.real_ord_ope), + "double_eq" => serde_json::to_value(&stored.double_eq), + "double_ord_ore" => serde_json::to_value(&stored.double_ord_ore), + "double_ord" => serde_json::to_value(&stored.double_ord), + "double_ord_ope" => serde_json::to_value(&stored.double_ord_ope), + other => panic!("`EncryptedColumns` has no field {other}"), } + .unwrap() } /// A field query for one operator, as what the tests compare: the bytes @@ -144,19 +279,27 @@ struct Typed { input: ValueFrame, } -/// The query `$field reference.$operator(value)` under `$keyset`, where -/// `value` is the row's `$field`, with the same value as the data path's -/// input. The row is built twice: a plaintext is not `Clone`. +/// The query `$reference.(value)` under `$keyset`, for the +/// operator named at run time among those the type answers: each of +/// `$exact` returns the twin, and `matches` a `MatchTwin` of it, whose twin +/// is what binds. `value` is the row's `$field`, and the data path's input +/// is the same value. The row is built again for each: a plaintext is not +/// `Clone`. An arm compiles only if the type implements `op::Answers` for +/// its operator. macro_rules! typed { - ($keyset:expr, $reference:expr, $operator:ident, $field:ident) => {{ + ($keyset:expr, $operator:expr, $reference:expr, $field:ident, [$($exact:ident),*] $(, $matches:ident)?) => {{ let reference = $reference; - let query = reference - .$operator(columns().$field) - .encrypt($keyset) - .await - .unwrap(); + let bytes = match $operator { + $(stringify!($exact) => typed_bytes( + &reference.$exact(columns().$field).encrypt($keyset).await.unwrap(), + ),)* + $(stringify!($matches) => typed_bytes( + reference.$matches(columns().$field).encrypt($keyset).await.unwrap().twin(), + ),)? + other => panic!("{} answers no `{other}` from a field reference", stringify!($field)), + }; Typed { - bytes: typed_bytes(&query), + bytes, column: reference.name(), input: frame(columns().$field), } @@ -165,35 +308,267 @@ macro_rules! typed { /// The field query for each operator a type answers, for the value the /// row `columns()` holds: one arm per row of `ANSWERS`, so a type that -/// starts answering an operator fails here until it has one, and an arm -/// compiles only if the type implements `op::Answers` for it. +/// starts answering an operator fails here until it has one. async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typed { - let row = columns(); - match (name, operator) { - ("TextEq", "eq") => typed!(keyset, EncryptedColumns::TEXT_EQ, eq, text_eq), - ("IntegerEq", "eq") => typed!(keyset, EncryptedColumns::INTEGER_EQ, eq, integer_eq), - ("SmallintEq", "eq") => typed!(keyset, EncryptedColumns::SMALLINT_EQ, eq, smallint_eq), - ("DateEq", "eq") => typed!(keyset, EncryptedColumns::DATE_EQ, eq, date_eq), - ("TimestampEq", "eq") => { - typed!(keyset, EncryptedColumns::TIMESTAMP_EQ, eq, timestamp_eq) - } - ("NumericEq", "eq") => typed!(keyset, EncryptedColumns::NUMERIC_EQ, eq, numeric_eq), - ("BigintEq", "eq") => typed!(keyset, EncryptedColumns::BIGINT_EQ, eq, bigint_eq), - ("RealEq", "eq") => typed!(keyset, EncryptedColumns::REAL_EQ, eq, real_eq), - ("DoubleEq", "eq") => typed!(keyset, EncryptedColumns::DOUBLE_EQ, eq, double_eq), - ("TextMatch", "matches") => { - let reference = EncryptedColumns::TEXT_MATCH; - let query: MatchTwin = reference - .matches(row.text_match.clone()) - .encrypt(keyset) - .await - .unwrap(); - Typed { - bytes: typed_bytes(query.twin()), - column: reference.name(), - input: frame(row.text_match), - } - } + match name { + "IntegerEq" => typed!( + keyset, + operator, + EncryptedColumns::INTEGER_EQ, + integer_eq, + [eq] + ), + "IntegerOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::INTEGER_ORD_ORE, + integer_ord_ore, + [lt, lte, gt, gte] + ), + "IntegerOrd" => typed!( + keyset, + operator, + EncryptedColumns::INTEGER_ORD, + integer_ord, + [lt, lte, gt, gte] + ), + "IntegerOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::INTEGER_ORD_OPE, + integer_ord_ope, + [lt, lte, gt, gte] + ), + "SmallintEq" => typed!( + keyset, + operator, + EncryptedColumns::SMALLINT_EQ, + smallint_eq, + [eq] + ), + "SmallintOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::SMALLINT_ORD_ORE, + smallint_ord_ore, + [lt, lte, gt, gte] + ), + "SmallintOrd" => typed!( + keyset, + operator, + EncryptedColumns::SMALLINT_ORD, + smallint_ord, + [lt, lte, gt, gte] + ), + "SmallintOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::SMALLINT_ORD_OPE, + smallint_ord_ope, + [lt, lte, gt, gte] + ), + "BigintEq" => typed!( + keyset, + operator, + EncryptedColumns::BIGINT_EQ, + bigint_eq, + [eq] + ), + "BigintOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::BIGINT_ORD_ORE, + bigint_ord_ore, + [lt, lte, gt, gte] + ), + "BigintOrd" => typed!( + keyset, + operator, + EncryptedColumns::BIGINT_ORD, + bigint_ord, + [lt, lte, gt, gte] + ), + "BigintOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::BIGINT_ORD_OPE, + bigint_ord_ope, + [lt, lte, gt, gte] + ), + "DateEq" => typed!(keyset, operator, EncryptedColumns::DATE_EQ, date_eq, [eq]), + "DateOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::DATE_ORD_ORE, + date_ord_ore, + [lt, lte, gt, gte] + ), + "DateOrd" => typed!( + keyset, + operator, + EncryptedColumns::DATE_ORD, + date_ord, + [lt, lte, gt, gte] + ), + "DateOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::DATE_ORD_OPE, + date_ord_ope, + [lt, lte, gt, gte] + ), + "TimestampEq" => typed!( + keyset, + operator, + EncryptedColumns::TIMESTAMP_EQ, + timestamp_eq, + [eq] + ), + "TimestampOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::TIMESTAMP_ORD_ORE, + timestamp_ord_ore, + [lt, lte, gt, gte] + ), + "TimestampOrd" => typed!( + keyset, + operator, + EncryptedColumns::TIMESTAMP_ORD, + timestamp_ord, + [lt, lte, gt, gte] + ), + "TimestampOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::TIMESTAMP_ORD_OPE, + timestamp_ord_ope, + [lt, lte, gt, gte] + ), + "NumericEq" => typed!( + keyset, + operator, + EncryptedColumns::NUMERIC_EQ, + numeric_eq, + [eq] + ), + "NumericOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::NUMERIC_ORD_ORE, + numeric_ord_ore, + [lt, lte, gt, gte] + ), + "NumericOrd" => typed!( + keyset, + operator, + EncryptedColumns::NUMERIC_ORD, + numeric_ord, + [lt, lte, gt, gte] + ), + "NumericOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::NUMERIC_ORD_OPE, + numeric_ord_ope, + [lt, lte, gt, gte] + ), + "TextEq" => typed!(keyset, operator, EncryptedColumns::TEXT_EQ, text_eq, [eq]), + "TextMatch" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_MATCH, + text_match, + [], + matches + ), + "TextOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_ORD_ORE, + text_ord_ore, + [eq, lt, lte, gt, gte] + ), + "TextOrd" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_ORD, + text_ord, + [eq, lt, lte, gt, gte] + ), + "TextOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_ORD_OPE, + text_ord_ope, + [eq, lt, lte, gt, gte] + ), + "TextSearchOre" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_SEARCH_ORE, + text_search_ore, + [eq, lt, lte, gt, gte], + matches + ), + "TextSearch" => typed!( + keyset, + operator, + EncryptedColumns::TEXT_SEARCH, + text_search, + [eq, lt, lte, gt, gte], + matches + ), + "RealEq" => typed!(keyset, operator, EncryptedColumns::REAL_EQ, real_eq, [eq]), + "RealOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::REAL_ORD_ORE, + real_ord_ore, + [lt, lte, gt, gte] + ), + "RealOrd" => typed!( + keyset, + operator, + EncryptedColumns::REAL_ORD, + real_ord, + [lt, lte, gt, gte] + ), + "RealOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::REAL_ORD_OPE, + real_ord_ope, + [lt, lte, gt, gte] + ), + "DoubleEq" => typed!( + keyset, + operator, + EncryptedColumns::DOUBLE_EQ, + double_eq, + [eq] + ), + "DoubleOrdOre" => typed!( + keyset, + operator, + EncryptedColumns::DOUBLE_ORD_ORE, + double_ord_ore, + [lt, lte, gt, gte] + ), + "DoubleOrd" => typed!( + keyset, + operator, + EncryptedColumns::DOUBLE_ORD, + double_ord, + [lt, lte, gt, gte] + ), + "DoubleOrdOpe" => typed!( + keyset, + operator, + EncryptedColumns::DOUBLE_ORD_OPE, + double_ord_ope, + [lt, lte, gt, gte] + ), _ => panic!( "{name} answers `{operator}` from a field reference: give it a field in \ `EncryptedColumns` and an arm here, with the input the data path is given" @@ -203,16 +578,11 @@ async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typ /// The operators each type answers from a field reference are exactly the /// ones the data path answers for a field that names it, type by type, in -/// order, for every type whose twin a field query assembles: one term, -/// from an equality or a match index. A producible type whose twin needs -/// an order term, or several terms, is the one gap: the data path answers -/// it and a field reference answers nothing, and this holds the gap to exactly -/// those types, so a type with an equality or match twin cannot drop out -/// unseen. The typed impls and `ANSWERS` are generated from one rule, so -/// this is what holds that rule to the engine's. +/// order: the equality, match and ordered types, and text search. The +/// typed impls and `ANSWERS` are generated from one rule, so this is what +/// holds that rule to the engine's. #[test] fn a_field_reference_answers_what_the_data_path_answers() { - let mut gap = Vec::new(); // A document's field reference answers through its JSON queries // (`JsonQueries`), not `Answers`: tests/json_tree_field_references.rs holds them // to the data path. @@ -230,123 +600,75 @@ fn a_field_reference_answers_what_the_data_path_answers() { .find(|(name, _)| *name == target.name) .map(|(_, ops)| ops.to_vec()) .unwrap_or_default(); - let one_term = target.indexes.len() <= 1 - && target - .indexes - .iter() - .all(|index| matches!(*index, "eq" | "match")); - if one_term { - assert_eq!(typed, data, "{}", target.name); - } else { - assert!( - typed.is_empty(), - "{}: a field reference answers nothing yet", - target.name - ); - if !data.is_empty() { - gap.push(target.name); - } - } + assert_eq!( + typed, data, + "{}: a field reference answers what the data path answers", + target.name + ); } - // The gap today: every producible ordered type (OPE and block ORE), and - // text search, whose twins carry an order term among their three. A type - // leaves this list when a field query assembles its twin, and its - // answers are then held to the data path's above. - assert_eq!( - gap, - [ - "IntegerOrdOre", - "IntegerOrd", - "IntegerOrdOpe", - "SmallintOrdOre", - "SmallintOrd", - "SmallintOrdOpe", - "BigintOrdOre", - "BigintOrd", - "BigintOrdOpe", - "DateOrdOre", - "DateOrd", - "DateOrdOpe", - "TimestampOrdOre", - "TimestampOrd", - "TimestampOrdOpe", - "NumericOrdOre", - "NumericOrd", - "NumericOrdOpe", - "TextOrdOre", - "TextOrd", - "TextOrdOpe", - "TextSearchOre", - "TextSearch", - "RealOrdOre", - "RealOrd", - "RealOrdOpe", - "DoubleOrdOre", - "DoubleOrd", - "DoubleOrdOpe", - ] - ); for (name, _) in ANSWERS { assert!(eql_targets::target(name).is_some(), "{name} is a target"); } - assert!(!ANSWERS.is_empty()); + let ordered = ANSWERS + .iter() + .filter(|(_, ops)| ops.contains(&"lt")) + .count(); + assert_eq!( + ordered, 29, + "every ordered type and both text search types answer the orderings" + ); } /// Every field query binds the bytes the data path derives for the same -/// column, operator and value, under the same query domain. The twin -/// names the column the field reference names: the record's scope, then the field. +/// column, operator and value, under the same query domain, save a block +/// ORE term's nonce. The twin names the column the field reference names: +/// the record's scope, then the field. #[tokio::test] async fn every_field_query_is_the_data_paths_query() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); + let mut block_ore = 0; for (name, operators) in ANSWERS { for operator in *operators { let typed = typed_and_input(&keyset, name, operator).await; let op = Op::parse(operator).unwrap(); - let data = data_term(&cipher, name, typed.column, op, typed.input).await; - assert_eq!(typed.bytes, data, "{name} {operator}"); + let (bytes, domain) = data_term(&cipher, name, typed.column, op, typed.input).await; + assert_eq!(typed.bytes.1, domain, "{name} {operator}: the query domain"); let json: serde_json::Value = serde_json::from_slice(&typed.bytes.0).unwrap(); + let data: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + if json.get("ob").is_some() { + block_ore += 1; + } else { + assert_eq!(typed.bytes.0, bytes, "{name} {operator}: the bytes"); + } + assertions::same_terms(name, operator, &json, &data); assert_eq!(json["v"], 4, "{name}"); assert_eq!( json["i"], - serde_json::json!({"t": "users", "c": typed.column}) + serde_json::json!({"t": "users", "c": typed.column}), + "{name}: the field reference's column" ); } } + assert!(block_ore > 0, "some queries carry a block ORE term"); } -/// Every field query carries the term of the row its record stored: the -/// `hm` of an exact type's field, and a filter the stored `bf` of a match -/// type's field contains. +/// Every field query carries the terms of the row its record stored for +/// the same value, so an equality finds the row and an ordering compares +/// equal to it: the `hm` and `op` of the row, a block ORE term that compares +/// equal to the row's, and for a match, a filter the stored `bf` contains. #[tokio::test] async fn every_field_query_is_the_term_of_the_row_its_record_stored() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); let stored: EncryptedColumns = columns().encrypt_into(&keyset).await.unwrap(); - let field = |column: &str| { - match column { - "text_eq" => serde_json::to_value(&stored.text_eq), - "integer_eq" => serde_json::to_value(&stored.integer_eq), - "smallint_eq" => serde_json::to_value(&stored.smallint_eq), - "date_eq" => serde_json::to_value(&stored.date_eq), - "timestamp_eq" => serde_json::to_value(&stored.timestamp_eq), - "numeric_eq" => serde_json::to_value(&stored.numeric_eq), - "bigint_eq" => serde_json::to_value(&stored.bigint_eq), - "real_eq" => serde_json::to_value(&stored.real_eq), - "double_eq" => serde_json::to_value(&stored.double_eq), - "text_match" => serde_json::to_value(&stored.text_match), - other => panic!("`EncryptedColumns` has no field {other}"), - } - .unwrap() - }; for (name, operators) in ANSWERS { for operator in *operators { let typed = typed_and_input(&keyset, name, operator).await; let query: serde_json::Value = serde_json::from_slice(&typed.bytes.0).unwrap(); - let row = field(typed.column); + let row = stored_field(&stored, typed.column); assert_eq!(query["i"], row["i"], "{name}: the same column"); match *operator { - "eq" => assert_eq!(query["hm"], row["hm"], "{name}: the stored term"), "matches" => { let stored = row["bf"].as_array().unwrap(); let asked = query["bf"].as_array().unwrap(); @@ -356,12 +678,73 @@ async fn every_field_query_is_the_term_of_the_row_its_record_stored() { "{name}: the stored filter contains the query's" ); } + "eq" | "lt" | "lte" | "gt" | "gte" => { + assertions::carries_the_rows_terms(name, operator, &query, &row) + } other => panic!("{name} answers `{other}`: say what its query finds here"), } } } } +mod assertions { + use super::*; + + /// 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. + pub(super) fn same_terms( + name: &str, + operator: &str, + typed: &serde_json::Value, + data: &serde_json::Value, + ) { + let (mut typed, mut data) = (typed.clone(), data.clone()); + let typed_ob = typed.as_object_mut().unwrap().remove("ob"); + let data_ob = data.as_object_mut().unwrap().remove("ob"); + match (&typed_ob, &data_ob) { + (Some(typed_ob), Some(data_ob)) => assert_eq!( + common::ob_order(name, typed_ob, data_ob), + Ordering::Equal, + "{name} {operator}: the block ORE terms of one value compare equal" + ), + (None, None) => {} + _ => panic!("{name} {operator}: one path carries a block ORE term, the other none"), + } + assert_eq!(typed, data, "{name} {operator}: the same terms"); + } + + /// An exact query of the row's own value carries the row's terms: each + /// of `hm` and `op` it carries is the row's, and a block ORE `ob` + /// compares equal to the row's. It carries at least one. + pub(super) fn carries_the_rows_terms( + name: &str, + operator: &str, + query: &serde_json::Value, + row: &serde_json::Value, + ) { + let mut carried = 0; + for key in ["hm", "op"] { + if let Some(term) = query.get(key) { + carried += 1; + assert_eq!(term, &row[key], "{name} {operator}: the row's `{key}`"); + } + } + if let Some(term) = query.get("ob") { + carried += 1; + assert_eq!( + common::ob_order(name, term, &row["ob"]), + Ordering::Equal, + "{name} {operator}: compares equal to the row's `ob`" + ); + } + assert!( + carried > 0, + "{name} {operator}: the query carries a term: {query}" + ); + } +} + #[derive(Clone, Zeroize)] struct User { email: String, From 026cb6aaaf89c65d5182d291843b288962fd8fb2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 02:22:20 +1100 Subject: [PATCH 2/4] fix(eql-bindings,stack-encrypt): refuse a TextOrd query for what either index refuses A TextOrd* query twin carries its hm and its order term whatever the operator, so an eq query derives a block ORE (or OPE) term too. Both paths checked the equality index alone for eq: the pair Eq impl's prepare in eql-bindings, and stack-encrypt's prepare_input in check_query and query_term. So TextOrdOre eq of text that ends in NUL, or is too long for block ORE, passed a binding's boundary and was refused only while its term was derived, after the keyset's index key was loaded. An ordering of the same text was refused before any key. The typed twin now prepares every index whose term it derives: the equality index, then the order index, for eq and the orderings alike. The data path does the same for a type whose twin carries every term: TargetDescriptor gains query_carries_every_term (not on the wire, set with with_query_carrying_every_term), which eql-bindings' EqlTargets sets for every type with a twin except the text search types, whose twin carries the answering index's term alone. A text search eq of the same text is still answered by both paths, as before. typed_queries.rs now holds both paths to the same refusal, before any key request, for block ORE text ending in NUL or over the limit and for text no index normalizes, on every ordered text type and operator, and checks each type's descriptor against the terms its query carries. The 39 answering types are listed once, in one macro that writes the record, the row and the dispatch from it; typed_order_queries.rs does the same for its six columns, and ob_order picks the plaintext from the type's family. eql-codegen keys its typed-query rules on an IndexKey enum, so each rule is an exhaustive match and a new index is a compile error rather than a missed arm or a dropped import. The generated files do not change. The README and module docs are rewrapped; the API plan names the follow-up for between and the state of #1658 and #1659. A changeset records the feature for @cipherstash/eql. --- .changeset/eql-bindings-order-queries.md | 9 + .../2026-10-24-stack-encrypt-api-plan.md | 11 +- languages/golang/CHANGELOG.md | 4 + packages/eql/crates/eql-bindings/CHANGELOG.md | 7 + packages/eql/crates/eql-bindings/README.md | 14 +- .../eql-bindings/src/encryption/query.rs | 49 +- .../eql-bindings/src/encryption/resolver.rs | 8 +- .../eql-bindings/src/encryption/targets.rs | 14 + .../eql/crates/eql-codegen/src/targets.rs | 387 +++++--- .../eql/tests/encryption/tests/common/mod.rs | 37 +- .../encryption/tests/typed_order_queries.rs | 252 ++--- .../tests/encryption/tests/typed_queries.rs | 861 +++++++++--------- packages/stack-encrypt/CHANGELOG.md | 15 + packages/stack-encrypt/src/dynamic/query.rs | 198 +++- packages/stack-encrypt/src/dynamic/target.rs | 23 + 15 files changed, 1075 insertions(+), 814 deletions(-) create mode 100644 .changeset/eql-bindings-order-queries.md diff --git a/.changeset/eql-bindings-order-queries.md b/.changeset/eql-bindings-order-queries.md new file mode 100644 index 0000000000..8d58b0941b --- /dev/null +++ b/.changeset/eql-bindings-order-queries.md @@ -0,0 +1,9 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: the field reference of an ordered EQL v4 type answers order queries. `EncryptedMember::AGE.gt(30).encrypt(&keyset)` gives the type's query twin (`IntegerOrdQuery`, `DateOrdOreQuery`, …) for `lt`, `lte`, `gt` and `gte` on every `…Ord`, `…OrdOpe` and `…OrdOre` type. `TextOrd`, `TextOrdOpe` and `TextOrdOre` answer `eq` too, and `TextSearch` and `TextSearchOre` answer `eq`, the orderings and `matches`. Each query is the one a data plan derives for a field that names the type. + +A `TextOrd*` query carries its `hm` and its order term whatever the operator, and is refused, before any key is requested, for text either index refuses. `between` is not answered from a field reference. + +The stored format, the SQL bundle and the TypeScript types do not change. diff --git a/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 34d94f7c5a..3999401962 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1597,18 +1597,21 @@ Base64. Each query is the data plan's for the same value, and each finds the rows the other finds (`packages/eql/tests/encryption/tests/typed_queries.rs`, - `typed_order_queries.rs`). `between` is not answered from a field - reference, as the data plan answers it on no EQL type. + `typed_order_queries.rs`). A `TextOrd*` query is refused, before any + key is requested, for text either of its indexes refuses, by both + paths. `between` is not answered from a field reference, as the data + plan answers it on no EQL type; #1286 answers it on both. - A data plan that names an EQL type takes a scope and a binding too. `TargetResolver` receives them after the field's label, and `TargetError::Extended` is removed. Under the same scope and binding, a data plan and a derived record write the same terms, and each opens the other's values. A Go struct with an `encrypt_into` field seals through `cipher.Scope(..).Bind(..)`. -- **Tracked in.** Issue #1658 is open. Pull request #1659, open, closes it. Issue #1668 is for order queries from a field reference. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. +- **Tracked in.** Issue #1658 is closed: pull request #1659 closed it and merged on 2026-11-21. Issue #1668 is for order queries from a field reference, and pull request #1752 closes it. Issue #1286 is for `between` from a field reference and from a data plan. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. - **Finished when** these are all true: - a Rust record with EQL fields encrypts, decrypts, and queries through - the new API, including order queries; + the new API, including the order queries `lt`, `lte`, `gt` and `gte`, + and `between` (#1286); - it writes the same terms as a Go record with the same declaration, with and without a scope. diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 959799136f..0c70e9a5d4 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -143,6 +143,10 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Changed +- An `eq` query on a `TextOrdOre` field of text that ends in NUL, or is too + long for block ORE, is refused before any key is requested, as an + ordering of the same text is (#1668). It was refused with the same error + after the keyset's index key was loaded. - `Children` through a cipher with a binding now prepares the read, as `Selector` and `Subtree` do (#1677). Before, the cipher refused it. The token derives under the cipher's scopes alone. The children open under diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index b13c4108a5..1d40581eb4 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -55,6 +55,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `OreBlockTerm`), for a pair `(Hmac256, OpeTerm)` or `(Hmac256, OreBlockTerm)`, and, for a twin whose terms are optional, once per term. + - A query on a twin that carries an order term beside its `hm` is + refused, before any key is requested, for what either index refuses: + `TextOrdOre` `eq` of text that ends in NUL or is too long for block ORE + is refused as an ordering of it is. The descriptor `EqlTargets` gives + Stack Encrypt says which types' twins carry every term + (`Target::query_carries_every_term`), so a data plan refuses the same + queries at the same point. - No type answers `between` from a field reference, as a data plan answers no `between` on an EQL type. diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 9534e96a47..d781e2d628 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -445,12 +445,14 @@ for an EQL type. A twin carries what its query domain requires. The twin of an ordered type other than text carries its one order term (`op` or `ob`). A -`TextOrd` twin carries both -its `hm` and its order term whatever the operator, because -`eql_v4.query_text_ord` requires both, so a field query derives the two -terms for the one value. A text search twin's terms are optional, so its -query carries only the term of the index that answers the operator: `hm` -for `eq`, `op` or `ob` for an ordering, `bf` for `matches`. +`TextOrd` twin carries both its `hm` and its order term whatever the +operator, because `eql_v4.query_text_ord` requires both, so a field query +derives the two terms for the one value. It is refused, before any key is +requested, for text either index refuses: `TextOrdOre.eq(..)` of text that +ends in NUL or is too long for block ORE, as the data path refuses it. A +text search twin's terms are optional, so its query carries only the term +of the index that answers the operator: `hm` for `eq`, `op` or `ob` for an +ordering, `bf` for `matches`. The query is derived under the field reference's label: the record's scope, then the field's name (or its `identity`). That is the column the field stores in diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 61bde437f4..6b67e626a3 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -40,11 +40,12 @@ //! //! The twin carries what the type's query domain requires, as the data //! path's does. The twin of an ordered type other than text carries its one -//! order term. A `TextOrd` twin carries the equality term and the order term whatever the -//! operator, since `eql_v4.query_text_ord` requires both: the query derives -//! the two terms for the one value. A text search twin's terms are -//! optional, so its query carries the term of the index that answers the -//! operator alone. +//! order term. A `TextOrd` twin carries the equality term and the order +//! term whatever the operator, since `eql_v4.query_text_ord` requires both: +//! the query derives the two terms for the one value, and is refused, +//! before any key is requested, for text either index refuses. A text +//! search twin's terms are optional, so its query carries the term of the +//! index that answers the operator alone. //! //! The query is derived under the field reference's label: the record's scope, then //! the field's name (or its `identity`). That is the column the field @@ -296,9 +297,10 @@ pub trait QueryTwin: Sized { /// `TwinIndex`. /// /// It derives the terms of `D`, under the label of the field's field -/// reference and any scope the query carries, and checks and refuses what -/// `I` refuses, as well as a label that names no column; it then writes the -/// terms into the twin, with the column the label names. It is declared as +/// reference and any scope the query carries. Before any key is requested +/// it refuses what each index of `D` refuses for the value, as the data +/// path does, and a label that names no column; it then writes the terms +/// into the twin, with the column the label names. It is declared as /// `I` is ([`Index::spec`]). It answers for the twin's own plaintext /// ([`QueryTwin::Plaintext`]) only. `TextEq` answers [`op::Eq`](struct@op::Eq) through /// `TwinIndex`, `IntegerOrd` answers [`op::Gt`] @@ -445,23 +447,31 @@ where /// derives, hex encoded as the stored value's is, and the term the order /// index `O` derives for the same value, under the same context, /// since the type's query domain requires both. Refuses what the equality -/// index refuses, as the data path does for `=`. Only for the plaintext -/// the twin's type is produced from. +/// index refuses, then what `O` refuses, as the data path does for `=` on a +/// field that names the type: the query derives both terms. An order index +/// refuses the same values for every ordering, so its `Lt` stands for +/// them. Only for the plaintext the twin's type is produced from. impl Supports for TwinIndex where - O: Index

, - Q: QueryTwin<(Hmac256, O::Term), Plaintext = P> + QueryTerm + MaybeSend + 'static, - P: Encrypt + EncryptRef + Zeroize + 'static, + O: Supports + Index

, + Q: QueryTwin<(Hmac256, >::Term), Plaintext = P> + QueryTerm + MaybeSend + 'static, + P: Orderable + Encrypt + EncryptRef + Zeroize + 'static, { type Query = Q; type Verifier = (); fn prepare(&self, value: &P) -> Result<(), Error> { - Supports::::prepare(&self.index, value) + let (equality, order) = &self.terms; + Supports::::prepare(equality, value)?; + Supports::::prepare(order, value) } fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { check_column(label) } - fn query((): (), (equality, order): (EqualityTerm, O::Term), token: QueryToken) -> Q { + fn query( + (): (), + (equality, order): (EqualityTerm, >::Term), + token: QueryToken, + ) -> Q { Q::assemble(column(&token), (hmac256(&equality), order)) } } @@ -472,8 +482,9 @@ where // `(Equality, O)`), as the pair's equality impl does. The term is the one // `O` sends for the operator, which is what it stores, so the twin compares // against the stored value's term under the same column. Refuses what `O` -// refuses for the operator. Only for the plaintext the twin's type is -// produced from. +// refuses for the operator; on the pair, what the equality index refuses +// first, since the query derives both terms. Only for the plaintext the +// twin's type is produced from. macro_rules! twin_orderings { ($($operator:ident),+ $(,)?) => {$( #[doc = concat!("`op::", stringify!($operator), "` on a twin that carries the order index's term alone.")] @@ -513,7 +524,9 @@ macro_rules! twin_orderings { type Query = Q; type Verifier = (); fn prepare(&self, value: &P) -> Result<(), Error> { - Supports::::prepare(&self.index, value) + let (equality, order) = &self.terms; + Supports::::prepare(equality, value)?; + Supports::::prepare(order, value) } fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { check_column(label) diff --git a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs index 6e8c8a082a..500459989a 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs @@ -94,7 +94,7 @@ impl TargetResolver for EqlTargets { /// Converts a row of the target table to the descriptor that Stack /// Encrypt uses. The row and the descriptor have the same wire format. /// -/// The descriptor also contains two things that Stack Encrypt needs and +/// The descriptor also contains three things that Stack Encrypt needs and /// the wire format leaves out: /// /// - The match options, for a type with a match index. Stack Encrypt runs @@ -102,6 +102,9 @@ impl TargetResolver for EqlTargets { /// - The three query domains, for a type that stores a JSON document. An /// ordering at a path uses the leaf domain. `element_match` uses the /// elements domain. `match` uses the predicate domain. +/// - Whether the query twin carries the term of every index the type +/// carries. Stack Encrypt then refuses a query for what any of those +/// indexes refuses, before any term is derived. impl From<&Target> for TargetDescriptor { fn from(target: &Target) -> Self { let mut descriptor = TargetDescriptor::new( @@ -128,6 +131,9 @@ impl From<&Target> for TargetDescriptor { if let Some(domain) = target.predicate_query_sql_domain() { descriptor = descriptor.with_predicate_query_sql_domain(domain); } + if target.query_carries_every_term() { + descriptor = descriptor.with_query_carrying_every_term(); + } descriptor } } diff --git a/packages/eql/crates/eql-bindings/src/encryption/targets.rs b/packages/eql/crates/eql-bindings/src/encryption/targets.rs index 70080f4afc..db961bd0d6 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/targets.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/targets.rs @@ -196,6 +196,20 @@ impl Target { .contains(&"match") .then(super::EqlMatch::options) } + + /// Whether the type's query twin carries the term of every index the + /// type carries, whatever index answers the operator: true for every + /// type with a query twin but the text search types, whose query terms + /// are optional in EQL v4 (a match index beside another), so their + /// twin carries the answering index's term alone. `TextOrd`'s twin + /// carries its `hm` and its `op` for `=` and `<` alike. Stack Encrypt + /// refuses a query on such a type for what any of its indexes refuses + /// (`TargetDescriptor::with_query_carrying_every_term`), as the typed + /// query does. + pub fn query_carries_every_term(&self) -> bool { + let optional_terms = self.indexes.len() > 1 && self.indexes.contains(&"match"); + self.query.is_some() && !optional_terms + } } /// Every EQL type a plan may name as a target, in catalog order — the diff --git a/packages/eql/crates/eql-codegen/src/targets.rs b/packages/eql/crates/eql-codegen/src/targets.rs index 3d37b67732..f423f2596a 100644 --- a/packages/eql/crates/eql-codegen/src/targets.rs +++ b/packages/eql/crates/eql-codegen/src/targets.rs @@ -62,12 +62,145 @@ const TARGET_VERSION: EqlVersion = EqlVersion::V4; /// 6-bit schemes), not its `ore` index, which is CLLW ORE and has no EQL /// domain. pub fn index_key(term: Term) -> &'static str { - match term { - Term::Hm => "eq", - Term::Bloom => "match", - Term::Ore => "ore_block", - Term::Ope => "ope", + IndexKey::of_term(term).as_str() +} + +/// An engine index a catalog term rides under, named by its +/// `IndexSpec::key()` ([`as_str`](Self::as_str)). Each rule the typed query +/// generator applies to an index matches on it exhaustively, so a new index +/// is a compile error in every rule rather than a missing arm. A row's +/// indexes stay strings, as the table spells them; [`parse`](Self::parse) +/// reads one back. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IndexKey { + /// `eq`: the equality index, EQL's `hm`. + Eq, + /// `match`: the match index, EQL's `bf`. + Match, + /// `ore_block`: block ORE, EQL's `ob`. + OreBlock, + /// `ope`: OPE, EQL's `op`. + Ope, +} + +impl IndexKey { + /// Every index, in the order `answers.rs` imports them. + const ALL: [IndexKey; 4] = [ + IndexKey::Eq, + IndexKey::Match, + IndexKey::Ope, + IndexKey::OreBlock, + ]; + + /// The index a catalog term rides under. + fn of_term(term: Term) -> Self { + match term { + Term::Hm => IndexKey::Eq, + Term::Bloom => IndexKey::Match, + Term::Ore => IndexKey::OreBlock, + Term::Ope => IndexKey::Ope, + } + } + + /// The catalog term the index derives: the inverse of + /// [`of_term`](Self::of_term). + fn term(self) -> Term { + match self { + IndexKey::Eq => Term::Hm, + IndexKey::Match => Term::Bloom, + IndexKey::OreBlock => Term::Ore, + IndexKey::Ope => Term::Ope, + } + } + + /// The key `IndexSpec::key()` spells. + pub(crate) fn as_str(self) -> &'static str { + match self { + IndexKey::Eq => "eq", + IndexKey::Match => "match", + IndexKey::OreBlock => "ore_block", + IndexKey::Ope => "ope", + } + } + + /// The index a row's key names. + /// + /// # Panics + /// + /// On a key no catalog term rides under, such as a document's `json`: + /// a typed query has no rule for it. + fn parse(type_name: &str, key: &str) -> Self { + Self::ALL + .into_iter() + .find(|index| index.as_str() == key) + .unwrap_or_else(|| { + panic!( + "{type_name}: a typed query has no rule for the {key} index; extend \ + eql-codegen's IndexKey" + ) + }) + } + + /// Stack Encrypt's index type, as `answers.rs` names it. + fn index_type(self) -> TokenStream { + match self { + IndexKey::Eq => quote!(Equality), + IndexKey::Match => quote!(Match), + IndexKey::Ope => quote!(Ope), + IndexKey::OreBlock => quote!(OreBlock), + } + } + + /// The name `answers.rs` imports Stack Encrypt's index type by. + fn index_import(self) -> &'static str { + match self { + IndexKey::Eq => "Equality", + IndexKey::Match => "Match", + IndexKey::Ope => "Ope", + IndexKey::OreBlock => "OreBlock", + } + } + + /// The type a query twin stores the index's term in, over the type's + /// plaintext `source`: the EQL newtype of an `hm` or a `bf`, Stack + /// Encrypt's own term of an `op` or an `ob`. + 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>), + } + } + + /// The name `answers.rs` imports the twin's term type by, and where + /// from. + fn term_import(self) -> TermImport { + match self { + IndexKey::Eq => TermImport::Newtype("Hmac256"), + IndexKey::Match => TermImport::Newtype("BloomFilter"), + IndexKey::Ope => TermImport::OrderTerm("OpeTerm"), + IndexKey::OreBlock => TermImport::OrderTerm("OreBlockTerm"), + } } + + /// How the index is named in the generated docs. + fn doc(self) -> &'static str { + match self { + IndexKey::Eq => "equality", + IndexKey::Match => "match", + IndexKey::Ope => "OPE", + IndexKey::OreBlock => "block ORE", + } + } +} + +/// Where `answers.rs` imports a twin's term type from. +enum TermImport { + /// An EQL newtype, from `crate::v4::terms`. + Newtype(&'static str), + /// Stack Encrypt's order term, from `stack_encrypt::sem`. + OrderTerm(&'static str), } /// An operator a producible EQL type answers in a Stack Encrypt typed @@ -123,50 +256,31 @@ impl Answer { self != Answer::Matches } - /// The operators the index under `key` ([`index_key`]) answers: the - /// engine's declarations (`Equality::OPERATORS`, `Ope::OPERATORS`, …) - /// less `between`, which the data path answers for no EQL type. - /// - /// # Panics - /// - /// On an index key the generator does not know: a new catalog term must - /// say what a typed query does with it. - fn of_index(type_name: &str, key: &str) -> &'static [Answer] { - match key { - "eq" => &[Answer::Eq], - "match" => &[Answer::Matches], - "ope" | "ore_block" => &[Answer::Lt, Answer::Lte, Answer::Gt, Answer::Gte], - other => panic!( - "{type_name}: a typed query has no rule for the {other} index; extend \ - eql-codegen's Answer::of_index" - ), + /// The operators `index` answers: the engine's declarations + /// (`Equality::OPERATORS`, `Ope::OPERATORS`, …) less `between`, which + /// the data path answers for no EQL type. + fn of_index(index: IndexKey) -> &'static [Answer] { + match index { + IndexKey::Eq => &[Answer::Eq], + IndexKey::Match => &[Answer::Matches], + IndexKey::Ope | IndexKey::OreBlock => { + &[Answer::Lt, Answer::Lte, Answer::Gt, Answer::Gte] + } } } - /// The key of the index among `indexes` that answers this operator. - fn index<'i>(self, indexes: &[&'i str]) -> &'i str { + /// The index among `indexes` that answers this operator. + fn index(self, indexes: &[IndexKey]) -> IndexKey { indexes .iter() .copied() - .find(|key| Answer::of_index("", key).contains(&self)) + .find(|index| Answer::of_index(*index).contains(&self)) .expect("an answer comes from one of the type's indexes") } } -/// The catalog term an index derives, by its [`index_key`]: the inverse of -/// that function. -fn term_of_key(key: &str) -> Term { - match key { - "eq" => Term::Hm, - "match" => Term::Bloom, - "ore_block" => Term::Ore, - "ope" => Term::Ope, - other => panic!("no catalog term rides under the {other} index"), - } -} - /// The operators a producible type with a query twin answers, given the -/// indexes it carries by [`index_key`] name, the same input the engine's +/// indexes it carries, the same input the engine's /// table reads: `Eq` for the `"eq"` index, `Matches` for the `"match"` /// index and the orderings (`Lt`, `Lte`, `Gt`, `Gte`) for the `"ope"` or /// `"ore_block"` index, as `Op::answered_by` answers a field that names the @@ -180,16 +294,15 @@ fn term_of_key(key: &str) -> Term { /// /// # Panics /// -/// On an index key the generator does not know, and on a twin that carries -/// a match term beside another term that it requires: its `matches` query -/// would carry them all, and a typed query has no rule to assemble a -/// verifying query from several terms. +/// On a twin that carries a match term beside another term that it +/// requires: its `matches` query would carry them all, and a typed query +/// has no rule to assemble a verifying query from several terms. pub(crate) fn answers_for_indexes( name: &str, - indexes: &[&str], + indexes: &[IndexKey], optional_terms: bool, ) -> Vec { - if indexes.len() > 1 && indexes.contains(&"match") && !optional_terms { + if indexes.len() > 1 && indexes.contains(&IndexKey::Match) && !optional_terms { panic!( "{name}: its twin requires a match term beside another term; a typed query \ assembles a match twin from the match term alone" @@ -197,7 +310,7 @@ pub(crate) fn answers_for_indexes( } let mut answers: Vec = indexes .iter() - .flat_map(|key| Answer::of_index(name, key).iter().copied()) + .flat_map(|index| Answer::of_index(*index).iter().copied()) .collect(); answers.sort_unstable(); answers @@ -303,10 +416,11 @@ fn suffix(domain: &Domain) -> String { } fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { - let indexes: Vec<&'static str> = Term::payload_terms(domain.terms) + let keys: Vec = Term::payload_terms(domain.terms) .into_iter() - .map(index_key) + .map(IndexKey::of_term) .collect(); + let indexes: Vec<&'static str> = keys.iter().map(|key| key.as_str()).collect(); let query = if domain.terms.is_empty() { None } else { @@ -323,7 +437,7 @@ fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { let reason = target_gap(family, domain); let optional_terms = v4_optional_query_terms(domain); let answers = if reason.is_none() && query.is_some() { - answers_for_indexes(&name, &indexes, optional_terms) + answers_for_indexes(&name, &keys, optional_terms) } else { Vec::new() }; @@ -358,41 +472,6 @@ fn row(family: &'static DomainFamily, domain: &'static Domain) -> Row { } } -/// Stack Encrypt's index type for an index key, as `answers.rs` names it. -fn index_type(key: &str) -> TokenStream { - match key { - "eq" => quote!(Equality), - "match" => quote!(Match), - "ope" => quote!(Ope), - "ore_block" => quote!(OreBlock), - other => panic!("no Stack Encrypt index for the {other} index"), - } -} - -/// The type a query twin stores the term of an index in, over the type's -/// plaintext `source`: the EQL newtype of an `hm` or a `bf`, Stack -/// Encrypt's own term of an `op` or an `ob`. -fn twin_term_type(key: &str, source: &syn::Path) -> TokenStream { - match key { - "eq" => quote!(Hmac256), - "match" => quote!(BloomFilter), - "ope" => quote!(OpeTerm<#source>), - "ore_block" => quote!(OreBlockTerm<#source>), - other => panic!("no query twin term for the {other} index"), - } -} - -/// How an index is named in the generated docs. -fn index_doc(key: &str) -> &'static str { - match key { - "eq" => "equality", - "match" => "match", - "ope" => "OPE", - "ore_block" => "block ORE", - other => panic!("no name for the {other} index"), - } -} - /// A typed query's impls for one type that answers an operator: its query /// twin's assembly from the terms it carries (every index's, or for a twin /// whose terms are optional, one assembly per index from that index's term @@ -410,7 +489,12 @@ fn answer_impls(r: &Row) -> TokenStream { let twin = format_ident!("{twin_name}"); let (_, rust) = plaintext_of(r.family).expect("a producible family has a specified plaintext"); let source: syn::Path = syn::parse_str(rust).expect("a family's Rust plaintext is a type path"); - let field = |key: &str| format_ident!("{}", term_of_key(key).json_key()); + let keys: Vec = r + .indexes + .iter() + .map(|key| IndexKey::parse(name, key)) + .collect(); + let field = |key: IndexKey| format_ident!("{}", key.term().json_key()); let optional_terms = !r.projections.is_empty(); let labelled_doc = format!( " `{name}` is sealed under the column a two-segment label names, so a field of this \ @@ -422,14 +506,14 @@ fn answer_impls(r: &Row) -> TokenStream { }; if optional_terms { // One assembly per index, each setting that index's term alone. - for key in &r.indexes { + for &key in &keys { let set = field(key); - let term = twin_term_type(key, &source); - let unset = r.indexes.iter().filter(|k| *k != key).map(|k| field(k)); + let term = key.twin_term_type(&source); + let unset = keys.iter().filter(|k| **k != key).map(|k| field(*k)); let doc = format!( " `{twin_name}` from the column it queries and its `{set}` term alone, at \ version 4: the query through its {} index.", - index_doc(key) + key.doc() ); out.extend(quote! { #[doc = #doc] @@ -442,12 +526,8 @@ fn answer_impls(r: &Row) -> TokenStream { }); } } else { - let fields: Vec<_> = r.indexes.iter().map(|key| field(key)).collect(); - let terms: Vec<_> = r - .indexes - .iter() - .map(|key| twin_term_type(key, &source)) - .collect(); + let fields: Vec<_> = keys.iter().map(|key| field(*key)).collect(); + let terms: Vec<_> = keys.iter().map(|key| key.twin_term_type(&source)).collect(); let named: Vec = fields.iter().map(|f| format!("`{f}`")).collect(); let doc = format!( " `{twin_name}` from the column it queries and its {} {}, at version 4.", @@ -486,8 +566,8 @@ fn answer_impls(r: &Row) -> TokenStream { } // A twin that requires every term derives them all, whichever index // answers; one whose terms are optional derives the answering index's. - let derived = (!optional_terms && r.indexes.len() > 1).then(|| { - let all = r.indexes.iter().map(|key| index_type(key)); + let derived = (!optional_terms && keys.len() > 1).then(|| { + let all = keys.iter().map(|key| key.index_type()); quote!(, (#(#all),*)) }); let carries = if derived.is_some() { @@ -498,8 +578,8 @@ fn answer_impls(r: &Row) -> TokenStream { "" }; for answer in &r.answers { - let key = answer.index(&r.indexes); - let index = index_type(key); + let key = answer.index(&keys); + let index = key.index_type(); let op = format_ident!("{}", answer.operator()); let (via, doc) = match answer { Answer::Matches => ( @@ -516,7 +596,7 @@ fn answer_impls(r: &Row) -> TokenStream { " `{name}` answers `op::{}` through its {} index. The query term is \ `{twin_name}`, bound as `{twin_domain}`{carries}.", exact.operator(), - index_doc(key) + key.doc() ), ), }; @@ -604,7 +684,10 @@ fn render_targets_from(rows: &[Row]) -> String { // plaintext does, and a null as a null with a null's terms (#1298). // Whether a field may hold one is its plan's. let stored_source = |r: &Row, source: TokenStream| { - if r.indexes.iter().all(|index| *index == "eq") { + if r.indexes + .iter() + .all(|index| *index == IndexKey::Eq.as_str()) + { quote!(Option<#source>) } else { source @@ -802,24 +885,24 @@ fn render_answers_from(rows: &[Row]) -> String { // Every index an answering type carries is named in its impls: as the // index an operator answers through, in the indexes a twin's terms are // derived by, and as the type of the term the twin stores. - let carries = |key: &str| answering.iter().any(|r| r.indexes.contains(&key)); + let carries = |key: IndexKey| answering.iter().any(|r| r.indexes.contains(&key.as_str())); let mut answer_imports = TokenStream::new(); if !answering.is_empty() { - let pick = |names: &[(&str, &'static str)]| -> Vec { - names - .iter() - .filter(|(key, _)| carries(key)) - .map(|(_, name)| format_ident!("{name}")) - .collect() - }; - let newtypes = pick(&[("match", "BloomFilter"), ("eq", "Hmac256")]); - let indexes = pick(&[ - ("eq", "Equality"), - ("match", "Match"), - ("ope", "Ope"), - ("ore_block", "OreBlock"), - ]); - let order_terms = pick(&[("ope", "OpeTerm"), ("ore_block", "OreBlockTerm")]); + let carried: Vec = IndexKey::ALL + .into_iter() + .filter(|key| carries(*key)) + .collect(); + let indexes: Vec<_> = carried + .iter() + .map(|key| format_ident!("{}", key.index_import())) + .collect(); + let (mut newtypes, mut order_terms) = (Vec::new(), Vec::new()); + for key in &carried { + match key.term_import() { + TermImport::Newtype(name) => newtypes.push(format_ident!("{name}")), + TermImport::OrderTerm(name) => order_terms.push(format_ident!("{name}")), + } + } answer_imports.extend(quote! { use crate::encryption::query::{QueryTwin, TwinIndex}; use crate::Identifier; @@ -831,7 +914,7 @@ fn render_answers_from(rows: &[Row]) -> String { if !order_terms.is_empty() { answer_imports.extend(quote!(use stack_encrypt::sem::{#(#order_terms),*};)); } - if carries("match") { + if carries(IndexKey::Match) { answer_imports.extend(quote!( use crate::encryption::EqlMatch; )); @@ -1117,17 +1200,17 @@ mod tests { continue; } let mut expected: Vec<&str> = Vec::new(); - if row.indexes.contains(&"eq") { + if row.indexes.contains(&IndexKey::Eq.as_str()) { expected.push("eq"); } if row .indexes .iter() - .any(|key| matches!(*key, "ope" | "ore_block")) + .any(|key| [IndexKey::Ope.as_str(), IndexKey::OreBlock.as_str()].contains(key)) { expected.extend(ORDERINGS); } - if row.indexes.contains(&"match") { + if row.indexes.contains(&IndexKey::Match.as_str()) { expected.push("matches"); } assert_eq!(answers, expected, "{}", row.name); @@ -1178,23 +1261,27 @@ mod tests { #[test] fn answers_for_indexes_maps_each_index_to_its_operators() { use Answer::*; + use IndexKey as Key; assert_eq!(answers_for_indexes("T", &[], false), Vec::::new()); - assert_eq!(answers_for_indexes("T", &["eq"], false), vec![Eq]); - assert_eq!(answers_for_indexes("T", &["match"], false), vec![Matches]); + assert_eq!(answers_for_indexes("T", &[Key::Eq], false), vec![Eq]); + assert_eq!( + answers_for_indexes("T", &[Key::Match], false), + vec![Matches] + ); assert_eq!( - answers_for_indexes("T", &["ope"], false), + answers_for_indexes("T", &[Key::Ope], false), vec![Lt, Lte, Gt, Gte] ); assert_eq!( - answers_for_indexes("T", &["ore_block"], false), + answers_for_indexes("T", &[Key::OreBlock], false), vec![Lt, Lte, Gt, Gte] ); assert_eq!( - answers_for_indexes("T", &["ope", "eq"], false), + answers_for_indexes("T", &[Key::Ope, Key::Eq], false), vec![Eq, Lt, Lte, Gt, Gte] ); assert_eq!( - answers_for_indexes("T", &["match", "ore_block", "eq"], true), + answers_for_indexes("T", &[Key::Match, Key::OreBlock, Key::Eq], true), vec![Eq, Lt, Lte, Gt, Gte, Matches] ); let names: Vec<&str> = [Eq, Lt, Lte, Gt, Gte, Matches] @@ -1210,20 +1297,36 @@ mod tests { assert!(!Matches.is_exact(), "a match query verifies its rows"); assert!([Eq, Lt, Lte, Gt, Gte].iter().all(|a| a.is_exact())); for (key, answer) in [ - ("eq", Eq), - ("ope", Lt), - ("ore_block", Gte), - ("match", Matches), + (Key::Eq, Eq), + (Key::Ope, Lt), + (Key::OreBlock, Gte), + (Key::Match, Matches), ] { - assert_eq!(answer.index(&["match", key]), key, "{answer:?}"); - assert_eq!(index_key(term_of_key(key)), key, "{key}"); + assert_eq!(answer.index(&[Key::Match, key]), key, "{answer:?}"); + } + } + + /// Every index round-trips through its catalog term and its key, and + /// `ALL` lists each once. + #[test] + fn every_index_key_round_trips() { + for key in IndexKey::ALL { + assert_eq!(IndexKey::of_term(key.term()), key, "{key:?}: its term"); + assert_eq!(index_key(key.term()), key.as_str(), "{key:?}: its key"); + assert_eq!(IndexKey::parse("T", key.as_str()), key, "{key:?}: parsed"); + } + for term in [Term::Hm, Term::Bloom, Term::Ore, Term::Ope] { + assert!( + IndexKey::ALL.contains(&IndexKey::of_term(term)), + "{term:?}: its index is listed" + ); } } #[test] #[should_panic(expected = "no rule for the json index")] fn an_unknown_index_stops_the_generator() { - answers_for_indexes("SteVecDocument", &["json"], false); + IndexKey::parse("SteVecDocument", "json"); } /// A twin that requires a match term beside another stops the @@ -1232,7 +1335,7 @@ mod tests { #[test] #[should_panic(expected = "requires a match term beside another term")] fn a_twin_requiring_a_match_term_and_another_stops_the_generator() { - answers_for_indexes("TextEqMatch", &["eq", "match"], false); + answers_for_indexes("TextEqMatch", &[IndexKey::Eq, IndexKey::Match], false); } /// The rendered file implements `op::Answers` once per answered @@ -1273,11 +1376,15 @@ mod tests { "{name}: its ANSWERS row" ); let optional = !row.projections.is_empty(); - let derived = if !optional && row.indexes.len() > 1 { - let all: Vec = row - .indexes + let keys: Vec = row + .indexes + .iter() + .map(|key| IndexKey::parse(name, key)) + .collect(); + let derived = if !optional && keys.len() > 1 { + let all: Vec = keys .iter() - .map(|key| index_type(key).to_string().replace(' ', "")) + .map(|key| key.index_type().to_string().replace(' ', "")) .collect(); format!(",({})", all.join(",")) } else { @@ -1285,7 +1392,9 @@ mod tests { }; for answer in &row.answers { let op = answer.operator(); - let index = index_type(answer.index(&row.indexes)) + let index = answer + .index(&keys) + .index_type() .to_string() .replace(' ', ""); let derived = if answer.is_exact() { diff --git a/packages/eql/tests/encryption/tests/common/mod.rs b/packages/eql/tests/encryption/tests/common/mod.rs index e44484392a..d091e3f4d1 100644 --- a/packages/eql/tests/encryption/tests/common/mod.rs +++ b/packages/eql/tests/encryption/tests/common/mod.rs @@ -145,29 +145,18 @@ pub fn ob_order(name: &str, a: &serde_json::Value, b: &serde_json::Value) -> std .collect() }; let (a, b) = (unhex(a), unhex(b)); - let family = [ - "Integer", - "Smallint", - "Bigint", - "Date", - "Timestamp", - "Numeric", - "Text", - "Real", - "Double", - ] - .into_iter() - .find(|family| name.starts_with(family)) - .unwrap_or_else(|| panic!("{name}: no family")); - match family { - "Integer" => compare::(&a, &b), - "Smallint" => compare::(&a, &b), - "Bigint" => compare::(&a, &b), - "Date" => compare::(&a, &b), - "Timestamp" => compare::(&a, &b), - "Numeric" => compare::(&a, &b), - "Text" => compare::(&a, &b), - "Real" => compare::(&a, &b), - _ => compare::(&a, &b), + let target = eql_bindings::encryption::targets::target(name) + .unwrap_or_else(|| panic!("{name}: no such EQL type")); + match target.family { + "integer" => compare::(&a, &b), + "smallint" => compare::(&a, &b), + "bigint" => compare::(&a, &b), + "date" => compare::(&a, &b), + "timestamp" => compare::(&a, &b), + "numeric" => compare::(&a, &b), + "text" => compare::(&a, &b), + "real" => compare::(&a, &b), + "double" => compare::(&a, &b), + other => panic!("{name}: no block ORE plaintext for the family {other}"), } } diff --git a/packages/eql/tests/encryption/tests/typed_order_queries.rs b/packages/eql/tests/encryption/tests/typed_order_queries.rs index 8f14f00564..c39943a87d 100644 --- a/packages/eql/tests/encryption/tests/typed_order_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_order_queries.rs @@ -16,8 +16,11 @@ mod common; use eql_bindings::encryption::EqlTargets; -use eql_bindings::v4::integer::{IntegerOrd, IntegerOrdOre}; -use eql_bindings::v4::text::{TextOrd, TextOrdOre, TextSearch, TextSearchOre}; +use eql_bindings::v4::integer::{IntegerOrd, IntegerOrdOre, IntegerOrdOreQuery, IntegerOrdQuery}; +use eql_bindings::v4::text::{ + TextOrd, TextOrdOre, TextOrdOreQuery, TextOrdQuery, TextSearch, TextSearchOre, + TextSearchOreQuery, TextSearchQuery, +}; use eql_bindings::v4::DomainType; use serde::Serialize; use stack_encrypt::dynamic::{self, record, FieldPlan, Op, Operand, ValueFrame}; @@ -27,47 +30,11 @@ use zeroize::Zeroize; type Cipher = StackCipher; -/// One row's plaintexts: a value for each ordered column. -#[derive(Zeroize)] -struct Ranking { - level: i32, - level_ore: i32, - title: String, - title_ore: String, - name: String, - name_ore: String, -} - -/// The table `rankings`, with a column of each shape of ordered twin. -#[derive(EncryptTarget)] -#[stash(struct = Ranking, scope = "rankings")] -struct EncryptedRanking { - level: IntegerOrd, - level_ore: IntegerOrdOre, - title: TextOrd, - title_ore: TextOrdOre, - name: TextSearch, - name_ore: TextSearchOre, -} - /// The integers the rows hold, ascending, and the texts, ascending by /// their fold. const LEVELS: [i32; 5] = [-200, -1, 0, 7, 1_000_000]; const TEXTS: [&str; 5] = ["Alpha", "bravo", "Charlie", "delta", "Echo"]; -/// The row at `at`: each column holds the `at`th value, so the rows ascend -/// in every column. -fn ranking(at: usize) -> Ranking { - Ranking { - level: LEVELS[at], - level_ore: LEVELS[at], - title: TEXTS[at].to_owned(), - title_ore: TEXTS[at].to_owned(), - name: TEXTS[at].to_owned(), - name_ore: TEXTS[at].to_owned(), - } -} - /// The row whose values every query below asks for: the middle one, so /// each ordering finds rows on both sides. const ASKED: usize = 2; @@ -81,80 +48,100 @@ struct Column { query_domain: &'static str, } -const fn column( - field: &'static str, - name: &'static str, - domain: &'static str, - query_domain: &'static str, -) -> Column { - Column { - field, - name, - domain, - query_domain, - } +/// Everything the tests below know of each column, written once per +/// column: the EQL type it names and that type's query twin, its field and +/// the field's reference, the plaintext and the values the rows hold, and +/// the operators it answers from a field reference. Each row becomes a +/// field of the plaintext record and of the encrypted one, a value of each +/// row, an entry of `columns()`, and an arm of `typed`, `asked_input` and +/// `stored_row`. +macro_rules! ranking_columns { + ($( + $name:ident ($query:path): $field:ident / $reference:ident, $plaintext:ty = $values:ident, + [$($op:ident),+]; + )+) => { + /// One row's plaintexts: a value for each ordered column. + #[derive(Zeroize)] + struct Ranking { + $($field: $plaintext,)+ + } + + /// The table `rankings`, with a column of each shape of ordered twin. + #[derive(EncryptTarget)] + #[stash(struct = Ranking, scope = "rankings")] + struct EncryptedRanking { + $($field: $name,)+ + } + + /// The row at `at`: each column holds the `at`th value, so the rows + /// ascend in every column. + fn ranking(at: usize) -> Ranking { + Ranking { + $($field: <$plaintext>::from($values[at]),)+ + } + } + + /// Every column, and the operators each answers from a field + /// reference. + fn columns() -> Vec<(Column, &'static [&'static str])> { + vec![$(( + Column { + field: stringify!($field), + name: stringify!($name), + domain: $name::sql_domain_static(), + query_domain: <$query>::sql_domain_static(), + }, + &[$(stringify!($op)),+], + ),)+] + } + + /// The field reference's query on `field` for `operator`, for the + /// value of the [asked](ASKED) row. + async fn typed(keyset: &Keyset<'_>, field: &str, operator: &str) -> serde_json::Value { + match field { + $(stringify!($field) => match operator { + $(stringify!($op) => json( + &EncryptedRanking::$reference + .$op(ranking(ASKED).$field) + .encrypt(keyset) + .await + .unwrap(), + ),)+ + other => panic!("{field} answers no `{other}`"), + },)+ + other => panic!("no column {other}"), + } + } + + /// The data path's input for the [asked](ASKED) row's value of + /// `field`. + fn asked_input(field: &str) -> ValueFrame { + match field { + $(stringify!($field) => ValueFrame::of($values[ASKED]).unwrap(),)+ + other => panic!("no column {other}"), + } + } + + /// A stored row, as JSON, by column. + fn stored_row(stored: &EncryptedRanking) -> serde_json::Map { + let mut row = serde_json::Map::new(); + $(row.insert( + stringify!($field).to_owned(), + serde_json::to_value(&stored.$field).unwrap(), + );)+ + row + } + }; } -/// Every column, and the operators each answers from a field reference. -fn columns() -> [(Column, &'static [&'static str]); 6] { - const ORDERINGS: &[&str] = &["lt", "lte", "gt", "gte"]; - const TEXT: &[&str] = &["eq", "lt", "lte", "gt", "gte"]; - [ - ( - column( - "level", - "IntegerOrd", - IntegerOrd::sql_domain_static(), - eql_bindings::v4::integer::IntegerOrdQuery::sql_domain_static(), - ), - ORDERINGS, - ), - ( - column( - "level_ore", - "IntegerOrdOre", - IntegerOrdOre::sql_domain_static(), - eql_bindings::v4::integer::IntegerOrdOreQuery::sql_domain_static(), - ), - ORDERINGS, - ), - ( - column( - "title", - "TextOrd", - TextOrd::sql_domain_static(), - eql_bindings::v4::text::TextOrdQuery::sql_domain_static(), - ), - TEXT, - ), - ( - column( - "title_ore", - "TextOrdOre", - TextOrdOre::sql_domain_static(), - eql_bindings::v4::text::TextOrdOreQuery::sql_domain_static(), - ), - TEXT, - ), - ( - column( - "name", - "TextSearch", - TextSearch::sql_domain_static(), - eql_bindings::v4::text::TextSearchQuery::sql_domain_static(), - ), - TEXT, - ), - ( - column( - "name_ore", - "TextSearchOre", - TextSearchOre::sql_domain_static(), - eql_bindings::v4::text::TextSearchOreQuery::sql_domain_static(), - ), - TEXT, - ), - ] +ranking_columns! { + IntegerOrd(IntegerOrdQuery): level / LEVEL, i32 = LEVELS, [lt, lte, gt, gte]; + IntegerOrdOre(IntegerOrdOreQuery): level_ore / LEVEL_ORE, i32 = LEVELS, [lt, lte, gt, gte]; + TextOrd(TextOrdQuery): title / TITLE, String = TEXTS, [eq, lt, lte, gt, gte]; + TextOrdOre(TextOrdOreQuery): title_ore / TITLE_ORE, String = TEXTS, [eq, lt, lte, gt, gte]; + TextSearch(TextSearchQuery): name / NAME, String = TEXTS, [eq, lt, lte, gt, gte]; + TextSearchOre(TextSearchOreQuery): name_ore / NAME_ORE, String = TEXTS, + [eq, lt, lte, gt, gte]; } /// The JSON a query binds. @@ -162,33 +149,6 @@ fn json(query: &Q) -> serde_json::Value { serde_json::to_value(query).unwrap() } -/// The field reference's query on `column` for `operator`, for the value -/// of the [asked](ASKED) row. -async fn typed(keyset: &Keyset<'_>, field: &str, operator: &str) -> serde_json::Value { - let row = || ranking(ASKED); - macro_rules! query { - ($reference:expr, $value:ident, [$($op:ident),+]) => { - match operator { - $(stringify!($op) => json(&$reference.$op(row().$value).encrypt(keyset).await.unwrap()),)+ - other => panic!("{field} answers no `{other}`"), - } - }; - } - match field { - "level" => query!(EncryptedRanking::LEVEL, level, [lt, lte, gt, gte]), - "level_ore" => query!(EncryptedRanking::LEVEL_ORE, level_ore, [lt, lte, gt, gte]), - "title" => query!(EncryptedRanking::TITLE, title, [eq, lt, lte, gt, gte]), - "title_ore" => query!( - EncryptedRanking::TITLE_ORE, - title_ore, - [eq, lt, lte, gt, gte] - ), - "name" => query!(EncryptedRanking::NAME, name, [eq, lt, lte, gt, gte]), - "name_ore" => query!(EncryptedRanking::NAME_ORE, name_ore, [eq, lt, lte, gt, gte]), - other => panic!("no column {other}"), - } -} - type Keyset<'k> = stack_encrypt::KeysetCipher<'k, common::RecordingKeySource>; /// The data path's query on `column` for `operator`, for the value of the @@ -205,11 +165,7 @@ async fn data(cipher: &Cipher, column: &Column, operator: &str) -> serde_json::V &EqlTargets, ) .unwrap(); - let input: ValueFrame = if column.name.starts_with("Integer") { - ValueFrame::of(LEVELS[ASKED]).unwrap() - } else { - ValueFrame::of(TEXTS[ASKED]).unwrap() - }; + let input = asked_input(column.field); let term = dynamic::query_term( &cipher.default_keyset(), &plan, @@ -294,17 +250,7 @@ async fn scenario() -> Scenario { let mut rows = Vec::new(); for at in 0..LEVELS.len() { let stored: EncryptedRanking = ranking(at).encrypt_into(&keyset).await.unwrap(); - let row = serde_json::json!({ - "level": stored.level, - "level_ore": stored.level_ore, - "title": stored.title, - "title_ore": stored.title_ore, - "name": stored.name, - "name_ore": stored.name_ore, - }); - let serde_json::Value::Object(row) = row else { - unreachable!("a row is an object") - }; + let row = stored_row(&stored); rows.push(row); } Scenario { cipher, rows } diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index 47a4c2c748..76a3dfdcf4 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -85,191 +85,6 @@ fn typed_bytes(query: &Q) -> (Vec, String) { ) } -/// One plaintext for each EQL type that answers an operator. Each field is -/// named after its type, and the name is its column. -#[derive(Zeroize)] -struct Columns { - integer_eq: i32, - integer_ord_ore: i32, - integer_ord: i32, - integer_ord_ope: i32, - smallint_eq: i16, - smallint_ord_ore: i16, - smallint_ord: i16, - smallint_ord_ope: i16, - bigint_eq: i64, - bigint_ord_ore: i64, - bigint_ord: i64, - bigint_ord_ope: i64, - date_eq: Date, - date_ord_ore: Date, - date_ord: Date, - date_ord_ope: Date, - timestamp_eq: Timestamp, - timestamp_ord_ore: Timestamp, - timestamp_ord: Timestamp, - timestamp_ord_ope: Timestamp, - numeric_eq: Decimal, - numeric_ord_ore: Decimal, - numeric_ord: Decimal, - numeric_ord_ope: Decimal, - text_eq: String, - text_match: String, - text_ord_ore: String, - text_ord: String, - text_ord_ope: String, - text_search_ore: String, - text_search: String, - real_eq: f32, - real_ord_ore: f32, - real_ord: f32, - real_ord_ope: f32, - double_eq: f64, - double_ord_ore: f64, - double_ord: f64, - double_ord_ope: f64, -} - -/// A record with a field of each EQL type that answers an operator, in the -/// table `users`. Its field references are the typed queries under test. -#[derive(EncryptTarget)] -#[stash(struct = Columns, scope = "users")] -struct EncryptedColumns { - integer_eq: integer::IntegerEq, - integer_ord_ore: integer::IntegerOrdOre, - integer_ord: integer::IntegerOrd, - integer_ord_ope: integer::IntegerOrdOpe, - smallint_eq: smallint::SmallintEq, - smallint_ord_ore: smallint::SmallintOrdOre, - smallint_ord: smallint::SmallintOrd, - smallint_ord_ope: smallint::SmallintOrdOpe, - bigint_eq: bigint::BigintEq, - bigint_ord_ore: bigint::BigintOrdOre, - bigint_ord: bigint::BigintOrd, - bigint_ord_ope: bigint::BigintOrdOpe, - date_eq: date::DateEq, - date_ord_ore: date::DateOrdOre, - date_ord: date::DateOrd, - date_ord_ope: date::DateOrdOpe, - timestamp_eq: timestamp::TimestampEq, - timestamp_ord_ore: timestamp::TimestampOrdOre, - timestamp_ord: timestamp::TimestampOrd, - timestamp_ord_ope: timestamp::TimestampOrdOpe, - numeric_eq: numeric::NumericEq, - numeric_ord_ore: numeric::NumericOrdOre, - numeric_ord: numeric::NumericOrd, - numeric_ord_ope: numeric::NumericOrdOpe, - text_eq: text::TextEq, - text_match: text::TextMatch, - text_ord_ore: text::TextOrdOre, - text_ord: text::TextOrd, - text_ord_ope: text::TextOrdOpe, - text_search_ore: text::TextSearchOre, - text_search: text::TextSearch, - real_eq: real::RealEq, - real_ord_ore: real::RealOrdOre, - real_ord: real::RealOrd, - real_ord_ope: real::RealOrdOpe, - double_eq: double::DoubleEq, - double_ord_ore: double::DoubleOrdOre, - double_ord: double::DoubleOrd, - double_ord_ope: double::DoubleOrdOpe, -} - -/// The row each query below asks for. The float values are the ones whose -/// terms the semantic baseline folds (`-0.0`, NaN), and the timestamp has -/// nanoseconds below a microsecond, which both paths truncate alike. -fn columns() -> Columns { - Columns { - integer_eq: -42, - integer_ord_ore: -42, - integer_ord: -42, - integer_ord_ope: -42, - smallint_eq: -7, - smallint_ord_ore: -7, - smallint_ord: -7, - smallint_ord_ope: -7, - bigint_eq: i64::MIN + 1, - bigint_ord_ore: i64::MIN + 1, - bigint_ord: i64::MIN + 1, - bigint_ord_ope: i64::MIN + 1, - date_eq: common::date_of_days(19_000), - date_ord_ore: common::date_of_days(19_000), - date_ord: common::date_of_days(19_000), - date_ord_ope: common::date_of_days(19_000), - timestamp_eq: common::timestamp_of(1_700_000_000, 123_456_789), - timestamp_ord_ore: common::timestamp_of(1_700_000_000, 123_456_789), - timestamp_ord: common::timestamp_of(1_700_000_000, 123_456_789), - timestamp_ord_ope: common::timestamp_of(1_700_000_000, 123_456_789), - numeric_eq: common::decimal_of(-1_234_567, 4), - numeric_ord_ore: common::decimal_of(-1_234_567, 4), - numeric_ord: common::decimal_of(-1_234_567, 4), - numeric_ord_ope: common::decimal_of(-1_234_567, 4), - text_eq: "bob@example.com".into(), - text_match: "alice".into(), - text_ord_ore: "bob@example.com".into(), - text_ord: "bob@example.com".into(), - text_ord_ope: "bob@example.com".into(), - text_search_ore: "alice smith".into(), - text_search: "alice smith".into(), - real_eq: -0.0, - real_ord_ore: -0.0, - real_ord: -0.0, - real_ord_ope: -0.0, - double_eq: f64::NAN, - double_ord_ore: f64::NAN, - double_ord: f64::NAN, - double_ord_ope: f64::NAN, - } -} - -/// The stored value of the field `column` of `stored`, as JSON. -fn stored_field(stored: &EncryptedColumns, column: &str) -> serde_json::Value { - match column { - "integer_eq" => serde_json::to_value(&stored.integer_eq), - "integer_ord_ore" => serde_json::to_value(&stored.integer_ord_ore), - "integer_ord" => serde_json::to_value(&stored.integer_ord), - "integer_ord_ope" => serde_json::to_value(&stored.integer_ord_ope), - "smallint_eq" => serde_json::to_value(&stored.smallint_eq), - "smallint_ord_ore" => serde_json::to_value(&stored.smallint_ord_ore), - "smallint_ord" => serde_json::to_value(&stored.smallint_ord), - "smallint_ord_ope" => serde_json::to_value(&stored.smallint_ord_ope), - "bigint_eq" => serde_json::to_value(&stored.bigint_eq), - "bigint_ord_ore" => serde_json::to_value(&stored.bigint_ord_ore), - "bigint_ord" => serde_json::to_value(&stored.bigint_ord), - "bigint_ord_ope" => serde_json::to_value(&stored.bigint_ord_ope), - "date_eq" => serde_json::to_value(&stored.date_eq), - "date_ord_ore" => serde_json::to_value(&stored.date_ord_ore), - "date_ord" => serde_json::to_value(&stored.date_ord), - "date_ord_ope" => serde_json::to_value(&stored.date_ord_ope), - "timestamp_eq" => serde_json::to_value(&stored.timestamp_eq), - "timestamp_ord_ore" => serde_json::to_value(&stored.timestamp_ord_ore), - "timestamp_ord" => serde_json::to_value(&stored.timestamp_ord), - "timestamp_ord_ope" => serde_json::to_value(&stored.timestamp_ord_ope), - "numeric_eq" => serde_json::to_value(&stored.numeric_eq), - "numeric_ord_ore" => serde_json::to_value(&stored.numeric_ord_ore), - "numeric_ord" => serde_json::to_value(&stored.numeric_ord), - "numeric_ord_ope" => serde_json::to_value(&stored.numeric_ord_ope), - "text_eq" => serde_json::to_value(&stored.text_eq), - "text_match" => serde_json::to_value(&stored.text_match), - "text_ord_ore" => serde_json::to_value(&stored.text_ord_ore), - "text_ord" => serde_json::to_value(&stored.text_ord), - "text_ord_ope" => serde_json::to_value(&stored.text_ord_ope), - "text_search_ore" => serde_json::to_value(&stored.text_search_ore), - "text_search" => serde_json::to_value(&stored.text_search), - "real_eq" => serde_json::to_value(&stored.real_eq), - "real_ord_ore" => serde_json::to_value(&stored.real_ord_ore), - "real_ord" => serde_json::to_value(&stored.real_ord), - "real_ord_ope" => serde_json::to_value(&stored.real_ord_ope), - "double_eq" => serde_json::to_value(&stored.double_eq), - "double_ord_ore" => serde_json::to_value(&stored.double_ord_ore), - "double_ord" => serde_json::to_value(&stored.double_ord), - "double_ord_ope" => serde_json::to_value(&stored.double_ord_ope), - other => panic!("`EncryptedColumns` has no field {other}"), - } - .unwrap() -} - /// A field query for one operator, as what the tests compare: the bytes /// it binds with its query domain, the column the field reference names, and the /// input the data path is given for the same query. @@ -306,274 +121,150 @@ macro_rules! typed { }}; } -/// The field query for each operator a type answers, for the value the -/// row `columns()` holds: one arm per row of `ANSWERS`, so a type that -/// starts answering an operator fails here until it has one. -async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typed { - match name { - "IntegerEq" => typed!( - keyset, - operator, - EncryptedColumns::INTEGER_EQ, - integer_eq, - [eq] - ), - "IntegerOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::INTEGER_ORD_ORE, - integer_ord_ore, - [lt, lte, gt, gte] - ), - "IntegerOrd" => typed!( - keyset, - operator, - EncryptedColumns::INTEGER_ORD, - integer_ord, - [lt, lte, gt, gte] - ), - "IntegerOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::INTEGER_ORD_OPE, - integer_ord_ope, - [lt, lte, gt, gte] - ), - "SmallintEq" => typed!( - keyset, - operator, - EncryptedColumns::SMALLINT_EQ, - smallint_eq, - [eq] - ), - "SmallintOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::SMALLINT_ORD_ORE, - smallint_ord_ore, - [lt, lte, gt, gte] - ), - "SmallintOrd" => typed!( - keyset, - operator, - EncryptedColumns::SMALLINT_ORD, - smallint_ord, - [lt, lte, gt, gte] - ), - "SmallintOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::SMALLINT_ORD_OPE, - smallint_ord_ope, - [lt, lte, gt, gte] - ), - "BigintEq" => typed!( - keyset, - operator, - EncryptedColumns::BIGINT_EQ, - bigint_eq, - [eq] - ), - "BigintOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::BIGINT_ORD_ORE, - bigint_ord_ore, - [lt, lte, gt, gte] - ), - "BigintOrd" => typed!( - keyset, - operator, - EncryptedColumns::BIGINT_ORD, - bigint_ord, - [lt, lte, gt, gte] - ), - "BigintOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::BIGINT_ORD_OPE, - bigint_ord_ope, - [lt, lte, gt, gte] - ), - "DateEq" => typed!(keyset, operator, EncryptedColumns::DATE_EQ, date_eq, [eq]), - "DateOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::DATE_ORD_ORE, - date_ord_ore, - [lt, lte, gt, gte] - ), - "DateOrd" => typed!( - keyset, - operator, - EncryptedColumns::DATE_ORD, - date_ord, - [lt, lte, gt, gte] - ), - "DateOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::DATE_ORD_OPE, - date_ord_ope, - [lt, lte, gt, gte] - ), - "TimestampEq" => typed!( - keyset, - operator, - EncryptedColumns::TIMESTAMP_EQ, - timestamp_eq, - [eq] - ), - "TimestampOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::TIMESTAMP_ORD_ORE, - timestamp_ord_ore, - [lt, lte, gt, gte] - ), - "TimestampOrd" => typed!( - keyset, - operator, - EncryptedColumns::TIMESTAMP_ORD, - timestamp_ord, - [lt, lte, gt, gte] - ), - "TimestampOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::TIMESTAMP_ORD_OPE, - timestamp_ord_ope, - [lt, lte, gt, gte] - ), - "NumericEq" => typed!( - keyset, - operator, - EncryptedColumns::NUMERIC_EQ, - numeric_eq, - [eq] - ), - "NumericOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::NUMERIC_ORD_ORE, - numeric_ord_ore, - [lt, lte, gt, gte] - ), - "NumericOrd" => typed!( - keyset, - operator, - EncryptedColumns::NUMERIC_ORD, - numeric_ord, - [lt, lte, gt, gte] - ), - "NumericOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::NUMERIC_ORD_OPE, - numeric_ord_ope, - [lt, lte, gt, gte] - ), - "TextEq" => typed!(keyset, operator, EncryptedColumns::TEXT_EQ, text_eq, [eq]), - "TextMatch" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_MATCH, - text_match, - [], - matches - ), - "TextOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_ORD_ORE, - text_ord_ore, - [eq, lt, lte, gt, gte] - ), - "TextOrd" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_ORD, - text_ord, - [eq, lt, lte, gt, gte] - ), - "TextOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_ORD_OPE, - text_ord_ope, - [eq, lt, lte, gt, gte] - ), - "TextSearchOre" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_SEARCH_ORE, - text_search_ore, - [eq, lt, lte, gt, gte], - matches - ), - "TextSearch" => typed!( - keyset, - operator, - EncryptedColumns::TEXT_SEARCH, - text_search, - [eq, lt, lte, gt, gte], - matches - ), - "RealEq" => typed!(keyset, operator, EncryptedColumns::REAL_EQ, real_eq, [eq]), - "RealOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::REAL_ORD_ORE, - real_ord_ore, - [lt, lte, gt, gte] - ), - "RealOrd" => typed!( - keyset, - operator, - EncryptedColumns::REAL_ORD, - real_ord, - [lt, lte, gt, gte] - ), - "RealOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::REAL_ORD_OPE, - real_ord_ope, - [lt, lte, gt, gte] - ), - "DoubleEq" => typed!( - keyset, - operator, - EncryptedColumns::DOUBLE_EQ, - double_eq, - [eq] - ), - "DoubleOrdOre" => typed!( - keyset, - operator, - EncryptedColumns::DOUBLE_ORD_ORE, - double_ord_ore, - [lt, lte, gt, gte] - ), - "DoubleOrd" => typed!( - keyset, - operator, - EncryptedColumns::DOUBLE_ORD, - double_ord, - [lt, lte, gt, gte] - ), - "DoubleOrdOpe" => typed!( - keyset, - operator, - EncryptedColumns::DOUBLE_ORD_OPE, - double_ord_ope, - [lt, lte, gt, gte] - ), - _ => panic!( - "{name} answers `{operator}` from a field reference: give it a field in \ - `EncryptedColumns` and an arm here, with the input the data path is given" - ), - } +/// Everything the tests below know of each EQL type that answers an +/// operator, written once per type: its name, the field of +/// `EncryptedColumns` that holds it and that field's reference, the type, +/// the plaintext and the row's value, and the operators it answers from a +/// field reference (`matches` after `+`). Each row becomes a field of the +/// plaintext record and of the encrypted one, a value of the row, an arm of +/// `stored_field`, `typed_and_input` and `column_of`. +macro_rules! answering_types { + ($( + $name:ident: $field:ident / $reference:ident: $ty:path, $plaintext:ty = $value:expr, + [$($exact:ident),*] $(+ $matches:ident)?; + )+) => { + /// One plaintext for each EQL type that answers an operator. Each + /// field is named after its type, and the name is its column. + #[derive(Zeroize)] + struct Columns { + $($field: $plaintext,)+ + } + + /// A record with a field of each EQL type that answers an operator, + /// in the table `users`. Its field references are the typed queries + /// under test. + #[derive(EncryptTarget)] + #[stash(struct = Columns, scope = "users")] + struct EncryptedColumns { + $($field: $ty,)+ + } + + /// The row each query below asks for. The float values are the ones + /// whose terms the semantic baseline folds (`-0.0`, NaN), and the + /// timestamp has nanoseconds below a microsecond, which both paths + /// truncate alike. + fn columns() -> Columns { + Columns { + $($field: $value,)+ + } + } + + /// The stored value of the field `column` of `stored`, as JSON. + fn stored_field(stored: &EncryptedColumns, column: &str) -> serde_json::Value { + match column { + $(stringify!($field) => serde_json::to_value(&stored.$field),)+ + other => panic!("`EncryptedColumns` has no field {other}"), + } + .unwrap() + } + + /// The field of `EncryptedColumns` that holds the type `name`, which + /// is its column. + fn column_of(name: &str) -> &'static str { + match name { + $(stringify!($name) => stringify!($field),)+ + other => panic!("`EncryptedColumns` holds no {other}"), + } + } + + /// The field query for each operator a type answers, for the value + /// the row `columns()` holds: one arm per row of `ANSWERS`, so a type + /// that starts answering an operator fails here until it has one. + async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typed { + match name { + $(stringify!($name) => typed!( + keyset, + operator, + EncryptedColumns::$reference, + $field, + [$($exact),*] + $(, $matches)? + ),)+ + _ => panic!( + "{name} answers `{operator}` from a field reference: give it a row in \ + `answering_types!`, with the value the data path is given" + ), + } + } + }; +} + +answering_types! { + IntegerEq: integer_eq / INTEGER_EQ: integer::IntegerEq, i32 = -42, [eq]; + IntegerOrdOre: integer_ord_ore / INTEGER_ORD_ORE: integer::IntegerOrdOre, i32 = -42, + [lt, lte, gt, gte]; + IntegerOrd: integer_ord / INTEGER_ORD: integer::IntegerOrd, i32 = -42, [lt, lte, gt, gte]; + IntegerOrdOpe: integer_ord_ope / INTEGER_ORD_OPE: integer::IntegerOrdOpe, i32 = -42, + [lt, lte, gt, gte]; + SmallintEq: smallint_eq / SMALLINT_EQ: smallint::SmallintEq, i16 = -7, [eq]; + SmallintOrdOre: smallint_ord_ore / SMALLINT_ORD_ORE: smallint::SmallintOrdOre, i16 = -7, + [lt, lte, gt, gte]; + SmallintOrd: smallint_ord / SMALLINT_ORD: smallint::SmallintOrd, i16 = -7, + [lt, lte, gt, gte]; + SmallintOrdOpe: smallint_ord_ope / SMALLINT_ORD_OPE: smallint::SmallintOrdOpe, i16 = -7, + [lt, lte, gt, gte]; + BigintEq: bigint_eq / BIGINT_EQ: bigint::BigintEq, i64 = i64::MIN + 1, [eq]; + BigintOrdOre: bigint_ord_ore / BIGINT_ORD_ORE: bigint::BigintOrdOre, i64 = i64::MIN + 1, + [lt, lte, gt, gte]; + BigintOrd: bigint_ord / BIGINT_ORD: bigint::BigintOrd, i64 = i64::MIN + 1, + [lt, lte, gt, gte]; + BigintOrdOpe: bigint_ord_ope / BIGINT_ORD_OPE: bigint::BigintOrdOpe, i64 = i64::MIN + 1, + [lt, lte, gt, gte]; + DateEq: date_eq / DATE_EQ: date::DateEq, Date = common::date_of_days(19_000), [eq]; + DateOrdOre: date_ord_ore / DATE_ORD_ORE: date::DateOrdOre, + Date = common::date_of_days(19_000), [lt, lte, gt, gte]; + DateOrd: date_ord / DATE_ORD: date::DateOrd, Date = common::date_of_days(19_000), + [lt, lte, gt, gte]; + DateOrdOpe: date_ord_ope / DATE_ORD_OPE: date::DateOrdOpe, + Date = common::date_of_days(19_000), [lt, lte, gt, gte]; + TimestampEq: timestamp_eq / TIMESTAMP_EQ: timestamp::TimestampEq, + Timestamp = common::timestamp_of(1_700_000_000, 123_456_789), [eq]; + TimestampOrdOre: timestamp_ord_ore / TIMESTAMP_ORD_ORE: timestamp::TimestampOrdOre, + Timestamp = common::timestamp_of(1_700_000_000, 123_456_789), [lt, lte, gt, gte]; + TimestampOrd: timestamp_ord / TIMESTAMP_ORD: timestamp::TimestampOrd, + Timestamp = common::timestamp_of(1_700_000_000, 123_456_789), [lt, lte, gt, gte]; + TimestampOrdOpe: timestamp_ord_ope / TIMESTAMP_ORD_OPE: timestamp::TimestampOrdOpe, + Timestamp = common::timestamp_of(1_700_000_000, 123_456_789), [lt, lte, gt, gte]; + NumericEq: numeric_eq / NUMERIC_EQ: numeric::NumericEq, + Decimal = common::decimal_of(-1_234_567, 4), [eq]; + NumericOrdOre: numeric_ord_ore / NUMERIC_ORD_ORE: numeric::NumericOrdOre, + Decimal = common::decimal_of(-1_234_567, 4), [lt, lte, gt, gte]; + NumericOrd: numeric_ord / NUMERIC_ORD: numeric::NumericOrd, + Decimal = common::decimal_of(-1_234_567, 4), [lt, lte, gt, gte]; + NumericOrdOpe: numeric_ord_ope / NUMERIC_ORD_OPE: numeric::NumericOrdOpe, + Decimal = common::decimal_of(-1_234_567, 4), [lt, lte, gt, gte]; + TextEq: text_eq / TEXT_EQ: text::TextEq, String = "bob@example.com".into(), [eq]; + TextMatch: text_match / TEXT_MATCH: text::TextMatch, String = "alice".into(), [] + matches; + TextOrdOre: text_ord_ore / TEXT_ORD_ORE: text::TextOrdOre, + String = "bob@example.com".into(), [eq, lt, lte, gt, gte]; + TextOrd: text_ord / TEXT_ORD: text::TextOrd, String = "bob@example.com".into(), + [eq, lt, lte, gt, gte]; + TextOrdOpe: text_ord_ope / TEXT_ORD_OPE: text::TextOrdOpe, + String = "bob@example.com".into(), [eq, lt, lte, gt, gte]; + TextSearchOre: text_search_ore / TEXT_SEARCH_ORE: text::TextSearchOre, + String = "alice smith".into(), [eq, lt, lte, gt, gte] + matches; + TextSearch: text_search / TEXT_SEARCH: text::TextSearch, String = "alice smith".into(), + [eq, lt, lte, gt, gte] + matches; + RealEq: real_eq / REAL_EQ: real::RealEq, f32 = -0.0, [eq]; + RealOrdOre: real_ord_ore / REAL_ORD_ORE: real::RealOrdOre, f32 = -0.0, [lt, lte, gt, gte]; + RealOrd: real_ord / REAL_ORD: real::RealOrd, f32 = -0.0, [lt, lte, gt, gte]; + RealOrdOpe: real_ord_ope / REAL_ORD_OPE: real::RealOrdOpe, f32 = -0.0, [lt, lte, gt, gte]; + DoubleEq: double_eq / DOUBLE_EQ: double::DoubleEq, f64 = f64::NAN, [eq]; + DoubleOrdOre: double_ord_ore / DOUBLE_ORD_ORE: double::DoubleOrdOre, f64 = f64::NAN, + [lt, lte, gt, gte]; + DoubleOrd: double_ord / DOUBLE_ORD: double::DoubleOrd, f64 = f64::NAN, [lt, lte, gt, gte]; + DoubleOrdOpe: double_ord_ope / DOUBLE_ORD_OPE: double::DoubleOrdOpe, f64 = f64::NAN, + [lt, lte, gt, gte]; } /// The operators each type answers from a field reference are exactly the @@ -642,6 +333,7 @@ async fn every_field_query_is_the_data_paths_query() { assert_eq!(typed.bytes.0, bytes, "{name} {operator}: the bytes"); } assertions::same_terms(name, operator, &json, &data); + assertions::carries_the_terms_its_descriptor_says(name, operator, &json); assert_eq!(json["v"], 4, "{name}"); assert_eq!( json["i"], @@ -714,6 +406,28 @@ mod assertions { assert_eq!(typed, data, "{name} {operator}: the same terms"); } + /// A query carries the term of every index its type carries exactly + /// when the type's descriptor says so, which is what the data path + /// prepares a query by; otherwise the answering index's term alone. + pub(super) fn carries_the_terms_its_descriptor_says( + name: &str, + operator: &str, + query: &serde_json::Value, + ) { + let target = eql_targets::target(name).unwrap(); + let carried = ["hm", "op", "ob", "bf"] + .into_iter() + .filter(|term| query.get(term).is_some()) + .count(); + let every = TargetDescriptor::from(target).query_carries_every_term; + assert_eq!( + carried, + if every { target.indexes.len() } else { 1 }, + "{name} {operator}: the query carries every index's term exactly when the \ + descriptor says so ({every}): {query}" + ); + } + /// An exact query of the row's own value carries the row's terms: each /// of `hm` and `op` it carries is the row's, and a block ORE `ob` /// compares equal to the row's. It carries at least one. @@ -882,6 +596,247 @@ async fn a_field_query_refuses_what_the_data_path_refuses() { ); } +/// An ordered text query whose terms cannot all be derived is refused by +/// both paths with the same error, before any key is requested: block ORE +/// text that ends in NUL or folds past the scheme's limit, and text no +/// index can normalize. Each case goes through a keyset whose index key is +/// not loaded yet, so a refusal that came only from deriving a term would +/// show as a key load. +/// +/// A `TextOrd*` twin carries its `hm` and its order term for every +/// operator, so its `eq` is refused for what the order index refuses. A +/// text search twin carries the answering index's term alone, so its `eq` +/// is answered for the same text. +mod given_order_text { + use super::*; + use stack_encrypt::sem::TermError; + use stack_kms::IdentifiedBy; + + const EVERY_OPERATOR: &[&str] = &["eq", "lt", "lte", "gt", "gte"]; + const ORDERINGS: &[&str] = &["lt", "lte", "gt", "gte"]; + + /// Block ORE text over the scheme's limit once folded. + fn too_long() -> String { + "a".repeat(2000) + } + + /// Block ORE text whose fold ends in NUL. + fn trailing_nul() -> String { + "ab\0".to_owned() + } + + /// Text with a code point Unicode 16 does not assign, which no index + /// normalizes. + fn unassigned() -> String { + "a\u{0378}b".to_owned() + } + + /// The refusal a case expects: a `TermError` variant. + #[derive(Clone, Copy, Debug)] + enum Refusal { + OreBlockTrailingNul, + OreBlockTooLong, + Normalize, + } + + impl Refusal { + fn is(self, error: &TermError) -> bool { + matches!( + (self, error), + (Self::OreBlockTrailingNul, TermError::OreBlockTrailingNul) + | (Self::OreBlockTooLong, TermError::OreBlockTooLong) + | (Self::Normalize, TermError::Normalize(_)) + ) + } + } + + /// `$reference.(value)` under `$keyset`, for an operator named + /// at run time, its query dropped. + macro_rules! field_query { + ($keyset:expr, $operator:expr, $reference:expr, $value:expr) => { + match $operator { + "eq" => $reference.eq($value).encrypt($keyset).await.map(drop), + "lt" => $reference.lt($value).encrypt($keyset).await.map(drop), + "lte" => $reference.lte($value).encrypt($keyset).await.map(drop), + "gt" => $reference.gt($value).encrypt($keyset).await.map(drop), + "gte" => $reference.gte($value).encrypt($keyset).await.map(drop), + other => panic!("no `{other}` case"), + } + }; + } + + /// The field query of `value` on the field of `EncryptedColumns` that + /// names the type `name`. + async fn field_query( + keyset: &Keyset<'_>, + name: &str, + operator: &str, + value: String, + ) -> Result<(), Error> { + match name { + "TextOrdOre" => field_query!(keyset, operator, EncryptedColumns::TEXT_ORD_ORE, value), + "TextOrd" => field_query!(keyset, operator, EncryptedColumns::TEXT_ORD, value), + "TextOrdOpe" => field_query!(keyset, operator, EncryptedColumns::TEXT_ORD_OPE, value), + "TextSearchOre" => { + field_query!(keyset, operator, EncryptedColumns::TEXT_SEARCH_ORE, value) + } + "TextSearch" => field_query!(keyset, operator, EncryptedColumns::TEXT_SEARCH, value), + other => panic!("no case for {other}"), + } + } + + /// One query by each path, each through its own cipher and a keyset + /// whose index key is not loaded: the field reference's, the data + /// path's at a binding's boundary (`check_query`, which has no keyset), + /// and the data path's own (`query_term`), with the key requests each + /// cipher saw. + struct Outcome { + typed: Result<(), Error>, + checked: Result<(), dynamic::Error>, + data: Result<(), dynamic::Error>, + typed_keys: usize, + data_keys: usize, + } + + /// Every key request a cipher's source saw: index key loads and data + /// keys generated or retrieved. + fn key_requests(calls: &std::sync::Mutex) -> usize { + let calls = calls.lock().unwrap(); + calls.loads + calls.generate.len() + calls.retrieve.len() + } + + fn unloaded(cipher: &Cipher) -> Keyset<'_> { + cipher.keyset(IdentifiedBy::Name("acme".to_string().into())) + } + + async fn scenario(name: &str, operator: &str, value: &str) -> Outcome { + let (typed_cipher, typed_calls) = common::cipher().await; + let typed = field_query(&unloaded(&typed_cipher), name, operator, value.to_owned()).await; + + let plan = data_plan(name, column_of(name)); + let op = Op::parse(operator).unwrap(); + let checked = dynamic::check_query(&plan, "value", op, frame(value), &EqlTargets); + let (data_cipher, data_calls) = common::cipher().await; + let keyset = unloaded(&data_cipher); + let data = match dynamic::query_term(&keyset, &plan, "value", op, frame(value), &EqlTargets) + { + Ok(pending) => pending.await.map(drop).map_err(dynamic::Error::Cipher), + Err(refused) => Err(refused), + }; + Outcome { + typed, + checked, + data, + typed_keys: key_requests(&typed_calls), + data_keys: key_requests(&data_calls), + } + } + + mod given_a_value_an_index_of_the_twin_refuses { + use super::*; + + /// Each type, the operators whose query derives a term the value + /// cannot have, the value, and the refusal. + fn cases() -> Vec<(&'static str, &'static [&'static str], String, Refusal)> { + use Refusal::{Normalize, OreBlockTooLong, OreBlockTrailingNul}; + vec![ + ( + "TextOrdOre", + EVERY_OPERATOR, + trailing_nul(), + OreBlockTrailingNul, + ), + ("TextOrdOre", EVERY_OPERATOR, too_long(), OreBlockTooLong), + ("TextOrdOre", EVERY_OPERATOR, unassigned(), Normalize), + ("TextOrd", EVERY_OPERATOR, unassigned(), Normalize), + ("TextOrdOpe", EVERY_OPERATOR, unassigned(), Normalize), + ( + "TextSearchOre", + ORDERINGS, + trailing_nul(), + OreBlockTrailingNul, + ), + ("TextSearchOre", ORDERINGS, too_long(), OreBlockTooLong), + ("TextSearchOre", EVERY_OPERATOR, unassigned(), Normalize), + ("TextSearch", EVERY_OPERATOR, unassigned(), Normalize), + ] + } + + #[tokio::test] + async fn both_paths_refuse_it_alike_before_any_key_request() { + for (name, operators, value, expected) in cases() { + for operator in operators { + let outcome = scenario(name, operator, &value).await; + assertions::refused_before_any_key(name, operator, &outcome, expected); + } + } + } + } + + mod given_a_value_only_an_index_the_query_does_not_derive_refuses { + use super::*; + + /// A text search `eq` derives the `hm` alone, so block ORE text it + /// could not order is still a query, by both paths. + #[tokio::test] + async fn both_paths_answer_it() { + for value in [trailing_nul(), too_long()] { + let outcome = scenario("TextSearchOre", "eq", &value).await; + assert!( + outcome.typed.is_ok(), + "the field query is answered: {:?}", + outcome.typed + ); + assert!( + outcome.checked.is_ok(), + "a binding's boundary passes it: {:?}", + outcome.checked + ); + assert!( + outcome.data.is_ok(), + "the data path answers it: {:?}", + outcome.data + ); + } + } + } + + mod assertions { + use super::*; + + pub(super) fn refused_before_any_key( + name: &str, + operator: &str, + outcome: &Outcome, + expected: Refusal, + ) { + assert!( + matches!(&outcome.typed, Err(Error::Term(error)) if expected.is(error)), + "{name} {operator}: the field query is refused with {expected:?}: {:?}", + outcome.typed + ); + assert!( + matches!(&outcome.checked, Err(dynamic::Error::Cipher(Error::Term(error))) if expected.is(error)), + "{name} {operator}: a binding's boundary refuses it with {expected:?}: {:?}", + outcome.checked + ); + assert!( + matches!(&outcome.data, Err(dynamic::Error::Cipher(Error::Term(error))) if expected.is(error)), + "{name} {operator}: the data path refuses it with {expected:?}: {:?}", + outcome.data + ); + assert_eq!( + outcome.typed_keys, 0, + "{name} {operator}: the field query requested no key" + ); + assert_eq!( + outcome.data_keys, 0, + "{name} {operator}: the data path requested no key" + ); + } + } +} + #[derive(Clone, Zeroize)] struct Person { email: String, diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 17d1861ef9..62e2e3bcd8 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1408,6 +1408,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A query on an EQL type whose twin carries every term is refused for + what any of its indexes refuses, before any key is requested** (#1668). + `eql_v4.query_text_ord_ore` requires its `hm` and its `ob` together, so + an `eq` query on a `TextOrdOre` field derives both. `dynamic::check_query` + and `dynamic::query_term` checked the equality index alone, so `eq` of + text that ends in NUL, or is too long for block ORE, passed a binding's + boundary and was refused only while its term was derived, after the + keyset's index key was loaded. Both now refuse it first, with + `TermError::OreBlockTrailingNul` or `TermError::OreBlockTooLong`, as for + an ordering. + - `TargetDescriptor::query_carries_every_term` says which types do, set + with `with_query_carrying_every_term()`. It is not on the wire. A + descriptor without it is taken to carry the answering index's term + alone, as before. + - **`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/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 9955d1f961..21744662c5 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -242,17 +242,7 @@ pub(super) fn target_operators(target: &TargetDescriptor) -> Vec<(Op, IndexSpec) else { return Vec::new(); }; - let indexes: Vec = target - .indexes - .iter() - .filter_map( - |key| match (IndexSpec::parse(key)?, &target.match_options) { - (IndexSpec::Match(_), Some(options)) => Some(IndexSpec::Match(options.clone())), - (IndexSpec::Match(_), None) => None, - (index, _) => Some(index), - }, - ) - .collect(); + let indexes = target_indexes(target); // `between` through an EQL type is not answered yet; `between_at` on a // document is (its bounds are two leaf operands). A JSON operator is // listed only when the type names the SQL type its operand binds as, @@ -271,6 +261,23 @@ pub(super) fn target_operators(target: &TargetDescriptor) -> Vec<(Op, IndexSpec) .collect() } +/// The indexes an EQL type answers through, in its order: each it carries, +/// the match index under the type's match options, and no match index when +/// they are not known. +fn target_indexes(target: &TargetDescriptor) -> Vec { + target + .indexes + .iter() + .filter_map( + |key| match (IndexSpec::parse(key)?, &target.match_options) { + (IndexSpec::Match(_), Some(options)) => Some(IndexSpec::Match(options.clone())), + (IndexSpec::Match(_), None) => None, + (index, _) => Some(index), + }, + ) + .collect() +} + /// A query term a binding asked for by operator: the operand to bind in /// SQL, and what it is. /// @@ -704,6 +711,25 @@ fn prepare_input(index: &IndexSpec, input: &Input) -> Result Ok(None) } +/// [`prepare_input`] for every index a query of `answer` derives a term +/// through: the index that answers the operator, and on a type whose query +/// twin carries every index's term +/// ([`TargetDescriptor::query_carries_every_term`]), each index the type +/// answers through, in the type's order, as a typed query of the type +/// prepares them. The first refusal is returned. +fn prepare_answer(answer: &Answer<'_>, input: &Input) -> Result<(), Error> { + match answer + .target + .as_ref() + .filter(|target| target.query_carries_every_term) + { + Some(target) => target_indexes(target) + .iter() + .try_for_each(|index| prepare_input(index, input).map(drop)), + None => prepare_input(&answer.index, input).map(drop), + } +} + /// Whether `value`, if it is order text, has an order encoding the index /// takes ([`crate::sem::query::order_text`]): the fold exists, and under /// block ORE (`block`) fits the scheme and does not end in NUL. Anything @@ -832,7 +858,7 @@ pub fn check_query( .map_err(|error| error.in_field(field)); } let input = read_input(&answer, operator, input)?; - prepare_input(&answer.index, &input).map(drop) + prepare_answer(&answer, &input) } /// The JSON index options a document field's plan resolved. @@ -1101,10 +1127,11 @@ pub fn query_term<'a, K: 'static>( return json_term(cipher, plan, answer, operator, input); } let input = read_input(&answer, operator, input)?; - // Prepared once, here: the derivation below refuses nothing a query - // refuses, so what passes is derived. A match query's tokens are - // plaintext the caller cuts again for `verify`; they cross no binding. - let _ = prepare_input(&answer.index, &input)?; + // Prepared once, here, through every index whose term the query + // derives: the derivation below refuses nothing a query refuses, so + // what passes is derived. A match query's tokens are plaintext the + // caller cuts again for `verify`; they cross no binding. + prepare_answer(&answer, &input)?; let index = answer.index.clone(); let made = move |domain: Option, operand| QueryTerm { operator, @@ -2902,6 +2929,145 @@ mod tests { (Some("email"), Some(Reason::ExactOperator)) ); } + + /// A resolver holding one text type with an equality and a block ORE + /// index, whose query twin carries both terms when `every_term` is set + /// and the answering index's alone otherwise. + struct OrderedText { + every_term: bool, + } + + impl TargetResolver for OrderedText { + fn targets(&self) -> Vec { + let descriptor = descriptor(Some(ValueKind::String), &["eq", "ore_block"], true, true); + vec![if self.every_term { + descriptor.with_query_carrying_every_term() + } else { + descriptor + }] + } + fn encrypt<'a, K: 'static>( + &self, + _: &str, + _: Option<&crate::dynamic::TargetOptions>, + _: &'a KeysetCipher<'_, K>, + _: &Label, + _: &crate::target::DeclaredContext, + _: ValueFrame, + ) -> Result, K>, TargetError> { + unreachable!("a query encrypts nothing") + } + fn decrypt<'a, K: 'static>( + &self, + _: &str, + _: &'a crate::StackCipher, + _: &Label, + _: &crate::target::DeclaredContext, + _: &[u8], + ) -> Result, TargetError> { + unreachable!("a query decrypts nothing") + } + fn query<'a, K: 'static>( + &self, + _: &str, + _: &IndexSpec, + keyset: &'a KeysetCipher<'_, K>, + _: &Label, + _: &crate::target::DeclaredContext, + _: ValueFrame, + ) -> Result, K>, TargetError> { + Ok(Pending::ready( + keyset, + Ok(br#"{"hm":"00","ob":"00"}"#.to_vec()), + )) + } + } + + /// A plan with one field, `email`, naming [`OrderedText`]'s type. + fn ordered_text_plan(resolver: &OrderedText) -> Plan { + record::plan_with( + frame_of(&Tree::Object(vec![( + "email".into(), + Tree::Object(vec![ + ( + "context".into(), + Tree::Array(vec![text("users"), text("email")]), + ), + ("target".into(), text("Some")), + ]), + )])) + .as_protected_ref() + .as_deref(), + resolver, + ) + .unwrap() + } + + mod given_a_twin_that_carries_every_term { + use super::*; + + /// `eq` derives the block ORE term too, so text block ORE cannot + /// order is refused at a binding's boundary and before the twin is + /// asked for, as for an ordering. + #[tokio::test] + async fn eq_is_refused_for_what_the_order_index_refuses() { + let resolver = OrderedText { every_term: true }; + let plan = ordered_text_plan(&resolver); + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + for op in [Op::Eq, Op::Lt] { + let checked = check_query(&plan, "email", op, text("ab\0"), &resolver); + ordered_text_assertions::trailing_nul(&checked, &format!("{op} at the boundary")); + let derived = + query_term(&keyset, &plan, "email", op, text("ab\0"), &resolver).map(drop); + ordered_text_assertions::trailing_nul(&derived, &format!("{op} before the twin")); + assert!( + check_query(&plan, "email", op, text("bob"), &resolver).is_ok(), + "{op}: text both indexes take is a query" + ); + } + } + } + + mod given_a_twin_that_carries_the_answering_term_alone { + use super::*; + + /// Nothing derives a block ORE term for `eq`, so text block ORE + /// cannot order is an `eq` query, and still no ordering. + #[tokio::test] + async fn eq_is_answered_for_text_the_order_index_refuses() { + let resolver = OrderedText { every_term: false }; + let plan = ordered_text_plan(&resolver); + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + assert!( + check_query(&plan, "email", Op::Eq, text("ab\0"), &resolver).is_ok(), + "the boundary passes `eq`" + ); + assert!( + query_term(&keyset, &plan, "email", Op::Eq, text("ab\0"), &resolver).is_ok(), + "`eq` is derived" + ); + let checked = check_query(&plan, "email", Op::Lt, text("ab\0"), &resolver); + ordered_text_assertions::trailing_nul(&checked, "lt at the boundary"); + } + } + + mod ordered_text_assertions { + use super::*; + + pub(super) fn trailing_nul(result: &Result, what: &str) { + assert!( + matches!( + result, + Err(Error::Cipher(crate::Error::Term( + TermError::OreBlockTrailingNul + ))) + ), + "{what}: refused as block ORE text ending in NUL: {result:?}" + ); + } + } } /// The engine's answers, pinned byte for byte: these are the frames the diff --git a/packages/stack-encrypt/src/dynamic/target.rs b/packages/stack-encrypt/src/dynamic/target.rs index d575d2241d..c89ad162bd 100644 --- a/packages/stack-encrypt/src/dynamic/target.rs +++ b/packages/stack-encrypt/src/dynamic/target.rs @@ -123,6 +123,15 @@ pub struct TargetDescriptor { /// what `match` binds as. Not on the wire; a type that names none does /// not answer `match`. pub predicate_query_sql_domain: Option, + /// Whether the query twin carries the term of every index the type + /// carries, whatever index answers the operator + /// ([`with_query_carrying_every_term`](Self::with_query_carrying_every_term)): + /// EQL v4's `query_text_ord_ore` requires its `hm` and its `ob` + /// together. A query on such a type derives every term, so it is + /// refused, before any term exists, for what any of those indexes + /// refuses, rather than for what the answering index refuses alone. + /// Not on the wire. + pub query_carries_every_term: bool, } /// The descriptor in its wire form: the object a guest's `se_targets` @@ -193,6 +202,7 @@ impl TargetDescriptor { leaf_query_sql_domain: None, elements_query_sql_domain: None, predicate_query_sql_domain: None, + query_carries_every_term: false, } } @@ -231,6 +241,19 @@ impl TargetDescriptor { self } + /// The descriptor of a type whose query twin carries the term of every + /// index the type carries, whatever index answers the operator. A + /// query on it is refused for what any of the type's indexes refuses + /// for the value ([`check_query`](super::check_query), + /// [`query_term`](super::query_term())). Without it, a twin is taken to + /// carry the answering index's term alone, as EQL v4's + /// `query_text_search` does. + #[must_use] + pub fn with_query_carrying_every_term(mut self) -> Self { + self.query_carries_every_term = true; + self + } + /// The entries of [`operators`](Self::operators), each with the index /// that answers it, as the wire form lists them. fn operator_entries(&self) -> Vec { From 36a3b8ed10789ecc5d93df48d8e5cf9ddfdc7d88 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 03:37:20 +1100 Subject: [PATCH 3/4] docs(eql-bindings): drop a stale changelog paragraph left by a rebase The restack of the order-query change onto the child-read review fix merged the old wording of the child entry under its new wording. The old text said a child opens as DecryptSource, which is no longer true. --- packages/eql/crates/eql-bindings/CHANGELOG.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 1d40581eb4..47f23cb247 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -27,11 +27,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the `JsonTreeToken` to send. The call also returns the key that decrypts what the query returns. - The stored format and the SQL do not change. - `JsonSubtreeKey` of its parent's path, and opens - (`DecryptSource`) to the child's value. It is checked - against the parent as Stack Encrypt's `JsonSubtreeKey::open_child` - checks it. A child with members of its own does not open alone: read it - through `JsonTreeSubtree`. The stored format and the SQL do not change. - **Order queries from a field reference** (#1668). The field reference of a field typed with an ordered EQL v4 type has `lt`, `lte`, `gt` and `gte`: `EncryptedMember::AGE.gt(30).encrypt(&keyset)` returns the type's query From a9148228bc93206c3a87a60824d6dbc0a6e989b4 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 23 Nov 2026 10:42:20 +1100 Subject: [PATCH 4/4] docs(stack-encrypt,eql-bindings): describe indexes and the missing between plainly Searchable-encryption indexes belong to Stack Encrypt. EQL is one consumer of them, so the doc of `target_indexes` no longer calls them the indexes an EQL type answers through. The note that a field reference has no `between` now says why: a range query sends both bounds in one operand, and no SDK builds that operand yet. The eql-bindings CHANGELOG points at the issue that tracks it. --- packages/eql/crates/eql-bindings/CHANGELOG.md | 5 +++-- packages/eql/crates/eql-bindings/src/encryption/query.rs | 3 ++- packages/stack-encrypt/src/dynamic/query.rs | 6 +++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 47f23cb247..01ff964aca 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -57,8 +57,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Stack Encrypt says which types' twins carry every term (`Target::query_carries_every_term`), so a data plan refuses the same queries at the same point. - - No type answers `between` from a field reference, as a data plan - answers no `between` on an EQL type. + - A field reference has no `between` yet. A range query sends both + bounds in one operand, and no SDK builds that operand. A data plan + refuses `between` on an EQL type for the same reason. #1286 tracks it. - **A `JsonTreeDocument` field is queried from its field reference** (#1459, #1687). As a field of a derived record, a `JsonTreeDocument` (and an diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 6b67e626a3..06e24a50e8 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -194,7 +194,8 @@ //! //! let _ = EncryptedUser::AGE.eq(42i32); //! ``` -//! nor `between`, which no EQL type answers from a field reference: +//! nor `between`. A range query sends both bounds in one operand, and a +//! field reference cannot build that operand yet: //! ```compile_fail //! use eql_bindings::v4::integer::IntegerOrd; //! use stack_encrypt::EncryptTarget; diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 21744662c5..90fd1b3f97 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -261,9 +261,9 @@ pub(super) fn target_operators(target: &TargetDescriptor) -> Vec<(Op, IndexSpec) .collect() } -/// The indexes an EQL type answers through, in its order: each it carries, -/// the match index under the type's match options, and no match index when -/// they are not known. +/// The searchable-encryption indexes the target type has, in the type's +/// order. A match index takes the type's match options. If the type does +/// not state its match options, its match index is left out. fn target_indexes(target: &TargetDescriptor) -> Vec { target .indexes