From a6206a8550ac3e02b656726c79c86f6f5ae560da Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 22 Nov 2026 03:14:16 +1100 Subject: [PATCH 1/3] refactor(stack-encrypt,stack-encrypt-jsonpath): read predicates with 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 --- AGENTS.md | 2 +- packages/stack-encrypt-jsonpath/CHANGELOG.md | 15 + packages/stack-encrypt-jsonpath/src/lib.rs | 16 +- .../stack-encrypt-jsonpath/src/predicate.rs | 1069 +++++++++++++++ .../src/predicate/tests.rs | 552 ++++++++ packages/stack-encrypt/src/json/derive.rs | 6 +- packages/stack-encrypt/src/json/mod.rs | 1 - packages/stack-encrypt/src/json/predicate.rs | 1142 +++-------------- 8 files changed, 1856 insertions(+), 947 deletions(-) create mode 100644 packages/stack-encrypt-jsonpath/src/predicate.rs create mode 100644 packages/stack-encrypt-jsonpath/src/predicate/tests.rs diff --git a/AGENTS.md b/AGENTS.md index bfe434984..656a48876 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l EQL issues in this repository, never in the historical `cipherstash/encrypt-query-language` repository. Old upstream issue and PR links are provenance only. -- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index, moved out of `stack-encrypt` so the derive can check a field's declared paths at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". +- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). - `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing and the `record` wire model). A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), a final version dispatched from anywhere but `main`, and a final version while `languages/golang/go.mod` pins a `github.com/cipherstash/vitaminc/…` module at a pseudo-version (vitaminc's Go bindings have no tags, and a TEMPORARY pin on an unreleased commit must be gone before the module is tagged); a pre-release may come from a branch and may carry such a pin. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. - `e2e/*`: Cross-package end-to-end tests (package managers, supply chain, Prisma example README) diff --git a/packages/stack-encrypt-jsonpath/CHANGELOG.md b/packages/stack-encrypt-jsonpath/CHANGELOG.md index b3db90024..d418fdb74 100644 --- a/packages/stack-encrypt-jsonpath/CHANGELOG.md +++ b/packages/stack-encrypt-jsonpath/CHANGELOG.md @@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **The predicate grammar** (#1459): the SQL/JSON path predicates the JSON + index can answer, read from text into an `Expression` + (`predicate::parse`), moved out of `stack-encrypt` unchanged so that + `stack_encrypt::predicate!` reads a predicate at compile time with the + engine's own parser. A refusal is a `PredicateError`: its kind, the + construct in the grammar's words (`predicate::construct`) and the byte + offset, never text from the predicate. The rules that refuse a construct + the index cannot answer whatever the variables hold are here too + (`Comparison::refuse_not_equal_at_wildcard`, `PathAt::element_member`, + `check_filter`, `Comparison::check_filter_condition`, + `single_equality`), so the engine and the macro apply one definition. + `MAX_DEPTH` (127), the depth of a document the index reads, moves here + as the depth a predicate's paths are read to; `stack-encrypt`'s + stored-format bound is the same constant. + - **The crate** (#1687): the JSONPath subset that `stack-encrypt`'s JSON index addresses, moved out of `stack-encrypt` unchanged so that `stack-encrypt-derive` can check a field's declared paths at compile diff --git a/packages/stack-encrypt-jsonpath/src/lib.rs b/packages/stack-encrypt-jsonpath/src/lib.rs index 0b8422974..9224d2f7d 100644 --- a/packages/stack-encrypt-jsonpath/src/lib.rs +++ b/packages/stack-encrypt-jsonpath/src/lib.rs @@ -3,13 +3,15 @@ //! A [`JsonPath`] names a node of a JSON document: `$`, object members //! (`.name` or `["name"]`), array elements by position (`[2]`) and every //! element of an array (`[*]`). Nothing else: no filters, no recursive -//! descent, no slices. +//! descent, no slices. The [`predicate`] module reads the SQL/JSON path +//! predicates built from those paths, which the JSON index can answer. //! //! The index stores a value under terms derived from its path, so the //! grammar is part of the stored format. It lives in its own crate so that -//! `stack-encrypt` and `stack-encrypt-derive` read a path the same way: the -//! engine when it seals and queries a document, and the derive when it -//! checks a field's declared paths at compile time. Use it through +//! `stack-encrypt` and `stack-encrypt-derive` read a path, and a predicate, +//! the same way: the engine when it seals and queries a document, and the +//! derive when it checks a field's declared paths, or a `predicate!`, at +//! compile time. Use it through //! `stack_encrypt::json`, which re-exports these types. //! //! ``` @@ -32,5 +34,11 @@ pub mod json_string; mod path; +pub mod predicate; pub use path::{JsonPath, JsonPathError, Segment}; + +/// How deep a document the JSON index reads: no stored document nests +/// deeper, so no path the index answers is longer. A predicate's paths are +/// read to this depth and no further. +pub const MAX_DEPTH: usize = 127; diff --git a/packages/stack-encrypt-jsonpath/src/predicate.rs b/packages/stack-encrypt-jsonpath/src/predicate.rs new file mode 100644 index 000000000..3a44d5f2a --- /dev/null +++ b/packages/stack-encrypt-jsonpath/src/predicate.rs @@ -0,0 +1,1069 @@ +//! The SQL/JSON path predicates the JSON index can answer: their grammar, +//! read from text into an [`Expression`]. +//! +//! The text is PostgreSQL's SQL/JSON path language, as `jsonb_path_match` +//! takes it ([SQL/JSON path language](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-SQLJSON-PATH)), +//! restricted to predicates the JSON index's terms can answer: +//! +//! ```text +//! $.age >= $min a comparison with a variable +//! $.name == "ann" || $."first name" != null literals and a quoted key +//! !($.age < 18) && exists($.email) negation and presence +//! $.tags[*] == $tag any element equals +//! $.orders[*].total > 100 any element's field orders +//! exists($.contacts[*] ? (@.relationship == $r && @.calls > 5)) +//! one element satisfies both +//! ``` +//! +//! `stack-encrypt` compiles an [`Expression`] onto the inputs of its JSON +//! operators when a query is encrypted, and `stack-encrypt-derive`'s +//! `predicate!` reads the same text when a program compiles. Both read it +//! with [`parse`], so the two cannot disagree about what a predicate says. +//! The rules that refuse a construct the index cannot answer, and that +//! depend on neither the variables' values nor the field's options, are +//! here too ([`Comparison::refuse_not_equal_at_wildcard`], +//! [`PathAt::element_member`], [`check_filter`], +//! [`Comparison::check_filter_condition`]), so each is written once. +//! +//! A refusal names a construct in the grammar's words ([`construct`]) and +//! an offset, never a slice of the text: a key name or a value in it can be +//! customer data. The tree holds offsets into the text, the key names in +//! [`JsonPath`]s, which wipe them, and a variable's name in storage that is +//! wiped. +//! +//! ``` +//! use stack_encrypt_jsonpath::predicate::{self, Expression, Operator}; +//! +//! let Expression::Compare(comparison) = predicate::parse("$.age >= $min")? else { +//! unreachable!("one comparison") +//! }; +//! assert_eq!(comparison.path.path.to_string(), "$.age"); +//! assert_eq!(comparison.operator, Operator::GreaterOrEqual); +//! assert_eq!(comparison.value.variable(), Some("min")); +//! +//! let refused = predicate::parse("$.age like_regex \"^4\"").unwrap_err(); +//! assert_eq!(refused.construct, predicate::construct::LIKE_REGEX); +//! assert_eq!(refused.at, 6); +//! # Ok::<(), predicate::PredicateError>(()) +//! ``` + +use zeroize::Zeroizing; + +use crate::json_string::{string_end, string_text}; +use crate::{JsonPath, Segment, MAX_DEPTH}; + +/// How deeply a predicate may nest parentheses, `!` and `exists`. The +/// parser descends once per level, so the bound keeps a hostile predicate +/// from overflowing the stack; the SQL evaluates the compiled tree by +/// recursion too. +pub const MAX_NESTING: usize = 32; + +/// The constructs a refusal names, in the grammar's own words. +pub mod construct { + /// Text the grammar does not read. + pub const TEXT: &str = "text the grammar does not read"; + /// Text after a whole predicate. + pub const TRAILING: &str = "text after the predicate"; + /// A string literal that is not JSON string text. + pub const STRING: &str = "a string literal"; + /// A numeric literal that is not JSON number text. + pub const NUMBER: &str = "a numeric literal"; + /// `strict` or `lax`. + pub const MODE: &str = "a mode (`strict`, `lax`)"; + /// `+`, `-`, `*`, `/` or `%`. + pub const ARITHMETIC: &str = "arithmetic (`+`, `-`, `*`, `/`, `%`)"; + /// `like_regex`. + pub const LIKE_REGEX: &str = "`like_regex`"; + /// `starts with`. + pub const STARTS_WITH: &str = "`starts with`"; + /// `is unknown`. + pub const IS_UNKNOWN: &str = "`is unknown`"; + /// A method call on a path. + pub const METHOD: &str = "a method (`.name()`)"; + /// Every member of an object. + pub const ANY_MEMBER: &str = "`.*`"; + /// Every node at any depth. + pub const ANY_DEPTH: &str = "`.**`"; + /// An array slice or a list of positions. + pub const SLICE: &str = "an array slice or list (`[a to b]`, `[a, b]`)"; + /// `last`. + pub const LAST: &str = "`last`"; + /// A subscript the grammar reads and the index cannot answer. + pub const SUBSCRIPT: &str = "a subscript other than `[*]`"; + /// One array element, by position. + pub const POSITION: &str = "a position (`[2]`)"; + /// `@` where there is no current element. + pub const AT_OUTSIDE: &str = "`@` outside a filter"; + /// A path from the root inside a filter. + pub const DOLLAR_IN_FILTER: &str = "a `$` path in a filter"; + /// A step after a variable. + pub const VARIABLE_PATH: &str = "an accessor on a variable"; + /// A comparison with a path on both sides. + pub const TWO_PATHS: &str = "a comparison of two paths"; + /// A comparison with a value on both sides. + pub const TWO_VALUES: &str = "a comparison of two values"; + /// A path or a value standing alone. + pub const ALONE: &str = "an operand with no comparison"; + /// A filter anywhere but inside `exists`. + pub const FILTER_OUTSIDE: &str = "a filter outside `exists`"; + /// A step after a filter. + pub const AFTER_FILTER: &str = "an accessor after a filter"; + /// A comparison inside `exists`. + pub const IN_EXISTS: &str = "a comparison inside `exists`"; + /// `||` inside a filter. + pub const OR_IN_FILTER: &str = "`||` in a filter"; + /// `!` inside a filter. + pub const NOT_IN_FILTER: &str = "`!` in a filter"; + /// `!=` inside a filter. + pub const NOT_EQUAL_IN_FILTER: &str = "`!=` in a filter"; + /// `exists` inside a filter. + pub const EXISTS_IN_FILTER: &str = "`exists` in a filter"; + /// An ordering of the elements of an array, rather than of their + /// members. + pub const ELEMENTS_THEMSELVES: &str = "an ordering of an array's elements themselves"; + /// A condition on `@` itself beside another condition. + pub const WHOLE_ELEMENT: &str = "`@` beside another condition"; + /// A filter on a path that names no array's elements. + pub const FILTER_WILDCARD: &str = "a filter on a path with no wildcard"; + /// A wildcard in the path a filter's condition names. + pub const MEMBER_WILDCARD: &str = "a wildcard in a filter's member"; + /// `!=` at a path with a wildcard. + pub const NOT_EQUAL: &str = "`!=` at a path with a wildcard"; + /// A value the comparison cannot take. + pub const VALUE: &str = "a value"; + /// A variable. + pub const VARIABLE: &str = "a variable"; + /// Nesting past the limits. + pub const NESTING: &str = "nesting"; +} + +/// What kind of refusal a [`PredicateError`] is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PredicateErrorKind { + /// The text is not predicate text. + Syntax, + /// The text uses a construct the index cannot answer. + Unsupported, + /// The text nests parentheses, `!` or `exists`, or a path, too deep. + TooDeep, + /// A path names an array position (`[2]`), which the index reads as + /// the wildcard. + Position, + /// `!=` at a path with a wildcard: whether some element differs, which + /// containment cannot say. + NotEqualAtWildcard, + /// A filter on a path with no wildcard: there are no elements to + /// filter. + FilterWithoutWildcard, + /// A wildcard in a filter's member: a condition holds of one element's + /// member, not of an array inside it. + MemberWildcard, +} + +/// Why a predicate is refused: the kind of refusal, the construct, and the +/// byte offset in the text where the construct starts. Never text from the +/// predicate, which can name customer data. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{construct} at byte {at}")] +pub struct PredicateError { + /// The kind of refusal. + pub kind: PredicateErrorKind, + /// The construct refused, in the grammar's words: one of [`construct`]. + pub construct: &'static str, + /// The byte offset in the text where the construct starts. + pub at: usize, +} + +impl PredicateError { + fn syntax(construct: &'static str, at: usize) -> Self { + Self { + kind: PredicateErrorKind::Syntax, + construct, + at, + } + } + + fn unsupported(construct: &'static str, at: usize) -> Self { + Self { + kind: PredicateErrorKind::Unsupported, + construct, + at, + } + } + + fn too_deep(at: usize) -> Self { + Self { + kind: PredicateErrorKind::TooDeep, + construct: construct::NESTING, + at, + } + } +} + +/// A comparison operator, as the text spells it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Operator { + /// `==`. + Equal, + /// `!=` or `<>`. + NotEqual, + /// `<`. + Less, + /// `<=`. + LessOrEqual, + /// `>`. + Greater, + /// `>=`. + GreaterOrEqual, +} + +impl Operator { + /// The operator with its operands swapped: `1 < $.a` is `$.a > 1`. + pub fn flipped(self) -> Self { + match self { + Operator::Less => Operator::Greater, + Operator::LessOrEqual => Operator::GreaterOrEqual, + Operator::Greater => Operator::Less, + Operator::GreaterOrEqual => Operator::LessOrEqual, + same => same, + } + } +} + +/// A path in the text: `$` or `@` and the steps after it, and where it +/// starts. +#[derive(Debug)] +pub struct PathAt { + /// The path. A path from `@` holds the steps after the current element. + pub path: JsonPath, + /// The byte offset of its `$` or `@`. + pub at: usize, +} + +/// A value in the text: a literal, by its bytes, or a variable, by name. +#[derive(Debug, PartialEq, Eq)] +pub enum ValueAt { + /// `"…"`, a number, `true`, `false` or `null`: the literal's bytes, + /// `start..end`, which are JSON text. + Literal { + /// The offset of its first byte. + start: usize, + /// The offset after its last byte. + end: usize, + }, + /// `$name` or `$"name"`. + Variable { + /// The name, decoded, wiped when it drops. + name: Zeroizing, + /// The offset of its `$`. + at: usize, + }, +} + +/// What a literal is, by the JSON type its text writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LiteralKind { + /// `"…"`. + String, + /// A number. + Number, + /// `true` or `false`. + Boolean, + /// `null`. + Null, +} + +impl ValueAt { + /// The offset where the value starts. + pub fn at(&self) -> usize { + match self { + ValueAt::Literal { start, .. } => *start, + ValueAt::Variable { at, .. } => *at, + } + } + + /// The variable's name, for a variable. + pub fn variable(&self) -> Option<&str> { + match self { + ValueAt::Variable { name, .. } => Some(name.as_str()), + ValueAt::Literal { .. } => None, + } + } + + /// What a literal is, read from `text`, the predicate the value was + /// parsed from; `None` for a variable. The parser reads a literal only + /// when it starts as one of these. + pub fn literal_kind(&self, text: &str) -> Option { + let ValueAt::Literal { start, .. } = self else { + return None; + }; + Some(match text.as_bytes().get(*start) { + Some(b'"') => LiteralKind::String, + Some(b't' | b'f') => LiteralKind::Boolean, + Some(b'n') => LiteralKind::Null, + _ => LiteralKind::Number, + }) + } + + /// The literal's text, read from `text`, the predicate the value was + /// parsed from; `None` for a variable. + pub fn literal_text<'t>(&self, text: &'t str) -> Option<&'t str> { + match self { + ValueAt::Literal { start, end } => text.get(*start..*end), + ValueAt::Variable { .. } => None, + } + } +} + +/// A comparison of a path with a value, the path on the left. +#[derive(Debug)] +pub struct Comparison { + /// The path compared. + pub path: PathAt, + /// The operator, turned round if the text wrote the value first. + pub operator: Operator, + /// The value compared with. + pub value: ValueAt, + /// Where the operator is. + pub at: usize, +} + +impl Comparison { + /// `!=` at a path with a wildcard is true when some element differs, + /// which containment cannot say: refused at the operator. + /// + /// # Errors + /// + /// [`PredicateErrorKind::NotEqualAtWildcard`] for `!=` at a path with + /// a wildcard. + pub fn refuse_not_equal_at_wildcard(&self) -> Result<(), PredicateError> { + if self.operator == Operator::NotEqual && !self.path.path.is_positional() { + return Err(PredicateError { + kind: PredicateErrorKind::NotEqualAtWildcard, + construct: construct::NOT_EQUAL, + at: self.at, + }); + } + Ok(()) + } + + /// One condition of a filter with more than one, which becomes one + /// member of an element-scoped predicate: an ordering or an equality on + /// a member below the element. + /// + /// # Errors + /// + /// [`PredicateErrorKind::Unsupported`] for `!=`, and for a condition on + /// `@` itself, which names no member. + pub fn check_filter_condition(&self) -> Result<(), PredicateError> { + if self.operator == Operator::NotEqual { + return Err(PredicateError::unsupported( + construct::NOT_EQUAL_IN_FILTER, + self.at, + )); + } + if self.path.path.segments().is_empty() { + let construct = if self.operator == Operator::Equal { + construct::WHOLE_ELEMENT + } else { + construct::ELEMENTS_THEMSELVES + }; + return Err(PredicateError::unsupported(construct, self.path.at)); + } + Ok(()) + } +} + +impl PathAt { + /// The array and the member of an ordering at a path with a wildcard: + /// the path up to its last wildcard, and the steps after it. + /// `operator_at` is where the ordering's operator is. + /// + /// # Errors + /// + /// [`PredicateErrorKind::Unsupported`] at the operator when no step + /// follows the last wildcard: an ordering of the elements themselves. + pub fn element_member( + &self, + operator_at: usize, + ) -> Result<(JsonPath, JsonPath), PredicateError> { + let steps = self.path.segments(); + let last = steps + .iter() + .rposition(|segment| *segment == Segment::Wildcard) + .unwrap_or_default(); + // Each half is copied straight into a path, which wipes its keys, + // before anything can refuse. + let (base, member) = steps.split_at(last + 1); + let (base, member) = ( + JsonPath::from(base.to_vec()), + JsonPath::from(member.to_vec()), + ); + if member.segments().is_empty() { + return Err(PredicateError::unsupported( + construct::ELEMENTS_THEMSELVES, + operator_at, + )); + } + Ok((base, member)) + } +} + +/// The checks of `exists(path ? (conditions))` that hold whatever the +/// conditions compare: the path names an array's elements, every condition +/// names a member below one element, and no member's full path is deeper +/// than a document. +/// +/// # Errors +/// +/// [`PredicateErrorKind::FilterWithoutWildcard`] at the path for a path +/// with no wildcard; [`PredicateErrorKind::TooDeep`] at the path for a +/// member whose full path is deeper than [`MAX_DEPTH`]; +/// [`PredicateErrorKind::MemberWildcard`] at a condition's path for a +/// member with a wildcard. +pub fn check_filter(path: &PathAt, conditions: &[Comparison]) -> Result<(), PredicateError> { + if path.path.is_positional() { + return Err(PredicateError { + kind: PredicateErrorKind::FilterWithoutWildcard, + construct: construct::FILTER_WILDCARD, + at: path.at, + }); + } + for condition in conditions { + if path.path.segments().len() + condition.path.path.segments().len() > MAX_DEPTH { + return Err(PredicateError::too_deep(path.at)); + } + if !condition.path.path.is_positional() { + return Err(PredicateError { + kind: PredicateErrorKind::MemberWildcard, + construct: construct::MEMBER_WILDCARD, + at: condition.path.at, + }); + } + } + Ok(()) +} + +/// The one condition of a filter that is a single equality, which is +/// containment at the condition's full path rather than an element-scoped +/// predicate. +pub fn single_equality(conditions: &[Comparison]) -> Option<&Comparison> { + match conditions { + [only] if only.operator == Operator::Equal => Some(only), + _ => None, + } +} + +/// A predicate as the text writes it. +#[derive(Debug)] +pub enum Expression { + /// Every term holds. + And(Vec), + /// Some term holds. + Or(Vec), + /// The term does not hold. + Not(Box), + /// A path compared with a value. + Compare(Comparison), + /// `exists(path)`, or `exists(path ? (conditions))`, each condition a + /// comparison of a path from `@`. + Exists { + /// The path whose node, or whose elements, exist. + path: PathAt, + /// The conditions one element satisfies together. + filter: Option>, + }, +} + +/// One side of a comparison. +#[derive(Debug)] +enum Side { + /// A path from `$`. + Root(PathAt), + /// A path from `@`, inside a filter. + Current(PathAt), + Value(ValueAt), +} + +/// The characters that end a name and are not a name's: what +/// PostgreSQL's jsonpath scanner reads as punctuation. +fn special(c: char) -> bool { + c.is_whitespace() || "?%$.[]{}()|&!=<>@#,*:-+/\\\"'".contains(c) +} + +/// A recursive descent over the text, holding the offset it has read to. +struct Parser<'t> { + text: &'t str, + pos: usize, + depth: usize, +} + +impl<'t> Parser<'t> { + fn rest(&self) -> &'t str { + &self.text[self.pos..] + } + + /// Skip whitespace and `/* … */` comments. + fn space(&mut self) -> Result<(), PredicateError> { + loop { + let rest = self.rest(); + let trimmed = rest.trim_start(); + self.pos += rest.len() - trimmed.len(); + if let Some(comment) = trimmed.strip_prefix("/*") { + let Some(end) = comment.find("*/") else { + return Err(PredicateError::syntax(construct::TEXT, self.pos)); + }; + self.pos += 2 + end + 2; + } else { + return Ok(()); + } + } + } + + /// The next character after any space, unread. + fn peek(&mut self) -> Result, PredicateError> { + self.space()?; + Ok(self.rest().chars().next()) + } + + /// Read `token` if it is next. + fn eat(&mut self, token: &str) -> Result { + self.space()?; + if self.rest().starts_with(token) { + self.pos += token.len(); + Ok(true) + } else { + Ok(false) + } + } + + fn expect(&mut self, token: &str) -> Result<(), PredicateError> { + if self.eat(token)? { + Ok(()) + } else { + Err(PredicateError::syntax(construct::TEXT, self.pos)) + } + } + + /// The name at the cursor, unread: a run of characters that are not + /// punctuation, not starting with a digit. + fn word(&mut self) -> Result, PredicateError> { + self.space()?; + let rest = self.rest(); + if rest.starts_with(|c: char| c.is_ascii_digit()) { + return Ok(None); + } + let end = rest.find(special).unwrap_or(rest.len()); + Ok((end > 0).then(|| &rest[..end])) + } + + /// One more level of nesting, refused past [`MAX_NESTING`]. + fn descend(&mut self) -> Result<(), PredicateError> { + self.depth += 1; + if self.depth > MAX_NESTING { + return Err(PredicateError::too_deep(self.pos)); + } + Ok(()) + } + + fn ascend(&mut self) { + self.depth -= 1; + } + + /// `or := and ('||' and)*`. + fn or(&mut self) -> Result { + let mut terms = vec![self.and()?]; + while self.eat("||")? { + terms.push(self.and()?); + } + Ok(if terms.len() == 1 { + terms.remove(0) + } else { + Expression::Or(terms) + }) + } + + /// `and := unary ('&&' unary)*`. + fn and(&mut self) -> Result { + let mut terms = vec![self.unary()?]; + while self.eat("&&")? { + terms.push(self.unary()?); + } + Ok(if terms.len() == 1 { + terms.remove(0) + } else { + Expression::And(terms) + }) + } + + /// `unary := '!' primary | primary`. As in PostgreSQL, `!` takes a + /// parenthesised predicate or `exists`, not a bare comparison. + fn unary(&mut self) -> Result { + self.space()?; + if self.rest().starts_with('!') && !self.rest().starts_with("!=") { + self.pos += 1; + self.descend()?; + let at = self.pos; + let negated = match self.peek()? { + Some('(') => self.primary()?, + _ if self.keyword("exists")? => self.primary()?, + _ => return Err(PredicateError::syntax(construct::TEXT, at)), + }; + self.ascend(); + return Ok(Expression::Not(Box::new(negated))); + } + self.primary() + } + + /// Whether the word at the cursor is `keyword`, in any case, as + /// PostgreSQL reads `exists`. + fn keyword(&mut self, keyword: &str) -> Result { + Ok(self + .word()? + .is_some_and(|word| word.eq_ignore_ascii_case(keyword))) + } + + /// `primary := '(' or ')' | 'exists' '(' path filter? ')' | comparison`. + fn primary(&mut self) -> Result { + if self.eat("(")? { + self.descend()?; + let inner = self.or()?; + self.expect(")")?; + self.ascend(); + return Ok(inner); + } + if self.keyword("exists")? { + self.pos += "exists".len(); + if self.eat("(")? { + return self.exists(); + } + return Err(PredicateError::syntax(construct::TEXT, self.pos)); + } + let comparison = self.comparison(false)?; + Ok(Expression::Compare(comparison)) + } + + /// The inside of `exists(…)`, the `(` read. + fn exists(&mut self) -> Result { + self.descend()?; + self.space()?; + let at = self.pos; + let path = match self.operand(false)? { + Side::Root(path) => path, + Side::Current(_) => return Err(PredicateError::unsupported(construct::AT_OUTSIDE, at)), + Side::Value(_) => return Err(PredicateError::syntax(construct::TEXT, at)), + }; + let filter = if self.eat("?")? { + self.expect("(")?; + self.descend()?; + let conditions = self.conditions()?; + self.expect(")")?; + self.ascend(); + let at = self.pos; + match self.peek()? { + Some('.' | '[') => { + return Err(PredicateError::unsupported(construct::AFTER_FILTER, at)) + } + Some('?') => { + return Err(PredicateError::unsupported(construct::FILTER_OUTSIDE, at)) + } + _ => {} + } + Some(conditions) + } else { + None + }; + if let Some(refusal) = self.after_operand()? { + return Err(refusal); + } + self.space()?; + if self.op()?.is_some() { + return Err(PredicateError::unsupported(construct::IN_EXISTS, at)); + } + self.expect(")")?; + self.ascend(); + Ok(Expression::Exists { path, filter }) + } + + /// A filter's conditions: comparisons of a path from `@`, joined by + /// `&&`, with parentheses. + fn conditions(&mut self) -> Result, PredicateError> { + let mut conditions = Vec::new(); + loop { + self.space()?; + let at = self.pos; + if self.rest().starts_with('!') && !self.rest().starts_with("!=") { + return Err(PredicateError::unsupported(construct::NOT_IN_FILTER, at)); + } + if self.keyword("exists")? { + return Err(PredicateError::unsupported(construct::EXISTS_IN_FILTER, at)); + } + if self.eat("(")? { + self.descend()?; + conditions.extend(self.conditions()?); + self.expect(")")?; + self.ascend(); + } else { + conditions.push(self.comparison(true)?); + } + self.space()?; + if self.rest().starts_with("||") { + return Err(PredicateError::unsupported( + construct::OR_IN_FILTER, + self.pos, + )); + } + if !self.eat("&&")? { + return Ok(conditions); + } + } + } + + /// A comparison operator at the cursor, read, and where it was. + fn op(&mut self) -> Result, PredicateError> { + self.space()?; + let at = self.pos; + let rest = self.rest(); + let (op, len) = if rest.starts_with("==") { + (Operator::Equal, 2) + } else if rest.starts_with("!=") || rest.starts_with("<>") { + (Operator::NotEqual, 2) + } else if rest.starts_with("<=") { + (Operator::LessOrEqual, 2) + } else if rest.starts_with(">=") { + (Operator::GreaterOrEqual, 2) + } else if rest.starts_with('<') { + (Operator::Less, 1) + } else if rest.starts_with('>') { + (Operator::Greater, 1) + } else { + return Ok(None); + }; + self.pos += len; + Ok(Some((op, at))) + } + + /// The construct at the cursor that follows an operand and that the + /// index cannot answer, if one is there. + fn after_operand(&mut self) -> Result, PredicateError> { + self.space()?; + let at = self.pos; + let rest = self.rest(); + if rest.starts_with(['+', '-', '*', '/', '%']) { + return Ok(Some(PredicateError::unsupported(construct::ARITHMETIC, at))); + } + if rest.starts_with('?') { + return Ok(Some(PredicateError::unsupported( + construct::FILTER_OUTSIDE, + at, + ))); + } + let word = self.word()?.unwrap_or_default(); + Ok(if word.eq_ignore_ascii_case("like_regex") { + Some(PredicateError::unsupported(construct::LIKE_REGEX, at)) + } else if word.eq_ignore_ascii_case("starts") { + Some(PredicateError::unsupported(construct::STARTS_WITH, at)) + } else if word.eq_ignore_ascii_case("is") { + Some(PredicateError::unsupported(construct::IS_UNKNOWN, at)) + } else { + None + }) + } + + /// `comparison := operand op operand`, one side a path and the other a + /// value; in a filter the path is from `@`. + fn comparison(&mut self, in_filter: bool) -> Result { + self.space()?; + let left = self.operand(in_filter)?; + if let Some(refusal) = self.after_operand()? { + return Err(refusal); + } + let Some((op, at)) = self.op()? else { + self.space()?; + let at = self.pos; + let ends = self.rest().is_empty() || self.rest().starts_with([')', '&', '|']); + return Err(if ends { + PredicateError::unsupported(construct::ALONE, at) + } else { + PredicateError::syntax(construct::TEXT, at) + }); + }; + if in_filter && op == Operator::NotEqual { + return Err(PredicateError::unsupported( + construct::NOT_EQUAL_IN_FILTER, + at, + )); + } + self.space()?; + let right = self.operand(in_filter)?; + if let Some(refusal) = self.after_operand()? { + return Err(refusal); + } + let (path, operator, value) = match (left, right) { + (Side::Root(path) | Side::Current(path), Side::Value(value)) => (path, op, value), + (Side::Value(value), Side::Root(path) | Side::Current(path)) => { + (path, op.flipped(), value) + } + (Side::Value(_), Side::Value(_)) => { + return Err(PredicateError::unsupported(construct::TWO_VALUES, at)) + } + _ => return Err(PredicateError::unsupported(construct::TWO_PATHS, at)), + }; + Ok(Comparison { + path, + operator, + value, + at, + }) + } + + /// A path, a variable or a literal. In a filter a path is from `@`; + /// outside one, from `$`. + fn operand(&mut self, in_filter: bool) -> Result { + self.space()?; + let at = self.pos; + let rest = self.rest(); + let Some(first) = rest.chars().next() else { + return Err(PredicateError::syntax(construct::TEXT, at)); + }; + match first { + '$' => { + let after = &rest[1..]; + if after.starts_with('"') { + let (name, len) = self.string_at(at + 1)?; + self.pos = at + 1 + len; + return self.variable(name, at); + } + if after.starts_with(|c: char| !special(c)) { + self.pos += 1; + let Some(name) = self.word()? else { + return Err(PredicateError::syntax(construct::TEXT, self.pos)); + }; + self.pos += name.len(); + return self.variable(Zeroizing::new(name.to_owned()), at); + } + if in_filter { + return Err(PredicateError::unsupported(construct::DOLLAR_IN_FILTER, at)); + } + self.pos += 1; + Ok(Side::Root(self.steps(at)?)) + } + '@' => { + if !in_filter { + return Err(PredicateError::unsupported(construct::AT_OUTSIDE, at)); + } + self.pos += 1; + Ok(Side::Current(self.steps(at)?)) + } + '"' => { + let (_, len) = self.string_at(at)?; + self.pos += len; + Ok(Side::Value(ValueAt::Literal { + start: at, + end: at + len, + })) + } + '-' | '0'..='9' => { + let len = number_len(rest).ok_or(PredicateError::syntax(construct::NUMBER, at))?; + self.pos += len; + Ok(Side::Value(ValueAt::Literal { + start: at, + end: at + len, + })) + } + '+' => Err(PredicateError::unsupported(construct::ARITHMETIC, at)), + _ => match self.word()? { + Some(word @ ("true" | "false" | "null")) => { + self.pos += word.len(); + Ok(Side::Value(ValueAt::Literal { + start: at, + end: at + word.len(), + })) + } + Some(word) if word.eq_ignore_ascii_case("last") => { + Err(PredicateError::unsupported(construct::LAST, at)) + } + Some(word) if is_mode(word) => { + Err(PredicateError::unsupported(construct::MODE, at)) + } + _ => Err(PredicateError::syntax(construct::TEXT, at)), + }, + } + } + + /// A variable named `name`, which takes no accessor. The name is the + /// caller's text, and is wiped when the predicate is dropped. + fn variable(&mut self, name: Zeroizing, at: usize) -> Result { + self.space()?; + if self.rest().starts_with(['.', '[']) { + return Err(PredicateError::unsupported( + construct::VARIABLE_PATH, + self.pos, + )); + } + Ok(Side::Value(ValueAt::Variable { name, at })) + } + + /// The JSON string at `at`, decoded, and its length in the text. Its + /// escapes are JSON's. The decoded text is wiped when it drops: a + /// literal's is a value, read only to check it, and a key's is moved + /// into its path, which wipes it. + fn string_at(&self, at: usize) -> Result<(Zeroizing, usize), PredicateError> { + let text = &self.text.as_bytes()[at..]; + string_end(text) + .and_then(|end| Some((string_text(&text[..=end])?, end + 1))) + .ok_or_else(|| PredicateError::syntax(construct::STRING, at)) + } + + /// The steps after `$` or `@`: `.name`, `."name"`, `[*]`, and the + /// accessors refused by name. A step past a document's depth is + /// refused before it is read, so the path held is never deeper than + /// [`MAX_DEPTH`]. + /// + /// The steps are read into the path itself, so a refusal part way + /// drops a path, which wipes the keys already read. + fn steps(&mut self, start: usize) -> Result { + let mut path = JsonPath::root(); + loop { + self.space()?; + let at = self.pos; + let rest = self.rest(); + if !rest.starts_with(['.', '[']) { + break; + } + if path.segments().len() >= MAX_DEPTH { + return Err(PredicateError::too_deep(start)); + } + if let Some(after) = rest.strip_prefix('.') { + let after_space = after.trim_start(); + let gap = after.len() - after_space.len(); + if after_space.starts_with("**") { + return Err(PredicateError::unsupported(construct::ANY_DEPTH, at)); + } + if after_space.starts_with('*') { + return Err(PredicateError::unsupported(construct::ANY_MEMBER, at)); + } + if after_space.starts_with('"') { + let (mut key, len) = self.string_at(at + 1 + gap)?; + self.pos = at + 1 + gap + len; + path.push(Segment::Key(std::mem::take(&mut *key))); + continue; + } + self.pos = at + 1; + let Some(name) = self.word()? else { + return Err(PredicateError::syntax(construct::TEXT, self.pos)); + }; + self.pos += name.len(); + if self.peek()? == Some('(') { + return Err(PredicateError::unsupported(construct::METHOD, at)); + } + path.push(Segment::Key(name.to_owned())); + } else { + self.pos += 1; + self.space()?; + if self.eat("*")? { + self.expect("]")?; + path.push(Segment::Wildcard); + } else if self.rest().starts_with(|c: char| c.is_ascii_digit()) { + let digits = self + .rest() + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(self.rest().len()); + self.pos += digits; + self.space()?; + if self.rest().starts_with(']') { + return Err(PredicateError { + kind: PredicateErrorKind::Position, + construct: construct::POSITION, + at, + }); + } + return Err(PredicateError::unsupported(construct::SLICE, at)); + } else if self.keyword("last")? { + return Err(PredicateError::unsupported(construct::LAST, at)); + } else { + return Err(PredicateError::unsupported(construct::SUBSCRIPT, at)); + } + } + } + Ok(PathAt { path, at: start }) + } +} + +/// The length of the JSON number at the front of `text`: +/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`, followed by +/// something that does not continue it. `None` for text that is not one. +fn number_len(text: &str) -> Option { + let bytes = text.as_bytes(); + let mut i = usize::from(bytes.first() == Some(&b'-')); + let digits = |from: usize| { + bytes[from..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count() + }; + match bytes.get(i) { + Some(b'0') => i += 1, + Some(b'1'..=b'9') => i += digits(i), + _ => return None, + } + if bytes.get(i) == Some(&b'.') { + let fraction = digits(i + 1); + if fraction == 0 { + return None; + } + i += 1 + fraction; + } + if matches!(bytes.get(i), Some(b'e' | b'E')) { + let mut j = i + 1; + if matches!(bytes.get(j), Some(b'+' | b'-')) { + j += 1; + } + let exponent = digits(j); + if exponent == 0 { + return None; + } + i = j + exponent; + } + match text[i..].chars().next() { + Some(c) if !special(c) || c == '.' => None, + _ => Some(i), + } +} + +/// Whether `word` is a mode word, `strict` or `lax`, in any case. +fn is_mode(word: &str) -> bool { + word.eq_ignore_ascii_case("strict") || word.eq_ignore_ascii_case("lax") +} + +/// Parse a predicate's text. +/// +/// # Errors +/// +/// A [`PredicateError`] for text the grammar does not read +/// ([`PredicateErrorKind::Syntax`]) or a construct it reads and the index +/// cannot answer ([`PredicateErrorKind::Unsupported`], +/// [`PredicateErrorKind::TooDeep`], [`PredicateErrorKind::Position`]), at +/// the byte where it starts. +pub fn parse(text: &str) -> Result { + let mut parser = Parser { + text, + pos: 0, + depth: 0, + }; + parser.space()?; + let at = parser.pos; + if parser.word()?.is_some_and(is_mode) { + return Err(PredicateError::unsupported(construct::MODE, at)); + } + let expression = parser.or()?; + parser.space()?; + if !parser.rest().is_empty() { + return Err(PredicateError::syntax(construct::TRAILING, parser.pos)); + } + Ok(expression) +} + +#[cfg(test)] +mod tests; diff --git a/packages/stack-encrypt-jsonpath/src/predicate/tests.rs b/packages/stack-encrypt-jsonpath/src/predicate/tests.rs new file mode 100644 index 000000000..aee26ef11 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/src/predicate/tests.rs @@ -0,0 +1,552 @@ +use super::*; + +/// The tree written out: each comparison as `path op value`, a literal as +/// its text and a variable as `$name`. +fn written(text: &str, expression: &Expression) -> String { + let list = |terms: &[Expression]| { + terms + .iter() + .map(|term| written(text, term)) + .collect::>() + .join(", ") + }; + match expression { + Expression::And(terms) => format!("and({})", list(terms)), + Expression::Or(terms) => format!("or({})", list(terms)), + Expression::Not(term) => format!("not({})", written(text, term)), + Expression::Compare(comparison) => compared(text, comparison), + Expression::Exists { path, filter: None } => format!("exists({})", path.path), + Expression::Exists { + path, + filter: Some(conditions), + } => format!( + "exists({} ? {})", + path.path, + conditions + .iter() + .map(|condition| compared(text, condition)) + .collect::>() + .join(" && ") + ), + } +} + +fn compared(text: &str, comparison: &Comparison) -> String { + let value = match &comparison.value { + ValueAt::Literal { start, end } => text[*start..*end].to_owned(), + ValueAt::Variable { name, .. } => format!("${}", name.as_str()), + }; + format!( + "{} {:?}@{} {value}", + comparison.path.path, comparison.operator, comparison.at + ) +} + +fn parses_to(text: &str, want: &str) { + let expression = parse(text).unwrap_or_else(|error| panic!("{text}: {error}")); + assert_eq!(written(text, &expression), want, "{text}"); +} + +fn refused(text: &str) -> (PredicateErrorKind, &'static str, usize) { + match parse(text) { + Err(error) => (error.kind, error.construct, error.at), + Ok(expression) => panic!("{text}: parsed to {}", written(text, &expression)), + } +} + +mod given_the_grammar_it_reads { + use super::*; + + /// Each operator is read, a value on the left turns the comparison + /// round, and `<>` is `!=`. + #[test] + fn reads_each_operator_either_way_round() { + for (text, want) in [ + ("$.a == 1", "$.a Equal@4 1"), + ("$.a != 1", "$.a NotEqual@4 1"), + ("$.a <> 1", "$.a NotEqual@4 1"), + ("$.a < 1", "$.a Less@4 1"), + ("$.a <= 1", "$.a LessOrEqual@4 1"), + ("$.a > 1", "$.a Greater@4 1"), + ("$.a >= 1", "$.a GreaterOrEqual@4 1"), + ("1 < $.a", "$.a Greater@2 1"), + ("1 <= $.a", "$.a GreaterOrEqual@2 1"), + ("1 > $.a", "$.a Less@2 1"), + ("1 >= $.a", "$.a LessOrEqual@2 1"), + ("1 == $.a", "$.a Equal@2 1"), + ("1 != $.a", "$.a NotEqual@2 1"), + ] { + parses_to(text, want); + } + } + + /// Literals, variables (bare and quoted), quoted keys, keys that are + /// words of the grammar, space and comments read as PostgreSQL reads + /// them. + #[test] + fn reads_values_and_paths_as_postgres_reads_them() { + for (text, want) in [ + (r#"$.name == "Ann""#, r#"$.name Equal@7 "Ann""#), + ("$.ok == true", "$.ok Equal@5 true"), + ("$.ok == false", "$.ok Equal@5 false"), + ("$.gone == null", "$.gone Equal@7 null"), + ("$.a == -1.5e3", "$.a Equal@4 -1.5e3"), + ("$.a == 10.125E+2", "$.a Equal@4 10.125E+2"), + ("$.a == 0", "$.a Equal@4 0"), + ("$.a == $min", "$.a Equal@4 $min"), + (r#"$.a == $"first name""#, "$.a Equal@4 $first name"), + (r#"$."first name" == 1"#, "$.first name Equal@15 1"), + (r#"$. "a b".c == 1"#, "$.a b.c Equal@12 1"), + (r#"$."a\"b" == 1"#, r#"$["a\"b"] Equal@9 1"#), + ("$.exists == 1", "$.exists Equal@9 1"), + ("$.true == 1", "$.true Equal@7 1"), + ("$ . a [ * ] . b == 1", "$.a[*].b Equal@16 1"), + (" $.a==1 ", "$.a Equal@5 1"), + ("$.a == 1 /* why */", "$.a Equal@4 1"), + ("/* a */ $.a == 1", "$.a Equal@12 1"), + ("$ == 1", "$ Equal@2 1"), + ("$.a == 1 && $.b == 2", "and($.a Equal@4 1, $.b Equal@16 2)"), + ] { + parses_to(text, want); + } + } + + /// `&&` binds tighter than `||`, parentheses group, `!` takes a group + /// or `exists`, and `exists` is read in any case, with or without a + /// filter. + #[test] + fn keeps_the_boolean_structure() { + for (text, want) in [ + ( + "$.a == 1 && $.b == 2 || $.c == 3", + "or(and($.a Equal@4 1, $.b Equal@16 2), $.c Equal@28 3)", + ), + ( + "$.a == 1 && ($.b == 2 || $.c == 3)", + "and($.a Equal@4 1, or($.b Equal@17 2, $.c Equal@29 3))", + ), + ("!($.a == 1)", "not($.a Equal@6 1)"), + ("! exists($.a)", "not(exists($.a))"), + ("((($.a == 1)))", "$.a Equal@7 1"), + ("EXISTS($.a) || Exists($.b)", "or(exists($.a), exists($.b))"), + ( + "exists($.c[*] ? (@.r == $r && @.n > 5))", + "exists($.c[*] ? $.r Equal@21 $r && $.n Greater@34 5)", + ), + ( + "exists($.c[*] ? ((@.n >= 1) && (@.n < 9)))", + "exists($.c[*] ? $.n GreaterOrEqual@22 1 && $.n Less@36 9)", + ), + ("exists($.t[*] ? (1 == @))", "exists($.t[*] ? $ Equal@19 1)"), + ] { + parses_to(text, want); + } + } + + /// The nesting limit is read, and nesting is depth, not count. + #[test] + fn reads_nesting_up_to_the_limit() { + let at_limit = format!( + "{}$.a == 1{}", + "(".repeat(MAX_NESTING), + ")".repeat(MAX_NESTING) + ); + assert!(parse(&at_limit).is_ok()); + for sibling in ["($.a == 1)", "!($.a == 1)", "exists($.a)"] { + let wide = vec![sibling; MAX_NESTING + 1].join(" && "); + assert!(parse(&wide).is_ok(), "{sibling} side by side"); + } + let deepest = format!("$.{} == 1", vec!["a"; MAX_DEPTH].join(".")); + assert!(parse(&deepest).is_ok(), "a path as deep as a document"); + } + + /// A literal's kind and text are read from the predicate; a variable + /// has neither, and gives its name. + #[test] + fn a_value_says_what_it_is() { + let text = + r#"$.a == "x" || $.a == 2 || $.a == true || $.a == false || $.a == null || $.a == $v"#; + let Expression::Or(terms) = parse(text).unwrap() else { + panic!("an or") + }; + // Each value's kind, literal text, variable name and offset. + type Read<'t> = (Option, Option<&'t str>, Option<&'t str>, usize); + let values: Vec> = terms + .iter() + .map(|term| match term { + Expression::Compare(comparison) => ( + comparison.value.literal_kind(text), + comparison.value.literal_text(text), + comparison.value.variable(), + comparison.value.at(), + ), + _ => panic!("a comparison"), + }) + .collect(); + assert_eq!( + values, + [ + (Some(LiteralKind::String), Some(r#""x""#), None, 7), + (Some(LiteralKind::Number), Some("2"), None, 21), + (Some(LiteralKind::Boolean), Some("true"), None, 33), + (Some(LiteralKind::Boolean), Some("false"), None, 48), + (Some(LiteralKind::Null), Some("null"), None, 64), + (None, None, Some("v"), 79), + ] + ); + assert_eq!( + ValueAt::Literal { start: 7, end: 9 }.literal_kind("$.a == -1"), + Some(LiteralKind::Number) + ); + } + + #[test] + fn an_operator_flips_to_the_one_with_its_operands_swapped() { + for (operator, flipped) in [ + (Operator::Equal, Operator::Equal), + (Operator::NotEqual, Operator::NotEqual), + (Operator::Less, Operator::Greater), + (Operator::LessOrEqual, Operator::GreaterOrEqual), + (Operator::Greater, Operator::Less), + (Operator::GreaterOrEqual, Operator::LessOrEqual), + ] { + assert_eq!(operator.flipped(), flipped); + } + } +} + +mod given_text_it_refuses { + use super::*; + + use PredicateErrorKind::{Position, Syntax, TooDeep, Unsupported}; + + /// Each construct the index cannot answer is refused by name, at the + /// byte where it starts. + #[test] + fn names_each_unsupported_construct_at_its_offset() { + use construct::*; + for (text, construct, at) in [ + ("strict $.a == 1", MODE, 0), + ("STRICT $.a == 1", MODE, 0), + (" lax $.a == 1", MODE, 2), + ("$.a == Lax", MODE, 7), + ("$.a == lax", MODE, 7), + (r#"$.a LIKE_REGEX "x""#, LIKE_REGEX, 4), + (r#"$.a like_regex "x""#, LIKE_REGEX, 4), + (r#"$.a Starts with "x""#, STARTS_WITH, 4), + ("$.a IS unknown", IS_UNKNOWN, 4), + ("$.a[LAST] == 1", LAST, 3), + ("$.a == LAST", LAST, 7), + ("$.a[last] == 1", LAST, 3), + (r#"exists($.a like_regex "x")"#, LIKE_REGEX, 11), + ("exists($.a + 1)", ARITHMETIC, 11), + ( + "exists($.a[*] ? (@ == 1) starts with \"x\")", + STARTS_WITH, + 25, + ), + ("$.a + 1 == 2", ARITHMETIC, 4), + ("$.a == 1 - 2", ARITHMETIC, 9), + ("$.a == 1 * 2", ARITHMETIC, 9), + ("$.a == 1 / 2", ARITHMETIC, 9), + ("$.a == 1 % 2", ARITHMETIC, 9), + ("$.a == +1", ARITHMETIC, 7), + ("$.a.size() == 1", METHOD, 3), + ("$.a.type () == 1", METHOD, 3), + ("$.* == 1", ANY_MEMBER, 1), + ("$.** == 1", ANY_DEPTH, 1), + ("$. * == 1", ANY_MEMBER, 1), + ("$.a[1 to 2] == 1", SLICE, 3), + ("$.a[1, 2] == 1", SLICE, 3), + ("$.a[$i] == 1", SUBSCRIPT, 3), + ("@ == 1", AT_OUTSIDE, 0), + ("$.a == $.b", TWO_PATHS, 4), + ("1 == 1", TWO_VALUES, 2), + ("$x == $y", TWO_VALUES, 3), + ("$.a", ALONE, 3), + ("$.a && $.b == 1", ALONE, 4), + ("($.a)", ALONE, 4), + ("$.a || $.b == 1", ALONE, 4), + ("true", ALONE, 4), + ("$.a[*] ? (@ == 1) == 1", FILTER_OUTSIDE, 7), + ("exists($.a[*] ? (@ == 1).b)", AFTER_FILTER, 24), + ("exists($.a[*] ? (@ == 1)[*])", AFTER_FILTER, 24), + ("exists($.a[*] ? (@ == 1) ? (@ == 2))", FILTER_OUTSIDE, 24), + ("exists($.a ?(@ == 1) ? (@ == 2))", FILTER_OUTSIDE, 20), + ("exists($.a == 1)", IN_EXISTS, 7), + ("exists(@)", AT_OUTSIDE, 7), + ("exists($.a[*] ? (@.b == 1 || @.c == 2))", OR_IN_FILTER, 26), + ("exists($.a[*] ? (!(@.b == 1)))", NOT_IN_FILTER, 17), + ("exists($.a[*] ? (@.b != 1))", NOT_EQUAL_IN_FILTER, 21), + ("exists($.a[*] ? (exists(@.b)))", EXISTS_IN_FILTER, 17), + ("exists($.a[*] ? ($.b == 1))", DOLLAR_IN_FILTER, 17), + ("$.v == $x.y", VARIABLE_PATH, 9), + ("$.v == $x[0]", VARIABLE_PATH, 9), + ] { + assert_eq!(refused(text), (Unsupported, construct, at), "{text}"); + } + } + + /// Text that is not a predicate is refused where reading stops. + #[test] + fn refuses_text_that_is_not_a_predicate_where_reading_stops() { + use construct::*; + for (text, construct, at) in [ + ("", TEXT, 0), + (" ", TEXT, 3), + ("$.a == 1 &&", TEXT, 11), + ("$.a = 1", TEXT, 4), + ("$.a === 1", TEXT, 6), + ("$.a > 1 > 2", TRAILING, 8), + ("$.a == 1 2", TRAILING, 9), + ("($.a == 1) is unknown", TRAILING, 11), + ("!$.a == 1", TEXT, 1), + ("!!($.a == 1)", TEXT, 1), + ("($.a == 1", TEXT, 9), + ("$.a == 01", NUMBER, 7), + ("$.a == 1.", NUMBER, 7), + ("$.a == 1e", NUMBER, 7), + ("$.a == 1e+", NUMBER, 7), + ("$.a == 1x", NUMBER, 7), + ("$.a == 1.5.2", NUMBER, 7), + ("$.a == -", NUMBER, 7), + ("$.a == .5", TEXT, 7), + ("$.a == 'x'", TEXT, 7), + (r#"$.a == "x"#, STRING, 7), + (r#"$.a == "\x41""#, STRING, 7), + (r#"$."a == 1"#, STRING, 2), + (r#"$.a == $"x"#, STRING, 8), + ("$.a == TRUE", TEXT, 7), + ("$.1a == 1", TEXT, 2), + ("$. == 1", TEXT, 3), + ("$.a[*", TEXT, 5), + ("$.a == 1 /* open", TEXT, 9), + ("exists $.a", TEXT, 7), + ("exists($.a", TEXT, 10), + ("exists(1)", TEXT, 7), + ("exists($.a[*] ? @.b == 1)", TEXT, 16), + ("exists($.a[*] ? (@.b == 1)", TEXT, 26), + ("$.a == $1", TEXT, 8), + ("$.a ==", TEXT, 6), + ] { + assert_eq!(refused(text), (Syntax, construct, at), "{text}"); + } + } + + /// A position, nesting past the limit and a path past a document's + /// depth are refused by their own kinds. + #[test] + fn refuses_positions_and_depth() { + let deep = format!( + "{} $.a == 1{}", + "(".repeat(MAX_NESTING + 1), + ")".repeat(MAX_NESTING + 1) + ); + let negations = format!( + "{}($.a == 1){}", + "!(".repeat(MAX_NESTING), + ")".repeat(MAX_NESTING) + ); + let long = format!("$.{} == 1", vec!["a"; MAX_DEPTH + 1].join(".")); + let past = format!("$.{}.** == 1", vec!["a"; MAX_DEPTH].join(".")); + for (text, want) in [ + ("$.a[2] == 1", (Position, construct::POSITION, 3)), + ("exists($.a[ 0 ])", (Position, construct::POSITION, 10)), + ( + deep.as_str(), + (TooDeep, construct::NESTING, MAX_NESTING + 1), + ), + (long.as_str(), (TooDeep, construct::NESTING, 0)), + (past.as_str(), (TooDeep, construct::NESTING, 0)), + ] { + assert_eq!(refused(text), want, "{text}"); + } + assert_eq!(refused(&negations).0, TooDeep); + } + + /// A refusal displays its construct and offset, and nothing of the + /// text. + #[test] + fn a_refusal_quotes_no_text_of_the_predicate() { + let secret = "zq-secret-key-name"; + for text in [ + format!(r#"$."{secret}" like_regex "x""#), + format!(r#"$.{secret} == "{secret}" + 1"#), + format!(r#"$.{secret} == "{secret}" {secret}"#), + ] { + let error = parse(&text).unwrap_err(); + let shown = format!("{error} {error:?}"); + assert!(!shown.contains(secret), "{shown}"); + } + assert_eq!( + parse("$.a like_regex \"x\"").unwrap_err().to_string(), + "`like_regex` at byte 4" + ); + } +} + +mod given_a_structure_the_index_cannot_answer { + use super::*; + + fn comparison(text: &str) -> Comparison { + match parse(text).unwrap() { + Expression::Compare(comparison) => comparison, + other => panic!("{text}: {other:?}"), + } + } + + fn filter(text: &str) -> (PathAt, Vec) { + match parse(text).unwrap() { + Expression::Exists { + path, + filter: Some(conditions), + } => (path, conditions), + other => panic!("{text}: {other:?}"), + } + } + + /// `!=` is refused at a wildcard and read at one node; every other + /// operator is read at both. + #[test] + fn refuses_not_equal_at_a_wildcard_only() { + let refusal = comparison("$.a[*].b != 1") + .refuse_not_equal_at_wildcard() + .unwrap_err(); + assert_eq!( + (refusal.kind, refusal.construct, refusal.at), + ( + PredicateErrorKind::NotEqualAtWildcard, + construct::NOT_EQUAL, + 9 + ) + ); + for text in ["$.a != 1", "$.a[*] == 1", "$.a[*].b > 1"] { + assert!( + comparison(text).refuse_not_equal_at_wildcard().is_ok(), + "{text}" + ); + } + } + + /// An ordering at a wildcard splits at the last wildcard, and is refused + /// when nothing follows it. + #[test] + fn an_ordering_at_a_wildcard_names_a_member() { + let (base, member) = comparison("$.a[*].b[*].c.d > 1") + .path + .element_member(16) + .unwrap(); + assert_eq!( + (base.to_string(), member.to_string()), + ("$.a[*].b[*]".to_owned(), "$.c.d".to_owned()) + ); + let refusal = comparison("$.a[*] > 1").path.element_member(7).unwrap_err(); + assert_eq!( + (refusal.kind, refusal.construct, refusal.at), + ( + PredicateErrorKind::Unsupported, + construct::ELEMENTS_THEMSELVES, + 7 + ) + ); + } + + /// A filter needs a wildcard on its path and none in its members, and + /// no member deeper than a document. + #[test] + fn a_filter_is_on_elements_and_names_their_members() { + let (path, conditions) = filter("exists($.a[*] ? (@.b == 1 && @.c > 2))"); + assert!(check_filter(&path, &conditions).is_ok()); + for (text, want) in [ + ( + "exists($.a ? (@ == 1))", + ( + PredicateErrorKind::FilterWithoutWildcard, + construct::FILTER_WILDCARD, + 7, + ), + ), + ( + "exists($.a[*] ? (@.b == 1 && @.c[*] == 1))", + ( + PredicateErrorKind::MemberWildcard, + construct::MEMBER_WILDCARD, + 29, + ), + ), + ] { + let (path, conditions) = filter(text); + let refusal = check_filter(&path, &conditions).unwrap_err(); + assert_eq!( + (refusal.kind, refusal.construct, refusal.at), + want, + "{text}" + ); + } + let member = + |steps: usize| format!("exists($.a[*] ? (@.{} == 1))", vec!["b"; steps].join(".")); + let (path, conditions) = filter(&member(MAX_DEPTH - 2)); + assert!( + check_filter(&path, &conditions).is_ok(), + "as deep as a document" + ); + let (path, conditions) = filter(&member(MAX_DEPTH - 1)); + let refusal = check_filter(&path, &conditions).unwrap_err(); + assert_eq!( + (refusal.kind, refusal.at), + (PredicateErrorKind::TooDeep, 7), + "deeper than a document" + ); + } + + /// One equality is containment; anything else is an element-scoped + /// predicate, whose conditions each name a member. + #[test] + fn a_filter_condition_names_a_member() { + let (_, one) = filter("exists($.a[*] ? (@.b == 1))"); + assert!(single_equality(&one).is_some()); + let (_, ordering) = filter("exists($.a[*] ? (@.b > 1))"); + assert!(single_equality(&ordering).is_none()); + let (_, two) = filter("exists($.a[*] ? (@.b == 1 && @.c == 2))"); + assert!(single_equality(&two).is_none()); + for condition in &two { + assert!(condition.check_filter_condition().is_ok()); + } + for (text, construct, at) in [ + ( + "exists($.a[*] ? (@ == 1 && @.c < 2))", + construct::WHOLE_ELEMENT, + 17, + ), + ( + "exists($.a[*] ? (@ > 1 && @.c < 2))", + construct::ELEMENTS_THEMSELVES, + 17, + ), + ] { + let (_, conditions) = filter(text); + let refusal = conditions[0].check_filter_condition().unwrap_err(); + assert_eq!( + (refusal.kind, refusal.construct, refusal.at), + (PredicateErrorKind::Unsupported, construct, at), + "{text}" + ); + } + // `!=` never reaches a filter from the parser; a comparison built + // with it is refused at its operator all the same. + let not_equal = Comparison { + path: PathAt { + path: JsonPath::parse("$.b").unwrap(), + at: 0, + }, + operator: Operator::NotEqual, + value: ValueAt::Literal { start: 0, end: 1 }, + at: 4, + }; + let refusal = not_equal.check_filter_condition().unwrap_err(); + assert_eq!( + (refusal.construct, refusal.at), + (construct::NOT_EQUAL_IN_FILTER, 4) + ); + } +} diff --git a/packages/stack-encrypt/src/json/derive.rs b/packages/stack-encrypt/src/json/derive.rs index 8aae125d6..b67125959 100644 --- a/packages/stack-encrypt/src/json/derive.rs +++ b/packages/stack-encrypt/src/json/derive.rs @@ -60,7 +60,11 @@ const ENTRY_AAD_DOMAIN: &[u8] = b"stack-encrypt/json/entry/v1"; /// where the value is lost, to the write, where the caller still holds it. /// The bound is the same under either root option, so the option never /// changes which documents the index accepts. -pub(crate) const MAX_DEPTH: usize = 127; +/// +/// The value is the grammar crate's, so a predicate's paths, which +/// `predicate!` reads at compile time with that crate, are read to the +/// same depth. +pub(crate) const MAX_DEPTH: usize = stack_encrypt_jsonpath::MAX_DEPTH; /// The largest number the index gives an array element's position, a /// node's ordinal or a node's child count: PostgreSQL's `integer`, which is diff --git a/packages/stack-encrypt/src/json/mod.rs b/packages/stack-encrypt/src/json/mod.rs index 9d101118b..9779f7226 100644 --- a/packages/stack-encrypt/src/json/mod.rs +++ b/packages/stack-encrypt/src/json/mod.rs @@ -174,7 +174,6 @@ pub(crate) use derive::MAX_DEPTH; pub(crate) use derive::{seal_pending, terms_pending}; pub(crate) use plain::PlainJson; pub(crate) use shuffle::Randomness; -pub(crate) use stack_encrypt_jsonpath::json_string::{string_end, string_text}; /// A sixteen-byte tag: a selector or a token. pub type Tag = [u8; 16]; diff --git a/packages/stack-encrypt/src/json/predicate.rs b/packages/stack-encrypt/src/json/predicate.rs index 8cfecedab..679f5bfd6 100644 --- a/packages/stack-encrypt/src/json/predicate.rs +++ b/packages/stack-encrypt/src/json/predicate.rs @@ -1,6 +1,5 @@ //! `match`'s predicate: the SQL/JSON path predicates the JSON index can -//! answer, parsed from the caller's text and compiled onto the inputs of -//! the other JSON operators. +//! answer, compiled onto the inputs of the other JSON operators. //! //! The text is PostgreSQL's SQL/JSON path language, as `jsonb_path_match` //! takes it ([SQL/JSON path language](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-SQLJSON-PATH)), @@ -16,16 +15,17 @@ //! one element satisfies both //! ``` //! -//! The dynamic interface's `match` operator and a field reference's -//! `predicate` both compile through it. The grammar and the compilation are -//! documented with the operator, in the dynamic interface's JSON operators -//! (`stack_encrypt::dynamic`, with the `dynamic` feature). This module holds the -//! parser ([`parse`]), which reads the text into an [`Ast`] and refuses -//! what the grammar does not read at the byte where it stops, and the -//! compiler ([`compile`]), which binds the values and maps each comparison -//! onto the inputs `eq_at`, `selector`, the orderings and `element_match` -//! take, so that every leaf is derived by that operator's own code -//! ([`derive`]). +//! The dynamic interface's `match` operator, a field reference's +//! `predicate` and the `predicate!` macro all compile through it. The +//! grammar and the compilation are documented with the operator, in the +//! dynamic interface's JSON operators (`stack_encrypt::dynamic`, with the +//! `dynamic` feature). The grammar itself is `stack-encrypt-jsonpath`'s +//! ([`predicate::parse`]), which `predicate!` reads the text with when a +//! program compiles, so the two read one grammar: it refuses what it does +//! not read at the byte where it stops. This module holds the compiler +//! ([`compile`]), which binds the values and maps each comparison onto the +//! inputs `eq_at`, `selector`, the orderings and `element_match` take, so +//! that every leaf is derived by that operator's own code ([`derive`]). //! //! A refusal names a construct in the grammar's words and an offset, never //! a slice of the text: a key name or a value in it can be customer data. @@ -34,757 +34,59 @@ //! and the values in [`Parsed`], which wipes them. use serde_json::Value; -use zeroize::Zeroizing; +use stack_encrypt_jsonpath::predicate::{ + self, check_filter, construct, single_equality, Comparison, Expression, Operator, PathAt, + PredicateError, PredicateErrorKind, ValueAt, +}; use super::inputs::{ derive as derive_input, json_reason, leaf, member_of, ordered_path_of, Bounds, Compare, Derived, Input, Parsed, Predicate, Under, }; -use super::{ - parse_text, string_end, string_text, IndexPath, JsonOptions, JsonPath, JsonPredicateQuery, - Segment, MAX_DEPTH, -}; +use super::{parse_text, IndexPath, JsonOptions, JsonPath, JsonPredicateQuery}; use crate::refusal::{Error, Reason}; use crate::{KeysetCipher, Pending}; -/// How deeply a predicate may nest parentheses, `!` and `exists`. The -/// parser descends once per level, so the bound keeps a hostile predicate -/// from overflowing the stack; the SQL evaluates the compiled tree by -/// recursion too. -pub(crate) const MAX_NESTING: usize = 32; - -// The constructs a refusal names, in the grammar's own words. -const C_TEXT: &str = "text the grammar does not read"; -const C_TRAILING: &str = "text after the predicate"; -const C_STRING: &str = "a string literal"; -const C_NUMBER: &str = "a numeric literal"; -const C_MODE: &str = "a mode (`strict`, `lax`)"; -const C_ARITHMETIC: &str = "arithmetic (`+`, `-`, `*`, `/`, `%`)"; -const C_LIKE_REGEX: &str = "`like_regex`"; -const C_STARTS_WITH: &str = "`starts with`"; -const C_IS_UNKNOWN: &str = "`is unknown`"; -const C_METHOD: &str = "a method (`.name()`)"; -const C_ANY_MEMBER: &str = "`.*`"; -const C_ANY_DEPTH: &str = "`.**`"; -const C_SLICE: &str = "an array slice or list (`[a to b]`, `[a, b]`)"; -const C_LAST: &str = "`last`"; -const C_SUBSCRIPT: &str = "a subscript other than `[*]`"; -const C_POSITION: &str = "a position (`[2]`)"; -const C_AT_OUTSIDE: &str = "`@` outside a filter"; -const C_DOLLAR_IN_FILTER: &str = "a `$` path in a filter"; -const C_VARIABLE_PATH: &str = "an accessor on a variable"; -const C_TWO_PATHS: &str = "a comparison of two paths"; -const C_TWO_VALUES: &str = "a comparison of two values"; -const C_ALONE: &str = "an operand with no comparison"; -const C_FILTER_OUTSIDE: &str = "a filter outside `exists`"; -const C_AFTER_FILTER: &str = "an accessor after a filter"; -const C_IN_EXISTS: &str = "a comparison inside `exists`"; -const C_OR_IN_FILTER: &str = "`||` in a filter"; -const C_NOT_IN_FILTER: &str = "`!` in a filter"; -const C_NE_IN_FILTER: &str = "`!=` in a filter"; -const C_EXISTS_IN_FILTER: &str = "`exists` in a filter"; -const C_ELEMENTS_THEMSELVES: &str = "an ordering of an array's elements themselves"; -const C_WHOLE_ELEMENT: &str = "`@` beside another condition"; -const C_FILTER_WILDCARD: &str = "a filter on a path with no wildcard"; -const C_MEMBER_WILDCARD: &str = "a wildcard in a filter's member"; -const C_NOT_EQUAL: &str = "`!=` at a path with a wildcard"; -const C_VALUE: &str = "a value"; -const C_VARIABLE: &str = "a variable"; -const C_NESTING: &str = "nesting"; - -/// A refusal at a byte of the predicate's text. -#[derive(Debug, PartialEq, Eq)] -struct Refusal { - reason: Reason, - construct: &'static str, - at: usize, -} - -impl Refusal { - fn syntax(construct: &'static str, at: usize) -> Self { - Self { - reason: Reason::JsonPredicateSyntax, - construct, - at, - } - } - - fn unsupported(construct: &'static str, at: usize) -> Self { - Self { - reason: Reason::JsonPredicateUnsupported, - construct, - at, - } - } -} - -impl From for Error { - fn from(refusal: Refusal) -> Self { - Error::Predicate { - field: None, - reason: refusal.reason, - construct: refusal.construct, - at: refusal.at, - } - } -} - -/// A comparison operator, as the text spells it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum PredicateOp { - Eq, - Ne, - Lt, - Lte, - Gt, - Gte, -} - -impl PredicateOp { - /// The operator with its operands swapped: `1 < $.a` is `$.a > 1`. - fn flipped(self) -> Self { - match self { - PredicateOp::Lt => PredicateOp::Gt, - PredicateOp::Lte => PredicateOp::Gte, - PredicateOp::Gt => PredicateOp::Lt, - PredicateOp::Gte => PredicateOp::Lte, - same => same, - } - } - - /// How an element-scoped filter's condition compares; `None` for - /// `!=`, which a filter does not take. - fn compare(self) -> Option { - match self { - PredicateOp::Eq => Some(Compare::Eq), - PredicateOp::Lt => Some(Compare::Lt), - PredicateOp::Lte => Some(Compare::Lte), - PredicateOp::Gt => Some(Compare::Gt), - PredicateOp::Gte => Some(Compare::Gte), - PredicateOp::Ne => None, - } - } -} - -/// A path in the text: `$` or `@` and the steps after it, and where it -/// starts. -#[derive(Debug)] -struct PathAt { - path: JsonPath, - at: usize, -} - -/// A value in the text: a literal, by its bytes, or a variable, by name. -#[derive(Debug, PartialEq, Eq)] -enum ValueAt { - /// `"…"`, a number, `true`, `false` or `null`: the literal's bytes, - /// `start..end`, which are JSON text. - Literal { start: usize, end: usize }, - /// `$name` or `$"name"`. - Variable { name: Zeroizing, at: usize }, -} - -impl ValueAt { - fn at(&self) -> usize { - match self { - ValueAt::Literal { start, .. } => *start, - ValueAt::Variable { at, .. } => *at, - } - } -} - -/// One side of a comparison. -#[derive(Debug)] -enum Side { - /// A path from `$`. - Root(PathAt), - /// A path from `@`, inside a filter. - Current(PathAt), - Value(ValueAt), -} - -/// A comparison of a path with a value, the path on the left. -#[derive(Debug)] -struct Comparison { - path: PathAt, - op: PredicateOp, - value: ValueAt, - /// Where the operator is. - at: usize, -} - -/// A predicate as the text writes it. -#[derive(Debug)] -enum Ast { - And(Vec), - Or(Vec), - Not(Box), - Compare(Comparison), - /// `exists(path)`, or `exists(path ? (conditions))`, each condition a - /// comparison of a path from `@`. - Exists { - path: PathAt, - filter: Option>, - }, -} - -/// The characters that end a name and are not a name's: what -/// PostgreSQL's jsonpath scanner reads as punctuation. -fn special(c: char) -> bool { - c.is_whitespace() || "?%$.[]{}()|&!=<>@#,*:-+/\\\"'".contains(c) -} - -/// A recursive descent over the text, holding the offset it has read to. -struct Parser<'t> { - text: &'t str, - pos: usize, - depth: usize, -} - -impl<'t> Parser<'t> { - fn rest(&self) -> &'t str { - &self.text[self.pos..] - } - - /// Skip whitespace and `/* … */` comments. - fn space(&mut self) -> Result<(), Refusal> { - loop { - let rest = self.rest(); - let trimmed = rest.trim_start(); - self.pos += rest.len() - trimmed.len(); - if let Some(comment) = trimmed.strip_prefix("/*") { - let Some(end) = comment.find("*/") else { - return Err(Refusal::syntax(C_TEXT, self.pos)); - }; - self.pos += 2 + end + 2; - } else { - return Ok(()); - } - } - } - - /// The next character after any space, unread. - fn peek(&mut self) -> Result, Refusal> { - self.space()?; - Ok(self.rest().chars().next()) - } - - /// Read `token` if it is next. - fn eat(&mut self, token: &str) -> Result { - self.space()?; - if self.rest().starts_with(token) { - self.pos += token.len(); - Ok(true) - } else { - Ok(false) - } - } - - fn expect(&mut self, token: &str) -> Result<(), Refusal> { - if self.eat(token)? { - Ok(()) - } else { - Err(Refusal::syntax(C_TEXT, self.pos)) - } - } - - /// The name at the cursor, unread: a run of characters that are not - /// punctuation, not starting with a digit. - fn word(&mut self) -> Result, Refusal> { - self.space()?; - let rest = self.rest(); - if rest.starts_with(|c: char| c.is_ascii_digit()) { - return Ok(None); - } - let end = rest.find(special).unwrap_or(rest.len()); - Ok((end > 0).then(|| &rest[..end])) - } - - /// One more level of nesting, refused past [`MAX_NESTING`]. - fn descend(&mut self) -> Result<(), Refusal> { - self.depth += 1; - if self.depth > MAX_NESTING { - return Err(Refusal { - reason: Reason::JsonPredicateTooDeep, - construct: C_NESTING, - at: self.pos, - }); - } - Ok(()) - } - - fn ascend(&mut self) { - self.depth -= 1; - } - - /// `or := and ('||' and)*`. - fn or(&mut self) -> Result { - let mut terms = vec![self.and()?]; - while self.eat("||")? { - terms.push(self.and()?); - } - Ok(if terms.len() == 1 { - terms.remove(0) - } else { - Ast::Or(terms) - }) - } - - /// `and := unary ('&&' unary)*`. - fn and(&mut self) -> Result { - let mut terms = vec![self.unary()?]; - while self.eat("&&")? { - terms.push(self.unary()?); - } - Ok(if terms.len() == 1 { - terms.remove(0) - } else { - Ast::And(terms) - }) - } - - /// `unary := '!' primary | primary`. As in PostgreSQL, `!` takes a - /// parenthesised predicate or `exists`, not a bare comparison. - fn unary(&mut self) -> Result { - self.space()?; - if self.rest().starts_with('!') && !self.rest().starts_with("!=") { - self.pos += 1; - self.descend()?; - let at = self.pos; - let negated = match self.peek()? { - Some('(') => self.primary()?, - _ if self.keyword("exists")? => self.primary()?, - _ => return Err(Refusal::syntax(C_TEXT, at)), - }; - self.ascend(); - return Ok(Ast::Not(Box::new(negated))); - } - self.primary() - } - - /// Whether the word at the cursor is `keyword`, in any case, as - /// PostgreSQL reads `exists`. - fn keyword(&mut self, keyword: &str) -> Result { - Ok(self - .word()? - .is_some_and(|word| word.eq_ignore_ascii_case(keyword))) - } - - /// `primary := '(' or ')' | 'exists' '(' path filter? ')' | comparison`. - fn primary(&mut self) -> Result { - if self.eat("(")? { - self.descend()?; - let inner = self.or()?; - self.expect(")")?; - self.ascend(); - return Ok(inner); - } - if self.keyword("exists")? { - self.pos += "exists".len(); - if self.eat("(")? { - return self.exists(); - } - return Err(Refusal::syntax(C_TEXT, self.pos)); - } - let comparison = self.comparison(false)?; - Ok(Ast::Compare(comparison)) - } - - /// The inside of `exists(…)`, the `(` read. - fn exists(&mut self) -> Result { - self.descend()?; - self.space()?; - let at = self.pos; - let path = match self.operand(false)? { - Side::Root(path) => path, - Side::Current(_) => return Err(Refusal::unsupported(C_AT_OUTSIDE, at)), - Side::Value(_) => return Err(Refusal::syntax(C_TEXT, at)), - }; - let filter = if self.eat("?")? { - self.expect("(")?; - self.descend()?; - let conditions = self.conditions()?; - self.expect(")")?; - self.ascend(); - let at = self.pos; - match self.peek()? { - Some('.' | '[') => return Err(Refusal::unsupported(C_AFTER_FILTER, at)), - Some('?') => return Err(Refusal::unsupported(C_FILTER_OUTSIDE, at)), - _ => {} - } - Some(conditions) - } else { - None +/// A grammar refusal as the crate's refusal: the same construct and +/// offset, under the [`Reason`] the dynamic interface reports for it. +impl From for Error { + fn from(refusal: PredicateError) -> Self { + let reason = match refusal.kind { + PredicateErrorKind::Syntax => Reason::JsonPredicateSyntax, + PredicateErrorKind::TooDeep => Reason::JsonPredicateTooDeep, + PredicateErrorKind::Position => Reason::JsonPathPosition, + PredicateErrorKind::NotEqualAtWildcard => Reason::JsonPredicateNotEqualAtWildcard, + PredicateErrorKind::FilterWithoutWildcard => Reason::JsonPathNoWildcard, + PredicateErrorKind::MemberWildcard => Reason::JsonPathWildcard, + // `Unsupported`, and any kind the grammar adds: a construct + // the index cannot answer. + _ => Reason::JsonPredicateUnsupported, }; - if let Some(refusal) = self.after_operand()? { - return Err(refusal); - } - self.space()?; - if self.op()?.is_some() { - return Err(Refusal::unsupported(C_IN_EXISTS, at)); - } - self.expect(")")?; - self.ascend(); - Ok(Ast::Exists { path, filter }) - } - - /// A filter's conditions: comparisons of a path from `@`, joined by - /// `&&`, with parentheses. - fn conditions(&mut self) -> Result, Refusal> { - let mut conditions = Vec::new(); - loop { - self.space()?; - let at = self.pos; - if self.rest().starts_with('!') && !self.rest().starts_with("!=") { - return Err(Refusal::unsupported(C_NOT_IN_FILTER, at)); - } - if self.keyword("exists")? { - return Err(Refusal::unsupported(C_EXISTS_IN_FILTER, at)); - } - if self.eat("(")? { - self.descend()?; - conditions.extend(self.conditions()?); - self.expect(")")?; - self.ascend(); - } else { - conditions.push(self.comparison(true)?); - } - self.space()?; - if self.rest().starts_with("||") { - return Err(Refusal::unsupported(C_OR_IN_FILTER, self.pos)); - } - if !self.eat("&&")? { - return Ok(conditions); - } - } - } - - /// A comparison operator at the cursor, read, and where it was. - fn op(&mut self) -> Result, Refusal> { - self.space()?; - let at = self.pos; - let rest = self.rest(); - let (op, len) = if rest.starts_with("==") { - (PredicateOp::Eq, 2) - } else if rest.starts_with("!=") || rest.starts_with("<>") { - (PredicateOp::Ne, 2) - } else if rest.starts_with("<=") { - (PredicateOp::Lte, 2) - } else if rest.starts_with(">=") { - (PredicateOp::Gte, 2) - } else if rest.starts_with('<') { - (PredicateOp::Lt, 1) - } else if rest.starts_with('>') { - (PredicateOp::Gt, 1) - } else { - return Ok(None); - }; - self.pos += len; - Ok(Some((op, at))) - } - - /// The construct at the cursor that follows an operand and that the - /// index cannot answer, if one is there. - fn after_operand(&mut self) -> Result, Refusal> { - self.space()?; - let at = self.pos; - let rest = self.rest(); - if rest.starts_with(['+', '-', '*', '/', '%']) { - return Ok(Some(Refusal::unsupported(C_ARITHMETIC, at))); - } - if rest.starts_with('?') { - return Ok(Some(Refusal::unsupported(C_FILTER_OUTSIDE, at))); - } - let word = self.word()?.unwrap_or_default(); - Ok(if word.eq_ignore_ascii_case("like_regex") { - Some(Refusal::unsupported(C_LIKE_REGEX, at)) - } else if word.eq_ignore_ascii_case("starts") { - Some(Refusal::unsupported(C_STARTS_WITH, at)) - } else if word.eq_ignore_ascii_case("is") { - Some(Refusal::unsupported(C_IS_UNKNOWN, at)) - } else { - None - }) - } - - /// `comparison := operand op operand`, one side a path and the other a - /// value; in a filter the path is from `@`. - fn comparison(&mut self, in_filter: bool) -> Result { - self.space()?; - let left = self.operand(in_filter)?; - if let Some(refusal) = self.after_operand()? { - return Err(refusal); - } - let Some((op, at)) = self.op()? else { - self.space()?; - let at = self.pos; - let ends = self.rest().is_empty() || self.rest().starts_with([')', '&', '|']); - return Err(if ends { - Refusal::unsupported(C_ALONE, at) - } else { - Refusal::syntax(C_TEXT, at) - }); - }; - if in_filter && op == PredicateOp::Ne { - return Err(Refusal::unsupported(C_NE_IN_FILTER, at)); - } - self.space()?; - let right = self.operand(in_filter)?; - if let Some(refusal) = self.after_operand()? { - return Err(refusal); - } - let (path, op, value) = match (left, right) { - (Side::Root(path) | Side::Current(path), Side::Value(value)) => (path, op, value), - (Side::Value(value), Side::Root(path) | Side::Current(path)) => { - (path, op.flipped(), value) - } - (Side::Value(_), Side::Value(_)) => return Err(Refusal::unsupported(C_TWO_VALUES, at)), - _ => return Err(Refusal::unsupported(C_TWO_PATHS, at)), - }; - Ok(Comparison { - path, - op, - value, - at, - }) - } - - /// A path, a variable or a literal. In a filter a path is from `@`; - /// outside one, from `$`. - fn operand(&mut self, in_filter: bool) -> Result { - self.space()?; - let at = self.pos; - let rest = self.rest(); - let Some(first) = rest.chars().next() else { - return Err(Refusal::syntax(C_TEXT, at)); - }; - match first { - '$' => { - let after = &rest[1..]; - if after.starts_with('"') { - let (name, len) = self.string_at(at + 1)?; - self.pos = at + 1 + len; - return self.variable(name, at); - } - if after.starts_with(|c: char| !special(c)) { - self.pos += 1; - let Some(name) = self.word()? else { - return Err(Refusal::syntax(C_TEXT, self.pos)); - }; - self.pos += name.len(); - return self.variable(Zeroizing::new(name.to_owned()), at); - } - if in_filter { - return Err(Refusal::unsupported(C_DOLLAR_IN_FILTER, at)); - } - self.pos += 1; - Ok(Side::Root(self.steps(at)?)) - } - '@' => { - if !in_filter { - return Err(Refusal::unsupported(C_AT_OUTSIDE, at)); - } - self.pos += 1; - Ok(Side::Current(self.steps(at)?)) - } - '"' => { - let (_, len) = self.string_at(at)?; - self.pos += len; - Ok(Side::Value(ValueAt::Literal { - start: at, - end: at + len, - })) - } - '-' | '0'..='9' => { - let len = number_len(rest).ok_or(Refusal::syntax(C_NUMBER, at))?; - self.pos += len; - Ok(Side::Value(ValueAt::Literal { - start: at, - end: at + len, - })) - } - '+' => Err(Refusal::unsupported(C_ARITHMETIC, at)), - _ => match self.word()? { - Some(word @ ("true" | "false" | "null")) => { - self.pos += word.len(); - Ok(Side::Value(ValueAt::Literal { - start: at, - end: at + word.len(), - })) - } - Some(word) if word.eq_ignore_ascii_case("last") => { - Err(Refusal::unsupported(C_LAST, at)) - } - Some(word) if is_mode(word) => Err(Refusal::unsupported(C_MODE, at)), - _ => Err(Refusal::syntax(C_TEXT, at)), - }, - } - } - - /// A variable named `name`, which takes no accessor. The name is the - /// caller's text, and is wiped when the predicate is dropped. - fn variable(&mut self, name: Zeroizing, at: usize) -> Result { - self.space()?; - if self.rest().starts_with(['.', '[']) { - return Err(Refusal::unsupported(C_VARIABLE_PATH, self.pos)); - } - Ok(Side::Value(ValueAt::Variable { name, at })) - } - - /// The JSON string at `at`, decoded, and its length in the text. Its - /// escapes are JSON's. The decoded text is wiped when it drops: a - /// literal's is a value, read only to check it, and a key's is moved - /// into its path, which wipes it. - fn string_at(&self, at: usize) -> Result<(Zeroizing, usize), Refusal> { - let text = &self.text.as_bytes()[at..]; - string_end(text) - .and_then(|end| Some((string_text(&text[..=end])?, end + 1))) - .ok_or_else(|| Refusal::syntax(C_STRING, at)) - } - - /// The steps after `$` or `@`: `.name`, `."name"`, `[*]`, and the - /// accessors refused by name. A step past a document's depth is - /// refused before it is read, so the path held is never deeper than - /// [`MAX_DEPTH`]. - /// - /// The steps are read into the path itself, so a refusal part way - /// drops a path, which wipes the keys already read. - fn steps(&mut self, start: usize) -> Result { - let mut path = JsonPath::root(); - loop { - self.space()?; - let at = self.pos; - let rest = self.rest(); - if !rest.starts_with(['.', '[']) { - break; - } - if path.segments().len() >= MAX_DEPTH { - return Err(Refusal { - reason: Reason::JsonPredicateTooDeep, - construct: C_NESTING, - at: start, - }); - } - if let Some(after) = rest.strip_prefix('.') { - let after_space = after.trim_start(); - let gap = after.len() - after_space.len(); - if after_space.starts_with("**") { - return Err(Refusal::unsupported(C_ANY_DEPTH, at)); - } - if after_space.starts_with('*') { - return Err(Refusal::unsupported(C_ANY_MEMBER, at)); - } - if after_space.starts_with('"') { - let (mut key, len) = self.string_at(at + 1 + gap)?; - self.pos = at + 1 + gap + len; - path.push(Segment::Key(std::mem::take(&mut *key))); - continue; - } - self.pos = at + 1; - let Some(name) = self.word()? else { - return Err(Refusal::syntax(C_TEXT, self.pos)); - }; - self.pos += name.len(); - if self.peek()? == Some('(') { - return Err(Refusal::unsupported(C_METHOD, at)); - } - path.push(Segment::Key(name.to_owned())); - } else { - self.pos += 1; - self.space()?; - if self.eat("*")? { - self.expect("]")?; - path.push(Segment::Wildcard); - } else if self.rest().starts_with(|c: char| c.is_ascii_digit()) { - let digits = self - .rest() - .find(|c: char| !c.is_ascii_digit()) - .unwrap_or(self.rest().len()); - self.pos += digits; - self.space()?; - if self.rest().starts_with(']') { - return Err(Refusal { - reason: Reason::JsonPathPosition, - construct: C_POSITION, - at, - }); - } - return Err(Refusal::unsupported(C_SLICE, at)); - } else if self.keyword("last")? { - return Err(Refusal::unsupported(C_LAST, at)); - } else { - return Err(Refusal::unsupported(C_SUBSCRIPT, at)); - } - } - } - Ok(PathAt { path, at: start }) + refusal_at(reason, refusal.construct, refusal.at) } } -/// The length of the JSON number at the front of `text`: -/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`, followed by -/// something that does not continue it. `None` for text that is not one. -fn number_len(text: &str) -> Option { - let bytes = text.as_bytes(); - let mut i = usize::from(bytes.first() == Some(&b'-')); - let digits = |from: usize| { - bytes[from..] - .iter() - .take_while(|b| b.is_ascii_digit()) - .count() - }; - match bytes.get(i) { - Some(b'0') => i += 1, - Some(b'1'..=b'9') => i += digits(i), - _ => return None, - } - if bytes.get(i) == Some(&b'.') { - let fraction = digits(i + 1); - if fraction == 0 { - return None; - } - i += 1 + fraction; +/// A refusal of the construct `construct` at the byte `at`, for `reason`. +fn refusal_at(reason: Reason, construct: &'static str, at: usize) -> Error { + Error::Predicate { + field: None, + reason, + construct, + at, } - if matches!(bytes.get(i), Some(b'e' | b'E')) { - let mut j = i + 1; - if matches!(bytes.get(j), Some(b'+' | b'-')) { - j += 1; - } - let exponent = digits(j); - if exponent == 0 { - return None; - } - i = j + exponent; - } - match text[i..].chars().next() { - Some(c) if !special(c) || c == '.' => None, - _ => Some(i), - } -} - -/// Whether `word` is a mode word, `strict` or `lax`, in any case. -fn is_mode(word: &str) -> bool { - word.eq_ignore_ascii_case("strict") || word.eq_ignore_ascii_case("lax") } -/// Parse a predicate's text. -fn parse(text: &str) -> Result { - let mut parser = Parser { - text, - pos: 0, - depth: 0, - }; - parser.space()?; - let at = parser.pos; - if parser.word()?.is_some_and(is_mode) { - return Err(Refusal::unsupported(C_MODE, at)); +/// How an element-scoped condition compares; `None` for `!=`, which a +/// filter does not take. +fn compare_of(operator: Operator) -> Option { + match operator { + Operator::Equal => Some(Compare::Eq), + Operator::Less => Some(Compare::Lt), + Operator::LessOrEqual => Some(Compare::Lte), + Operator::Greater => Some(Compare::Gt), + Operator::GreaterOrEqual => Some(Compare::Gte), + Operator::NotEqual => None, } - let ast = parser.or()?; - parser.space()?; - if !parser.rest().is_empty() { - return Err(Refusal::syntax(C_TRAILING, parser.pos)); - } - Ok(ast) } /// A predicate compiled: a tree of the inputs of the operators whose @@ -843,8 +145,8 @@ pub(crate) fn compile( options, bound, }; - let ast = parse(text)?; - Ok(simplify(compiler.node(ast, false)?)) + let expression = predicate::parse(text)?; + Ok(simplify(compiler.node(expression, false)?)) } impl Compiler<'_> { @@ -852,24 +154,24 @@ impl Compiler<'_> { /// `negated`. `and` and `or` are monotone in each child, so only a `!` /// turns a child's NULL into a different row set than its false; see /// [`Compiler::comparison`]. - fn node(&self, ast: Ast, negated: bool) -> Result { - Ok(match ast { - Ast::And(terms) => Node::And( + fn node(&self, expression: Expression, negated: bool) -> Result { + Ok(match expression { + Expression::And(terms) => Node::And( terms .into_iter() .map(|t| self.node(t, negated)) .collect::>()?, ), - Ast::Or(terms) => Node::Or( + Expression::Or(terms) => Node::Or( terms .into_iter() .map(|t| self.node(t, negated)) .collect::>()?, ), - Ast::Not(inner) => Node::Not(Box::new(self.node(*inner, !negated)?)), - Ast::Compare(comparison) => self.comparison(comparison, negated)?, - Ast::Exists { path, filter: None } => Node::Leaf(Input::Selector(path.path)), - Ast::Exists { + Expression::Not(inner) => Node::Not(Box::new(self.node(*inner, !negated)?)), + Expression::Compare(comparison) => self.comparison(comparison, negated)?, + Expression::Exists { path, filter: None } => Node::Leaf(Input::Selector(path.path)), + Expression::Exists { path, filter: Some(conditions), } => self.filter(path, conditions)?, @@ -881,25 +183,17 @@ impl Compiler<'_> { match value { ValueAt::Literal { start, end } => parse_text(&self.text.as_bytes()[*start..*end]) .map(Parsed) - .map_err(|error| { - Refusal { - reason: json_reason(error), - construct: C_VALUE, - at: *start, - } - .into() - }), + .map_err(|error| refusal_at(json_reason(error), construct::VALUE, *start)), ValueAt::Variable { name, at } => self .vars .get(name.as_str()) .map(|value| Parsed(value.clone())) .ok_or_else(|| { - Refusal { - reason: Reason::JsonPredicateUnknownVariable, - construct: C_VARIABLE, - at: *at, - } - .into() + refusal_at( + Reason::JsonPredicateUnknownVariable, + construct::VARIABLE, + *at, + ) }), } } @@ -943,56 +237,38 @@ impl Compiler<'_> { /// `path op value`, under an odd number of `!` when `negated`. fn comparison(&self, comparison: Comparison, negated: bool) -> Result { + // `!=` over several elements is true when one differs, which + // containment cannot say. + comparison.refuse_not_equal_at_wildcard()?; let Comparison { path, - op, + operator, value, at, } = comparison; let wild = !path.path.is_positional(); - let compare = match op { + let compare = match operator { // `==`: containment of the value at the path, exact; at a // wildcard, of any element. - PredicateOp::Eq => return Ok(Node::Leaf(Input::EqAt(path.path, self.scalar(&value)?))), - // `!=` over several elements is true when one differs, which - // containment cannot say. - PredicateOp::Ne if wild => { - return Err(Refusal { - reason: Reason::JsonPredicateNotEqualAtWildcard, - construct: C_NOT_EQUAL, - at, - } - .into()) - } + Operator::Equal => return Ok(Node::Leaf(Input::EqAt(path.path, self.scalar(&value)?))), // `!=` at one node: a node there that is not the value. - PredicateOp::Ne => { + Operator::NotEqual => { let value = self.scalar(&value)?; return Ok(Node::And(vec![ Node::Leaf(Input::Selector(path.path.clone())), Node::Not(Box::new(Node::Leaf(Input::EqAt(path.path, value)))), ])); } - PredicateOp::Lt => Compare::Lt, - PredicateOp::Lte => Compare::Lte, - PredicateOp::Gt => Compare::Gt, - PredicateOp::Gte => Compare::Gte, + Operator::Less => Compare::Lt, + Operator::LessOrEqual => Compare::Lte, + Operator::Greater => Compare::Gt, + Operator::GreaterOrEqual => Compare::Gte, }; Ok(if wild { // An ordering at a wildcard: some element's field, which is // `element_match` on the array through the last wildcard. let value = self.ordered(&value)?; - let steps = path.path.segments(); - let last = steps - .iter() - .rposition(|segment| *segment == Segment::Wildcard) - .unwrap_or_default(); - // Each half is copied straight into a path, which wipes its - // keys, before anything can refuse. - let (base, member) = steps.split_at(last + 1); - let (base, member) = (JsonPath::of(base.to_vec()), JsonPath::of(member.to_vec())); - if member.segments().is_empty() { - return Err(Refusal::unsupported(C_ELEMENTS_THEMSELVES, at).into()); - } + let (base, member) = path.element_member(at)?; let predicate = self.member(&base, member, compare, value)?; Node::Leaf(Input::Elements(self.bound, vec![predicate])) } else { @@ -1039,61 +315,27 @@ impl Compiler<'_> { /// path, exact; anything else is `element_match`, every condition on a /// field of one element. fn filter(&self, path: PathAt, conditions: Vec) -> Result { - if path.path.is_positional() { - return Err(Refusal { - reason: Reason::JsonPathNoWildcard, - construct: C_FILTER_WILDCARD, - at: path.at, - } - .into()); - } + check_filter(&path, &conditions)?; let base = path.path; - for condition in &conditions { - if base.segments().len() + condition.path.path.segments().len() > MAX_DEPTH { - return Err(Refusal { - reason: Reason::JsonPredicateTooDeep, - construct: C_NESTING, - at: path.at, - } - .into()); - } - if !condition.path.path.is_positional() { - return Err(Refusal { - reason: Reason::JsonPathWildcard, - construct: C_MEMBER_WILDCARD, - at: condition.path.at, - } - .into()); - } - } - if let [only] = conditions.as_slice() { - if only.op == PredicateOp::Eq { - let full = only.path.path.segments().iter().fold( - base.segments().to_vec(), - |mut at, segment| { - at.push(segment.clone()); - at - }, - ); - return Ok(Node::Leaf(Input::EqAt( - JsonPath::of(full), - self.scalar(&only.value)?, - ))); - } + if let Some(only) = single_equality(&conditions) { + let full = only.path.path.segments().iter().fold( + base.segments().to_vec(), + |mut at, segment| { + at.push(segment.clone()); + at + }, + ); + return Ok(Node::Leaf(Input::EqAt( + JsonPath::of(full), + self.scalar(&only.value)?, + ))); } let mut predicates = Vec::with_capacity(conditions.len()); for condition in conditions { - let Some(compare) = condition.op.compare() else { - return Err(Refusal::unsupported(C_NE_IN_FILTER, condition.at).into()); + condition.check_filter_condition()?; + let Some(compare) = compare_of(condition.operator) else { + return Err(Error::Internal); }; - if condition.path.path.segments().is_empty() { - let construct = if compare == Compare::Eq { - C_WHOLE_ELEMENT - } else { - C_ELEMENTS_THEMSELVES - }; - return Err(Refusal::unsupported(construct, condition.path.at).into()); - } let value = self.ordered(&condition.value)?; predicates.push(self.member(&base, condition.path.path, compare, value)?); } @@ -1102,12 +344,7 @@ impl Compiler<'_> { } fn value_type(at: &ValueAt) -> Error { - Refusal { - reason: Reason::JsonPredicateValueType, - construct: C_VALUE, - at: at.at(), - } - .into() + refusal_at(Reason::JsonPredicateValueType, construct::VALUE, at.at()) } /// The tree with every `and` in an `and` and every `or` in an `or` lifted @@ -1271,7 +508,9 @@ pub(crate) fn derive<'a, K: 'static>( mod tests { use super::*; + use crate::json::MAX_DEPTH; use crate::sem::TermError; + use stack_encrypt_jsonpath::predicate::MAX_NESTING; use serde_json::json; @@ -1570,69 +809,89 @@ mod tests { #[test] fn names_each_unsupported_construct_at_its_offset() { for (text, construct, at) in [ - ("strict $.a == 1", C_MODE, 0), - ("STRICT $.a == 1", C_MODE, 0), - ("$.a == Lax", C_MODE, 7), - (r#"$.a LIKE_REGEX "x""#, C_LIKE_REGEX, 4), - (r#"$.a Starts with "x""#, C_STARTS_WITH, 4), - ("$.a IS unknown", C_IS_UNKNOWN, 4), - ("$.a[LAST] == 1", C_LAST, 3), - ("$.a == LAST", C_LAST, 7), - (r#"exists($.a like_regex "x")"#, C_LIKE_REGEX, 11), - ("exists($.a + 1)", C_ARITHMETIC, 11), + ("strict $.a == 1", construct::MODE, 0), + ("STRICT $.a == 1", construct::MODE, 0), + ("$.a == Lax", construct::MODE, 7), + (r#"$.a LIKE_REGEX "x""#, construct::LIKE_REGEX, 4), + (r#"$.a Starts with "x""#, construct::STARTS_WITH, 4), + ("$.a IS unknown", construct::IS_UNKNOWN, 4), + ("$.a[LAST] == 1", construct::LAST, 3), + ("$.a == LAST", construct::LAST, 7), + (r#"exists($.a like_regex "x")"#, construct::LIKE_REGEX, 11), + ("exists($.a + 1)", construct::ARITHMETIC, 11), ( "exists($.a[*] ? (@ == 1) starts with \"x\")", - C_STARTS_WITH, + construct::STARTS_WITH, 25, ), - (" lax $.a == 1", C_MODE, 2), - ("$.a + 1 == 2", C_ARITHMETIC, 4), - ("$.a == 1 - 2", C_ARITHMETIC, 9), - ("$.a == +1", C_ARITHMETIC, 7), - (r#"$.a like_regex "x""#, C_LIKE_REGEX, 4), - (r#"$.a starts with "x""#, C_STARTS_WITH, 4), - ("$.a is unknown", C_IS_UNKNOWN, 4), - ("$.a.size() == 1", C_METHOD, 3), - ("$.a.type () == 1", C_METHOD, 3), - ("$.* == 1", C_ANY_MEMBER, 1), - ("$.** == 1", C_ANY_DEPTH, 1), - ("$.a[1 to 2] == 1", C_SLICE, 3), - ("$.a[1, 2] == 1", C_SLICE, 3), - ("$.a[last] == 1", C_LAST, 3), - ("$.a == last", C_LAST, 7), - ("$.a == lax", C_MODE, 7), - ("$.a[$i] == 1", C_SUBSCRIPT, 3), - ("@ == 1", C_AT_OUTSIDE, 0), - ("$.a == $.b", C_TWO_PATHS, 4), - ("1 == 1", C_TWO_VALUES, 2), - ("$x == $y", C_TWO_VALUES, 3), - ("$.a", C_ALONE, 3), - ("$.a && $.b == 1", C_ALONE, 4), - ("true", C_ALONE, 4), - ("$.a[*] ? (@ == 1) == 1", C_FILTER_OUTSIDE, 7), - ("exists($.a[*] ? (@ == 1).b)", C_AFTER_FILTER, 24), - ("exists($.a[*] ? (@ == 1) ? (@ == 2))", C_FILTER_OUTSIDE, 24), - ("exists($.a == 1)", C_IN_EXISTS, 7), - ("exists(@)", C_AT_OUTSIDE, 7), + (" lax $.a == 1", construct::MODE, 2), + ("$.a + 1 == 2", construct::ARITHMETIC, 4), + ("$.a == 1 - 2", construct::ARITHMETIC, 9), + ("$.a == +1", construct::ARITHMETIC, 7), + (r#"$.a like_regex "x""#, construct::LIKE_REGEX, 4), + (r#"$.a starts with "x""#, construct::STARTS_WITH, 4), + ("$.a is unknown", construct::IS_UNKNOWN, 4), + ("$.a.size() == 1", construct::METHOD, 3), + ("$.a.type () == 1", construct::METHOD, 3), + ("$.* == 1", construct::ANY_MEMBER, 1), + ("$.** == 1", construct::ANY_DEPTH, 1), + ("$.a[1 to 2] == 1", construct::SLICE, 3), + ("$.a[1, 2] == 1", construct::SLICE, 3), + ("$.a[last] == 1", construct::LAST, 3), + ("$.a == last", construct::LAST, 7), + ("$.a == lax", construct::MODE, 7), + ("$.a[$i] == 1", construct::SUBSCRIPT, 3), + ("@ == 1", construct::AT_OUTSIDE, 0), + ("$.a == $.b", construct::TWO_PATHS, 4), + ("1 == 1", construct::TWO_VALUES, 2), + ("$x == $y", construct::TWO_VALUES, 3), + ("$.a", construct::ALONE, 3), + ("$.a && $.b == 1", construct::ALONE, 4), + ("true", construct::ALONE, 4), + ("$.a[*] ? (@ == 1) == 1", construct::FILTER_OUTSIDE, 7), + ("exists($.a[*] ? (@ == 1).b)", construct::AFTER_FILTER, 24), + ( + "exists($.a[*] ? (@ == 1) ? (@ == 2))", + construct::FILTER_OUTSIDE, + 24, + ), + ("exists($.a == 1)", construct::IN_EXISTS, 7), + ("exists(@)", construct::AT_OUTSIDE, 7), ( "exists($.a[*] ? (@.b == 1 || @.c == 2))", - C_OR_IN_FILTER, + construct::OR_IN_FILTER, 26, ), - ("exists($.a[*] ? (!(@.b == 1)))", C_NOT_IN_FILTER, 17), - ("exists($.a[*] ? (@.b != 1))", C_NE_IN_FILTER, 21), - ("exists($.a[*] ? (exists(@.b)))", C_EXISTS_IN_FILTER, 17), - ("exists($.a[*] ? ($.b == 1))", C_DOLLAR_IN_FILTER, 17), - ("$.v == $x.y", C_VARIABLE_PATH, 9), - ("$.tags[*] < 1", C_ELEMENTS_THEMSELVES, 10), + ( + "exists($.a[*] ? (!(@.b == 1)))", + construct::NOT_IN_FILTER, + 17, + ), + ( + "exists($.a[*] ? (@.b != 1))", + construct::NOT_EQUAL_IN_FILTER, + 21, + ), + ( + "exists($.a[*] ? (exists(@.b)))", + construct::EXISTS_IN_FILTER, + 17, + ), + ( + "exists($.a[*] ? ($.b == 1))", + construct::DOLLAR_IN_FILTER, + 17, + ), + ("$.v == $x.y", construct::VARIABLE_PATH, 9), + ("$.tags[*] < 1", construct::ELEMENTS_THEMSELVES, 10), ( "exists($.contacts[*] ? (@ > 1 && @.calls < 2))", - C_ELEMENTS_THEMSELVES, + construct::ELEMENTS_THEMSELVES, 24, ), ( "exists($.contacts[*] ? (@ == 1 && @.calls < 2))", - C_WHOLE_ELEMENT, + construct::WHOLE_ELEMENT, 24, ), ] { @@ -1648,29 +907,29 @@ mod tests { #[test] fn refuses_text_that_is_not_a_predicate_where_reading_stops() { for (text, construct, at) in [ - ("", C_TEXT, 0), - ("$.a == 1 &&", C_TEXT, 11), - ("$.a = 1", C_TEXT, 4), - ("$.a === 1", C_TEXT, 6), - ("$.a > 1 > 2", C_TRAILING, 8), - ("$.a == 1 2", C_TRAILING, 9), - ("($.a == 1) is unknown", C_TRAILING, 11), - ("!$.a == 1", C_TEXT, 1), - ("!!($.a == 1)", C_TEXT, 1), - ("($.a == 1", C_TEXT, 9), - ("$.a == 01", C_NUMBER, 7), - ("$.a == 1.", C_NUMBER, 7), - ("$.a == 1e", C_NUMBER, 7), - ("$.a == .5", C_TEXT, 7), - ("$.a == 'x'", C_TEXT, 7), - (r#"$.a == "x"#, C_STRING, 7), - (r#"$."a == 1"#, C_STRING, 2), - ("$.a == TRUE", C_TEXT, 7), - ("$.1a == 1", C_TEXT, 2), - ("$. == 1", C_TEXT, 3), - ("$.a == 1 /* open", C_TEXT, 9), - ("exists $.a", C_TEXT, 7), - ("$.a == $1", C_TEXT, 8), + ("", construct::TEXT, 0), + ("$.a == 1 &&", construct::TEXT, 11), + ("$.a = 1", construct::TEXT, 4), + ("$.a === 1", construct::TEXT, 6), + ("$.a > 1 > 2", construct::TRAILING, 8), + ("$.a == 1 2", construct::TRAILING, 9), + ("($.a == 1) is unknown", construct::TRAILING, 11), + ("!$.a == 1", construct::TEXT, 1), + ("!!($.a == 1)", construct::TEXT, 1), + ("($.a == 1", construct::TEXT, 9), + ("$.a == 01", construct::NUMBER, 7), + ("$.a == 1.", construct::NUMBER, 7), + ("$.a == 1e", construct::NUMBER, 7), + ("$.a == .5", construct::TEXT, 7), + ("$.a == 'x'", construct::TEXT, 7), + (r#"$.a == "x"#, construct::STRING, 7), + (r#"$."a == 1"#, construct::STRING, 2), + ("$.a == TRUE", construct::TEXT, 7), + ("$.1a == 1", construct::TEXT, 2), + ("$. == 1", construct::TEXT, 3), + ("$.a == 1 /* open", construct::TEXT, 9), + ("exists $.a", construct::TEXT, 7), + ("$.a == $1", construct::TEXT, 8), ] { assert_eq!( refusal(text, json!({})), @@ -1721,29 +980,32 @@ mod tests { ); let long = format!("$.{} == 1", vec!["a"; MAX_DEPTH + 1].join(".")); for (text, want) in [ - ("$.a[2] == 1", (JsonPathPosition, C_POSITION, 3)), - ("exists($.a[ 0 ])", (JsonPathPosition, C_POSITION, 10)), + ("$.a[2] == 1", (JsonPathPosition, construct::POSITION, 3)), + ( + "exists($.a[ 0 ])", + (JsonPathPosition, construct::POSITION, 10), + ), ( "$.a[*] != 1", - (JsonPredicateNotEqualAtWildcard, C_NOT_EQUAL, 7), + (JsonPredicateNotEqualAtWildcard, construct::NOT_EQUAL, 7), ), ( "$.a[*].b != null", - (JsonPredicateNotEqualAtWildcard, C_NOT_EQUAL, 9), + (JsonPredicateNotEqualAtWildcard, construct::NOT_EQUAL, 9), ), ( "exists($.a ? (@ == 1))", - (JsonPathNoWildcard, C_FILTER_WILDCARD, 7), + (JsonPathNoWildcard, construct::FILTER_WILDCARD, 7), ), ( "exists($.a[*] ? (@.b[*] == 1))", - (JsonPathWildcard, C_MEMBER_WILDCARD, 17), + (JsonPathWildcard, construct::MEMBER_WILDCARD, 17), ), ( deep.as_str(), - (JsonPredicateTooDeep, C_NESTING, MAX_NESTING + 1), + (JsonPredicateTooDeep, construct::NESTING, MAX_NESTING + 1), ), - (long.as_str(), (JsonPredicateTooDeep, C_NESTING, 0)), + (long.as_str(), (JsonPredicateTooDeep, construct::NESTING, 0)), ] { assert_eq!(refusal(text, json!({})), want, "{text}"); } @@ -1763,7 +1025,7 @@ mod tests { ); assert_eq!( refusal(&member(MAX_DEPTH - 1), json!({})), - (JsonPredicateTooDeep, C_NESTING, 7), + (JsonPredicateTooDeep, construct::NESTING, 7), "one equality: a filter's full path deeper than a document" ); let members = |steps: usize| { @@ -1774,7 +1036,7 @@ mod tests { }; assert_eq!( refusal(&members(MAX_DEPTH - 1), json!({})), - (JsonPredicateTooDeep, C_NESTING, 7), + (JsonPredicateTooDeep, construct::NESTING, 7), "two conditions: a member's full path deeper than a document" ); assert!( @@ -1795,7 +1057,7 @@ mod tests { let past = format!("$.{}.** == 1", vec!["a"; MAX_DEPTH].join(".")); assert_eq!( refusal(&past, json!({})), - (JsonPredicateTooDeep, C_NESTING, 0), + (JsonPredicateTooDeep, construct::NESTING, 0), "the step past the depth is not read" ); // Nesting is depth, not count: siblings past the limit, each From ef70c7ee28d61311b4e4d847a69e4fa7ee744534 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 22 Nov 2026 03:14:17 +1100 Subject: [PATCH 2/3] feat(stack-encrypt,stack-encrypt-derive): check a JSON predicate when 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 --- .cargo/mutants.toml | 5 + .../2026-10-24-stack-encrypt-api-plan.md | 18 +- .../tests/json_tree_field_references.rs | 52 ++ .../stack-encrypt-derive/src/json_paths.rs | 66 ++ packages/stack-encrypt-derive/src/lib.rs | 36 + .../stack-encrypt-derive/src/predicate.rs | 743 ++++++++++++++++++ packages/stack-encrypt/CHANGELOG.md | 20 + .../stack-encrypt/src/field_reference/json.rs | 146 ++++ .../field_reference/json/predicate_checks.rs | 302 +++++++ .../tests/json_predicate_macro.rs | 525 +++++++++++++ ...ld_reference_json_on_a_scalar_field.stderr | 10 +- .../tests/ui/predicate_on_a_scalar_field.rs | 20 + .../ui/predicate_on_a_scalar_field.stderr | 42 + .../ui/predicate_paths_must_be_declared.rs | 58 ++ .../predicate_paths_must_be_declared.stderr | 144 ++++ .../tests/ui/predicate_text_is_refused.rs | 37 + .../tests/ui/predicate_text_is_refused.stderr | 65 ++ .../tests/ui/predicate_values_must_fit.rs | 34 + .../tests/ui/predicate_values_must_fit.stderr | 76 ++ .../ui/predicate_variables_must_match.rs | 27 + .../ui/predicate_variables_must_match.stderr | 17 + 21 files changed, 2431 insertions(+), 12 deletions(-) create mode 100644 packages/stack-encrypt-derive/src/predicate.rs create mode 100644 packages/stack-encrypt/src/field_reference/json/predicate_checks.rs create mode 100644 packages/stack-encrypt/tests/json_predicate_macro.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.stderr create mode 100644 packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.stderr create mode 100644 packages/stack-encrypt/tests/ui/predicate_text_is_refused.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_text_is_refused.stderr create mode 100644 packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr create mode 100644 packages/stack-encrypt/tests/ui/predicate_variables_must_match.rs create mode 100644 packages/stack-encrypt/tests/ui/predicate_variables_must_match.stderr diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index eb0765398..a54fa4be6 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -61,6 +61,11 @@ exclude_globs = ["packages/stack-encrypt-derive/**"] # same reason. The future that a native `into_future` returns has no # `Default`, so the native mutant does not compile. exclude_re = [ + # stack-encrypt — equivalent. `predicate!`'s finders return the type of a + # path's values as a `PhantomData`, a zero-sized type with one value, so + # `PhantomData::from(Default::default())` is the same value. (Nothing calls + # them at run time either: the macro's checks are type-checked, never run.) + 'stack-encrypt/src/field_reference/json/predicate_checks\.rs:\d+:\d+: replace .* -> PhantomData<[^>]*> with PhantomData::from\(Default::default\(\)\)$', # stack-auth — unreachable under the native test build. 'stack-auth/src/transport\.rs:\d+:\d+: replace ::fmt ', 'stack-auth/src/transport\.rs:\d+:\d+: replace ::send_dyn -> std::pin::Pin>\+\x27a>> ', 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 f839b7ca4..e0640dd68 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1627,13 +1627,17 @@ Base64. form's operand and to the data plan's, the compile-fail cases under `packages/stack-encrypt/tests/ui` hold the refusals, and the [JSON query example](#query-a-json-document) runs. -- **Not done.** Checking a predicate's text at compile time (a - `predicate!` macro built on the typed paths), which a following pull - request adds. Until then the predicate text is checked when the query is - encrypted. -- **Tracked in.** Issue #1459 is open until the predicate pull request - merges; #1687 refers to it. Issue #1677 is open for opening one child. - Issue #1486 is closed. +- **Done** too: `predicate!(FIELD, "text", name = value, ..)` checks a + predicate's text at compile time, in the pull request stacked on #1687 + (22 November 2026). It reads the text with the engine's parser, which + moved into `stack-encrypt-jsonpath`; refuses what the parser and the + index refuse whatever the variables hold; matches the variables with + the text's `$name`s; and checks each path, member and value through the + accessors the derive generated, found by the path's text. When the + program runs it is `predicate(text).var(..)`, so the operand is the text + form's and the data plan's `match` operand. +- **Tracked in.** Issue #1459 closes with the `predicate!` pull request. + Issue #1677 is open for opening one child. Issue #1486 is closed. - **Finished when** these are all true: - the [JSON query example](#query-a-json-document) compiles; - a path, a member or a value type the field does not declare does not diff --git a/packages/eql/tests/encryption/tests/json_tree_field_references.rs b/packages/eql/tests/encryption/tests/json_tree_field_references.rs index e74550ef2..6cc767647 100644 --- a/packages/eql/tests/encryption/tests/json_tree_field_references.rs +++ b/packages/eql/tests/encryption/tests/json_tree_field_references.rs @@ -440,3 +440,55 @@ async fn a_path_declared_for_equality_is_the_data_plans_operand() { "{refused:?}" ); } + +/// `predicate!` on a `JsonTreeDocument` field: the macro's query is the +/// text form's for the same text and variables, as the EQL predicate type, +/// and it checks an ordered path, a path declared for equality alone and an +/// array's members alike. +#[tokio::test] +async fn the_predicate_macro_is_the_text_form() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let min: u32 = 30; + let from_macro: JsonTreePredicateQuery = stack_encrypt::predicate!( + NamedCustomer::PROFILE, + r#"$.age >= $min && $.name == "Ada" && exists($.visits[*] ? (@.place == $p && @.at > 10))"#, + min, + p = "home", + ) + .encrypt(&keyset) + .await + .unwrap(); + let from_text: JsonTreePredicateQuery = NamedCustomer::PROFILE + .predicate( + r#"$.age >= $min && $.name == "Ada" && exists($.visits[*] ? (@.place == $p && @.at > 10))"#, + ) + .var("min", min) + .var("p", "home") + .encrypt(&keyset) + .await + .unwrap(); + // The equality leaf is a containment needle, whose selectors each + // derivation sends in a random order of its own: compare the trees + // with each selector set sorted. + let sorted = |query: &JsonTreePredicateQuery| { + fn sort(value: &mut Value) { + match value { + Value::Object(map) => { + for (key, inner) in map.iter_mut() { + if let (true, Value::Array(items)) = (key == "sv", &mut *inner) { + items.sort_by_key(|item| item.to_string()); + } + sort(inner); + } + } + Value::Array(items) => items.iter_mut().for_each(sort), + _ => {} + } + } + let mut value = serde_json::to_value(query).unwrap(); + sort(&mut value); + value + }; + assert_eq!(sorted(&from_macro), sorted(&from_text)); +} diff --git a/packages/stack-encrypt-derive/src/json_paths.rs b/packages/stack-encrypt-derive/src/json_paths.rs index 8ba0de79e..3bada6d4a 100644 --- a/packages/stack-encrypt-derive/src/json_paths.rs +++ b/packages/stack-encrypt-derive/src/json_paths.rs @@ -18,6 +18,12 @@ //! member's type. It implements `ElementArray`, so a predicate on the //! array reaches its members again through `and()`. //! +//! For `predicate!`, which sees a predicate's paths as text, it also +//! implements a lookup of each path, array and member keyed by its text +//! (`PathLookup`, `ArrayLookup`, `MemberLookup`), each calling the +//! accessor above. The key is the path's text, so the lookup is the same +//! whatever word `names = {..}` gives a key. +//! //! # Names //! //! A JSON key gives a word: its ASCII letters in lower case, with `_` @@ -67,6 +73,13 @@ pub(crate) fn accessors( let at = format_ident!("{}At", prefix); let elements = format_ident!("{}Elements", prefix); let json_mod = quote!(#krate::field_reference::json); + let support = quote!(#json_mod::predicate_checks); + let lookup_bounds = quote! { + W: #krate::field_reference::Place, + T: #krate::json::JsonQueries, + C: #krate::field_reference::ScopeInput, + }; + let mut lookups = Vec::new(); let reference = quote!(#krate::FieldReference); let bounds = quote! { W: #krate::field_reference::Place, @@ -128,6 +141,22 @@ pub(crate) fn accessors( #json_mod::DeclaredPath::new(self.0, #text) } }); + let key = key_type(&support, &ordered.path.to_string()); + lookups.push(quote! { + #[automatically_derived] + impl #support::PathLookup<#key> for #paths { + type Value = #ty; + type Accessor = #json_mod::DeclaredPath; + fn path( + reference: #krate::FieldReference, + ) -> Self::Accessor + where + #lookup_bounds + { + reference.at().#method() + } + } + }); at_names.push((name, ordered)); } @@ -182,6 +211,21 @@ pub(crate) fn accessors( #members_type(#json_mod::ArrayElements::new(self.0, #array_text)) } }); + let key = key_type(&support, &array_text); + lookups.push(quote! { + #[automatically_derived] + impl #support::ArrayLookup<#key> for #paths { + type Array = #members_type; + fn array( + reference: #krate::FieldReference, + ) -> #members_type<#json_mod::ArrayElements> + where + #lookup_bounds + { + reference.elements().#method() + } + } + }); array_names.push((name, array.first)); let mut member_methods = Vec::new(); @@ -219,6 +263,19 @@ pub(crate) fn accessors( #json_mod::ElementMember::new(self.0, #member_text) } }); + // A member's key is its steps below the element, written from + // `$`, as the macro writes a filter's `@` path. + let key = key_type(&support, &JsonPath::from(member.clone()).to_string()); + lookups.push(quote! { + #[automatically_derived] + impl #support::MemberLookup<#key> for #members_type { + type Value = #ty; + type Accessor = #json_mod::ElementMember; + fn member(members: #members_type) -> #json_mod::ElementMember { + members.#method() + } + } + }); member_names.push((name, ordered)); } let doc = format!( @@ -300,6 +357,8 @@ pub(crate) fn accessors( #(#array_items)* + #(#lookups)* + #[automatically_derived] impl #json_mod::DocumentPaths for #paths { type At = #at; @@ -318,6 +377,13 @@ pub(crate) fn accessors( }) } +/// A path's text as a type, for `predicate!`'s lookups: the tuple of its +/// characters, each a `Char` of `support`. +pub(crate) fn key_type(support: &TokenStream, text: &str) -> TokenStream { + let chars = text.chars().map(|c| quote!(#support::Char<#c>)); + quote!((#(#chars,)*)) +} + /// One array a field declares through its ordered members. struct Array<'a> { path: JsonPath, diff --git a/packages/stack-encrypt-derive/src/lib.rs b/packages/stack-encrypt-derive/src/lib.rs index 896340a4c..2b8b177b6 100644 --- a/packages/stack-encrypt-derive/src/lib.rs +++ b/packages/stack-encrypt-derive/src/lib.rs @@ -325,6 +325,7 @@ mod attrs; mod json_paths; mod owned_decrypt; mod owned_encrypt; +mod predicate; mod shape; /// Derive the owned `EncryptTarget` declaration for a record struct. See @@ -356,3 +357,38 @@ pub fn derive_decrypt_source(input: TokenStream) -> TokenStream { .unwrap_or_else(syn::Error::into_compile_error) .into() } + +/// `stack_encrypt::predicate!`, given the path `stack-encrypt` is reached by: +/// `predicate_with_crate!($crate; reference, "text", variables…)`. Called +/// by that macro, which passes its `$crate`, and by nothing else. +#[doc(hidden)] +#[proc_macro] +pub fn predicate_with_crate(input: TokenStream) -> TokenStream { + let location = predicate_location(&input); + predicate::expand(input.into(), location) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// The line and column of the predicate literal, the second argument after +/// the crate path: what makes the names of an expansion's checks unique in +/// the crate, so the compiler names one by its name alone. `(0, 0)` when +/// the literal is not found, which costs only that. +fn predicate_location(input: &TokenStream) -> (usize, usize) { + use proc_macro::TokenTree; + let mut after_crate = false; + let mut commas = 0; + for token in input.clone() { + match token { + TokenTree::Punct(punct) if !after_crate && punct.as_char() == ';' => { + after_crate = true; + } + TokenTree::Punct(punct) if after_crate && punct.as_char() == ',' => commas += 1, + TokenTree::Literal(literal) if after_crate && commas == 1 => { + return (literal.span().line(), literal.span().column()); + } + _ => {} + } + } + (0, 0) +} diff --git a/packages/stack-encrypt-derive/src/predicate.rs b/packages/stack-encrypt-derive/src/predicate.rs new file mode 100644 index 000000000..4bdb14f3d --- /dev/null +++ b/packages/stack-encrypt-derive/src/predicate.rs @@ -0,0 +1,743 @@ +//! `predicate!`: a SQL/JSON path predicate on a document field, checked +//! when the program compiles and sent as written when it runs. +//! +//! `stack_encrypt::predicate!` passes `$crate` and its own input here, so +//! the expansion names `stack-encrypt` however the caller reaches it. +//! +//! The text is read with the grammar the engine reads it with +//! (`stack_encrypt_jsonpath::predicate`), and refused here, at the literal, +//! when it does not parse or uses a construct the JSON index cannot answer +//! whatever the variables hold. The variables are matched with the `$name`s +//! the text uses. What is left needs the field's declaration, which a macro +//! cannot see: for each path the text compares, the expansion asks the +//! compiler for the derive's lookup of that path (see +//! `stack_encrypt::field_reference::json::predicate_checks`), so the +//! compiler refuses a path, an array or a member the field does not +//! declare, and a value of another type, at the literal or at the +//! variable's expression. That code is type-checked and never run. +//! +//! When the program runs, the expansion is +//! `reference.predicate(text).var(name, value)…`: the same text, through +//! the engine's own path, so the operand is the one `predicate(text)` +//! derives. + +use proc_macro2::{Delimiter, Span, TokenStream, TokenTree}; +use quote::{format_ident, quote, quote_spanned}; +use stack_encrypt_jsonpath::predicate::{ + self, check_filter, single_equality, Comparison, Expression, LiteralKind, Operator, + PredicateError, PredicateErrorKind, ValueAt, MAX_NESTING, +}; +use stack_encrypt_jsonpath::{JsonPath, MAX_DEPTH}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{Expr, Ident, LitStr, Token}; + +use crate::json_paths::key_type; + +/// What `predicate!` was given, after the crate path. +struct Arguments { + reference: Expr, + text: LitStr, + variables: Vec, +} + +/// One variable: `name = value`, `"any name" = value`, or `name` alone for +/// `name = name`. +struct Variable { + name: String, + /// Where the name is written. + name_span: Span, + value: Expr, +} + +impl Parse for Arguments { + fn parse(input: ParseStream<'_>) -> syn::Result { + let reference: Expr = input.parse()?; + input.parse::()?; + let text: LitStr = input.parse().map_err(|error| { + syn::Error::new( + error.span(), + "`predicate!` takes a field reference, then the predicate as a string literal, \ + then its variables: `predicate!(Record::FIELD, \"$.age >= $min\", min = 30)`", + ) + })?; + let mut variables = Vec::new(); + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + variables.push(input.parse()?); + } + Ok(Self { + reference, + text, + variables, + }) + } +} + +impl Parse for Variable { + fn parse(input: ParseStream<'_>) -> syn::Result { + if input.peek(LitStr) { + let name: LitStr = input.parse()?; + input.parse::()?; + return Ok(Self { + name: name.value(), + name_span: name.span(), + value: input.parse()?, + }); + } + let ident: Ident = input.parse().map_err(|error| { + syn::Error::new( + error.span(), + "a variable is `name = value`, `\"any name\" = value`, or a local variable's \ + name alone", + ) + })?; + let name = ident.to_string(); + let name = name.strip_prefix("r#").unwrap_or(&name).to_owned(); + let value = if input.peek(Token![=]) { + input.parse::()?; + input.parse()? + } else { + syn::parse_quote!(#ident) + }; + Ok(Self { + name, + name_span: ident.span(), + value, + }) + } +} + +/// Expand `$crate ; reference, "text", variables…`. +pub(crate) fn expand(input: TokenStream, location: (usize, usize)) -> syn::Result { + let mut tokens = input.into_iter(); + let mut krate = TokenStream::new(); + for token in tokens.by_ref() { + match &token { + TokenTree::Punct(punct) if punct.as_char() == ';' => break, + // A `$crate` passed through a declarative macro can arrive + // wrapped in an undelimited group. + TokenTree::Group(group) if group.delimiter() == Delimiter::None => { + krate.extend(group.stream()); + } + _ => krate.extend([token]), + } + } + let arguments: Arguments = syn::parse2(tokens.collect())?; + let text = arguments.text.value(); + let expression = predicate::parse(&text) + .map_err(|error| syn::Error::new(arguments.text.span(), refusal_message(error)))?; + check_variables(&arguments, &expression)?; + check_structure(&text, &expression) + .map_err(|message| syn::Error::new(arguments.text.span(), message))?; + Ok(Expansion::new(krate, &arguments, &text, location).expand(&expression)) +} + +/// The message for a refusal of the grammar's, at the predicate literal. +fn refusal_message(error: PredicateError) -> String { + let PredicateError { + kind, + construct, + at, + } = error; + match kind { + PredicateErrorKind::Syntax => { + format!("this predicate does not parse: {construct} at byte {at}") + } + PredicateErrorKind::TooDeep => format!( + "this predicate nests too deep at byte {at}: the JSON index reads up to \ + {MAX_NESTING} levels of parentheses, `!` and `exists`, and paths of up to \ + {MAX_DEPTH} steps" + ), + PredicateErrorKind::Position => format!( + "this predicate names an array position at byte {at}: the JSON index reads every \ + element of an array alike, so write `[*]`" + ), + PredicateErrorKind::NotEqualAtWildcard => format!( + "the JSON index cannot answer `!=` at a path with a wildcard, at byte {at}: it \ + asks whether some element differs" + ), + PredicateErrorKind::FilterWithoutWildcard => format!( + "the filter at byte {at} is on a path with no wildcard: a filter tests the \ + elements of an array, as `exists($.visits[*] ? (@.place == \"home\"))`" + ), + PredicateErrorKind::MemberWildcard => format!( + "the filter condition at byte {at} names a path with a wildcard: a condition \ + names a member of one element" + ), + _ => { + format!("the JSON index cannot answer this predicate: it uses {construct} at byte {at}") + } + } +} + +/// Every variable the text uses is given, once, and every one given is +/// used. +fn check_variables(arguments: &Arguments, expression: &Expression) -> syn::Result<()> { + let mut used: Vec<&str> = Vec::new(); + variables_of(expression, &mut used); + let mut errors: Option = None; + let mut add = |error: syn::Error| match &mut errors { + Some(errors) => errors.combine(error), + None => errors = Some(error), + }; + for (index, variable) in arguments.variables.iter().enumerate() { + let name = &variable.name; + if arguments.variables[..index] + .iter() + .any(|earlier| earlier.name == *name) + { + add(syn::Error::new( + variable.name_span, + format!("`{name}` is given twice: give each variable once"), + )); + } else if !used.contains(&name.as_str()) { + add(syn::Error::new( + variable.name_span, + format!( + "`{name}` was given and the predicate does not use it: it names no `${name}`" + ), + )); + } + } + let mut missing: Vec<&str> = Vec::new(); + for name in used { + if !missing.contains(&name) && !arguments.variables.iter().any(|v| v.name == name) { + missing.push(name); + } + } + for name in missing { + let give = if syn::parse_str::(name).is_ok() { + format!("{name} = value") + } else { + format!("{name:?} = value") + }; + add(syn::Error::new( + arguments.text.span(), + format!("the predicate uses `${name}` and no `{name}` was given: add `{give}`"), + )); + } + errors.map_or(Ok(()), Err) +} + +/// The names of the variables `expression` uses, each once, in order. +fn variables_of<'e>(expression: &'e Expression, out: &mut Vec<&'e str>) { + let mut add = |comparison: &'e Comparison| { + if let Some(name) = comparison.value.variable() { + if !out.contains(&name) { + out.push(name); + } + } + }; + match expression { + Expression::And(terms) | Expression::Or(terms) => { + for term in terms { + variables_of(term, out); + } + } + Expression::Not(term) => variables_of(term, out), + Expression::Compare(comparison) => add(comparison), + Expression::Exists { filter, .. } => { + for condition in filter.iter().flatten() { + add(condition); + } + } + } +} + +/// The refusals the engine makes when the query is encrypted that depend +/// on neither the variables' values nor the field's options, in the order +/// the engine makes them, so the first is the one it would report. +fn check_structure(text: &str, expression: &Expression) -> Result<(), String> { + match expression { + Expression::And(terms) | Expression::Or(terms) => terms + .iter() + .try_for_each(|term| check_structure(text, term)), + Expression::Not(term) => check_structure(text, term), + Expression::Compare(comparison) => { + comparison + .refuse_not_equal_at_wildcard() + .map_err(refusal_message)?; + match comparison.operator { + Operator::Equal | Operator::NotEqual => literal(text, &comparison.value, false), + _ => { + literal(text, &comparison.value, true)?; + if comparison.path.path.is_positional() { + Ok(()) + } else { + comparison + .path + .element_member(comparison.at) + .map(drop) + .map_err(refusal_message) + } + } + } + } + Expression::Exists { filter: None, .. } => Ok(()), + Expression::Exists { + path, + filter: Some(conditions), + } => { + check_filter(path, conditions).map_err(refusal_message)?; + if let Some(only) = single_equality(conditions) { + return literal(text, &only.value, false); + } + conditions.iter().try_for_each(|condition| { + condition + .check_filter_condition() + .map_err(refusal_message)?; + literal(text, &condition.value, true) + }) + } + } +} + +/// A literal the engine reads, and one an ordering takes when `ordering`: +/// a number or a string. +fn literal(text: &str, value: &ValueAt, ordering: bool) -> Result<(), String> { + let (Some(kind), Some(literal)) = (value.literal_kind(text), value.literal_text(text)) else { + return Ok(()); + }; + let at = value.at(); + if kind == LiteralKind::Number && !number_is_read(literal) { + return Err(format!( + "the number `{literal}` at byte {at} is not one the JSON index reads: an integer \ + fits in 64 bits, and a number with a fraction or an exponent is a finite `f64`" + )); + } + if ordering && matches!(kind, LiteralKind::Boolean | LiteralKind::Null) { + return Err(format!( + "an ordering compares a number or a string, and the literal at byte {at} is \ + `{literal}`: ask for it with `==`" + )); + } + Ok(()) +} + +/// Whether the engine reads `token`, JSON number text, as a number: an +/// integer that fits a signed or unsigned 64-bit integer, or a number with +/// a fraction or an exponent whose nearest `f64` is finite. +pub(crate) fn number_is_read(token: &str) -> bool { + if token.contains(['.', 'e', 'E']) { + token.parse::().is_ok_and(f64::is_finite) + } else if token.starts_with('-') { + token.parse::().is_ok() + } else { + token.parse::().is_ok() + } +} + +/// What a check site asks of a path's accessor. +#[derive(Clone, Copy)] +enum Ask { + /// Its selector: `exists(path)`. + Selector, + /// A comparison: equality or an ordering. + Compare(Operator), +} + +/// The expansion: the run-time call, and the checks the compiler makes. +struct Expansion<'a> { + support: TokenStream, + arguments: &'a Arguments, + text: &'a str, + /// The field reference's type, in the checks. + reference: Ident, + /// Its paths type, in the checks. + paths: Ident, + /// Each variable's value, bound once, in the order given. + values: Vec, + checks: Vec, + /// The predicate literal's line and column, and how many checks have + /// been named: each check's trait has a name of its own in the crate, + /// so the compiler names it without its path. + location: (usize, usize), + named: std::cell::Cell, +} + +impl<'a> Expansion<'a> { + fn new( + krate: TokenStream, + arguments: &'a Arguments, + text: &'a str, + location: (usize, usize), + ) -> Self { + let local = |name: &str| Ident::new(name, Span::mixed_site()); + Self { + support: quote!(#krate::field_reference::json::predicate_checks), + arguments, + text, + reference: local("reference"), + paths: local("paths"), + values: (0..arguments.variables.len()) + .map(|index| format_ident!("value_{}", index, span = Span::mixed_site())) + .collect(), + checks: Vec::new(), + location, + named: std::cell::Cell::new(0), + } + } + + /// A name for a check's trait: `role`, the predicate's line and column, + /// and a count. + fn name(&self, role: &str) -> Ident { + let (line, column) = self.location; + let count = self.named.replace(self.named.get() + 1); + format_ident!("{role}Line{line}Column{column}Check{count}") + } + + fn expand(mut self, expression: &Expression) -> TokenStream { + self.visit(expression); + let Self { + support, + arguments, + reference, + paths, + values, + checks, + .. + } = self; + let reference_expression = &arguments.reference; + let text = &arguments.text; + let bindings = arguments + .variables + .iter() + .zip(&values) + .map(|(variable, value)| { + let expression = &variable.value; + quote_spanned!(expression.span()=> let #value = #expression;) + }); + let calls = arguments + .variables + .iter() + .zip(&values) + .map(|(variable, value)| { + let name = &variable.name; + quote_spanned!(variable.value.span()=> .var(#name, #value)) + }); + // The field reference's value, written at its expression, so a + // refusal of the field points there. + let field = Ident::new( + "field", + Span::mixed_site().located_at(reference_expression.span()), + ); + let query = Ident::new("query", Span::mixed_site()); + // The field reference is evaluated first, then each variable's + // value, once each. One call takes the field reference, so a field + // that stores no document is refused once, at the reference. + let document = quote_spanned! {reference_expression.span()=> + #support::document(#field, #text) + }; + quote! {{ + let #field = #reference_expression; + #(#bindings)* + let (#query, #paths, #reference) = #document; + #[allow(unused, clippy::all, clippy::pedantic)] + let _ = || { + #[allow(unused_imports)] + use #support::{ + FoundArray as _, FoundMember as _, FoundPath as _, MissingArray as _, + MissingMember as _, MissingPath as _, + }; + #(#checks)* + }; + #query #(#calls)* + }} + } + + fn visit(&mut self, expression: &Expression) { + match expression { + Expression::And(terms) | Expression::Or(terms) => { + for term in terms { + self.visit(term); + } + } + Expression::Not(term) => self.visit(term), + Expression::Compare(comparison) => { + self.at_path( + &comparison.path.path, + Ask::Compare(comparison.operator), + Some(&comparison.value), + ); + } + Expression::Exists { path, filter: None } => { + self.at_path(&path.path, Ask::Selector, None); + } + Expression::Exists { + path, + filter: Some(conditions), + } => { + // One equality is containment at the condition's full + // path, as the engine compiles it: that path's accessor + // answers it, ordered or not. + if let Some(only) = single_equality(conditions) { + let mut full = path.path.segments().to_vec(); + full.extend_from_slice(only.path.path.segments()); + self.at_path( + &JsonPath::from(full), + Ask::Compare(Operator::Equal), + Some(&only.value), + ); + return; + } + for condition in conditions { + self.member(&path.path, condition); + } + } + } + } + + /// The span of the predicate literal, resolving as the expansion's own + /// names do. + fn at_literal(&self) -> Span { + Span::mixed_site().located_at(self.arguments.text.span()) + } + + /// Check a path under `at()`: that the field declares it, that its + /// accessor answers `ask`, and that `value` fits its type. + fn at_path(&mut self, path: &JsonPath, ask: Ask, value: Option<&ValueAt>) { + let support = &self.support; + let shown = path.to_string(); + let key = key_type(support, &shown); + let declared = self.declared( + |name| quote!(impl> #name for D {}), + format!("this field declares no path `{}`", escaped(&shown)), + format!( + "`{}` is not one of the field's declared paths", + escaped(&shown) + ), + format!( + "`predicate!` checks each path against the field's `#[stash(json(..))]`. \ + Declare `{}` with its type under `ordered = {{..}}` to compare it, or under \ + `paths = {{..}}` for equality alone, or build this query at run time with \ + `predicate(text)`", + escaped(&shown) + ), + ); + let reference = &self.reference; + let paths = &self.paths; + let call = self.ask(ask); + let fits = value + .map(|value| self.fits(&shown, value)) + .unwrap_or_default(); + self.checks.push(quote! {{ + #declared + let find = #support::PathFind::<_, #key>::new(#paths); + let accessor = (&find).accessor(#support::placeholder_of(#reference)); + let value = (&find).value(); + accessor #call; + #fits + }}); + } + + /// Check one condition of a filter on the array `base`: that the field + /// declares the array with the member, that the member's accessor + /// answers the comparison, and that the value fits its type. + fn member(&mut self, base: &JsonPath, condition: &Comparison) { + let support = &self.support; + let array = base.to_string(); + let member = condition.path.path.to_string(); + let written = member.replacen('$', "@", 1); + let mut full = base.segments().to_vec(); + full.extend_from_slice(condition.path.path.segments()); + let full = JsonPath::from(full).to_string(); + let array_key = key_type(support, &array); + let member_key = key_type(support, &member); + let declared = self.declared( + |name| quote! { + impl #name for D + where + D: #support::ArrayLookup<#array_key>, + >::Array: #support::MemberLookup<#member_key>, + {} + }, + format!( + "this field declares no array `{}` whose elements have the ordered member `{}`", + escaped(&array), + escaped(&written) + ), + format!( + "`{}` is not one of the field's ordered paths", + escaped(&full) + ), + format!( + "a filter with more than one condition compares each member by its ordering \ + term. Declare `{}` with its type under `ordered = {{..}}` in the field's \ + `#[stash(json(..))]`, or build this query at run time with `predicate(text)`", + escaped(&full) + ), + ); + let reference = &self.reference; + let paths = &self.paths; + let call = self.ask(Ask::Compare(condition.operator)); + let fits = self.fits(&full, &condition.value); + self.checks.push(quote! {{ + #declared + let array = #support::ArrayFind::<_, #array_key>::new(#paths); + let members = (&array).members(#support::placeholder_of(#reference)); + let find = #support::MemberFind::<_, #member_key>::new((&array).array()); + let accessor = (&find).accessor(members); + let value = (&find).value(); + accessor #call; + #fits + }}); + } + + /// The method call a check makes on an accessor, with a value of the + /// path's own type. + fn ask(&self, ask: Ask) -> TokenStream { + let support = &self.support; + let method = match ask { + Ask::Selector => return quote!(.selector()), + Ask::Compare(Operator::Equal | Operator::NotEqual) => "eq", + Ask::Compare(Operator::Less) => "lt", + Ask::Compare(Operator::LessOrEqual) => "lte", + Ask::Compare(Operator::Greater) => "gt", + Ask::Compare(Operator::GreaterOrEqual) => "gte", + }; + // At the predicate, so a refused ordering of a path declared for + // equality alone points there. + let method = Ident::new( + method, + Span::call_site().located_at(self.arguments.text.span()), + ); + quote!(.#method(#support::placeholder_of(value))) + } + + /// The trait a check site requires of the paths type, refused with the + /// message given, at the predicate literal. + fn declared( + &self, + implementation: impl FnOnce(&Ident) -> TokenStream, + message: String, + label: String, + note: String, + ) -> TokenStream { + let paths = Ident::new("paths", self.at_literal()); + let name = self.name("Declares"); + let implementation = implementation(&name); + quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label, note = #note)] + trait #name {} + #[diagnostic::do_not_recommend] + #implementation + fn declared(_: ::core::marker::PhantomData) {} + declared(#paths); + } + } + + /// That `value` fits the type the path `shown` holds: a variable's + /// expression, at the expression; a literal's kind, at the predicate. + fn fits(&self, shown: &str, value: &ValueAt) -> TokenStream { + let support = &self.support; + let shown = escaped(shown); + if let Some(name) = value.variable() { + let Some(index) = self.arguments.variables.iter().position(|v| v.name == name) else { + // Refused already: a variable that is not given. + return TokenStream::new(); + }; + let expression = &self.arguments.variables[index].value; + let local = Ident::new( + &format!("value_{index}"), + Span::mixed_site().located_at(expression.span()), + ); + let message = format!("`{shown}` holds `{{V}}`, and `{{Self}}` is not one"); + let label = format!("the value of `${}`", escaped(name)); + let note = "a declared path takes the type its `ordered = {..}` or `paths = {..}` \ + entry names; a `String` path takes a `&str` or a `&String` too" + .replace('{', "{{") + .replace('}', "}}"); + let name = self.name("Fits"); + // Written at the value's expression, so a refusal points there; + // the names resolve as the check's own. + let here = Span::call_site().located_at(expression.span()); + let (fits, value) = (Ident::new("fits", here), Ident::new("value", here)); + let check = quote_spanned!(expression.span()=> #fits(#value, &#local);); + return quote! {{ + #[diagnostic::on_unimplemented(message = #message, label = #label, note = #note)] + trait #name {} + #[diagnostic::do_not_recommend] + impl> #name for X {} + fn fits>(_: ::core::marker::PhantomData, _: &X) {} + #check + }}; + } + let (Some(kind), Some(literal)) = + (value.literal_kind(self.text), value.literal_text(self.text)) + else { + return TokenStream::new(); + }; + let (bound, what) = match kind { + LiteralKind::Number => (quote!(#support::NumberFits), "a number"), + LiteralKind::String => (quote!(#support::StringFits), "a string"), + LiteralKind::Boolean => (quote!(#support::BooleanFits), "a boolean"), + LiteralKind::Null => return TokenStream::new(), + }; + let literal = escaped(literal); + let message = format!("`{shown}` holds `{{Self}}`, and the literal `{literal}` is {what}"); + let label = format!("this predicate compares `{shown}` with `{literal}`"); + // The check's own `value`, written at the predicate so a refusal + // points there. + let value = Ident::new( + "value", + Span::call_site().located_at(self.arguments.text.span()), + ); + let name = self.name("Fits"); + quote! {{ + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #name {} + #[diagnostic::do_not_recommend] + impl #name for V {} + fn fits(_: ::core::marker::PhantomData) {} + fits(#value); + }} + } +} + +/// Text for a `diagnostic::on_unimplemented` string, where `{` and `}` +/// name a type parameter unless doubled. +fn escaped(text: &str) -> String { + text.replace('{', "{{").replace('}', "}}") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The engine's parser of JSON text, and this crate's reading of a + /// number literal, agree on which numbers they read. + #[test] + fn reads_the_numbers_the_engine_reads() { + for token in [ + "0", + "-0", + "1", + "-1", + "1.5", + "-0.0", + "1e3", + "1E-2", + "2e+2", + "18446744073709551615", + "18446744073709551616", + "-9223372036854775808", + "-9223372036854775809", + "1e308", + "1e309", + "-1e999", + "5e-324", + "1e-400", + "123456789012345678.5", + ] { + assert_eq!( + number_is_read(token), + stack_encrypt::json::parse_text(token.as_bytes()).is_ok(), + "{token}" + ); + } + } +} diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 94bdd0259..d402c6f07 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -57,6 +57,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Three more records derive** (#1661). The owned derives did not accept +- **`predicate!`** (#1459). `predicate!(EncryptedCustomer::PROFILE, "$.age + >= $min && $.name == $name", min = 30, name)` checks a SQL/JSON path + predicate when the program compiles and sends the same text when it + runs: it expands to `predicate(text)` with a `var` for each variable, + so its query, its `scope` and `encrypt`, and its operand are the text + form's. The text is read with the engine's own parser, now in + `stack-encrypt-jsonpath`. Refused at compile time: text that does not + parse; a construct the JSON index cannot answer whatever the variables + hold; a variable used and not given, given and not used, or given twice; + a path the field does not declare (under `ordered` or `paths`), an + ordering of a path declared under `paths`, and a member of an array, in + a filter of more than one condition, that the array does not order; and + a value, variable or literal, of another type than the path's. The + macro finds a path's accessor by the path's text, through lookups the + derive now generates (hidden, in `field_reference::json::predicate_checks`), + so a `names` override changes nothing. It is a `macro_rules` wrapper + that passes `$crate`, so it works however a program reaches this crate. + The predicate parser moved to `stack-encrypt-jsonpath` with no change to + what it reads, refuses or derives. + - **Typed JSON queries from a field reference** (#1459, #1687). A field whose type stores a JSON document (`JsonDocument`, or EQL's `JsonTreeDocument`) has one field reference method for each kind of JSON diff --git a/packages/stack-encrypt/src/field_reference/json.rs b/packages/stack-encrypt/src/field_reference/json.rs index a0595f878..c7d23aa18 100644 --- a/packages/stack-encrypt/src/field_reference/json.rs +++ b/packages/stack-encrypt/src/field_reference/json.rs @@ -194,6 +194,152 @@ use crate::sem::TermError; use crate::target::Pending; use crate::KeysetCipher; +#[doc(hidden)] +pub mod predicate_checks; + +/// A SQL/JSON path predicate on a document field, checked when the program +/// compiles and sent as written when it runs. +/// +/// ```text +/// predicate!(FIELD_REFERENCE, "PREDICATE", name = value, …) +/// ``` +/// +/// The first argument is a document field's reference, such as +/// `EncryptedCustomer::PROFILE`, or one reached through an outer record +/// with [`field`](crate::FieldReference::field). The second is the +/// predicate's text, a string literal in the grammar +/// [`predicate(text)`](FieldReference::predicate) reads. Then each variable +/// the text names as `$name`: `name = value`, a local variable's name alone +/// for `name = name` (as `format!` takes one), or `"any name" = value` for +/// a `$"any name"` that is not a Rust identifier. Each value is evaluated +/// once, in the order given. +/// +/// It returns what `predicate(text)` returns, with each variable given by +/// [`var`](JsonFieldQuery::var): a query whose +/// [`scope`](JsonFieldQuery::scope), [`wildcard_bound`](JsonFieldQuery::wildcard_bound) +/// and [`encrypt`](JsonFieldQuery::encrypt) work as they do there, and +/// whose operand is the one `predicate(text)` and the dynamic interface's +/// `match` operator derive for the same text and values. +/// +/// The compiler refuses, at the predicate or at the variable: +/// +/// - text the grammar does not read, and a construct the JSON index cannot +/// answer, with the construct and its byte offset; +/// - a variable the text uses and that is not given, one given and not +/// used, and one given twice; +/// - a path the field does not declare, under `ordered = {..}` or +/// `paths = {..}`; an ordering of a path declared under `paths`; and a +/// condition, in a filter of more than one, on a member its array does +/// not order (such a filter compares each member by its ordering term; +/// a filter of one equality is containment at the member's path, which +/// any declared path answers); +/// - a value of another type than the path's: a variable's value, a +/// literal in the text (`$.age > "x"`), and an ordering's `true`, +/// `false` or `null`. +/// +/// So every path the text names must be declared. A predicate on a path +/// the field does not declare, or one built at run time from a user's +/// input, is [`predicate(text)`](FieldReference::predicate), which checks +/// the same rules when the query is encrypted. A JSON `null` is the +/// literal `null` in the text (`$.note == null`); a variable cannot be +/// one here, but can with [`var_null`](JsonFieldQuery::var_null). +/// +/// For example, a café keeps each customer's profile encrypted under +/// `customers/profile`, ordering the age and each visit's time and place, +/// and declaring the name for equality. It looks for Ada's profile if she +/// is 30 or more and once visited from home after 10 o'clock: +/// +/// ``` +/// use serde_json::json; +/// use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +/// use stack_encrypt::target::EncryptTarget; +/// use stack_encrypt::{predicate, EncryptInto, StackCipher}; +/// use zeroize::Zeroize; +/// +/// #[derive(Zeroize)] +/// struct Customer { +/// profile: JsonPlaintext, +/// } +/// +/// #[derive(EncryptTarget)] +/// #[stash(struct = Customer, scope = "customers")] +/// struct EncryptedCustomer { +/// #[stash(json( +/// ordered = { "$.age": u32, "$.visits[*].at": u64, "$.visits[*].place": String }, +/// paths = { "$.name": String }, +/// ))] +/// profile: JsonDocument, +/// } +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// let stored: EncryptedCustomer = Customer { +/// profile: json!({"name": "Ada", "age": 35, "visits": [{"place": "home", "at": 15}]}).into(), +/// } +/// .encrypt_into(&keyset) +/// .await?; +/// +/// let min_age: u32 = 30; +/// let after: u64 = 10; +/// // `col @@ $1`, which `eql_v4.json_tree_match` evaluates. +/// let regulars = predicate!( +/// EncryptedCustomer::PROFILE, +/// r#"$.name == "Ada" && $.age >= $min_age && exists($.visits[*] ? (@.place == "home" && @.at > $after))"#, +/// min_age, +/// after, +/// ) +/// .encrypt(&keyset) +/// .await?; +/// +/// // The operand `predicate(text)` derives for the same text and values. +/// let from_text = EncryptedCustomer::PROFILE +/// .predicate(r#"$.name == "Ada" && $.age >= $min_age && exists($.visits[*] ? (@.place == "home" && @.at > $after))"#) +/// .var("min_age", min_age) +/// .var("after", after) +/// .encrypt(&keyset) +/// .await?; +/// // An equality is a containment needle, which sends its selectors in a +/// // random order: compare the two with every selector set (`sv`) sorted. +/// fn sorted(value: &mut serde_json::Value) { +/// match value { +/// serde_json::Value::Object(map) => { +/// for (key, inner) in map.iter_mut() { +/// if let (true, serde_json::Value::Array(items)) = (key == "sv", &mut *inner) { +/// items.sort_by_key(|item| item.to_string()); +/// } +/// sorted(inner); +/// } +/// } +/// serde_json::Value::Array(items) => items.iter_mut().for_each(sorted), +/// _ => {} +/// } +/// } +/// let (mut regulars, mut from_text) = (serde_json::to_value(®ulars)?, serde_json::to_value(&from_text)?); +/// sorted(&mut regulars); +/// sorted(&mut from_text); +/// assert_eq!(regulars, from_text); +/// # let _ = stored; +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// These do not compile, each with a message that names the mistake +/// (`tests/ui/predicate_*.rs`): `"$.agee >= $min"` (no such path), +/// `"$.name > \"A\""` (a path declared for equality alone), +/// `min = "thirty"` for `$.age` (a `u32` path), `"$.age >= $min"` with no +/// `min`, `limit = 5` that the text does not use, and +/// `"$.age like_regex \"^3\""` (a construct the index cannot answer). +#[macro_export] +macro_rules! predicate { + ($($input:tt)*) => { + $crate::field_reference::json::predicate_checks::predicate_with_crate!($crate; $($input)*) + }; +} + /// The kind of a JSON query from a field reference that returns a path's selector: /// [`ValueAt::selector`]. A type tag, with no values. pub enum Selector {} diff --git a/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs b/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs new file mode 100644 index 000000000..d32fb1592 --- /dev/null +++ b/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs @@ -0,0 +1,302 @@ +//! What [`predicate!`](crate::predicate) expands to so that the compiler +//! checks a predicate against the paths its field declares. For generated +//! code only: nothing here is called when a program runs. +//! +//! The macro sees the predicate's text and the field reference's +//! expression, never the field's declaration. So it names each path the +//! text uses as a type, [`Char`] by [`Char`], and asks for the derive's +//! lookup of that path: [`PathLookup`], [`ArrayLookup`] and +//! [`MemberLookup`], which `#[derive(EncryptTarget)]` implements once for +//! each path, array and member the field's `#[stash(json(ordered = {..}))]` +//! declares, by calling the accessor it generated for it. The lookup is +//! keyed by the path's text, not the accessor's name, so a `names = {..}` +//! override, which the macro cannot see, changes nothing here. +//! +//! The macro's own trait, generated at each use, refuses a path the field +//! does not declare with a message that names it. The finders below then +//! fetch the accessor and the path's type when there is one, and +//! [`Unknown`], which takes anything, when there is not, so that one +//! mistake is reported once. +use std::marker::PhantomData; + +pub use stack_encrypt_derive::predicate_with_crate; + +use super::{ + ArrayElements, DocumentPaths, ElementArray, JsonFieldQuery, JsonScalarType, PathValue, + Predicate, +}; +use crate::field_reference::{FieldReference, Place, ScopeInput}; +use crate::json::JsonQueries; + +/// `reference.predicate(text)`, with the paths the field declares and the +/// field reference's type, for the checks. One call takes the field +/// reference, so a field that stores no document is refused once for it, +/// with [`JsonQueries`]'s message. (Each path is refused too: such a field +/// declares none.) +#[allow(clippy::type_complexity)] +pub fn document( + reference: FieldReference, + text: &str, +) -> ( + JsonFieldQuery, + PhantomData, + PhantomData>, +) { + (reference.predicate(text), PhantomData, PhantomData) +} + +/// One character of a path's text, as a type. A path is the tuple of its +/// characters, as `JsonPath`'s `Display` writes it: `$.age` is +/// `(Char<'$'>, Char<'.'>, Char<'a'>, Char<'g'>, Char<'e'>)`. +pub struct Char; + +/// A path the field declares, keyed by its text: what `at()` gives for it. +/// Implemented by the derive on the field's paths type. +pub trait PathLookup: DocumentPaths { + /// The type the path holds. + type Value; + /// What the path's accessor under `at()` returns. + type Accessor; + /// The path's accessor under `at()`. + fn path( + reference: FieldReference, + ) -> Self::Accessor; +} + +/// What an array's accessor under `elements()` returns: the array `A`'s +/// members, adding to the array's first condition. +pub type ArrayMembers = ::Members>; + +/// An array the field declares, keyed by its text (`$.visits[*]`): what +/// `elements()` gives for it. Implemented by the derive on the field's paths +/// type. +pub trait ArrayLookup: DocumentPaths { + /// The array's type, whose methods are its members. + type Array: ElementArray; + /// The array's accessor under `elements()`. + fn array( + reference: FieldReference, + ) -> ArrayMembers; +} + +/// A member of an array's elements, keyed by its text below the element, +/// written from `$` (`$.place`). Implemented by the derive on the array's +/// type. +pub trait MemberLookup: ElementArray { + /// The type the member holds. + type Value; + /// What the member's accessor returns. + type Accessor; + /// The member's accessor, adding to the predicate `Q`. + fn member(members: Self::Members) -> Self::Accessor; +} + +/// What a finder gives for a path, an array or a member the field does not +/// declare: a type whose methods take anything, so that the code that uses +/// it compiles and the one refusal is the missing path's. No value of it +/// exists. +pub enum Unknown {} + +macro_rules! takes_anything { + ($($method:ident),+) => { + impl Unknown { + $( + #[doc(hidden)] + pub fn $method(self, _: X) {} + )+ + } + }; +} +takes_anything!(eq, lt, lte, gt, gte); + +impl Unknown { + #[doc(hidden)] + pub fn is_null(self) {} + #[doc(hidden)] + pub fn selector(self) {} +} + +/// A value `V` may be compared with: what a path of type `V` takes +/// ([`PathValue`]), or anything at all for an [`Unknown`] path. +pub trait ValueFits {} +impl> ValueFits for X {} +impl ValueFits for X {} + +/// A type a number literal fits: the number types a path holds, and +/// [`Unknown`]. +pub trait NumberFits {} +/// A type a string literal fits: `String`, and [`Unknown`]. +pub trait StringFits {} +/// A type `true` or `false` fits: `bool`, which a path under `paths` can +/// hold, and [`Unknown`]. +pub trait BooleanFits {} + +macro_rules! number_fits { + ($($ty:ty),+) => {$(impl NumberFits for $ty {})+}; +} +number_fits!(i8, i16, i32, i64, u8, u16, u32, u64, f64, Unknown); +impl StringFits for String {} +impl StringFits for Unknown {} +impl BooleanFits for bool {} +impl BooleanFits for Unknown {} + +/// A value of the type `V`, for code that is type-checked and never run. +pub fn placeholder_of(_: PhantomData) -> V { + unreachable!("predicate! checks types and never runs this") +} + +/// Finds the path keyed `K` among the paths `D`. +pub struct PathFind(PhantomData (D, K)>); + +impl PathFind { + /// The finder for the paths `D`. + pub fn new(_: PhantomData) -> Self { + Self(PhantomData) + } +} + +/// The path, when the field declares it. +pub trait FoundPath { + /// The type the path holds. + type Value; + /// What the path's accessor returns. + type Accessor; + /// The type the path holds. + fn value(&self) -> PhantomData; + /// The path's accessor. + fn accessor( + &self, + reference: FieldReference, + ) -> Self::Accessor; +} + +impl, K> FoundPath for PathFind { + type Value = D::Value; + type Accessor = D::Accessor; + fn value(&self) -> PhantomData { + PhantomData + } + fn accessor( + &self, + reference: FieldReference, + ) -> D::Accessor { + D::path(reference) + } +} + +/// The path, when the field does not declare it: [`Unknown`]. Found only +/// when [`FoundPath`] is not. +pub trait MissingPath { + /// [`Unknown`]. + fn value(&self) -> PhantomData { + PhantomData + } + /// [`Unknown`]. + fn accessor(&self, _: R) -> Unknown { + unreachable!("predicate! checks types and never runs this") + } +} + +impl MissingPath for &PathFind {} + +/// Finds the array keyed `K` among the paths `D`. +pub struct ArrayFind(PhantomData (D, K)>); + +impl ArrayFind { + /// The finder for the paths `D`. + pub fn new(_: PhantomData) -> Self { + Self(PhantomData) + } +} + +/// The array, when the field declares it. +pub trait FoundArray { + /// The array's type. + type Array; + /// What the array's accessor returns. + type Members; + /// The array's type. + fn array(&self) -> PhantomData; + /// The array's accessor. + fn members( + &self, + reference: FieldReference, + ) -> Self::Members; +} + +impl, K> FoundArray for ArrayFind { + type Array = D::Array; + type Members = ArrayMembers; + fn array(&self) -> PhantomData { + PhantomData + } + fn members( + &self, + reference: FieldReference, + ) -> Self::Members { + D::array(reference) + } +} + +/// The array, when the field does not declare it: [`Unknown`]. Found only +/// when [`FoundArray`] is not. +pub trait MissingArray { + /// [`Unknown`]. + fn array(&self) -> PhantomData { + PhantomData + } + /// [`Unknown`]. + fn members(&self, _: R) -> Unknown { + unreachable!("predicate! checks types and never runs this") + } +} + +impl MissingArray for &ArrayFind {} + +/// Finds the member keyed `K` of the array `A`. +pub struct MemberFind(PhantomData (A, K)>); + +impl MemberFind { + /// The finder for the array `A`. + pub fn new(_: PhantomData) -> Self { + Self(PhantomData) + } +} + +/// The member, when the array has it. +pub trait FoundMember { + /// The type the member holds. + type Value; + /// What the member's accessor returns. + type Accessor; + /// The type the member holds. + fn value(&self) -> PhantomData; + /// The member's accessor. + fn accessor(&self, members: A::Members) -> Self::Accessor; +} + +impl, K> FoundMember for MemberFind { + type Value = A::Value; + type Accessor = A::Accessor; + fn value(&self) -> PhantomData { + PhantomData + } + fn accessor(&self, members: A::Members) -> A::Accessor { + A::member(members) + } +} + +/// The member, when the array does not have it, or is not declared: +/// [`Unknown`]. Found only when [`FoundMember`] is not. +pub trait MissingMember { + /// [`Unknown`]. + fn value(&self) -> PhantomData { + PhantomData + } + /// [`Unknown`]. + fn accessor(&self, _: R) -> Unknown { + unreachable!("predicate! checks types and never runs this") + } +} + +impl MissingMember for &MemberFind {} diff --git a/packages/stack-encrypt/tests/json_predicate_macro.rs b/packages/stack-encrypt/tests/json_predicate_macro.rs new file mode 100644 index 000000000..e669f85bc --- /dev/null +++ b/packages/stack-encrypt/tests/json_predicate_macro.rs @@ -0,0 +1,525 @@ +//! `predicate!`: a SQL/JSON path predicate on a document field, checked when +//! the program compiles and sent as written when it runs. +//! +//! Each test holds the macro's query to the one `predicate(text)` builds with +//! the same variables, byte for byte under one seed of the deterministic key +//! source (with the crate's `test-support` feature, which seeds the JSON +//! index's permutations), and as sets of selectors without it. With the +//! `dynamic` feature, it is also held to the operand the data plan's `match` +//! operator derives for the same text and variables. The compile-time +//! refusals are the `tests/ui/predicate_*.rs` cases. + +mod common; + +use std::cell::Cell; +use std::num::NonZeroU32; + +use serde_json::Value; +use stack_encrypt::field_reference::json::{JsonFieldQuery, Predicate}; +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::target::{EncryptTarget, Scope}; +use stack_encrypt::{predicate, Ready}; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +/// A profile with every kind of declared path: ordered numbers and strings, +/// paths for equality alone (a string, a boolean, a keyword key, quoted keys +/// named with `names`, an array's elements, an array's member), and members +/// of two arrays and of a nested array. +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +#[allow(dead_code)] // only queried +struct EncryptedCustomer { + #[stash(json( + ordered = { + "$.age": u32, + "$.score": f64, + "$.visits[*].at": u64, + "$.visits[*].place": String, + "$.contacts[*].relationship": String, + "$.contacts[*].calls": u32, + "$.orders[*].lines[*].qty": u32, + }, + paths = { + "$.name": String, + "$.note": String, + "$.vip": bool, + "$.type": String, + "$[\"first name\"]": String, + "$[\"ship to\"].zip": String, + "$.tags[*]": String, + "$.visits[*].kind": String, + }, + names = { "first name": given_name, "ship to": shipping }, + ))] + profile: JsonDocument, +} + +/// The same profile under a record that lists a scope. +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers", scope(tenant: u64))] +#[allow(dead_code)] // only queried +struct TenantCustomer { + #[stash(json(ordered = { "$.age": u32 }, paths = { "$.name": String }))] + profile: JsonDocument, +} + +#[derive(Zeroize)] +struct Account { + customer: Customer, +} + +/// The profile reached through an outer record. +#[derive(EncryptTarget)] +#[stash(struct = Account, scope = "accounts")] +#[allow(dead_code)] // only queried +struct EncryptedAccount { + customer: EncryptedCustomer, +} + +type Query = JsonFieldQuery; + +/// The seed every comparison derives under: both sides start from a fresh +/// cipher at the same seed, so they draw the same permutations. +const SEED: [u8; 32] = [5; 32]; + +/// The operand `query` derives, from a fresh cipher at [`SEED`]. +async fn operand(query: Query) -> Value { + let cipher = common::deterministic_cipher(SEED).await; + let keyset = cipher.default_keyset(); + serde_json::to_value(query.encrypt(&keyset).await.expect("derives")).unwrap() +} + +/// `value` with every selector set (`sv`) sorted, so two needles compare as +/// sets whatever order each was sent in. +fn sets(mut value: Value) -> Value { + fn sort(value: &mut Value) { + match value { + Value::Object(map) => { + for (key, inner) in map.iter_mut() { + if let (true, Value::Array(items)) = (key == "sv", &mut *inner) { + items.sort_by_key(|item| item.to_string()); + } + sort(inner); + } + } + Value::Array(items) => items.iter_mut().for_each(sort), + _ => {} + } + } + sort(&mut value); + value +} + +/// The macro's query and the text form's derive the same operand. +async fn assert_same(text: &str, from_macro: Query, from_text: Query) { + let (from_macro, from_text) = (operand(from_macro).await, operand(from_text).await); + #[cfg(feature = "test-support")] + assert_eq!(from_macro, from_text, "byte for byte: {text}"); + assert_eq!(sets(from_macro), sets(from_text), "{text}"); +} + +/// The macro and `predicate(text)` with the same variables, through a +/// declarative macro, as a caller's own macro would reach it. +macro_rules! same_as_text { + ($text:literal $(, $name:ident = $value:expr)* $(,)?) => { + assert_same( + $text, + predicate!(EncryptedCustomer::PROFILE, $text $(, $name = $value)*), + EncryptedCustomer::PROFILE.predicate($text) $(.var(stringify!($name), $value))*, + ) + .await + }; +} + +mod given_each_construct_of_the_grammar { + use super::*; + + #[tokio::test] + async fn each_comparison_at_one_node() { + same_as_text!("$.age >= $min", min = 30u32); + same_as_text!("$.age < 18"); + same_as_text!("$.age <= 18"); + same_as_text!("$.age > 18"); + same_as_text!("$.age == 35"); + same_as_text!("$.age != 35"); + same_as_text!("$.age <> 35"); + same_as_text!("18 < $.age"); + same_as_text!("$.score > 1.5"); + same_as_text!("$.score >= 2"); + same_as_text!("$.score < $s", s = 2.5); + same_as_text!(r#"$.name == "Ada""#); + same_as_text!("$.name == $name", name = "Ada"); + same_as_text!("$.name == null"); + same_as_text!("$.name != null"); + same_as_text!("$.vip == true"); + same_as_text!("$.vip == $vip", vip = false); + } + + #[tokio::test] + async fn keys_that_are_not_rust_names() { + same_as_text!(r#"$.type == "retail""#); + same_as_text!(r#"$."type" == "retail""#); + same_as_text!(r#"$."first name" == $first"#, first = "Ada"); + same_as_text!(r#"$."ship to".zip == "3000""#); + same_as_text!(r#"$ . "ship to" . zip == "3000""#); + } + + #[tokio::test] + async fn wildcards_presence_and_filters() { + same_as_text!(r#"$.tags[*] == "a""#); + same_as_text!("$.visits[*].at > 10"); + same_as_text!("exists($.age)"); + same_as_text!("exists($.visits[*].place)"); + same_as_text!("!exists($.name)"); + same_as_text!(r#"exists($.visits[*] ? (@.place == "home"))"#); + same_as_text!(r#"exists($.visits[*] ? (@.kind == "walk-in"))"#); + same_as_text!( + "exists($.visits[*] ? (@.place == $p && @.at > $after))", + p = "home", + after = 10u64, + ); + same_as_text!( + "exists($.contacts[*] ? (@.relationship == $r && @.calls > 5))", + r = "Sibling", + ); + same_as_text!("exists($.contacts[*] ? ((@.calls >= 1) && (@.calls < 9)))"); + same_as_text!("$.orders[*].lines[*].qty > 2"); + same_as_text!("exists($.orders[*].lines[*] ? (@.qty >= 1 && @.qty < 9))"); + } + + #[tokio::test] + async fn the_boolean_structure_and_the_text_around_it() { + same_as_text!(r#"$.age > 1 && ($.name == "Ada" || !($.score < 2))"#); + same_as_text!( + "$.age >= $min && $.name == $name && $.vip == $vip && $.note == null", + min = 30u32, + name = "Ada", + vip = true, + ); + same_as_text!(" $.age /* why */ >= $min ", min = 30u32); + same_as_text!("EXISTS($.age) && Exists($.name)"); + } +} + +mod given_how_a_caller_writes_it { + use super::*; + + /// A local variable's name alone gives it, as `format!` takes one; a + /// quoted variable is given by its name as a string; a value is any + /// expression, and a trailing comma is read. + #[tokio::test] + async fn variables_by_name_by_string_and_by_expression() { + let min: u32 = 30; + let name = "Ada".to_owned(); + let name = &name; + assert_same( + "shorthand", + predicate!( + EncryptedCustomer::PROFILE, + "$.age >= $min && $.name == $name", + min, + name + ), + EncryptedCustomer::PROFILE + .predicate("$.age >= $min && $.name == $name") + .var("min", min) + .var("name", name), + ) + .await; + assert_same( + "a quoted variable", + predicate!( + EncryptedCustomer::PROFILE, + r#"$.age >= $"min age""#, + "min age" = min + 1, + ), + EncryptedCustomer::PROFILE + .predicate(r#"$.age >= $"min age""#) + .var("min age", 31u32), + ) + .await; + let r#type = "retail"; + assert_same( + "a keyword variable", + predicate!(EncryptedCustomer::PROFILE, "$.type == $type", r#type), + EncryptedCustomer::PROFILE + .predicate("$.type == $type") + .var("type", "retail"), + ) + .await; + } + + /// Each variable's expression runs once, in the order given, and the + /// field reference's first. + #[tokio::test] + async fn each_expression_is_evaluated_once_in_order() { + let order = Cell::new(Vec::new()); + let note = |what: &'static str| { + let mut seen = order.take(); + seen.push(what); + order.set(seen); + }; + let query = predicate!( + { + note("reference"); + EncryptedCustomer::PROFILE + }, + "$.age >= $min && $.name == $name", + name = { + note("name"); + "Ada" + }, + min = { + note("min"); + 30u32 + }, + ); + assert_eq!(order.take(), ["reference", "name", "min"]); + assert_same( + "evaluated once", + query, + EncryptedCustomer::PROFILE + .predicate("$.age >= $min && $.name == $name") + .var("name", "Ada") + .var("min", 30u32), + ) + .await; + } + + /// The query takes `wildcard_bound`, as the text form's does. + #[tokio::test] + async fn a_wildcard_bound_is_kept() { + let bound = NonZeroU32::new(8).unwrap(); + let text = "exists($.visits[*] ? (@.place == \"home\" && @.at > 10))"; + assert_same( + text, + predicate!( + EncryptedCustomer::PROFILE, + "exists($.visits[*] ? (@.place == \"home\" && @.at > 10))" + ) + .wildcard_bound(bound), + EncryptedCustomer::PROFILE + .predicate(text) + .wildcard_bound(bound), + ) + .await; + } + + /// A record that lists a scope takes it after the macro. + #[tokio::test] + async fn a_scope_is_given_after_the_macro() { + assert_same( + "scoped", + predicate!( + TenantCustomer::PROFILE, + r#"$.age > $min && $.name == "Ada""#, + min = 3u32 + ) + .scope(Scope::new(7u64)), + TenantCustomer::PROFILE + .predicate(r#"$.age > $min && $.name == "Ada""#) + .var("min", 3u32) + .scope(Scope::new(7u64)), + ) + .await; + } + + /// A field reached through an outer record checks its paths as its own, + /// and derives under the outer field's context. + #[tokio::test] + async fn a_field_through_an_outer_record() { + let reference = EncryptedAccount::CUSTOMER.field(EncryptedCustomer::PROFILE); + assert_same( + "through an outer field", + predicate!( + EncryptedAccount::CUSTOMER.field(EncryptedCustomer::PROFILE), + "$.age >= $min && exists($.visits[*] ? (@.place == $p && @.at > 3))", + min = 30u32, + p = "home", + ), + reference + .predicate("$.age >= $min && exists($.visits[*] ? (@.place == $p && @.at > 3))") + .var("min", 30u32) + .var("p", "home"), + ) + .await; + } + + /// What only a run-time value can make wrong is refused when the query + /// is encrypted, as the text form refuses it. + #[tokio::test] + async fn the_query_is_refused_at_run_time_as_the_text_form_is() { + let cipher = common::deterministic_cipher(SEED).await; + let keyset = cipher.default_keyset(); + // A NaN is no JSON number: refused when the query is encrypted, + // before any key is requested, on both paths. + let from_macro = predicate!(EncryptedCustomer::PROFILE, "$.score > $s", s = f64::NAN) + .encrypt(&keyset) + .await + .unwrap_err(); + let from_text = EncryptedCustomer::PROFILE + .predicate("$.score > $s") + .var("s", f64::NAN) + .encrypt(&keyset) + .await + .unwrap_err(); + assert_eq!(from_macro.to_string(), from_text.to_string()); + } +} + +#[cfg(feature = "dynamic")] +mod as_the_data_plan_derives { + use super::*; + use serde_json::json; + use stack_encrypt::dynamic::{ + self, record, Op, Operand, TargetDescriptor, TargetError, TargetOptions, TargetResolver, + ValueFrame, ValueKind, + }; + use stack_encrypt::target::{DeclaredContext, IndexSpec}; + use stack_encrypt::{AsProtectedRef as _, KeysetCipher, Label, Pending, StackCipher}; + + /// A resolver holding `JsonSearch`, a document. The engine derives the + /// JSON operators itself, so it is asked for the description alone. + struct Documents; + + impl TargetResolver for Documents { + fn targets(&self) -> Vec { + vec![TargetDescriptor::new( + "JsonSearch", + "json", + "", + Some(ValueKind::Json), + "public.eql_v4_json_search", + vec!["json".to_string()], + Some("JsonSearchQuery".to_string()), + Some("eql_v4.query_json".to_string()), + true, + None, + ) + .with_leaf_query_sql_domain("eql_v4.query_json_leaf") + .with_elements_query_sql_domain("eql_v4.query_json_elements") + .with_predicate_query_sql_domain("eql_v4.query_json_predicate")] + } + + fn encrypt<'a, K: 'static>( + &self, + _: &str, + _: Option<&TargetOptions>, + _: &'a KeysetCipher<'_, K>, + _: &Label, + _: &DeclaredContext, + _: ValueFrame, + ) -> Result, K>, TargetError> { + unreachable!("only queried") + } + + fn decrypt<'a, K: 'static>( + &self, + _: &str, + _: &'a StackCipher, + _: &Label, + _: &DeclaredContext, + _: &[u8], + ) -> Result, TargetError> { + unreachable!("only queried") + } + + fn query<'a, K: 'static>( + &self, + _: &str, + _: &IndexSpec, + _: &'a KeysetCipher<'_, K>, + _: &Label, + _: &DeclaredContext, + _: ValueFrame, + ) -> Result, K>, TargetError> { + unreachable!("the JSON operators are the engine's") + } + } + + /// The record's field as a data plan: its ordered paths, and none of + /// its `paths`, which add nothing to its options. + fn plan() -> record::Plan { + let wire = json!({ + "profile": { + "context": ["customers", "profile"], + "type": "json", + "null": "sql", + "target": { + "name": "JsonSearch", + "options": { + "sealed_root": true, + "ordered": [ + "$.age", "$.score", "$.visits[*].at", "$.visits[*].place", + "$.contacts[*].relationship", "$.contacts[*].calls", + "$.orders[*].lines[*].qty" + ] + } + } + } + }); + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &Documents, + ) + .unwrap() + } + + /// The operand the data plan's `match` derives for `text` and `vars`, + /// from a fresh cipher at [`SEED`]. + async fn matched(text: &str, vars: Value) -> Value { + let cipher = common::deterministic_cipher(SEED).await; + let keyset = cipher.default_keyset(); + let input = json!({"predicate": text, "vars": vars.to_string()}); + let frame = ValueFrame::from_bytes( + dynamic::frame::serde::to_vec(&input) + .unwrap() + .as_protected_ref(), + ) + .unwrap(); + let operand = + dynamic::query_term(&keyset, &plan(), "profile", Op::Match, frame, &Documents) + .unwrap() + .await + .unwrap() + .operand() + .clone(); + match operand { + Operand::One(bytes) => serde_json::from_slice(&bytes).unwrap(), + other => panic!("one operand: {other:?}"), + } + } + + #[tokio::test] + async fn the_macro_derives_the_match_operand() { + let text = "$.age >= $min && $.name == $name && $.vip == $vip && $.note == null \ + && exists($.contacts[*] ? (@.relationship == $r && @.calls > 5)) \ + && $.\"first name\" == \"Ada\""; + let from_macro = operand(predicate!( + EncryptedCustomer::PROFILE, + "$.age >= $min && $.name == $name && $.vip == $vip && $.note == null \ + && exists($.contacts[*] ? (@.relationship == $r && @.calls > 5)) \ + && $.\"first name\" == \"Ada\"", + min = 30u32, + name = "Ada", + vip = true, + r = "Sibling", + )) + .await; + let data = matched( + text, + json!({"min": 30, "name": "Ada", "vip": true, "r": "Sibling"}), + ) + .await; + #[cfg(feature = "test-support")] + assert_eq!(from_macro, data, "byte for byte"); + assert_eq!(sets(from_macro), sets(data)); + } +} diff --git a/packages/stack-encrypt/tests/ui/field_reference_json_on_a_scalar_field.stderr b/packages/stack-encrypt/tests/ui/field_reference_json_on_a_scalar_field.stderr index 2eb78c5d6..134d24431 100644 --- a/packages/stack-encrypt/tests/ui/field_reference_json_on_a_scalar_field.stderr +++ b/packages/stack-encrypt/tests/ui/field_reference_json_on_a_scalar_field.stderr @@ -18,16 +18,16 @@ error[E0599]: the method `at` exists for struct `FieldReference { | --------------------------- doesn't satisfy `Encrypted: JsonQueries` | + ::: src/field_reference/json.rs + | + | pub enum TextPaths {} + | ------------------ doesn't satisfy `TextPaths: DocumentPaths` + | = note: the following trait bounds were not satisfied: `TextPaths: DocumentPaths` `Encrypted: JsonQueries` diff --git a/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.rs b/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.rs new file mode 100644 index 000000000..750940ced --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.rs @@ -0,0 +1,20 @@ +//! `predicate!` takes a field that stores a JSON document. +use stack_encrypt::predicate; +use stack_encrypt::target::EncryptTarget; +use stack_encrypt::StackCipherText; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + name: String, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + name: StackCipherText, +} + +fn main() { + let _ = predicate!(EncryptedCustomer::NAME, "$.age >= 30"); +} diff --git a/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.stderr b/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.stderr new file mode 100644 index 000000000..4f3409cf7 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_on_a_scalar_field.stderr @@ -0,0 +1,42 @@ +error[E0277]: `CipherText` does not store a JSON document, so its field reference has no JSON queries + --> tests/ui/predicate_on_a_scalar_field.rs:19:13 + | +19 | let _ = predicate!(EncryptedCustomer::NAME, "$.age >= 30"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | this field's type is `CipherText` + | required by a bound introduced by this call + | + = help: the trait `JsonQueries` is not implemented for `CipherText` + = note: the JSON queries (`contains`, `at`, `elements`, `predicate`, `children`) belong to a field whose type stores a JSON document, such as `JsonDocument` or `eql_bindings::v4::json_tree::JsonTreeDocument` +help: the following other types implement trait `JsonQueries` + --> src/json/target.rs + | + | impl JsonQueries for JsonDocument { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `JsonDocument` +... + | impl JsonQueries for Option { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Option` + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree +note: required by a bound in `document` + --> src/field_reference/json/predicate_checks.rs + | + | pub fn document( + | ^^^^^^^^^^^ required by this bound in `document` + = note: this error originates in the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no path `$.age` + --> tests/ui/predicate_on_a_scalar_field.rs:19:49 + | +19 | let _ = predicate!(EncryptedCustomer::NAME, "$.age >= 30"); + | ^^^^^^^^^^^^^ `$.age` is not one of the field's declared paths + | + = help: the trait `DeclaresLine19Column49Check0` is not implemented for `TextPaths` + = note: `predicate!` checks each path against the field's `#[stash(json(..))]`. Declare `$.age` with its type under `ordered = {..}` to compare it, or under `paths = {..}` for equality alone, or build this query at run time with `predicate(text)` +note: required by a bound in `declared` + --> tests/ui/predicate_on_a_scalar_field.rs:19:13 + | +19 | let _ = predicate!(EncryptedCustomer::NAME, "$.age >= 30"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.rs b/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.rs new file mode 100644 index 000000000..bc03bf0ce --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.rs @@ -0,0 +1,58 @@ +//! Every path a predicate names is one its field declares, under `ordered` +//! or `paths`: a path the field does not declare, an ordering of a path +//! declared for equality alone, a filter condition on a member its array +//! does not order or on a member of another array, and any path of a field +//! that declares none, do not compile. Each refusal names the path. +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::predicate; +use stack_encrypt::target::EncryptTarget; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { + "$.age": u32, + "$.visits[*].place": String, + "$.contacts[*].calls": u32, + }, paths = { "$.name": String, "$.visits[*].kind": String }))] + profile: JsonDocument, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct UndeclaredCustomer { + profile: JsonDocument, +} + +fn main() { + // A path the field does not declare. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.agee >= 30"); + // Equality on a path the field does not declare. + let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.email == "ada@example.com""#); + // An ordering of a path declared for equality alone. + let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.name > "A""#); + // A member declared for equality alone, in a filter of two conditions, + // which compares each member by its ordering term. + let _ = predicate!( + EncryptedCustomer::PROFILE, + r#"exists($.visits[*] ? (@.place == "home" && @.kind == "walk-in"))"# + ); + // A member its array does not declare. + let _ = predicate!( + EncryptedCustomer::PROFILE, + r#"exists($.visits[*] ? (@.place == "home" && @.at > 10))"# + ); + // A member of another array. + let _ = predicate!( + EncryptedCustomer::PROFILE, + r#"exists($.visits[*] ? (@.place == "home" && @.calls > 5))"# + ); + // A field that declares no paths. + let _ = predicate!(UndeclaredCustomer::PROFILE, "$.age >= 30"); +} diff --git a/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.stderr b/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.stderr new file mode 100644 index 000000000..aeb979579 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_paths_must_be_declared.stderr @@ -0,0 +1,144 @@ +error[E0277]: this field declares no path `$.agee` + --> tests/ui/predicate_paths_must_be_declared.rs:35:52 + | +35 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.agee >= 30"); + | ^^^^^^^^^^^^^^ `$.agee` is not one of the field's declared paths + | +help: the trait `DeclaresLine35Column52Check0` is not implemented for `EncryptedCustomerProfilePaths` + --> tests/ui/predicate_paths_must_be_declared.rs:16:10 + | +16 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ + = note: `predicate!` checks each path against the field's `#[stash(json(..))]`. Declare `$.agee` with its type under `ordered = {..}` to compare it, or under `paths = {..}` for equality alone, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#0}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:35:13 + | +35 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.agee >= 30"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no path `$.email` + --> tests/ui/predicate_paths_must_be_declared.rs:37:52 + | +37 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.email == "ada@example.com""#); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `$.email` is not one of the field's declared paths + | +help: the trait `DeclaresLine37Column52Check0` is not implemented for `EncryptedCustomerProfilePaths` + --> tests/ui/predicate_paths_must_be_declared.rs:16:10 + | +16 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ + = note: `predicate!` checks each path against the field's `#[stash(json(..))]`. Declare `$.email` with its type under `ordered = {..}` to compare it, or under `paths = {..}` for equality alone, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#1}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:37:13 + | +37 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.email == "ada@example.com""#); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this path is not ordered: declare it under `ordered` to compare it + --> tests/ui/predicate_paths_must_be_declared.rs:39:52 + | +39 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.name > "A""#); + | ^^^^^^^^^^^^^^^^^ an ordering of a path declared under `paths` + | + = help: the trait `OrderedPathKind` is not implemented for `EqualityPath` + = note: a path under `paths = {..}` is compared with `eq` and `is_null`; one under `ordered = {..}` with the orderings too, and its values carry an ordering term +help: the trait `OrderedPathKind` is implemented for `OrderedPath` + --> src/field_reference/json.rs + | + | impl OrderedPathKind for OrderedPath {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `DeclaredPath::::gt` + --> src/field_reference/json.rs + | + | pub fn gt(self, value: impl PathValue) -> JsonFieldQuery, C::Start> + | -- required by a bound in this associated function + | where + | O: OrderedPathKind, + | ^^^^^^^^^^^^^^^ required by this bound in `DeclaredPath::::gt` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no array `$.visits[*]` whose elements have the ordered member `@.kind` + --> tests/ui/predicate_paths_must_be_declared.rs:44:9 + | +44 | r#"exists($.visits[*] ? (@.place == "home" && @.kind == "walk-in"))"# + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `$.visits[*].kind` is not one of the field's ordered paths + | +help: the trait `DeclaresLine44Column9Check2` is not implemented for `EncryptedCustomerProfilePaths` + --> tests/ui/predicate_paths_must_be_declared.rs:16:10 + | +16 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ + = note: a filter with more than one condition compares each member by its ordering term. Declare `$.visits[*].kind` with its type under `ordered = {..}` in the field's `#[stash(json(..))]`, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#3}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:42:13 + | +42 | let _ = predicate!( + | _____________^ +43 | | EncryptedCustomer::PROFILE, +44 | | r#"exists($.visits[*] ? (@.place == "home" && @.kind == "walk-in"))"# +45 | | ); + | |_____^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no array `$.visits[*]` whose elements have the ordered member `@.at` + --> tests/ui/predicate_paths_must_be_declared.rs:49:9 + | +49 | r#"exists($.visits[*] ? (@.place == "home" && @.at > 10))"# + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `$.visits[*].at` is not one of the field's ordered paths + | +help: the trait `DeclaresLine49Column9Check2` is not implemented for `EncryptedCustomerProfilePaths` + --> tests/ui/predicate_paths_must_be_declared.rs:16:10 + | +16 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ + = note: a filter with more than one condition compares each member by its ordering term. Declare `$.visits[*].at` with its type under `ordered = {..}` in the field's `#[stash(json(..))]`, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#4}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:47:13 + | +47 | let _ = predicate!( + | _____________^ +48 | | EncryptedCustomer::PROFILE, +49 | | r#"exists($.visits[*] ? (@.place == "home" && @.at > 10))"# +50 | | ); + | |_____^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no array `$.visits[*]` whose elements have the ordered member `@.calls` + --> tests/ui/predicate_paths_must_be_declared.rs:54:9 + | +54 | r#"exists($.visits[*] ? (@.place == "home" && @.calls > 5))"# + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `$.visits[*].calls` is not one of the field's ordered paths + | +help: the trait `DeclaresLine54Column9Check2` is not implemented for `EncryptedCustomerProfilePaths` + --> tests/ui/predicate_paths_must_be_declared.rs:16:10 + | +16 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ + = note: a filter with more than one condition compares each member by its ordering term. Declare `$.visits[*].calls` with its type under `ordered = {..}` in the field's `#[stash(json(..))]`, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#5}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:52:13 + | +52 | let _ = predicate!( + | _____________^ +53 | | EncryptedCustomer::PROFILE, +54 | | r#"exists($.visits[*] ? (@.place == "home" && @.calls > 5))"# +55 | | ); + | |_____^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: this field declares no path `$.age` + --> tests/ui/predicate_paths_must_be_declared.rs:57:53 + | +57 | let _ = predicate!(UndeclaredCustomer::PROFILE, "$.age >= 30"); + | ^^^^^^^^^^^^^ `$.age` is not one of the field's declared paths + | + = help: the trait `DeclaresLine57Column53Check0` is not implemented for `TextPaths` + = note: `predicate!` checks each path against the field's `#[stash(json(..))]`. Declare `$.age` with its type under `ordered = {..}` to compare it, or under `paths = {..}` for equality alone, or build this query at run time with `predicate(text)` +note: required by a bound in `main::{closure#6}::declared` + --> tests/ui/predicate_paths_must_be_declared.rs:57:13 + | +57 | let _ = predicate!(UndeclaredCustomer::PROFILE, "$.age >= 30"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `declared` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/stack-encrypt/tests/ui/predicate_text_is_refused.rs b/packages/stack-encrypt/tests/ui/predicate_text_is_refused.rs new file mode 100644 index 000000000..4dcce30f4 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_text_is_refused.rs @@ -0,0 +1,37 @@ +//! `predicate!` reads its text with the engine's grammar when the program +//! compiles: text that does not parse, and a construct the JSON index +//! cannot answer whatever the variables hold, do not compile. Each refusal +//! names the construct and its byte offset. +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::predicate; +use stack_encrypt::target::EncryptTarget; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32, "$.visits[*].place": String, "$.tags[*]": String }))] + profile: JsonDocument, +} + +fn main() { + // Text that does not parse. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age = 30"); + // Constructs the index cannot answer. + let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age like_regex "^3""#); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age + 1 > 30"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[2].place == \"home\""); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.tags[*] != \"x\""); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.tags[*] > \"x\""); + let _ = predicate!(EncryptedCustomer::PROFILE, "exists($.age ? (@ == 1))"); + let _ = predicate!(EncryptedCustomer::PROFILE, "exists($.visits[*] ? (@ > 1 && @.place == \"x\"))"); + // A literal the engine refuses whatever the field declares. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= null"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == 1e999"); +} diff --git a/packages/stack-encrypt/tests/ui/predicate_text_is_refused.stderr b/packages/stack-encrypt/tests/ui/predicate_text_is_refused.stderr new file mode 100644 index 000000000..7b8ff5997 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_text_is_refused.stderr @@ -0,0 +1,65 @@ +error: this predicate does not parse: text the grammar does not read at byte 7 + --> tests/ui/predicate_text_is_refused.rs:24:52 + | +24 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >"); + | ^^^^^^^^^ + +error: this predicate does not parse: text the grammar does not read at byte 6 + --> tests/ui/predicate_text_is_refused.rs:25:52 + | +25 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age = 30"); + | ^^^^^^^^^^^^ + +error: the JSON index cannot answer this predicate: it uses `like_regex` at byte 6 + --> tests/ui/predicate_text_is_refused.rs:27:52 + | +27 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age like_regex "^3""#); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: the JSON index cannot answer this predicate: it uses arithmetic (`+`, `-`, `*`, `/`, `%`) at byte 6 + --> tests/ui/predicate_text_is_refused.rs:28:52 + | +28 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age + 1 > 30"); + | ^^^^^^^^^^^^^^^^ + +error: this predicate names an array position at byte 8: the JSON index reads every element of an array alike, so write `[*]` + --> tests/ui/predicate_text_is_refused.rs:29:52 + | +29 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[2].place == \"home\""); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: the JSON index cannot answer `!=` at a path with a wildcard, at byte 10: it asks whether some element differs + --> tests/ui/predicate_text_is_refused.rs:30:52 + | +30 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.tags[*] != \"x\""); + | ^^^^^^^^^^^^^^^^^^^^ + +error: the JSON index cannot answer this predicate: it uses an ordering of an array's elements themselves at byte 10 + --> tests/ui/predicate_text_is_refused.rs:31:52 + | +31 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.tags[*] > \"x\""); + | ^^^^^^^^^^^^^^^^^^^ + +error: the filter at byte 7 is on a path with no wildcard: a filter tests the elements of an array, as `exists($.visits[*] ? (@.place == "home"))` + --> tests/ui/predicate_text_is_refused.rs:32:52 + | +32 | let _ = predicate!(EncryptedCustomer::PROFILE, "exists($.age ? (@ == 1))"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: the JSON index cannot answer this predicate: it uses an ordering of an array's elements themselves at byte 22 + --> tests/ui/predicate_text_is_refused.rs:33:52 + | +33 | let _ = predicate!(EncryptedCustomer::PROFILE, "exists($.visits[*] ? (@ > 1 && @.place == \"x\"))"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: an ordering compares a number or a string, and the literal at byte 9 is `null`: ask for it with `==` + --> tests/ui/predicate_text_is_refused.rs:35:52 + | +35 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= null"); + | ^^^^^^^^^^^^^^^ + +error: the number `1e999` at byte 9 is not one the JSON index reads: an integer fits in 64 bits, and a number with a fraction or an exponent is a finite `f64` + --> tests/ui/predicate_text_is_refused.rs:36:52 + | +36 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == 1e999"); + | ^^^^^^^^^^^^^^^^ diff --git a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs new file mode 100644 index 000000000..1866cf6cb --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs @@ -0,0 +1,34 @@ +//! A value compared with a path is of the path's type: a variable's +//! value, refused at the value, and a literal in the text, refused at the +//! predicate. +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::predicate; +use stack_encrypt::target::EncryptTarget; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32, "$.visits[*].place": String }))] + profile: JsonDocument, +} + +fn main() { + // A variable of another type. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); + let place = 7_u8; + let _ = predicate!( + EncryptedCustomer::PROFILE, + "exists($.visits[*] ? (@.place == $place))", + place + ); + // A literal of another type. + let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); +} diff --git a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr new file mode 100644 index 000000000..dfc71219c --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr @@ -0,0 +1,76 @@ +error[E0277]: `$.age` holds `u32`, and `&str` is not one + --> tests/ui/predicate_values_must_fit.rs:23:75 + | +23 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); + | ^^^^^^^^ the value of `$min` + | + = help: the trait `FitsLine23Column52Check1` is not implemented for `&str` + = note: a declared path takes the type its `ordered = {..}` or `paths = {..}` entry names; a `String` path takes a `&str` or a `&String` too +note: required by a bound in `main::{closure#0}::fits` + --> tests/ui/predicate_values_must_fit.rs:23:13 + | +23 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.visits[*].place` holds `std::string::String`, and `u8` is not one + --> tests/ui/predicate_values_must_fit.rs:28:9 + | +28 | place + | ^^^^^ the value of `$place` + | + = help: the trait `FitsLine27Column9Check1` is not implemented for `u8` + = note: a declared path takes the type its `ordered = {..}` or `paths = {..}` entry names; a `String` path takes a `&str` or a `&String` too +note: required by a bound in `main::{closure#1}::fits` + --> tests/ui/predicate_values_must_fit.rs:25:13 + | +25 | let _ = predicate!( + | _____________^ +26 | | EncryptedCustomer::PROFILE, +27 | | "exists($.visits[*] ? (@.place == $place))", +28 | | place +29 | | ); + | |_____^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.age` holds `u32`, and the literal `"x"` is a string + --> tests/ui/predicate_values_must_fit.rs:31:52 + | +31 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); + | ^^^^^^^^^^^^^^^^ this predicate compares `$.age` with `"x"` + | + = help: the trait `FitsLine31Column52Check1` is not implemented for `u32` +note: required by a bound in `main::{closure#2}::fits` + --> tests/ui/predicate_values_must_fit.rs:31:13 + | +31 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.visits[*].place` holds `std::string::String`, and the literal `3` is a number + --> tests/ui/predicate_values_must_fit.rs:32:52 + | +32 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); + | ^^^^^^^^^^^^^^^^^^^^^^^^ this predicate compares `$.visits[*].place` with `3` + | + = help: the trait `FitsLine32Column52Check1` is not implemented for `std::string::String` +note: required by a bound in `main::{closure#3}::fits` + --> tests/ui/predicate_values_must_fit.rs:32:13 + | +32 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.age` holds `u32`, and the literal `true` is a boolean + --> tests/ui/predicate_values_must_fit.rs:33:52 + | +33 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); + | ^^^^^^^^^^^^^^^ this predicate compares `$.age` with `true` + | + = help: the trait `FitsLine33Column52Check1` is not implemented for `u32` +note: required by a bound in `main::{closure#4}::fits` + --> tests/ui/predicate_values_must_fit.rs:33:13 + | +33 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/stack-encrypt/tests/ui/predicate_variables_must_match.rs b/packages/stack-encrypt/tests/ui/predicate_variables_must_match.rs new file mode 100644 index 000000000..b3fa253e7 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_variables_must_match.rs @@ -0,0 +1,27 @@ +//! Every `$name` the text uses is given, every variable given is used, and +//! none is given twice. +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::predicate; +use stack_encrypt::target::EncryptTarget; +use zeroize::Zeroize; + +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32 }))] + profile: JsonDocument, +} + +fn main() { + // A variable the text uses and no value for it. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min"); + // A variable given and not used. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = 30, limit = 5); + // A variable given twice. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = 30, min = 40); +} diff --git a/packages/stack-encrypt/tests/ui/predicate_variables_must_match.stderr b/packages/stack-encrypt/tests/ui/predicate_variables_must_match.stderr new file mode 100644 index 000000000..d7b4e7316 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/predicate_variables_must_match.stderr @@ -0,0 +1,17 @@ +error: the predicate uses `$min` and no `min` was given: add `min = value` + --> tests/ui/predicate_variables_must_match.rs:22:52 + | +22 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min"); + | ^^^^^^^^^^^^^^^ + +error: `limit` was given and the predicate does not use it: it names no `$limit` + --> tests/ui/predicate_variables_must_match.rs:24:79 + | +24 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = 30, limit = 5); + | ^^^^^ + +error: `min` is given twice: give each variable once + --> tests/ui/predicate_variables_must_match.rs:26:79 + | +26 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = 30, min = 40); + | ^^^ From 3e98a8aff68ecad4455dbd272473c88314fb1755 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 22 Nov 2026 14:46:46 +1100 Subject: [PATCH 3/3] fix(stack-encrypt,stack-encrypt-derive,stack-encrypt-jsonpath): address 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. --- .../2026-10-24-stack-encrypt-api-plan.md | 12 +- packages/stack-encrypt-derive/Cargo.toml | 5 +- packages/stack-encrypt-derive/src/lib.rs | 26 +--- .../stack-encrypt-derive/src/predicate.rs | 140 +++++++++++++++--- packages/stack-encrypt-jsonpath/src/lib.rs | 22 ++- .../stack-encrypt-jsonpath/src/predicate.rs | 13 +- .../src/predicate/tests.rs | 12 +- packages/stack-encrypt/CHANGELOG.md | 8 +- .../stack-encrypt/src/field_reference/json.rs | 14 +- .../field_reference/json/predicate_checks.rs | 57 +++++-- packages/stack-encrypt/src/json/predicate.rs | 7 +- .../tests/json_predicate_macro.rs | 2 +- .../tests/ui/predicate_values_must_fit.rs | 21 ++- .../tests/ui/predicate_values_must_fit.stderr | 123 +++++++++++---- 14 files changed, 349 insertions(+), 113 deletions(-) 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 e0640dd68..76e803c6f 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -516,7 +516,7 @@ The kinds of JSON query, the field reference method for each, and what each find | Comparison at a path | `at().age().gt(v)`, `.lt(v)`, `.between(a, b)`, and the rest | Rows where the value at an ordered path orders against, or lies between, the given values | `JsonTreeLeafQuery`; two for `between`, low then high | | A path's selector | `at().age().selector()` | The selector `->` and `ORDER BY eql_v4.ord_term(col -> $1)` take | `JsonTreeSelector` | | Element match | `elements().visits().place().eq(v).and().at().gt(v)` | Rows where one element of an array meets several conditions together | `JsonTreeElementsQuery` | -| Jsonpath predicate | `predicate(text)`, with `.var(name, v)` for each variable | Rows where a SQL/JSON path predicate is true | `JsonTreePredicateQuery` | +| Jsonpath predicate | `predicate!(FIELD, "text", name = v, ..)`, checked when the program compiles, and `predicate(text)`, with `.var(name, v)` for each variable, for text built at run time | Rows where a SQL/JSON path predicate is true | `JsonTreePredicateQuery` | | Children and child count | `children(path)` | The entries directly below one node, or how many there are | `JsonTreeToken` | Paths are typed, from the attribute. Decided by Dan on 21 November 2026: @@ -547,8 +547,14 @@ Paths are typed, from the attribute. Decided by Dan on 21 November 2026: path and value. A field that declares no paths has only these. - A predicate's variables are given one at a time: `.var(name, v)`, with `v` a scalar, and `.var_null(name)`. A repeated name, a NaN and an - infinity are refused before any key is fetched. The predicate text is - checked when the query is encrypted. + infinity are refused before any key is fetched. The text of + `predicate(text)` is checked when the query is encrypted. +- `predicate!(FIELD, "text", name = v, ..)` checks a predicate written in + the program when the program compiles: that the text parses, that the + index can answer it, that each variable is given once and used, that the + field declares each path and member, and that each value, a variable's or + a literal's, is of the path's type. It sends the same text, so its + operand is the one `predicate(text)` derives. Two limits of the SQL stay, from the reference page's sections on comparing a value at a path and on what the SQL cannot do. Sorting rows by a path through an array diff --git a/packages/stack-encrypt-derive/Cargo.toml b/packages/stack-encrypt-derive/Cargo.toml index 8cc735f9c..3c9cc3357 100644 --- a/packages/stack-encrypt-derive/Cargo.toml +++ b/packages/stack-encrypt-derive/Cargo.toml @@ -26,10 +26,11 @@ syn = { version = "3", features = ["full", "extra-traits"] } # built into the compiler's process. stack-encrypt-jsonpath = { path = "../stack-encrypt-jsonpath", version = "0.3.0" } -# The dev-dependencies below are used only by the crate-level doctests. +# `tokio` and `zeroize` are used only by the crate-level doctests. # `cargo-udeps` cannot see into rustdoc, so it reports them as unused. +# (`stack-encrypt` is used by a unit test too, which `cargo-udeps` sees.) [package.metadata.cargo-udeps.ignore] -development = ["stack-encrypt", "tokio", "zeroize"] +development = ["tokio", "zeroize"] [dev-dependencies] # The plain-segment rule is copied from stack-encrypt (a proc-macro crate cannot diff --git a/packages/stack-encrypt-derive/src/lib.rs b/packages/stack-encrypt-derive/src/lib.rs index 2b8b177b6..9e3e75367 100644 --- a/packages/stack-encrypt-derive/src/lib.rs +++ b/packages/stack-encrypt-derive/src/lib.rs @@ -364,31 +364,7 @@ pub fn derive_decrypt_source(input: TokenStream) -> TokenStream { #[doc(hidden)] #[proc_macro] pub fn predicate_with_crate(input: TokenStream) -> TokenStream { - let location = predicate_location(&input); - predicate::expand(input.into(), location) + predicate::expand(input.into()) .unwrap_or_else(syn::Error::into_compile_error) .into() } - -/// The line and column of the predicate literal, the second argument after -/// the crate path: what makes the names of an expansion's checks unique in -/// the crate, so the compiler names one by its name alone. `(0, 0)` when -/// the literal is not found, which costs only that. -fn predicate_location(input: &TokenStream) -> (usize, usize) { - use proc_macro::TokenTree; - let mut after_crate = false; - let mut commas = 0; - for token in input.clone() { - match token { - TokenTree::Punct(punct) if !after_crate && punct.as_char() == ';' => { - after_crate = true; - } - TokenTree::Punct(punct) if after_crate && punct.as_char() == ',' => commas += 1, - TokenTree::Literal(literal) if after_crate && commas == 1 => { - return (literal.span().line(), literal.span().column()); - } - _ => {} - } - } - (0, 0) -} diff --git a/packages/stack-encrypt-derive/src/predicate.rs b/packages/stack-encrypt-derive/src/predicate.rs index 4bdb14f3d..e69c76df1 100644 --- a/packages/stack-encrypt-derive/src/predicate.rs +++ b/packages/stack-encrypt-derive/src/predicate.rs @@ -112,7 +112,7 @@ impl Parse for Variable { } /// Expand `$crate ; reference, "text", variables…`. -pub(crate) fn expand(input: TokenStream, location: (usize, usize)) -> syn::Result { +pub(crate) fn expand(input: TokenStream) -> syn::Result { let mut tokens = input.into_iter(); let mut krate = TokenStream::new(); for token in tokens.by_ref() { @@ -133,6 +133,9 @@ pub(crate) fn expand(input: TokenStream, location: (usize, usize)) -> syn::Resul check_variables(&arguments, &expression)?; check_structure(&text, &expression) .map_err(|message| syn::Error::new(arguments.text.span(), message))?; + // Where the predicate literal is written, for the names of the checks. + let literal = arguments.text.span().unwrap(); + let location = (literal.line(), literal.column()); Ok(Expansion::new(krate, &arguments, &text, location).expand(&expression)) } @@ -265,15 +268,11 @@ fn check_structure(text: &str, expression: &Expression) -> Result<(), String> { Operator::Equal | Operator::NotEqual => literal(text, &comparison.value, false), _ => { literal(text, &comparison.value, true)?; - if comparison.path.path.is_positional() { - Ok(()) - } else { - comparison - .path - .element_member(comparison.at) - .map(drop) - .map_err(refusal_message) - } + comparison + .path + .element_member(comparison.at) + .map(drop) + .map_err(refusal_message) } } } @@ -331,6 +330,45 @@ pub(crate) fn number_is_read(token: &str) -> bool { } } +/// The type a number literal is named by in `NumberFits`, from its text: +/// `Fraction` for a number with a fraction or an exponent, else `UpTo` or +/// `DownTo` the narrowest integer type that holds it. `None` for a number +/// the engine does not read, which is refused before this is asked. +pub(crate) fn number_class(token: &str) -> Option<(&'static str, Option<&'static str>)> { + if token.contains(['.', 'e', 'E']) { + return Some(("Fraction", None)); + } + if let Ok(value) = token.parse::() { + let narrowest = [ + ("i8", u64::from(i8::MAX.unsigned_abs())), + ("u8", u64::from(u8::MAX)), + ("i16", u64::from(i16::MAX.unsigned_abs())), + ("u16", u64::from(u16::MAX)), + ("i32", u64::from(i32::MAX.unsigned_abs())), + ("u32", u64::from(u32::MAX)), + ("i64", i64::MAX.unsigned_abs()), + ] + .into_iter() + .find(|(_, max)| value <= *max) + .map_or("u64", |(name, _)| name); + return Some(("UpTo", Some(narrowest))); + } + let value = token.parse::().ok()?; + if value >= 0 { + // `-0`. + return Some(("UpTo", Some("i8"))); + } + let narrowest = [ + ("i8", i64::from(i8::MIN)), + ("i16", i64::from(i16::MIN)), + ("i32", i64::from(i32::MIN)), + ] + .into_iter() + .find(|(_, min)| value >= *min) + .map_or("i64", |(name, _)| name); + Some(("DownTo", Some(narrowest))) +} + /// What a check site asks of a path's accessor. #[derive(Clone, Copy)] enum Ask { @@ -353,8 +391,11 @@ struct Expansion<'a> { values: Vec, checks: Vec, /// The predicate literal's line and column, and how many checks have - /// been named: each check's trait has a name of its own in the crate, - /// so the compiler names it without its path. + /// been named: each check's trait has a name of its own in its file, + /// so the compiler names it without its path. (Two predicates at the + /// same line and column of two files of one crate share a name, and + /// the compiler then prints the path of each. Each check is in a block + /// of its own, so that changes a message and nothing else.) location: (usize, usize), named: std::cell::Cell, } @@ -671,10 +712,33 @@ impl<'a> Expansion<'a> { else { return TokenStream::new(); }; - let (bound, what) = match kind { - LiteralKind::Number => (quote!(#support::NumberFits), "a number"), - LiteralKind::String => (quote!(#support::StringFits), "a string"), - LiteralKind::Boolean => (quote!(#support::BooleanFits), "a boolean"), + let (bound, what, note) = match kind { + LiteralKind::Number => { + let Some((class, narrowest)) = number_class(literal) else { + // Refused already: a number the engine does not read. + return TokenStream::new(); + }; + let class = Ident::new(class, Span::call_site()); + let narrowest = narrowest.map(|name| { + let name = Ident::new(name, Span::call_site()); + quote!(<::core::primitive::#name>) + }); + ( + quote!(#support::NumberFits<#support::#class #narrowest>), + "a number it does not hold", + "an integer path holds the integers of its type, and an `f64` path any number", + ) + } + LiteralKind::String => ( + quote!(#support::StringFits), + "a string", + "a string literal fits a `String` path", + ), + LiteralKind::Boolean => ( + quote!(#support::BooleanFits), + "a boolean", + "`true` and `false` fit a `bool` path, which `paths = {{..}}` can declare", + ), LiteralKind::Null => return TokenStream::new(), }; let literal = escaped(literal); @@ -688,7 +752,7 @@ impl<'a> Expansion<'a> { ); let name = self.name("Fits"); quote! {{ - #[diagnostic::on_unimplemented(message = #message, label = #label)] + #[diagnostic::on_unimplemented(message = #message, label = #label, note = #note)] trait #name {} #[diagnostic::do_not_recommend] impl #name for V {} @@ -740,4 +804,46 @@ mod tests { ); } } + + /// A number literal is named by the narrowest type that holds it, at + /// each type's limits. + #[test] + fn names_a_number_by_the_narrowest_type_that_holds_it() { + for (token, class) in [ + ("0", ("UpTo", Some("i8"))), + ("-0", ("UpTo", Some("i8"))), + ("127", ("UpTo", Some("i8"))), + ("128", ("UpTo", Some("u8"))), + ("255", ("UpTo", Some("u8"))), + ("256", ("UpTo", Some("i16"))), + ("32767", ("UpTo", Some("i16"))), + ("32768", ("UpTo", Some("u16"))), + ("65535", ("UpTo", Some("u16"))), + ("65536", ("UpTo", Some("i32"))), + ("2147483647", ("UpTo", Some("i32"))), + ("2147483648", ("UpTo", Some("u32"))), + ("4294967295", ("UpTo", Some("u32"))), + ("4294967296", ("UpTo", Some("i64"))), + ("9223372036854775807", ("UpTo", Some("i64"))), + ("9223372036854775808", ("UpTo", Some("u64"))), + ("18446744073709551615", ("UpTo", Some("u64"))), + ("-1", ("DownTo", Some("i8"))), + ("-128", ("DownTo", Some("i8"))), + ("-129", ("DownTo", Some("i16"))), + ("-32768", ("DownTo", Some("i16"))), + ("-32769", ("DownTo", Some("i32"))), + ("-2147483648", ("DownTo", Some("i32"))), + ("-2147483649", ("DownTo", Some("i64"))), + ("-9223372036854775808", ("DownTo", Some("i64"))), + ("1.5", ("Fraction", None)), + ("-0.0", ("Fraction", None)), + ("1e3", ("Fraction", None)), + ("2E-2", ("Fraction", None)), + ] { + assert_eq!(number_class(token), Some(class), "{token}"); + } + for token in ["18446744073709551616", "-9223372036854775809"] { + assert_eq!(number_class(token), None, "{token}"); + } + } } diff --git a/packages/stack-encrypt-jsonpath/src/lib.rs b/packages/stack-encrypt-jsonpath/src/lib.rs index 9224d2f7d..827111c74 100644 --- a/packages/stack-encrypt-jsonpath/src/lib.rs +++ b/packages/stack-encrypt-jsonpath/src/lib.rs @@ -1,3 +1,24 @@ +// Security lints +#![forbid(unsafe_code)] +#![warn(clippy::unwrap_used)] +#![warn(clippy::expect_used)] +#![warn(clippy::panic)] +// Prevent mem::forget from bypassing ZeroizeOnDrop +#![warn(clippy::mem_forget)] +// Prevent accidental data leaks via output +#![warn(clippy::print_stdout)] +#![warn(clippy::print_stderr)] +#![warn(clippy::dbg_macro)] +// Code quality +#![warn(unreachable_pub)] +#![warn(unused_results)] +#![warn(clippy::todo)] +#![warn(clippy::unimplemented)] +// Relax in tests +#![cfg_attr(test, allow(clippy::unwrap_used))] +#![cfg_attr(test, allow(clippy::expect_used))] +#![cfg_attr(test, allow(clippy::panic))] +#![cfg_attr(test, allow(unused_results))] //! The JSONPath subset that `stack-encrypt`'s JSON index addresses. //! //! A [`JsonPath`] names a node of a JSON document: `$`, object members @@ -30,7 +51,6 @@ //! assert!(JsonPath::parse("visits").is_err(), "a path starts with `$`"); //! # Ok::<(), stack_encrypt_jsonpath::JsonPathError>(()) //! ``` -#![forbid(unsafe_code)] pub mod json_string; mod path; diff --git a/packages/stack-encrypt-jsonpath/src/predicate.rs b/packages/stack-encrypt-jsonpath/src/predicate.rs index 3a44d5f2a..cbd0da8c5 100644 --- a/packages/stack-encrypt-jsonpath/src/predicate.rs +++ b/packages/stack-encrypt-jsonpath/src/predicate.rs @@ -377,7 +377,8 @@ impl Comparison { impl PathAt { /// The array and the member of an ordering at a path with a wildcard: - /// the path up to its last wildcard, and the steps after it. + /// the path up to its last wildcard, and the steps after it. `None` + /// for a path with no wildcard, which names one node and no array. /// `operator_at` is where the ordering's operator is. /// /// # Errors @@ -387,12 +388,14 @@ impl PathAt { pub fn element_member( &self, operator_at: usize, - ) -> Result<(JsonPath, JsonPath), PredicateError> { + ) -> Result, PredicateError> { let steps = self.path.segments(); - let last = steps + let Some(last) = steps .iter() .rposition(|segment| *segment == Segment::Wildcard) - .unwrap_or_default(); + else { + return Ok(None); + }; // Each half is copied straight into a path, which wipes its keys, // before anything can refuse. let (base, member) = steps.split_at(last + 1); @@ -406,7 +409,7 @@ impl PathAt { operator_at, )); } - Ok((base, member)) + Ok(Some((base, member))) } } diff --git a/packages/stack-encrypt-jsonpath/src/predicate/tests.rs b/packages/stack-encrypt-jsonpath/src/predicate/tests.rs index aee26ef11..7a4734748 100644 --- a/packages/stack-encrypt-jsonpath/src/predicate/tests.rs +++ b/packages/stack-encrypt-jsonpath/src/predicate/tests.rs @@ -429,13 +429,14 @@ mod given_a_structure_the_index_cannot_answer { } /// An ordering at a wildcard splits at the last wildcard, and is refused - /// when nothing follows it. + /// when nothing follows it. A path with no wildcard names no array. #[test] fn an_ordering_at_a_wildcard_names_a_member() { let (base, member) = comparison("$.a[*].b[*].c.d > 1") .path .element_member(16) - .unwrap(); + .unwrap() + .expect("a path with a wildcard"); assert_eq!( (base.to_string(), member.to_string()), ("$.a[*].b[*]".to_owned(), "$.c.d".to_owned()) @@ -449,6 +450,13 @@ mod given_a_structure_the_index_cannot_answer { 7 ) ); + for text in ["$ > 1", "$.a > 1", "$.a.b > 1"] { + assert_eq!( + comparison(text).path.element_member(4).unwrap(), + None, + "{text}" + ); + } } /// A filter needs a wildcard on its path and none in its members, and diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index d402c6f07..8283f2529 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -55,8 +55,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 feature. - Needs stack-auth 0.44.0 and stack-kms 0.2.0. -- **Three more records derive** (#1661). The owned derives did not accept - - **`predicate!`** (#1459). `predicate!(EncryptedCustomer::PROFILE, "$.age >= $min && $.name == $name", min = 30, name)` checks a SQL/JSON path predicate when the program compiles and sends the same text when it @@ -69,8 +67,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 a path the field does not declare (under `ordered` or `paths`), an ordering of a path declared under `paths`, and a member of an array, in a filter of more than one condition, that the array does not order; and - a value, variable or literal, of another type than the path's. The - macro finds a path's accessor by the path's text, through lookups the + a value, variable or literal, of another type than the path's, which + for a number literal means one the path's type does not hold (`1.5`, + `-1` and `99999999999` for a `u32`). A variable's value is moved into + the query. The macro finds a path's accessor by the path's text, through lookups the derive now generates (hidden, in `field_reference::json::predicate_checks`), so a `names` override changes nothing. It is a `macro_rules` wrapper that passes `$crate`, so it works however a program reaches this crate. diff --git a/packages/stack-encrypt/src/field_reference/json.rs b/packages/stack-encrypt/src/field_reference/json.rs index c7d23aa18..b0bd2bf19 100644 --- a/packages/stack-encrypt/src/field_reference/json.rs +++ b/packages/stack-encrypt/src/field_reference/json.rs @@ -210,9 +210,11 @@ pub mod predicate_checks; /// predicate's text, a string literal in the grammar /// [`predicate(text)`](FieldReference::predicate) reads. Then each variable /// the text names as `$name`: `name = value`, a local variable's name alone -/// for `name = name` (as `format!` takes one), or `"any name" = value` for -/// a `$"any name"` that is not a Rust identifier. Each value is evaluated -/// once, in the order given. +/// for `name = name`, or `"any name" = value` for a `$"any name"` that is +/// not a Rust identifier. Each value is evaluated once, in the order given, +/// and moved into the query: a local given by its name alone is moved, as +/// [`var`](JsonFieldQuery::var) takes its value, so pass `name.clone()` or +/// `name.as_str()` to keep a `String`. /// /// It returns what `predicate(text)` returns, with each variable given by /// [`var`](JsonFieldQuery::var): a query whose @@ -234,8 +236,10 @@ pub mod predicate_checks; /// a filter of one equality is containment at the member's path, which /// any declared path answers); /// - a value of another type than the path's: a variable's value, a -/// literal in the text (`$.age > "x"`), and an ordering's `true`, -/// `false` or `null`. +/// literal in the text (`$.age > "x"`), a number literal the path's type +/// does not hold (`$.age > 1.5`, `$.age >= -1` and `$.age == 99999999999` +/// for a `u32`; an `f64` path takes any number), and an ordering's +/// `true`, `false` or `null`. /// /// So every path the text names must be declared. A predicate on a path /// the field does not declare, or one built at run time from a user's diff --git a/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs b/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs index d32fb1592..7c53e9587 100644 --- a/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs +++ b/packages/stack-encrypt/src/field_reference/json/predicate_checks.rs @@ -1,16 +1,20 @@ //! What [`predicate!`](crate::predicate) expands to so that the compiler //! checks a predicate against the paths its field declares. For generated -//! code only: nothing here is called when a program runs. +//! code only. [`document`] is what an expansion calls when the program +//! runs; everything else here is type-checked and never run. //! //! The macro sees the predicate's text and the field reference's //! expression, never the field's declaration. So it names each path the //! text uses as a type, [`Char`] by [`Char`], and asks for the derive's -//! lookup of that path: [`PathLookup`], [`ArrayLookup`] and -//! [`MemberLookup`], which `#[derive(EncryptTarget)]` implements once for -//! each path, array and member the field's `#[stash(json(ordered = {..}))]` -//! declares, by calling the accessor it generated for it. The lookup is -//! keyed by the path's text, not the accessor's name, so a `names = {..}` -//! override, which the macro cannot see, changes nothing here. +//! lookup of that path. `#[derive(EncryptTarget)]` implements +//! [`PathLookup`] once for each path the field's `#[stash(json(..))]` +//! declares, under `ordered = {..}` or under `paths = {..}`, and +//! [`ArrayLookup`] and [`MemberLookup`] once for each array and member +//! under `ordered = {..}` alone, since an element condition compares by an +//! ordering term. Each lookup calls the accessor the derive generated. The +//! lookup is keyed by the path's text, not the accessor's name, so a +//! `names = {..}` override, which the macro cannot see, changes nothing +//! here. //! //! The macro's own trait, generated at each use, refuses a path the field //! does not declare with a message that names it. The finders below then @@ -122,9 +126,21 @@ pub trait ValueFits {} impl> ValueFits for X {} impl ValueFits for X {} -/// A type a number literal fits: the number types a path holds, and -/// [`Unknown`]. -pub trait NumberFits {} +/// A number literal that is an integer of zero or more, named by the +/// narrowest of the integer types that holds it: `UpTo` is 128 to 255. +pub struct UpTo(PhantomData); +/// A number literal that is an integer below zero, named by the narrowest +/// of the signed types that holds it: `DownTo` is -32768 to -129. +pub struct DownTo(PhantomData); +/// A number literal with a fraction or an exponent. +pub enum Fraction {} + +/// A type the number literal `L` fits: an integer type that holds the +/// literal, `f64` for any number, and [`Unknown`]. The macro names `L` +/// from the literal's text, so `$.age > 1.5`, `$.age >= -1` and +/// `$.age == 99999999999` are refused for a `u32`, as the typed accessor +/// refuses those values. +pub trait NumberFits {} /// A type a string literal fits: `String`, and [`Unknown`]. pub trait StringFits {} /// A type `true` or `false` fits: `bool`, which a path under `paths` can @@ -132,9 +148,26 @@ pub trait StringFits {} pub trait BooleanFits {} macro_rules! number_fits { - ($($ty:ty),+) => {$(impl NumberFits for $ty {})+}; + ($($literal:ty => $($ty:ty),+;)+) => { + $($(impl NumberFits<$literal> for $ty {})+)+ + }; +} +number_fits! { + UpTo => i8, u8, i16, u16, i32, u32, i64, u64, f64; + UpTo => u8, i16, u16, i32, u32, i64, u64, f64; + UpTo => i16, u16, i32, u32, i64, u64, f64; + UpTo => u16, i32, u32, i64, u64, f64; + UpTo => i32, u32, i64, u64, f64; + UpTo => u32, i64, u64, f64; + UpTo => i64, u64, f64; + UpTo => u64, f64; + DownTo => i8, i16, i32, i64, f64; + DownTo => i16, i32, i64, f64; + DownTo => i32, i64, f64; + DownTo => i64, f64; + Fraction => f64; } -number_fits!(i8, i16, i32, i64, u8, u16, u32, u64, f64, Unknown); +impl NumberFits for Unknown {} impl StringFits for String {} impl StringFits for Unknown {} impl BooleanFits for bool {} diff --git a/packages/stack-encrypt/src/json/predicate.rs b/packages/stack-encrypt/src/json/predicate.rs index 679f5bfd6..df488ba3c 100644 --- a/packages/stack-encrypt/src/json/predicate.rs +++ b/packages/stack-encrypt/src/json/predicate.rs @@ -246,7 +246,6 @@ impl Compiler<'_> { value, at, } = comparison; - let wild = !path.path.is_positional(); let compare = match operator { // `==`: containment of the value at the path, exact; at a // wildcard, of any element. @@ -264,11 +263,10 @@ impl Compiler<'_> { Operator::Greater => Compare::Gt, Operator::GreaterOrEqual => Compare::Gte, }; - Ok(if wild { + let value = self.ordered(&value)?; + Ok(if let Some((base, member)) = path.element_member(at)? { // An ordering at a wildcard: some element's field, which is // `element_match` on the array through the last wildcard. - let value = self.ordered(&value)?; - let (base, member) = path.element_member(at)?; let predicate = self.member(&base, member, compare, value)?; Node::Leaf(Input::Elements(self.bound, vec![predicate])) } else { @@ -281,7 +279,6 @@ impl Compiler<'_> { // into true and NULL into NULL, so the tree also asks that the // node is not null. That `null` needle tells the database which // rows hold null at the path, so it is sent only there. - let value = self.ordered(&value)?; let path = ordered_path_of(self.options, path.path)?; let mut leaves = vec![Node::Leaf(Input::Selector(path.clone()))]; if negated { diff --git a/packages/stack-encrypt/tests/json_predicate_macro.rs b/packages/stack-encrypt/tests/json_predicate_macro.rs index e669f85bc..c1f0eab78 100644 --- a/packages/stack-encrypt/tests/json_predicate_macro.rs +++ b/packages/stack-encrypt/tests/json_predicate_macro.rs @@ -209,7 +209,7 @@ mod given_each_construct_of_the_grammar { mod given_how_a_caller_writes_it { use super::*; - /// A local variable's name alone gives it, as `format!` takes one; a + /// A local variable's name alone gives it, and moves it; a /// quoted variable is given by its name as a string; a value is any /// expression, and a trailing comma is read. #[tokio::test] diff --git a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs index 1866cf6cb..021dd85c5 100644 --- a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs +++ b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.rs @@ -14,7 +14,10 @@ struct Customer { #[derive(EncryptTarget)] #[stash(struct = Customer, scope = "customers")] struct EncryptedCustomer { - #[stash(json(ordered = { "$.age": u32, "$.visits[*].place": String }))] + #[stash(json( + ordered = { "$.age": u32, "$.visits[*].place": String, "$.balance": i16 }, + paths = { "$.score": f64 } + ))] profile: JsonDocument, } @@ -31,4 +34,20 @@ fn main() { let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); + // A number the path's type does not hold: a fraction, a number below + // zero and one past the type's range. + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age > 1.5"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= -1"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == 4294967296"); + let _ = predicate!(EncryptedCustomer::PROFILE, "$.balance < -32769"); + // And the numbers it does hold, which compile: each type's limits, and + // any number for an `f64`. + let _ = predicate!( + EncryptedCustomer::PROFILE, + "$.age == 0 && $.age <= 4294967295 && $.balance >= -32768 && $.balance <= 32767" + ); + let _ = predicate!( + EncryptedCustomer::PROFILE, + "$.score == 1.5 || $.score == -3 || $.score == 18446744073709551615 || $.score == 1e3" + ); } diff --git a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr index dfc71219c..a6ad97f32 100644 --- a/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr +++ b/packages/stack-encrypt/tests/ui/predicate_values_must_fit.stderr @@ -1,76 +1,139 @@ error[E0277]: `$.age` holds `u32`, and `&str` is not one - --> tests/ui/predicate_values_must_fit.rs:23:75 + --> tests/ui/predicate_values_must_fit.rs:26:75 | -23 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); +26 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); | ^^^^^^^^ the value of `$min` | - = help: the trait `FitsLine23Column52Check1` is not implemented for `&str` + = help: the trait `FitsLine26Column52Check1` is not implemented for `&str` = note: a declared path takes the type its `ordered = {..}` or `paths = {..}` entry names; a `String` path takes a `&str` or a `&String` too note: required by a bound in `main::{closure#0}::fits` - --> tests/ui/predicate_values_must_fit.rs:23:13 + --> tests/ui/predicate_values_must_fit.rs:26:13 | -23 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); +26 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= $min", min = "thirty"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `$.visits[*].place` holds `std::string::String`, and `u8` is not one - --> tests/ui/predicate_values_must_fit.rs:28:9 + --> tests/ui/predicate_values_must_fit.rs:31:9 | -28 | place +31 | place | ^^^^^ the value of `$place` | - = help: the trait `FitsLine27Column9Check1` is not implemented for `u8` + = help: the trait `FitsLine30Column9Check1` is not implemented for `u8` = note: a declared path takes the type its `ordered = {..}` or `paths = {..}` entry names; a `String` path takes a `&str` or a `&String` too note: required by a bound in `main::{closure#1}::fits` - --> tests/ui/predicate_values_must_fit.rs:25:13 + --> tests/ui/predicate_values_must_fit.rs:28:13 | -25 | let _ = predicate!( +28 | let _ = predicate!( | _____________^ -26 | | EncryptedCustomer::PROFILE, -27 | | "exists($.visits[*] ? (@.place == $place))", -28 | | place -29 | | ); +29 | | EncryptedCustomer::PROFILE, +30 | | "exists($.visits[*] ? (@.place == $place))", +31 | | place +32 | | ); | |_____^ required by this bound in `fits` = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `$.age` holds `u32`, and the literal `"x"` is a string - --> tests/ui/predicate_values_must_fit.rs:31:52 + --> tests/ui/predicate_values_must_fit.rs:34:52 | -31 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); +34 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); | ^^^^^^^^^^^^^^^^ this predicate compares `$.age` with `"x"` | - = help: the trait `FitsLine31Column52Check1` is not implemented for `u32` + = help: the trait `FitsLine34Column52Check1` is not implemented for `u32` + = note: a string literal fits a `String` path note: required by a bound in `main::{closure#2}::fits` - --> tests/ui/predicate_values_must_fit.rs:31:13 + --> tests/ui/predicate_values_must_fit.rs:34:13 | -31 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); +34 | let _ = predicate!(EncryptedCustomer::PROFILE, r#"$.age > "x""#); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: `$.visits[*].place` holds `std::string::String`, and the literal `3` is a number - --> tests/ui/predicate_values_must_fit.rs:32:52 +error[E0277]: `$.visits[*].place` holds `std::string::String`, and the literal `3` is a number it does not hold + --> tests/ui/predicate_values_must_fit.rs:35:52 | -32 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); +35 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); | ^^^^^^^^^^^^^^^^^^^^^^^^ this predicate compares `$.visits[*].place` with `3` | - = help: the trait `FitsLine32Column52Check1` is not implemented for `std::string::String` + = help: the trait `FitsLine35Column52Check1` is not implemented for `std::string::String` + = note: an integer path holds the integers of its type, and an `f64` path any number note: required by a bound in `main::{closure#3}::fits` - --> tests/ui/predicate_values_must_fit.rs:32:13 + --> tests/ui/predicate_values_must_fit.rs:35:13 | -32 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); +35 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.visits[*].place == 3"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `$.age` holds `u32`, and the literal `true` is a boolean - --> tests/ui/predicate_values_must_fit.rs:33:52 + --> tests/ui/predicate_values_must_fit.rs:36:52 | -33 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); +36 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); | ^^^^^^^^^^^^^^^ this predicate compares `$.age` with `true` | - = help: the trait `FitsLine33Column52Check1` is not implemented for `u32` + = help: the trait `FitsLine36Column52Check1` is not implemented for `u32` + = note: `true` and `false` fit a `bool` path, which `paths = {..}` can declare note: required by a bound in `main::{closure#4}::fits` - --> tests/ui/predicate_values_must_fit.rs:33:13 + --> tests/ui/predicate_values_must_fit.rs:36:13 | -33 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); +36 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == true"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.age` holds `u32`, and the literal `1.5` is a number it does not hold + --> tests/ui/predicate_values_must_fit.rs:39:52 + | +39 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age > 1.5"); + | ^^^^^^^^^^^^^ this predicate compares `$.age` with `1.5` + | + = help: the trait `FitsLine39Column52Check1` is not implemented for `u32` + = note: an integer path holds the integers of its type, and an `f64` path any number +note: required by a bound in `main::{closure#5}::fits` + --> tests/ui/predicate_values_must_fit.rs:39:13 + | +39 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age > 1.5"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.age` holds `u32`, and the literal `-1` is a number it does not hold + --> tests/ui/predicate_values_must_fit.rs:40:52 + | +40 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= -1"); + | ^^^^^^^^^^^^^ this predicate compares `$.age` with `-1` + | + = help: the trait `FitsLine40Column52Check1` is not implemented for `u32` + = note: an integer path holds the integers of its type, and an `f64` path any number +note: required by a bound in `main::{closure#6}::fits` + --> tests/ui/predicate_values_must_fit.rs:40:13 + | +40 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age >= -1"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.age` holds `u32`, and the literal `4294967296` is a number it does not hold + --> tests/ui/predicate_values_must_fit.rs:41:52 + | +41 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == 4294967296"); + | ^^^^^^^^^^^^^^^^^^^^^ this predicate compares `$.age` with `4294967296` + | + = help: the trait `FitsLine41Column52Check1` is not implemented for `u32` + = note: an integer path holds the integers of its type, and an `f64` path any number +note: required by a bound in `main::{closure#7}::fits` + --> tests/ui/predicate_values_must_fit.rs:41:13 + | +41 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.age == 4294967296"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `$.balance` holds `i16`, and the literal `-32769` is a number it does not hold + --> tests/ui/predicate_values_must_fit.rs:42:52 + | +42 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.balance < -32769"); + | ^^^^^^^^^^^^^^^^^^^^ this predicate compares `$.balance` with `-32769` + | + = help: the trait `FitsLine42Column52Check1` is not implemented for `i16` + = note: an integer path holds the integers of its type, and an `f64` path any number +note: required by a bound in `main::{closure#8}::fits` + --> tests/ui/predicate_values_must_fit.rs:42:13 + | +42 | let _ = predicate!(EncryptedCustomer::PROFILE, "$.balance < -32769"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `fits` + = note: this error originates in the macro `$crate::field_reference::json::predicate_checks::predicate_with_crate` which comes from the expansion of the macro `predicate` (in Nightly builds, run with -Z macro-backtrace for more info)