Skip to content

Commit 54e952c

Browse files
committed
fix(stack-encrypt): address the review of the query preparation
`dynamic::term` re-framed its probe value, which a uuid cannot survive, so a probe `defines` took was refused; it now reads the value as given. `Operator::OP` and `Leaf::AT` default to `None`, so an operator outside the crate needs nothing new. The jsonpath doctest moves to `check_query`. The one-index-per-operator rule is stated as a plan's rule, since the low-level `indexed` and `encrypt_as` run any set, and two match indexes were already a duplicate. A conformance case pins `overlapping_outputs`, a unit test ties each index's operator list to its `Supports` impls, and a heap-hygiene watch covers the typed equality query. The typed match query's own unwiped text is #1593. Refs #1279
1 parent 0c78142 commit 54e952c

13 files changed

Lines changed: 270 additions & 77 deletions

File tree

‎conformance/stack-encrypt/v1/record-declarations-v1.cases.json‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3067,6 +3067,33 @@
30673067
"fields": { "reason": "unknown_output", "field": "value" }
30683068
}
30693069
},
3070+
{
3071+
"id": "two-order-indexes",
3072+
"input": {
3073+
"json": {
3074+
"value": {
3075+
"context": [
3076+
"users",
3077+
"value"
3078+
],
3079+
"outputs": [
3080+
"c",
3081+
"ore",
3082+
"ope"
3083+
],
3084+
"type": "uint32"
3085+
}
3086+
}
3087+
},
3088+
"accepted": false,
3089+
"expected_error": {
3090+
"code": "stack_encrypt::dynamic_plan",
3091+
"fields": {
3092+
"reason": "overlapping_outputs",
3093+
"field": "value"
3094+
}
3095+
}
3096+
},
30703097
{
30713098
"id": "match-invalid-short-standard",
30723099
"input": {

‎languages/golang/stashgen/enginetest/enginetest.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,10 @@ func (e Static) check(ctx context.Context, d stashgen.Declaration) error {
147147
return nil
148148
}
149149

150-
// operatorNames are the operators, in the engine's order (OpSpec::ALL).
150+
// operatorNames are the scalar operators, in the engine's order (Op::ALL).
151151
var operatorNames = []string{"eq", "lt", "lte", "gt", "gte", "between", "matches"}
152152

153-
// operators applies the engine's table as it stands today: OpSpec::answered_by
153+
// operators applies the engine's table as it stands today: Op::answered_by
154154
// for a field with indexes, and for an EQL type the operators of one value
155155
// its indexes answer (matches included).
156156
func (e Static) operators(ctx context.Context, d stashgen.Declaration) (map[string][]stashgen.Operator, error) {
@@ -196,11 +196,12 @@ func (e Static) operators(ctx context.Context, d stashgen.Declaration) (map[stri
196196
return out, nil
197197
}
198198

199-
// answeredBy mirrors OpSpec::answered_by in stack-encrypt: eq through an
199+
// answeredBy mirrors Op::answered_by in stack-encrypt: eq through an
200200
// equality index, matches through a match index, and the orderings through
201-
// ORE, else block ORE, else OPE, over an integer of 16 bits or wider, a
202-
// float, text, a decimal, a date or a timestamp; each only where the index
203-
// applies to the type.
201+
// the one order index the field declares (ORE, block ORE or OPE; check
202+
// refused a field with two), over an integer of 16 bits or wider, a float,
203+
// text, a decimal, a date or a timestamp; each only where the index applies
204+
// to the type.
204205
func answeredBy(operator string, t stashgen.GoType, indexes []stashgen.IndexName) (stashgen.IndexName, bool) {
205206
declared := func(want stashgen.IndexName) bool {
206207
for _, idx := range indexes {

‎languages/golang/stashgen/refusal_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ func TestRefusalsHoldAgainstTheEmbeddedEngine(t *testing.T) {
324324
{"every index on an integer", "\tScore int64 `stash:\"score,encrypt,index=equality;ore\"`\n\tRank int32 `stash:\"rank,index=ope\"`"},
325325
{"two order indexes on an integer", "\tScore int64 `stash:\"score,encrypt,index=ore;ope\"`"},
326326
{"orders on a decimal, a date and a timestamp", "\tAmount encrypt.Decimal `stash:\"amount,encrypt,index=equality;ore\"`\n\tDay encrypt.Date `stash:\"day,encrypt,index=ope\"`\n\tAt time.Time `stash:\"at,encrypt,index=equality;ore\"`"},
327-
{"orders on text, bytes and a float", "\tName string `stash:\"name,encrypt,index=ore;ope;match\"`\n\tBlob []byte `stash:\"blob,encrypt,index=equality;ore\"`\n\tScore float64 `stash:\"score,encrypt,index=ore\"`"},
327+
{"orders on text, bytes and a float", "\tName string `stash:\"name,encrypt,index=ope;match\"`\n\tBlob []byte `stash:\"blob,encrypt,index=equality;ore\"`\n\tScore float64 `stash:\"score,encrypt,index=ore\"`"},
328328
{"a match query on an index-only field", "\tName string `stash:\"name,index=match\"`"},
329329
} {
330330
dir := writeModule(t, map[string]string{"model.go": user(ctx + c.line), "crm/contact.go": crmPackage})

‎packages/eql/crates/eql-bindings/src/encryption/query.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,6 @@ use super::{bloom_filter, hmac256, EqlMatch};
161161
use crate::v3::terms::{BloomFilter, Hmac256};
162162
use crate::Identifier;
163163

164-
/// EQL's match configuration folds case, so its index answers the
165-
/// case-insensitive [`op::Matches`](struct@op::Matches).
166164
/// An EQL v4 query twin, assembled from the column it queries and the one
167165
/// term its type's index derived for the query's value. eql-codegen
168166
/// implements it for the twin of every type that answers an operator

‎packages/eql/tests/encryption/tests/typed_queries.rs‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@ use eql_bindings::v4::{
2121
use eql_bindings::Identifier;
2222
use serde::Serialize;
2323
use stack_encrypt::dynamic::{
24-
self, record, FieldPlan, Op, Operand, TargetDescriptor, TargetError, TargetResolver,
25-
ValueFrame,
24+
self, record, FieldPlan, Op, Operand, TargetDescriptor, TargetError, TargetResolver, ValueFrame,
2625
};
2726
use stack_encrypt::op::{self, Probabilistic, Stats};
2827
use stack_encrypt::{
@@ -421,8 +420,7 @@ async fn a_typed_match_query_verifies_and_sizes_as_the_data_path_does() {
421420
let input = frame(needle);
422421

423422
let page = ["Alice Smith", "alicia", "Bob", "malice", "ALICE", "al", ""];
424-
let data =
425-
dynamic::verify(&plan, "value", Op::Matches, input.clone(), page, &Eql).unwrap();
423+
let data = dynamic::verify(&plan, "value", Op::Matches, input.clone(), page, &Eql).unwrap();
426424
let typed: Vec<bool> = page.iter().map(|v| query.verify(v)).collect();
427425
assert_eq!(typed, data, "{needle}");
428426
assert!(query.verify("Alice Smith"), "{needle}");
@@ -440,16 +438,9 @@ async fn a_typed_match_query_verifies_and_sizes_as_the_data_path_does() {
440438
Stats::declared(1_000_000),
441439
] {
442440
for want in [0, 1, 10, 1_000] {
443-
let data = dynamic::target_limit(
444-
&plan,
445-
"value",
446-
Op::Matches,
447-
&term,
448-
want,
449-
&stats,
450-
&Eql,
451-
)
452-
.unwrap();
441+
let data =
442+
dynamic::target_limit(&plan, "value", Op::Matches, &term, want, &stats, &Eql)
443+
.unwrap();
453444
assert_eq!(query.target_limit(want, &stats), data, "{needle} {want}");
454445
}
455446
}

‎packages/stack-encrypt/CHANGELOG.md‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1818
- `Supports::check`, `verifier` and `admit` are one
1919
`prepare(&self, input) -> Result<Self::Verifier, Error>`, called once
2020
per query, when the query is awaited and before any keyset is
21-
resolved. A match query cuts its tokens once and keeps them. An index
22-
outside this crate implements `prepare` in place of the three.
21+
resolved. A match query is prepared once and keeps its tokens as the
22+
verifier. An index outside this crate implements `prepare` in place of
23+
the three. `Operator::OP` and `Leaf::AT` are new, with `None` defaults,
24+
so an operator outside this crate needs nothing more.
2325
- What a query is refused for is written once, in the `sem` module, for
2426
the typed chain and the dynamic path alike. So the typed chain now
2527
refuses an equality or order query of text with no normal form, and
@@ -34,10 +36,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3436
- `dynamic::term` prepares its probe as `query_term` does, and the
3537
stored-term derivation no longer carries a query flag.
3638
- **A field declares at most one index per operator** (#1233).
37-
`(Ore, Ope)`, `(Ore, OreBlock)` and two match indexes are refused when
38-
the plan is built, as `PlanError::IndexOverlap` on the typed path and
39-
`overlapping_outputs` on the dynamic one, before any key is requested.
40-
`(Equality, Ore)` answer different operators and are allowed. Each index
39+
`(Ore, Ope)` and `(Ore, OreBlock)` are refused when the plan is built,
40+
as `PlanError::IndexOverlap` on the typed path and `overlapping_outputs`
41+
on the dynamic one, before any key is requested; two match indexes were
42+
already one index twice (`DuplicateIndex`). `(Equality, Ore)` answer
43+
different operators and are allowed. The rule is a plan's: `indexed(..)`
44+
and `encrypt_as` with two order indexes still run, since no plan holds
45+
them and no query reads the second term. Each index
4146
declares the operators it answers once (`Equality::OPERATORS`,
4247
`Ore::OPERATORS`, …; `IndexSpec::operators` and `IndexSpec::answers`
4348
read them), and `Op::answered_by` has no priority between order indexes.

‎packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,22 +1240,29 @@ query chain calls it once, when the query is awaited and before any keyset
12401240
is resolved, then keeps the verifier until the term is derived. A match
12411241
query cuts its tokens once. `check_label` and `QueryToken` are unchanged.
12421242

1243-
**Refusals are written once.** What a query is refused for before any term
1244-
exists lives in `sem::query`, one function per index: match options the
1245-
index cannot use, text that cuts no token, text an equality or order index
1246-
cannot normalize, and block ORE text over its limit. The typed `prepare`
1247-
impls and the dynamic path (`check_query`, `query_term`, `verify`) call the
1248-
same functions, so neither has a copy of a rule. A consequence for the
1243+
**The scalar refusals are written once.** What a scalar query is refused
1244+
for before any term exists lives in `sem::query`, one function per index:
1245+
match options the index cannot use, text that cuts no token, text an
1246+
equality or order index cannot normalize, and block ORE text over its
1247+
limit. The typed `prepare` impls and the dynamic path (`check_query`,
1248+
`query_term`, `verify`) call the same functions, so neither has a copy of
1249+
a rule. The JSON document operators' refusals (a path that does not parse,
1250+
a container at a path, a path the field does not order) are still written
1251+
for the typed index and for the dynamic path separately; they join when
1252+
the dynamic path runs the typed derivation (the plan's step 4). A consequence for the
12491253
typed chain: an equality or order query of text that cannot be normalized
12501254
is refused before the keyset is resolved, as the dynamic path refused it
12511255
already. The equality index reads a copy of the value for that check, so
12521256
its plaintext is `Clone`. The shared conformance profile
12531257
`record-query-refusals-v1` pins both paths at the same stage.
12541258

1255-
**A field declares at most one index per operator.** `(Equality, Ore)`
1256-
answer different operators and are allowed. `(Ore, Ope)`, `(Ore,
1257-
OreBlock)` and two match indexes are refused when the plan is built, on
1258-
both paths (`PlanError::IndexOverlap`, `overlapping_outputs`). Each index
1259+
**A field of a plan declares at most one index per operator.** `(Equality,
1260+
Ore)` answer different operators and are allowed. `(Ore, Ope)` and `(Ore,
1261+
OreBlock)` are refused when the plan is built, on both paths
1262+
(`PlanError::IndexOverlap`, `overlapping_outputs`); two match indexes were
1263+
already one index twice (`DuplicateIndex`). The rule is a plan's: the
1264+
low-level `indexed(..)` operation and `encrypt_as` run any set of indexes,
1265+
since no plan holds them and no query reads the second term. Each index
12591266
declares the operators it answers once (`Equality::OPERATORS`,
12601267
`Ore::OPERATORS`, …), and the dynamic lookup reads that declaration with
12611268
no priority between indexes, since a plan never holds two that answer one

‎packages/stack-encrypt/src/dynamic/query.rs‎

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -730,16 +730,6 @@ fn prepare_input(index: &IndexSpec, input: &Input) -> Result<Option<QueryTokens>
730730
Ok(None)
731731
}
732732

733-
/// [`prepare_input`] for one scalar, for [`term`](super::term): the same
734-
/// refusals for a query term derived by index.
735-
///
736-
/// # Errors
737-
///
738-
/// As [`prepare_input`].
739-
pub(super) fn prepare_scalar(index: &IndexSpec, value: &ValueFrame) -> Result<(), Error> {
740-
prepare_input(index, &Input::One(value.clone())).map(drop)
741-
}
742-
743733
/// Whether `value`, if it is order text, has an order encoding the index
744734
/// takes ([`crate::sem::query::order_text`]): the fold exists, and under
745735
/// block ORE (`block`) fits the scheme and does not end in NUL. Anything
@@ -784,6 +774,66 @@ fn query_tokens(value: &ValueFrame, options: &MatchOptions) -> Result<QueryToken
784774
/// it derives anything. A binding calls this at its boundary, so a bad
785775
/// query is refused before a keyset is resolved.
786776
///
777+
/// A document field's `match` operator takes a jsonpath predicate, and
778+
/// refuses what the index's terms cannot answer at the byte it starts,
779+
/// by name, never quoting the text:
780+
///
781+
/// ```
782+
/// use serde_json::json;
783+
/// use stack_encrypt::dynamic::{check_query, frame, record, Op, Reason, ValueFrame};
784+
/// use stack_encrypt::AsProtectedRef;
785+
/// # use stack_encrypt::dynamic::{TargetDescriptor, TargetError, TargetOptions, TargetResolver, ValueKind};
786+
/// # use stack_encrypt::target::IndexSpec;
787+
/// # use stack_encrypt::{KeysetCipher, Label, Pending, StackCipher};
788+
/// # /// A host whose `JsonSearch` names the compiled predicate's domain.
789+
/// # struct Documents;
790+
/// # impl TargetResolver for Documents {
791+
/// # fn targets(&self) -> Vec<TargetDescriptor> {
792+
/// # vec![TargetDescriptor::new(
793+
/// # "JsonSearch", "json", "", Some(ValueKind::Json), "public.eql_v4_json_search",
794+
/// # vec!["json".to_owned()], Some("JsonSearchQuery".to_owned()),
795+
/// # Some("eql_v4.query_json".to_owned()), true, None,
796+
/// # )
797+
/// # .with_predicate_query_sql_domain("eql_v4.query_json_predicate")]
798+
/// # }
799+
/// # fn encrypt<'a, K: 'static>(&self, _: &str, _: Option<&TargetOptions>,
800+
/// # _: &'a KeysetCipher<'_, K>, _: &Label, _: ValueFrame,
801+
/// # ) -> Result<Pending<'a, Vec<u8>, K>, TargetError> { unreachable!() }
802+
/// # fn decrypt<'a, K: 'static>(&self, _: &str, _: &'a StackCipher<K>, _: &Label, _: &[u8],
803+
/// # ) -> Result<Pending<'a, ValueFrame, K>, TargetError> { unreachable!() }
804+
/// # fn query<'a, K: 'static>(&self, _: &str, _: &IndexSpec, _: &'a KeysetCipher<'_, K>,
805+
/// # _: &Label, _: ValueFrame,
806+
/// # ) -> Result<Pending<'a, Vec<u8>, K>, TargetError> { unreachable!() }
807+
/// # }
808+
/// // A document field that orders `$.age`.
809+
/// let declaration = frame::serde::to_vec(&json!({"profile": {
810+
/// "context": ["users", "profile"], "type": "json", "null": "sql",
811+
/// "target": {"name": "JsonSearch", "options": {"ordered": ["$.age"]}}
812+
/// }}))?;
813+
/// let plan = record::plan_with(declaration.as_protected_ref(), &Documents)?;
814+
/// // What `jsonb_path_match(col, $1, $2)` takes: the predicate, and its
815+
/// // variables as the JSON text of one object.
816+
/// let input = |predicate: &str| -> ValueFrame {
817+
/// let input = json!({"predicate": predicate, "vars": r#"{"min": 18, "r": "sibling"}"#});
818+
/// ValueFrame::from_bytes(frame::serde::to_vec(&input).unwrap().as_protected_ref()).unwrap()
819+
/// };
820+
/// let check = |predicate: &str| {
821+
/// check_query(&plan, "profile", Op::Match, input(predicate), &Documents)
822+
/// };
823+
///
824+
/// check("$.age >= $min && !(exists($.retired))")?;
825+
/// check(r#"$.name == "ann" || $."first name" != null"#)?;
826+
/// check("exists($.contacts[*] ? (@.relationship == $r))")?;
827+
///
828+
/// // Refused at the byte the construct starts, by name, never quoting
829+
/// // the text.
830+
/// let error = check(r#"$.email like_regex "@""#).unwrap_err();
831+
/// assert_eq!(error.reason(), Some(Reason::JsonPredicateUnsupported));
832+
/// let error = check("$.age + 1 > $min").unwrap_err();
833+
/// assert!(error.to_string().contains("at byte 6"), "{error}");
834+
/// # Ok::<(), Box<dyn std::error::Error>>(())
835+
/// ```
836+
///
787837
/// # Errors
788838
///
789839
/// As [`query_term`].

‎packages/stack-encrypt/src/dynamic/term.rs‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -457,27 +457,61 @@ pub async fn term<'c, K, P, D>(
457457
) -> Result<Vec<u8>, Error>
458458
where
459459
K: DataKeySource + IndexKeySource + Sync + 'static,
460-
P: Encrypt,
460+
P: Encrypt + Clone,
461461
D: IntoPrfContext<'c>,
462462
{
463-
// The query refusals first, as `query_term` makes them: a probe is a
464-
// query, so match text that cuts no token is refused here rather than
465-
// derived as the empty filter a stored value keeps.
466-
let not_taken = || Error::Term {
467-
field: None,
468-
kind: kind.clone(),
469-
};
470-
let frame = ValueFrame::of(value).map_err(|_| not_taken())?;
471-
if !kind.defines(&frame) {
472-
return Err(not_taken());
463+
// A value the index does not take is refused as that kind, first.
464+
if !kind.defines(value.clone()) {
465+
return Err(Error::Term {
466+
field: None,
467+
kind: kind.clone(),
468+
});
473469
}
474-
super::query::prepare_scalar(kind, &frame)?;
475-
derive(cipher, &frame, kind, context)?
470+
// Then the query refusals, as `query_term` makes them: a probe is a
471+
// query, so match text that cuts no token is refused here rather than
472+
// derived as the empty filter a stored value keeps. The value is read
473+
// as it is, not re-framed, so every scalar `defines` takes is one a
474+
// probe takes.
475+
prepare_probe(kind, value.clone())?;
476+
derive(cipher, value, kind, context)?
476477
.await
477478
.map(TermBytes::into_bytes)
478479
.map_err(Error::Cipher)
479480
}
480481

482+
/// The query refusals of a probe of `value` through `kind`: the `sem`
483+
/// module's rules, as `query_term` applies them to a field's input.
484+
///
485+
/// # Errors
486+
///
487+
/// [`Error::Cipher`] with the term error, as `query_term`.
488+
fn prepare_probe<P: Encrypt>(kind: &IndexSpec, value: P) -> Result<(), Error> {
489+
let refused = |error: TermError| Error::Cipher(error.into());
490+
let text_rule = |value: P, rule: &dyn Fn(&str) -> Result<(), TermError>| {
491+
value
492+
.visit(OneScalar::new(
493+
|ty: Option<Logical>, value: Physical<'_>| match (ty, value) {
494+
(None, Physical::Text(text)) => Ok(rule(text)),
495+
_ => Err(None),
496+
},
497+
))
498+
// Not one text scalar: nothing to refuse here.
499+
.unwrap_or(Ok(()))
500+
.map_err(refused)
501+
};
502+
match kind {
503+
IndexSpec::Equality => crate::sem::query::equality(value).map_err(refused),
504+
IndexSpec::Match(options) => text_rule(value, &|text| {
505+
crate::sem::query::match_tokens(text, options).map(drop)
506+
}),
507+
IndexSpec::Ore | IndexSpec::Ope => {
508+
text_rule(value, &|text| crate::sem::query::order_text(text, false))
509+
}
510+
IndexSpec::OreBlock => text_rule(value, &|text| crate::sem::query::order_text(text, true)),
511+
IndexSpec::Json(_) => Ok(()),
512+
}
513+
}
514+
481515
/// An index term in its frozen byte encoding, as a binding stores and
482516
/// compares it: the raw 32 PRF bytes of an equality term, a match term's
483517
/// positions, the raw CLLW bytes of an ORE or OPE term (see

0 commit comments

Comments
 (0)