Skip to content

feat(stack-encrypt): check a JSON predicate when the program compiles - #1743

Merged
coderdan merged 3 commits into
nextfrom
feat/stack-encrypt-predicate-macro
Nov 22, 2026
Merged

coderdan merged 3 commits into
nextfrom
feat/stack-encrypt-predicate-macro

Conversation

@coderdan

@coderdan coderdan commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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's query!. The compiler checks the predicate's text against the field's declared paths, and the program sends the same text when it runs:

let regulars = predicate!(
    EncryptedCustomer::PROFILE,
    r#"$.name == "Ada" && $.age >= $min && exists($.visits[*] ? (@.place == "home" && @.at > $after))"#,
    min = 30,
    after,
)
.encrypt(&keyset)
.await?;

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's match operator 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)

  • The parser and its syntax tree (predicate::parse -> Expression), the constructs a refusal names, and PredicateError (kind, construct, byte offset; never text from the predicate) move out of stack-encrypt, so the proc macro reads text with the engine's parser.
  • The refusals that depend on neither the variables nor the field's options are written once there (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.
  • No stored or derived byte, refusal or reason changes. The grammar's tests move with it, so its mutants are caught in that crate.

predicate! (99820087a)

  • stack_encrypt::predicate!(FIELD_REFERENCE, "text", name = value, ..): a macro_rules wrapper that passes $crate to the hidden proc macro predicate_with_crate in stack-encrypt-derive, so it works however a program reaches the crate (a renamed dependency, eql-bindings' types).
  • Refused at the literal: text that does not parse, and every construct the index cannot answer whatever the variables hold, with the construct and the byte offset; an ordering of true, false or null; 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.
  • The derive now also implements a hidden lookup of each declared path, array and member, keyed by the path's text as a type, each calling the accessor it generated (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.
  • Hidden support items: field_reference::json::predicate_checks (Char, the three lookups and ArrayMembers, document, the finders and their fallback Unknown, ValueFits, NumberFits, StringFits, BooleanFits, placeholder_of, and the re-exported predicate_with_crate).
  • .cargo/mutants.toml excludes one equivalent replacement: a finder returning PhantomData replaced by PhantomData::from(Default::default()), the same value of a zero-sized type.
  • Docs: the macro's doc example (runs), the stack-encrypt and stack-encrypt-jsonpath CHANGELOGs, the API plan's "Static JSON queries" section, and AGENTS.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-encrypt with 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 (and stack-encrypt with 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 and null, exists, !, &&/|| nesting, comments, a wildcard equality and ordering, filters of one and several conditions, nested arrays), a keyword key, quoted keys named with names, a member declared under paths, several variables, a quoted and a keyword variable, a scope, a field reached through an outer record and wildcard_bound. Each is compared byte for byte with predicate(text).var(..) from a fresh deterministic cipher at one seed (and as sets of selectors without test-support), and one case with several variables and a null against the data plan's match operand. 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_form for JsonTreeDocument (5 tests in the file pass). eql-encryption-tests, eql-bindings (stack-encrypt, targets) and eql-codegen pass with --locked; EQL clippy and fmt clean. eql-bindings' own source uses nothing new.
  • Compile-fail (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 of null, 1e999); predicate_variables_must_match (missing, unused, repeated); predicate_paths_must_be_declared (an undeclared path, an undeclared equality path, an ordering of a paths path, a paths member in a two-condition filter, an undeclared member, a member of another array, a field that declares no paths); predicate_values_must_fit (a &str and a u8 variable, 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.
  • The grammar's own tests in stack-encrypt-jsonpath: 31 unit tests and a doctest. The first commit builds and passes them on its own.
  • Mutation testing (-j 1): the whole of stack-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's PhantomData return with PhantomData::from(Default::default()), the same value; they are excluded as equivalent, and a listing confirms only those are.
  • Go: all four stack-encrypt guests rebuilt (wasm:guest:build, :deterministic, :eql, :eql:deterministic), go:test passes, go:lint 0 issues. The Go SDK is unchanged.
  • pnpm run test:scripts: 95 files, 1550 passed. cargo metadata --locked passes for the EQL workspace, the encrypt guest and the stack-encrypt fuzz crate. fuzz:json-text -- -runs=0 replays 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 (ordered and paths) the macro checks against.

Review notes

Design choices you may want to overrule:

  1. Finding an accessor from a path. The macro sees $.age, not the accessor's name, which names = {..} can change. The derive implements a lookup per path keyed by the path's text as a type: $.age is (Char<'$'>, Char<'.'>, Char<'a'>, Char<'g'>, Char<'e'>), the text JsonPath's Display writes, so $."age" and $ . age are 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 under names); a const table checked in a const block (its errors are post-monomorphization and silent under cargo check).
  2. Error quality. Each check site declares a trait of its own with #[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 under ordered or paths, or to use predicate(text). The trait names are unique in a file (DeclaresLine35Column52Check0, from the literal's line and column) because rustc prints a full main::{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 the JsonQueries error, once, and one "declares no path" error per path. No snapshot has a $RUST/ snippet.
  3. Variable syntax. name = value, a local's name alone (which moves the local), and "any name" = value for a $"any name" that is not an identifier; a raw identifier r#type names $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 literal null in the text; a variable cannot be one here (predicate(text).var_null can). I chose not to accept Option<T> as a variable: it would need its own trait, and an ordering would then refuse None only at run time.
  4. Literals. A string literal fits a String path, a number literal a number type that holds it (1.5, -1 and 4294967296 are refused for a u32; an f64 path takes any number), true and false a bool path, and null any path under == and !=. The message names the path and the literal: "$.age holds u32, and the literal "x" is a string". An ordering of true, false or null is refused by the macro itself, as the engine refuses it.
  5. Element filters. A filter of one equality compiles to containment at the member's full path, so it is checked through that path's at() accessor and works on a paths member. 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 through elements().array().member(); a member its array does not order is "this field declares no array $.visits[*] whose elements have the ordered member @.kind".
  6. Constructs the index cannot answer. Everything the parser refuses, plus != 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).
  7. A path with no typed accessor. With feat(stack-encrypt,eql-bindings): typed JSON queries from a field reference #1687's 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[*] == $tag needs "$.tags[*]" under paths or ordered; exists($.email) needs $.email declared; the element filter needs both members under ordered.
  8. Where it lives. The proc macro is stack-encrypt-derive's, re-exported through stack_encrypt::predicate! (crate root). The derive's crate = .. renaming is not needed by the macro: $crate covers 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), and packages/stack-encrypt/tests/json_predicate_macro.rs.

