Repository navigation
feat(stack-encrypt): check a JSON predicate when the program compiles - #1743
Conversation
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
Mutation testing (cargo-mutants,
|
| caught | missed | unviable | timeout |
|---|---|---|---|
| 215 | 0 | 81 | 0 |
Every mutant in the changed lines was caught by a test.
…the shared grammar `predicate!` is to check a predicate's text when a program compiles, and it can only agree with the engine if it reads the text with the engine's parser. A proc-macro crate cannot depend on stack-encrypt, so the parser moves, as the path grammar did, into stack-encrypt-jsonpath. The new `predicate` module holds the parser and its syntax tree (`parse` -> `Expression`, with `Comparison`, `PathAt`, `ValueAt` and `Operator`), the constructs a refusal names, and `PredicateError`: the kind, the construct and the byte offset, never text from the predicate. The refusals `compile` makes that depend on neither the variables' values nor the field's options are written there once (`Comparison::refuse_not_equal_at_wildcard`, `PathAt::element_member`, `check_filter`, `Comparison::check_filter_condition`, `single_equality`), and the engine calls them at the points it checked them before, so a predicate with two mistakes is still refused for the first. The engine keeps the compilation, which binds values and checks paths against the field's options, and the derivation. It maps a grammar refusal to the `Reason` it always reported. `MAX_DEPTH` moves to the grammar crate as the depth a predicate's paths are read to; the engine's stored-format bound is now that constant, with the same value. No byte that is stored or derived, no refusal and no reason changes. The grammar's own tests move with it, so its mutants are caught in the crate. Refs #1459
… the program compiles A predicate on a document field was text the engine read only when the query was encrypted, so a misspelt path, a member of the wrong array or a value of the wrong type failed at run time, if at all. Issue #1459 asks the compiler to refuse them, as the typed accessors already do. `predicate!(EncryptedCustomer::PROFILE, "$.age >= $min && $.name == $name", min = 30, name)` reads the text with the engine's own parser and refuses, at the literal, text that does not parse and every construct the index cannot answer whatever the variables hold, naming the construct and its byte offset. It matches the variables with the text's `$name`s: `name = value`, a local's name alone, or `"any name" = value`; one used and not given, given and not used, or given twice is refused at the name. When the program runs it is `predicate(text).var(..)`, the same text through the same code, so the query, its `scope` and `encrypt`, and its operand are the text form's and the data plan's `match` operand. The macro cannot see the field's declaration, so it asks the compiler. The derive now implements a lookup of each declared path, array and member keyed by its text as a type (`Char` by `Char`), each calling the accessor it generated, so a `names` override changes nothing. For each comparison the expansion requires the lookup through a trait of its own whose `#[diagnostic::on_unimplemented]` names the path ("this field declares no path `$.agee`"), then calls the accessor's comparison, so an ordering of a path declared under `paths` is refused by the accessor's own bound, and checks each variable's value, at its expression, and each literal against the path's type. A filter of one equality is containment at the member's full path and is checked there; a filter of more is checked against the array's ordered members, as the engine compares them. A missing path resolves to a stand-in that takes anything, so one mistake is one error. The check code is type-checked and never run, and each value expression is evaluated once, after the field reference. `stack_encrypt::predicate!` is a `macro_rules` wrapper that passes `$crate` to the hidden proc macro, so the expansion works however a program reaches this crate. The hidden items live in `field_reference::json::predicate_checks`. Closes #1459
9982008 to
ef70c7e
Compare
coderdan
left a comment
There was a problem hiding this comment.
Human review. LGTM.
cipherstash-agent
left a comment
There was a problem hiding this comment.
Review attestation
Reviewed ef70c7e · posted from Claude Code · claude-opus-5-5 · effort medium
Sources: code-review · claude-opus-5-5; rust-security agent · claude-opus-5-5; mattpocock-skills:code-review · claude-opus-5-5
Skills: code-review, rust-security, mattpocock-skills:code-review, review-cross-check
Findings (11): 11 minor — 8 inline, 3 below.
-
packages/stack-encrypt-jsonpath/src/lib.rs:33(outside diff) minor The run-time predicate parser moved here fromstack-encrypt, but this crate carries only#[forbid(unsafe_code)], not the company security lint blockstack-encrypt/src/lib.rs:3-22has (unwrap_used,expect_used,panic, print/dbglints). The block is clippy-clean on this crate today, so copy it over with itscfg_attr(test, ..)relaxations.Source: rust-security agent · claude-opus-5-5
-
docs/plans/2026-10-24-stack-encrypt-api-plan.md:551(outside diff) minor The design section's table (line 519) lists onlypredicate(text), and line 551 says the text "is checked when the query is encrypted"; only the tracking bullets (~1630) mentionpredicate!. Add the macro to the table and say it checks the text at compile time.Source: mattpocock-skills:code-review · claude-opus-5-5
-
packages/stack-encrypt-derive/Cargo.toml:29(outside diff) minor The comment says the dev-dependencies are doctest-only, but the new unit testreads_the_numbers_the_engine_reads(src/predicate.rs:738) usesstack_encrypt::json::parse_text. Dropstack-encryptfrom the udepsdevelopmentignore (udeps runs--all-targets) and reword the comment.Source: mattpocock-skills:code-review · claude-opus-5-5
Generated by Claude Code
…ss the review of predicate! A number literal is now checked against the path's type. `NumberFits` was implemented for every number type, so `$.age > 1.5`, `$.age >= -1` and `$.age == 99999999999` compiled for a `u32` path, although the typed accessor refuses those values and the docs promised a refusal. The macro now names a literal by the narrowest integer type that holds it, or as a fraction, and the path's type must hold that. An `f64` path takes any number. `PathAt::element_member` is public and took step 0 as the array of a path with no wildcard, so it panicked on `$` and split `$.a.b` wrongly. It now returns `None` for such a path, and both callers use that in place of their own wildcard test. No refusal changes. The names of a predicate's checks take their line and column from the parsed literal. Counting commas missed the literal after a field reference written with a turbofish of two arguments. `stack-encrypt-jsonpath` takes the security lints `stack-encrypt` has, now that the predicate parser runs there. Docs: a variable given by its name alone is moved, which `format!` does not do; `document` is what an expansion calls at run time; the derive implements `PathLookup` for paths under `ordered` and `paths`; the check names are unique in a file, not a crate. The plan's query table names the macro. A stray line is removed from the CHANGELOG, and `stack-encrypt` leaves the derive's udeps ignore list, since a unit test uses it.
|
The three findings outside the diff from the review of
|
Summary
Stack Encrypt (
packages/stack-encrypt) is the Rust engine every CipherStash language SDK runs on. A field that stores an encrypted JSON document can be queried with a predicate: a SQL/JSON path condition such as$.age >= $min, which EQL's@@operator answers over the encrypted column. Until now the predicate was text that the engine read only when the query was encrypted, so a misspelt path, a member of the wrong array or a value of the wrong type failed at run time, if at all.This pull request adds
predicate!, modelled on SQLx'squery!. The compiler checks the predicate's text against the field's declared paths, and the program sends the same text when it runs:A path the field does not declare, a value of another type, a member of another array, a variable that is missing, unused or repeated, and a construct the JSON index cannot answer are compile errors that name the mistake. The query is the one
predicate(text).var(..)builds, so its operand is byte for byte what that form and the data plan'smatchoperator derive.predicate(text)stays, for text built at run time from a user's input. It builds on #1687, which is merged.Changes
The predicate grammar moves to
stack-encrypt-jsonpath(a61aed2bc, no behaviour change)predicate::parse->Expression), the constructs a refusal names, andPredicateError(kind, construct, byte offset; never text from the predicate) move out ofstack-encrypt, so the proc macro reads text with the engine's parser.Comparison::refuse_not_equal_at_wildcard,PathAt::element_member,check_filter,Comparison::check_filter_condition,single_equality). The engine calls them where it checked them before, so a predicate with two mistakes is still refused for the first.MAX_DEPTH(127) moves to the grammar crate; the engine's stored-format bound is now that constant.predicate!(99820087a)stack_encrypt::predicate!(FIELD_REFERENCE, "text", name = value, ..): amacro_ruleswrapper that passes$crateto the hidden proc macropredicate_with_crateinstack-encrypt-derive, so it works however a program reaches the crate (a renamed dependency,eql-bindings' types).true,falseornull; a number JSON cannot hold. Refused at the name: a variable given and not used, or given twice. Refused at the literal: a variable used and not given.PathLookup,ArrayLookup,MemberLookup). The expansion requires the lookup for each path the text uses, through a trait of its own whose message names the path, then calls the accessor's comparison and checks each value's type, so the compiler refuses an undeclared path, a member its array does not order, an ordering of a path declared for equality alone, and a value of another type.field_reference::json::predicate_checks(Char, the three lookups andArrayMembers,document, the finders and their fallbackUnknown,ValueFits,NumberFits,StringFits,BooleanFits,placeholder_of, and the re-exportedpredicate_with_crate)..cargo/mutants.tomlexcludes one equivalent replacement: a finder returningPhantomDatareplaced byPhantomData::from(Default::default()), the same value of a zero-sized type.stack-encryptandstack-encrypt-jsonpathCHANGELOGs, the API plan's "Static JSON queries" section, andAGENTS.md's description of the grammar crate.Verification
Run on this branch (
99820087a), Rust 1.94.1:mise x --env test -- cargo nextest run --workspace --all-features: 2141 passed, 2 skipped, with no fixture, frozen-bytes or conformance file changed.stack-encryptwith no default features: 921 passed.mise run test:doc(the macro's doc example runs),mise run doc,mise run wasm:wasi-check, workspace clippy with-D warnings(andstack-encryptwith no default features),cargo fmt --check: clean.crap:stack-encrypt: passes.tests/json_predicate_macro.rs: 11 tests. Every construct of the grammar (each operator at one node and both ways round, numbers, strings, booleans andnull,exists,!,&&/||nesting, comments, a wildcard equality and ordering, filters of one and several conditions, nested arrays), a keyword key, quoted keys named withnames, a member declared underpaths, several variables, a quoted and a keyword variable, a scope, a field reached through an outer record andwildcard_bound. Each is compared byte for byte withpredicate(text).var(..)from a fresh deterministic cipher at one seed (and as sets of selectors withouttest-support), and one case with several variables and anullagainst the data plan'smatchoperand. A test shows each expression evaluated once, in order, after the field reference. A NaN variable is refused at run time with the text form's error.packages/eql/tests/encryption:the_predicate_macro_is_the_text_formforJsonTreeDocument(5 tests in the file pass).eql-encryption-tests,eql-bindings(stack-encrypt,targets) andeql-codegenpass with--locked; EQL clippy and fmt clean.eql-bindings' own source uses nothing new.tests/ui/predicate_*.rs), none with a$RUST/snippet:predicate_text_is_refused(two that do not parse,like_regex, arithmetic, a position,!=at a wildcard, an ordering of an array's elements, a filter with no wildcard,@beside another condition, an ordering ofnull,1e999);predicate_variables_must_match(missing, unused, repeated);predicate_paths_must_be_declared(an undeclared path, an undeclared equality path, an ordering of apathspath, apathsmember in a two-condition filter, an undeclared member, a member of another array, a field that declares no paths);predicate_values_must_fit(a&strand au8variable, a string, a number and a boolean literal);predicate_on_a_scalar_field. One existing snapshot changed:field_reference_json_on_a_scalar_field, two notes swapped in order.stack-encrypt-jsonpath: 31 unit tests and a doctest. The first commit builds and passes them on its own.-j 1): the whole ofstack-encrypt-jsonpath, 347 mutants, 305 caught, 42 unviable, 0 missed, 0 timeouts. In-diff over both commits (-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath): 302 mutants, 215 caught, 81 unviable, 6 missed. The 6 replace a finder'sPhantomDatareturn withPhantomData::from(Default::default()), the same value; they are excluded as equivalent, and a listing confirms only those are.stack-encryptguests rebuilt (wasm:guest:build,:deterministic,:eql,:eql:deterministic),go:testpasses,go:lint0 issues. The Go SDK is unchanged.pnpm run test:scripts: 95 files, 1550 passed.cargo metadata --lockedpasses for the EQL workspace, the encrypt guest and the stack-encrypt fuzz crate.fuzz:json-text -- -runs=0replays clean; no fuzz target names the predicate parser.Not run: the PostgreSQL tests (no database with the EQL v4 bundle here).
Related
Closes #1459. Builds on #1687 (merged), which adds the typed paths (
orderedandpaths) the macro checks against.Review notes
Design choices you may want to overrule:
$.age, not the accessor's name, whichnames = {..}can change. The derive implements a lookup per path keyed by the path's text as a type:$.ageis(Char<'$'>, Char<'.'>, Char<'a'>, Char<'g'>, Char<'e'>), the textJsonPath'sDisplaywrites, so$."age"and$ . ageare the same key. Each lookup calls the generated accessor. Rejected: a mangled hidden method name per path (a missing one gives rustc's "no method named__stash_path_2461…" and suggests similar internal names); computing the accessor's name in the macro (wrong undernames); a const table checked in aconstblock (its errors are post-monomorphization and silent undercargo check).#[diagnostic::on_unimplemented]naming the path, implemented with#[diagnostic::do_not_recommend]over the lookup, so the error is "this field declares no path$.agee" with a note saying to declare it underorderedorpaths, or to usepredicate(text). The trait names are unique in a file (DeclaresLine35Column52Check0, from the literal's line and column) because rustc prints a fullmain::{closure#0}::…path, and "implements similarly named trait", when two traits share a name. When a path is missing, the code that uses its accessor gets a stand-in (Unknown) that takes anything, chosen by autoref, so one mistake is one error. A field that stores no document gives theJsonQuerieserror, once, and one "declares no path" error per path. No snapshot has a$RUST/snippet.name = value, a local's name alone (which moves the local), and"any name" = valuefor a$"any name"that is not an identifier; a raw identifierr#typenames$type. Each expression is bound once, in the order given, after the field reference; the check code borrows the bindings in a closure that is never called. A JSON null is the literalnullin the text; a variable cannot be one here (predicate(text).var_nullcan). I chose not to acceptOption<T>as a variable: it would need its own trait, and an ordering would then refuseNoneonly at run time.Stringpath, a number literal a number type that holds it (1.5,-1and4294967296are refused for au32; anf64path takes any number),trueandfalseaboolpath, andnullany path under==and!=. The message names the path and the literal: "$.ageholdsu32, and the literal"x"is a string". An ordering oftrue,falseornullis refused by the macro itself, as the engine refuses it.at()accessor and works on apathsmember. A filter of more than one condition compiles to an element-scoped predicate, which compares each member by its ordering term, so each condition is checked throughelements().array().member(); a member its array does not order is "this field declares no array$.visits[*]whose elements have the ordered member@.kind".!=at a wildcard, an ordering of an array's elements themselves, a filter on a path with no wildcard, a wildcard in a filter's member,@beside another condition, a filter member deeper than a document, an ordering of a boolean or null literal, and a number that is not one JSON reads. Left to run time, as they depend on run-time values: a variable's NaN or infinity, and a variable's value type for a path the field does not declare (which cannot reach run time from the macro).paths = {..}, every path can now have a typed accessor, ordered or not; the macro depends only on the accessor existing. All six of the grammar's example predicates (in the predicate module's docs) compile with the macro once their paths are declared:$.tags[*] == $tagneeds"$.tags[*]"underpathsorordered;exists($.email)needs$.emaildeclared; the element filter needs both members underordered.stack-encrypt-derive's, re-exported throughstack_encrypt::predicate!(crate root). The derive'scrate = ..renaming is not needed by the macro:$cratecovers it.Where to look first:
packages/stack-encrypt-derive/src/predicate.rs(the expansion),packages/stack-encrypt/src/field_reference/json/predicate_checks.rs(what it expands to),packages/stack-encrypt/tests/ui/predicate_*.stderr(the messages), andpackages/stack-encrypt/tests/json_predicate_macro.rs.