@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 3e98a8a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI; Enforced overrides: Organization
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ad220150-6845-4b4b-a00a-034409991ac9

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

@github-actions

Copy link
Copy Markdown
Contributor

Mutation testing (cargo-mutants, --in-diff, stack-auth + stack-encrypt + stack-encrypt-jsonpath)

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
@coderdan
coderdan force-pushed the feat/stack-encrypt-predicate-macro branch from 9982008 to ef70c7e Compare November 22, 2026 01:30
@coderdan
coderdan marked this pull request as ready for review November 22, 2026 01:48
@coderdan
coderdan requested a review from a team as a code owner November 22, 2026 01:48

@coderdan coderdan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Human review. LGTM.

@cipherstash-agent cipherstash-agent left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 from stack-encrypt, but this crate carries only #[forbid(unsafe_code)], not the company security lint block stack-encrypt/src/lib.rs:3-22 has (unwrap_used, expect_used, panic, print/dbg lints). The block is clippy-clean on this crate today, so copy it over with its cfg_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 only predicate(text), and line 551 says the text "is checked when the query is encrypted"; only the tracking bullets (~1630) mention predicate!. 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 test reads_the_numbers_the_engine_reads (src/predicate.rs:738) uses stack_encrypt::json::parse_text. Drop stack-encrypt from the udeps development ignore (udeps runs --all-targets) and reword the comment.

    Source: mattpocock-skills:code-review · claude-opus-5-5


Generated by Claude Code

Comment thread packages/stack-encrypt/CHANGELOG.md Resolved
Base automatically changed from feat/stack-encrypt-typed-json-queries to next November 22, 2026 02:32
…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.
@coderdan

Copy link
Copy Markdown
Contributor Author

The three findings outside the diff from the review of ef70c7e are fixed in 3e98a8a:

  • stack-encrypt-jsonpath/src/lib.rs: the crate now carries the security lint block stack-encrypt has, with the same relaxations in tests. Clippy is clean with -D warnings.
  • docs/plans/2026-10-24-stack-encrypt-api-plan.md: the query table names predicate! beside predicate(text), and the design section says what the macro checks at compile time.
  • stack-encrypt-derive/Cargo.toml: stack-encrypt is removed from the udeps development ignore list, and the comment says why the other two stay.

@coderdan
coderdan merged commit 6ce79b3 into next Nov 22, 2026
57 checks passed
@coderdan
coderdan deleted the feat/stack-encrypt-predicate-macro branch November 22, 2026 04:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stack-encrypt: element match and jsonpath match have no typed Rust API — only the binding layer, with no compile-time checks

2 participants