diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index e4e3a1c2cf..eb07653982 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -92,6 +92,11 @@ exclude_re = [ # `Ok(())`, so the replacement is the body. Text overrides it with # `query::order_text`, pinned by `an_ordering_refuses_only_text_it_cannot_encode`. 'stack-encrypt/src/sem/mod\.rs:\d+:\d+: replace sealed::Sealed::check_query -> Result<\(\), super::TermError> with Ok\(\(\)\)$', + # A JSON document type's default options are the defaults: the trait's + # body is `JsonOptions::default()`. A type that overrides them is pinned + # by `a_field_that_names_no_options_queries_under_its_types_own`, and + # `Option` forwarding by `a_nullable_field_queries_under_its_types_own_options`. + 'stack-encrypt/src/json/target\.rs:\d+:\d+: replace JsonQueries::default_options -> JsonOptions with Default::default\(\)$', # Both unit-context conversions explicitly return Self::default(). 'stack-encrypt/src/target/context\.rs:\d+:\d+: replace for (DeclaredContext|ExpectedContext)>::from -> Self with Default::default\(\)$', # A caller shape with no placeholder IS `CallerShape::default()`: @@ -145,7 +150,7 @@ exclude_re = [ # bits with a low nibble below 16: the bits never overlap, so `^` is `|`. 'stack-encrypt/src/json/mod\.rs:\d+:\d+: replace \| with \^ in unhex$', # `JsonPath::root` is `Self::default()`. - 'stack-encrypt/src/json/path\.rs:\d+:\d+: replace JsonPath::root -> Self with Default::default\(\)$', + 'stack-encrypt-jsonpath/src/path\.rs:\d+:\d+: replace JsonPath::root -> Self with Default::default\(\)$', # A document always has a root, so its terms are never empty: `false` is # the value `is_empty` returns. The `true` replacement is still caught. 'stack-encrypt/src/json/derive\.rs:\d+:\d+: replace JsonTerms::is_empty -> bool with false$', diff --git a/.changeset/eql-json-field-reference-queries.md b/.changeset/eql-json-field-reference-queries.md new file mode 100644 index 0000000000..2d1e36db80 --- /dev/null +++ b/.changeset/eql-json-field-reference-queries.md @@ -0,0 +1,17 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: a `JsonTreeDocument` field of a derived Stack Encrypt record is queried from its field reference, and each query returns the EQL query type a parameter binds as. + +- `EncryptedCustomer::PROFILE.contains(doc)` gives a `JsonTreeQuery` for `@>`, and `contained_by(doc)` one for `<@`. +- `#[stash(json(ordered = { "$.age": u32, "$.visits[*].place": String }))]` on the field names the paths the documents order and the type of the values at each. The field is sealed under those options and queried under them. `paths = { "$.name": String }` beside it declares a path compared with equality alone, which adds no ordering term. Stack Encrypt's derive checks every path when it compiles the record. +- Each declared path has a typed method: `at().age().gt(v)` and the other comparisons give a `JsonTreeLeafQuery`, `at().age().between(lo, hi)` two of them, and `at().age().selector()` the `JsonTreeSelector` that `->` takes. A path, a member or a value type the field does not declare does not compile, and neither does an ordering of a `paths` path. +- `elements().visits().place().eq(v).and()..` gives a `JsonTreeElementsQuery`, `predicate(text).var(name, v)` a `JsonTreePredicateQuery`, and `children(path)` a `JsonTreeToken`. +- A path built at run time is text: `at_text_path(path)` and `elements_text_path(path)` check it when the query is encrypted. + +Each query is the operand a data plan naming `JsonSearch` derives for the same column and options, which is what the Go SDK sends. + +A value passed by value is now sealed without a copy when its type seals it and derives no search term: a `JsonTreeDocument`, a data plan field that names `JsonSearch`, and the storage-only v4 types (`Integer`, `Text`, `Json` and the rest). The copy was wiped before, so nothing leaked; it was not needed. + +The stored format, the SQL bundle and the TypeScript types do not change. diff --git a/.changeset/eql-remove-structural-traits.md b/.changeset/eql-remove-structural-traits.md index 5303f7c2d7..ec53add9c4 100644 --- a/.changeset/eql-remove-structural-traits.md +++ b/.changeset/eql-remove-structural-traits.md @@ -6,7 +6,7 @@ - Every type keeps `EncryptTarget` and `DecryptSource`. Write with `value.encrypt_into_with_context(&keyset, column)` and read with `P::decrypt_from_with_context(stored, &keyset, column)`. - A typed query is a field reference of a derived record, such as `EncryptedMember::EMAIL.eq("bob").encrypt(&keyset)`. -- A JSON document is a `JsonPlaintext`, not a `serde_json::Value`. A typed JSON query has no replacement yet: derive the operand through a data plan that names `JsonSearch`. +- A JSON document is a `JsonPlaintext`, not a `serde_json::Value`. A typed JSON query is a document field's reference query, such as `EncryptedCustomer::PROFILE.at().age().gt(30).encrypt(&keyset)`. - `JsonTree` no longer implements `stack_encrypt::target::Layout`. `encryption()`, `index()` and `specs()` are its own methods. The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/.github/workflows/bench-eql.yml b/.github/workflows/bench-eql.yml index 390745c0f4..a03ede56b7 100644 --- a/.github/workflows/bench-eql.yml +++ b/.github/workflows/bench-eql.yml @@ -67,6 +67,7 @@ on: - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/crap-crates.yml b/.github/workflows/crap-crates.yml index 79020aa40e..8fc0a4253f 100644 --- a/.github/workflows/crap-crates.yml +++ b/.github/workflows/crap-crates.yml @@ -21,6 +21,7 @@ on: - packages/stack-auth/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - Cargo.toml - Cargo.lock - mise.toml diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 3bbac30e6f..76616e68a4 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -1,7 +1,8 @@ name: Mutants # Gates pull requests on mutation testing of the lines they change in -# stack-auth and stack-encrypt. Ported from cipherstash-suite's `mutants.yml`. +# stack-auth, stack-encrypt and stack-encrypt-jsonpath (the path grammar, +# moved out of stack-encrypt). Ported from cipherstash-suite's `mutants.yml`. # # cargo-mutants rewrites small pieces of logic (flip `<` to `<=`, replace a # body with `Default::default()`) and reruns the tests; a mutant that survives @@ -11,7 +12,7 @@ name: Mutants # filter (which drops the trybuild `ui` binary), excludes and timeouts live in # .cargo/mutants.toml, so the gate and the local tasks agree. # -# Scoped to the two crates with `-p`: the baseline runs the unmutated tests of +# Scoped to those crates with `-p`: the baseline runs the unmutated tests of # those packages only. A diff touching only other crates yields no mutants and # passes. # @@ -27,6 +28,7 @@ on: paths: - packages/stack-auth/** - packages/stack-encrypt/** + - packages/stack-encrypt-jsonpath/** - Cargo.toml - Cargo.lock - mise.toml @@ -140,7 +142,7 @@ jobs: EVENT_NAME: ${{ github.event_name }} run: | set +e - crates=(-p stack-auth -p stack-encrypt) + crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath) if [ "$EVENT_NAME" = "pull_request" ]; then cargo mutants --no-shuffle -vV "${crates[@]}" --in-diff pr.diff else @@ -161,7 +163,7 @@ jobs: timeout=$(count timeout.txt) { echo '' - echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth + stack-encrypt)" + echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth + stack-encrypt + stack-encrypt-jsonpath)" echo if [ ! -d "$out" ]; then # No output dir: either nothing to mutate (exit 0) or the run diff --git a/.github/workflows/release-plz.yml b/.github/workflows/release-plz.yml index 3e65aee137..8a5130e683 100644 --- a/.github/workflows/release-plz.yml +++ b/.github/workflows/release-plz.yml @@ -275,7 +275,7 @@ jobs: run: | set -euo pipefail publish_needed=false - for crate in stack-auth stack-profile stack-kms stack-encrypt stack-encrypt-derive; do + for crate in stack-auth stack-profile stack-kms stack-encrypt stack-encrypt-derive stack-encrypt-jsonpath; do version="$(grep -m1 '^version = ' "packages/${crate}/Cargo.toml" | cut -d'"' -f2)" # crates.io 403s curl's default User-Agent. published="$(curl -fsSL --retry 3 -H "User-Agent: cipherstash-stack-release (https://github.com/cipherstash/stack)" "https://crates.io/api/v1/crates/${crate}/versions" | jq -r '.versions[].num' | grep -Fx "$version" || true)" diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index 529bcf8b2c..1e9f613be1 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -112,6 +112,7 @@ on: - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -213,6 +214,7 @@ jobs: - "conformance/stack-encrypt/**" - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" + - "packages/stack-encrypt-jsonpath/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index 425dca68cb..f0f2648aeb 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -23,6 +23,7 @@ on: - packages/stack-encrypt/** - conformance/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** @@ -47,6 +48,7 @@ on: - packages/stack-encrypt/** - conformance/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** @@ -144,7 +146,7 @@ jobs: run: cargo build --locked -p stack-encrypt --examples # The crates release-plz publishes. `--dry-run` packages and compiles - # each the way crates.io would (all five together, so each resolves the + # each the way crates.io would (all six together, so each resolves the # others from cargo's temporary local registry rather than from # crates.io), catching a publish-blocker on the PR instead of in # release-crates on main: missing metadata, a runtime path dependency @@ -156,7 +158,7 @@ jobs: # version is on crates.io, cargo warns rather than fails on a dry run of # it. - name: Verify the stack-* crates package cleanly for crates.io - run: cargo publish --locked --dry-run --allow-dirty -p stack-profile -p stack-auth -p stack-kms -p stack-encrypt-derive -p stack-encrypt + run: cargo publish --locked --dry-run --allow-dirty -p stack-profile -p stack-auth -p stack-kms -p stack-encrypt-jsonpath -p stack-encrypt-derive -p stack-encrypt node-bindings: name: node bindings, napi typings, stack-auth-wasm diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 4395f7a993..bf0533fe4b 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -40,6 +40,7 @@ on: - packages/stack-encrypt/** - conformance/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** @@ -84,6 +85,7 @@ on: - packages/stack-encrypt/** - conformance/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 75d11eb130..f0003ed28e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -105,6 +105,7 @@ jobs: - '!languages/golang/**' - '!packages/stack-encrypt/**' - '!packages/stack-encrypt-derive/**' + - '!packages/stack-encrypt-jsonpath/**' - '!packages/stack-kms/**' - '!packages/stack-guest-abi/**' - '!packages/stack-auth/fuzz/**' diff --git a/.github/workflows/udeps.yml b/.github/workflows/udeps.yml index db3d33b98c..ed857c2590 100644 --- a/.github/workflows/udeps.yml +++ b/.github/workflows/udeps.yml @@ -16,6 +16,7 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** @@ -35,6 +36,7 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** diff --git a/AGENTS.md b/AGENTS.md index 9d886ec992..bfe4349840 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-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history — `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), 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, 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". - `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) @@ -736,7 +736,7 @@ term. `cts-common` and `zerokms-protocol` take caret requirements, because the published `stack-auth` inherits them, and an exact pin would stop the suite sharing one `cts-common` with it. -- **Three Cargo workspaces, not one.** The root workspace (the six stack-* +- **Three Cargo workspaces, not one.** The root workspace (the seven stack-* crates and the three node binding crates), protect-ffi's and EQL's. The root `Cargo.toml` excludes the other two, and they pin their own vitaminc. The three fuzz crates, the two Go guests and the EQL v4 block ORE timing @@ -778,7 +778,7 @@ exact pin would stop the suite sharing one `cts-common` with it. `MISE_ENV=test` cargo tools — and the live tests), `crap-crates.yml`, `mutants.yml`, `fuzz.yml`, `miri.yml` and `udeps.yml`. `scripts/__tests__/crates-ci.test.mjs` fails when a mise task in the root - `mise.toml` or the five crate `tasks.toml` files loses its last CI caller. + `mise.toml` or the six crate `tasks.toml` files loses its last CI caller. - **Auth refresh cancellation soak:** `tests-auth-refresh.yml` runs a short, seeded, virtual-time soak on every PR and the long run on auth changes and Version Packages PRs. `release-plz.yml` also requires the long run before diff --git a/Cargo.lock b/Cargo.lock index 80d4b0fe38..0ed8dfd1fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3470,6 +3470,7 @@ dependencies = [ "sha2 0.11.0", "stack-auth", "stack-encrypt-derive", + "stack-encrypt-jsonpath", "stack-kms", "temp-env", "thiserror 1.0.69", @@ -3497,11 +3498,24 @@ dependencies = [ "quote", "serde_json", "stack-encrypt", + "stack-encrypt-jsonpath", "syn 3.0.9", "tokio", "zeroize", ] +[[package]] +name = "stack-encrypt-jsonpath" +version = "0.3.0" +dependencies = [ + "miette", + "serde", + "serde_json", + "stack-auth", + "thiserror 1.0.69", + "zeroize", +] + [[package]] name = "stack-guest-abi" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index 1967aa6173..21eca1577d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "packages/stack-kms", "packages/stack-encrypt", "packages/stack-encrypt-derive", + "packages/stack-encrypt-jsonpath", "packages/stack-guest-abi", "languages/typescript/packages/auth", "languages/typescript/packages/profile", @@ -34,7 +35,7 @@ exclude = [ [workspace.package] # Used by the node binding crates, which take `version.workspace`. The # published crates (stack-auth, stack-profile, stack-kms, stack-encrypt, -# stack-encrypt-derive) carry their own version. +# stack-encrypt-derive, stack-encrypt-jsonpath) carry their own version. version = "0.35.0" edition = "2021" authors = [ diff --git a/SECURITY.md b/SECURITY.md index e6b4c946c3..e9b6782ed3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,11 +28,12 @@ This repository also carries the source of the **`eql-bindings`** Rust crate lockstep with `@cipherstash/eql`. It is in scope for security reports on the same terms as the npm packages above. -It also carries the source of five Rust crates published to crates.io, +It also carries the source of six Rust crates published to crates.io, **`stack-auth`** and **`stack-profile`** (`packages/stack-auth`, -`packages/stack-profile`) and **`stack-kms`**, **`stack-encrypt`** and -**`stack-encrypt-derive`** (`packages/stack-kms`, `packages/stack-encrypt`, -`packages/stack-encrypt-derive`), and of the **Go modules** at +`packages/stack-profile`) and **`stack-kms`**, **`stack-encrypt`**, +**`stack-encrypt-derive`** and **`stack-encrypt-jsonpath`** +(`packages/stack-kms`, `packages/stack-encrypt`, +`packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`), and of the **Go modules** at `languages/golang` (`encrypt` and `auth`, over WASI guests built from the stack-* crates) and `languages/golang/encrypt/encrypttest`, released by `.github/workflows/release-golang.yml` as `languages/golang/vX.Y.Z` and @@ -44,7 +45,7 @@ engine whose keys derive from a published seed. Those keys are not secret by design: the package is for tests only. A way for a production client to load a test build, or for a test build to reach ZeroKMS, is in scope. -The five stack-* crates are licensed under the PolyForm Internal Use License +The six stack-* crates are licensed under the PolyForm Internal Use License 1.0.0 (each crate's `LICENSE`), not the repository's MIT licence: they may be used for internal business operations only, and not redistributed. That includes the optional `stack-encrypt` feature of the MIT-licensed @@ -67,10 +68,11 @@ in scope as documentation/code-example issues. > seven `@cipherstash/protect-ffi*` packages, all seven `@cipherstash/auth*` > packages and `@cipherstash/eql`, is published from this repository by > `.github/workflows/release.yml`; the `eql-bindings`, `stack-auth`, -> `stack-profile`, `stack-kms`, `stack-encrypt` and `stack-encrypt-derive` -> crates are published from here by `.github/workflows/release-plz.yml` (the -> first version of each of the last three was published by hand, because -> crates.io configures Trusted Publishing on an existing crate). The Go module +> `stack-profile`, `stack-kms`, `stack-encrypt`, `stack-encrypt-derive` and +> `stack-encrypt-jsonpath` crates are published from here by +> `.github/workflows/release-plz.yml` (the first version of each of the last +> four was, or will be, published by hand, because crates.io configures +> Trusted Publishing on an existing crate). The Go module > is released from here by `.github/workflows/release-golang.yml`, as > `languages/golang/vX.Y.Z` tags that `go get` fetches through the Go module > proxy. EQL moved here at the Phase 5 cutover in 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 efc653ff4b..f839b7ca48 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -421,30 +421,33 @@ the strict checks on JSON input. A program can also encrypt a borrowed any [borrowed value](#encrypt-borrowed-values). With the default options, no path has an ordering term. So a query cannot -compare the order of the values at a path. To order some paths, declare a -named type with typed Rust options: +compare the order of the values at a path. To order some paths, a record +field names them with `#[stash(json(..))]`, as Go's struct tag does +(`encrypt_into=JsonSearch(ordered=$.age)`). Decided by Dan on 16 November +2026, in place of a named type with options in a `target(..)` attribute: ```rust -use stack_encrypt::json::JsonOptions; - -fn profile_options() -> Result { - JsonOptions::new().ordering(["$.age", "$.visits[*].at"]) +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, } -// Not on `next` yet: a JSON target with typed options. #[derive(EncryptTarget, DecryptSource)] -#[stash( - plaintext = JsonPlaintext, - transparent, - target(column = ("customers", "profile"), options = profile_options) -)] -struct EncryptedProfile(JsonTreeDocument); - -let profile = JsonPlaintext::parse(r#"{"name":"Ada","age":35}"#)?; -let encrypted: EncryptedProfile = profile.encrypt_into(&keyset).await?; -let opened = JsonPlaintext::decrypt_from(encrypted, &keyset).await?; +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32, "$.visits[*].at": u64, "$.visits[*].place": String }))] + profile: JsonTreeDocument, +} + +let customer = Customer { profile: JsonPlaintext::parse(r#"{"name":"Ada","age":35}"#)? }; +let encrypted: EncryptedCustomer = customer.encrypt_into(&keyset).await?; +let opened = Customer::decrypt_from(encrypted, &keyset).await?; ``` +The field is sealed under the options, and its field queries under them. +`ordered` maps each ordered path to the type of the values at it. +`sealed_root = false` in the same list turns off the sealed root. + #### Query a JSON document A JSON query is a query on the document's field reference. The field reference has @@ -461,31 +464,33 @@ declaration: The field reference carries both, so the query names only its kind and its values. The output type is the EQL query type, fixed by the field reference. -Decided on 7 November 2026. +Decided on 7 November 2026. Built in #1459; this example runs as +`packages/eql/tests/encryption/tests/json_tree_field_references.rs`. ```rust use eql_bindings::v4::json_tree::{JsonTreeElementsQuery, JsonTreeLeafQuery, JsonTreeQuery}; -// Not on `next` yet: field references and their query methods. The method -// names are proposals. -let ada: JsonTreeQuery = EncryptedProfile::DOCUMENT +let ada: JsonTreeQuery = EncryptedCustomer::PROFILE .contains(json!({ "name": "Ada" })) .encrypt(&keyset) .await?; -let older: JsonTreeLeafQuery = EncryptedProfile::DOCUMENT - .at("$.age") +let older: JsonTreeLeafQuery = EncryptedCustomer::PROFILE + .at() + .age() .gt(30) .encrypt(&keyset) .await?; -let adults: JsonTreeLeafQuery = EncryptedProfile::DOCUMENT - .at("$.age") +let (low, high): (JsonTreeLeafQuery, JsonTreeLeafQuery) = EncryptedCustomer::PROFILE + .at() + .age() .between(18, 65) .encrypt(&keyset) .await?; -let home: JsonTreeElementsQuery = EncryptedProfile::DOCUMENT - .elements("$.visits[*]") - .eq("place", "home") - .gt("at", 15) +let home: JsonTreeElementsQuery = EncryptedCustomer::PROFILE + .elements() + .visits() + .place().eq("home") + .and().at().gt(15) .encrypt(&keyset) .await?; ``` @@ -507,14 +512,43 @@ The kinds of JSON query, the field reference method for each, and what each find | Query | Field reference method | What it finds | EQL query type | | --- | --- | --- | --- | -| Containment | `contains(doc)`, `contained_by(doc)`, and `at(path).eq(v)` | Rows whose document contains the given document, or is contained by it. Equality of a scalar at a path is containment of a one-entry document, so `at(path).eq(v)` lowers to it | `JsonTreeQuery` | -| Comparison at a path | `at(path).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` | -| Element match | `elements(path).eq(member, v).gt(member, v)` | Rows where one element of an array meets several conditions together | `JsonTreeElementsQuery` | -| Jsonpath predicate | `predicate(text)` | 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 | A node token | - -A path is text. So an order query on a path the options do not order is -refused at run time, before any key is fetched. +| Containment | `contains(doc)`, `contained_by(doc)`, and `at().age().eq(v)` | Rows whose document contains the given document, or is contained by it. Equality of a scalar at a path is containment of a one-entry document, so a path's `eq(v)` lowers to it | `JsonTreeQuery` | +| 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` | +| 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: + +- `ordered = { "$.age": u32, .. }` names each ordered path and the type of + the values at it. The derive parses every path at compile time with the + engine's grammar, from the `stack-encrypt-jsonpath` crate that + `stack-encrypt` and its derive share. A path that does not parse, names + an array position, or is given twice does not compile. +- `paths = { "$.name": String, .. }` names a path compared with equality + alone, and its type: a number, a string or a boolean. It adds nothing to + the field's options, so the field stores no ordering term for it, and + an ordering of it does not compile. A path given under both keys does + not compile. Decided by Dan on 22 November 2026. +- The derive gives each path a method under `at()`, and each array whose + elements have an ordered member a method under `elements()`, whose + methods are the members. The names come from the path's keys + (`$.visits[*].at` is `at().visits_at()`), and `names = { "key": word }` + names a key that gives no Rust name. Each method takes the path's + type. So a path or a member the field does not declare, a value of + another type, a member of another array, and an element match on a path + that is not an array do not compile. These are the Go SDK's generated + `At`, `Elements` and `Paths`. +- A filter a program builds at run time names its paths as text: + `at_text_path(path)` and `elements_text_path(path)`, whose members are + text. A text path is checked when the query is encrypted, before any key + is fetched, and derives the operand the typed method derives for the same + 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. 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 @@ -525,13 +559,20 @@ page](../../packages/eql/docs/reference/json-tree.md) gives the SQL for each query. A scope chains on a JSON query as on a scalar one: `.contains(doc).scope(tenant)`. -The engine already has one private input type for each JSON operator, -in `stack_encrypt::dynamic`. `DocumentInput` is for containment, `AtInput` -for a comparison at a path, and `ElementsInput` for element match. The field reference -methods build those same inputs, so the typed form and the dynamic form -share one set of input rules. The operand types `Contains`, `AtPath`, +The field reference methods build the same inputs the dynamic interface reads a +binding's frames into (`json::inputs`, compiled without the `dynamic` +feature), so the typed form and the dynamic form share one set of input +rules and derive the same operands. The operand types `Contains`, `AtPath`, `ElementMatch`, `Predicate`, and `Children` that the plan proposed earlier -are retired, replaced by these methods, on 7 November 2026. +were retired as operands a caller builds, on 7 November 2026: a caller +writes the methods above. The query a method returns, +`field_reference::json::JsonFieldQuery`, names its kind as a type with no +values, `Op`: `op::Contains`, `op::ContainedBy`, or `op::AtPath` of a +comparison, which the dynamic `Op` enum is generated from, and, for the +kinds that have no operator type, `field_reference::json::Selector`, +`ElementMatch`, `Predicate` and `Children`. That kind decides what +`encrypt` returns. Recorded on 16 November 2026, in #1459's pull +request. A document encrypted straight into `JsonTreeDocument`, with no record, has no field reference. It is queried through a [query plan](#a-query-plan), as any @@ -1555,29 +1596,51 @@ Base64. - **What to build.** One method for each kind of JSON query on a JSON document's field reference. The methods are `contains` and `contained_by`; - `at(path)` with the comparison operators; `elements(path)` with its - member conditions; `predicate`; and `children`. Each method builds the input type the + `at()` with a method per declared path and the comparison operators; + `elements()` with a method per declared array and its member conditions; + `predicate` with its variables; and `children`. Paths are typed from the + attribute, and `at_text_path` and `elements_text_path` take paths built + at run time (decided on 21 November 2026, see [Query a JSON + document](#query-a-json-document)). Each method builds the input type the dynamic interface already has for that operator, and `encrypt(&keyset)` returns the EQL query type. The field reference supplies the column and the options. The dynamic parser keeps reading into the same input types, so there is one definition of each input. -- **Names.** The method names above are proposals. The operand types - `Contains`, `AtPath`, `ElementMatch`, `Predicate`, and `Children` that - this plan proposed earlier are retired, on 7 November 2026. +- **Names.** The method names above were confirmed in the naming review + of 8 November 2026. The operand types `Contains`, `AtPath`, + `ElementMatch`, `Predicate`, and `Children` that this plan proposed + earlier were retired as operands a caller builds, on 7 November 2026; + the query a method returns names its kind with value-free type tags of + those names (see [Query a JSON document](#query-a-json-document)). - **Why.** On `next`, a Rust program needs a plan for any JSON query, and needs the dynamic interface for element match, predicates, and children. Go already has typed methods for these. -- **Done already.** The input types and their parsing rules, as private - types in `stack_encrypt::dynamic::json_query`. The EQL query types - exist in `eql-bindings`. Typed containment and comparison at a path - went through the chain (`op::Contains`, `op::AtPath`), which #1666 - removes, so until this item is built every JSON query from Rust goes - through a query plan. -- **Tracked in.** Issue #1459 is open. It is exactly this item. Issue #1677 is open for opening one child. Issue #1486 is closed. -- **Finished when** these are both true: +- **Done** in the pull request for #1459. Each method builds the input + the dynamic parser reads into (`json::inputs`, out of the `dynamic` + feature), and returns the field type's query type (`JsonQueries`): + the EQL types for `JsonTreeDocument`. A field's options are its + `#[stash(json(..))]`, decided on 16 November 2026. Pull request #1687 + types the paths: `ordered = { "$.age": u32, .. }`, parsed at compile time + through `stack-encrypt-jsonpath`, with a typed method per path, array + and member (21 November 2026), and `paths = { "$.name": String, .. }` + for a path compared with equality alone (22 November 2026). Tests hold every typed query to the text + 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. +- **Finished when** these are all true: - the [JSON query example](#query-a-json-document) compiles; - - an order query on a path the options do not order is refused before - any key is fetched. + - a path, a member or a value type the field does not declare does not + compile; + - a text path the options do not order is refused before any key is + fetched; + - a predicate's text is checked at compile time. #### Field references and the encryption plan @@ -1605,8 +1668,7 @@ review. indexes, a nullable field and a record field their operator methods, and a field its query type (`#[stash(query = ..)]`). The chain query `cipher.query(op, value).on(&plan)` is removed (#1662). It was the only - typed JSON query, so until the JSON field reference methods exist (#1459) a JSON - query goes through a query plan. + typed JSON query; a document field's reference methods replace it (#1459). - **No hand-built plan.** The review of 7 November 2026 gave a hand-built plan the same field references, through `Plan::::scope(..)` with `pick!`. That is withdrawn. No Rust program builds a plan by hand. diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 5194555cd7..0a33c5123d 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2133,6 +2133,7 @@ dependencies = [ "serdect", "sha2 0.11.0", "stack-encrypt-derive", + "stack-encrypt-jsonpath", "stack-kms", "thiserror 1.0.69", "uuid", @@ -2154,6 +2155,7 @@ version = "0.3.0" dependencies = [ "proc-macro2", "quote", + "stack-encrypt-jsonpath", "syn 3.0.4", ] @@ -2177,6 +2179,18 @@ dependencies = [ "zerokms-protocol", ] +[[package]] +name = "stack-encrypt-jsonpath" +version = "0.3.0" +dependencies = [ + "miette", + "serde", + "serde_json", + "stack-auth", + "thiserror 1.0.69", + "zeroize", +] + [[package]] name = "stack-guest-abi" version = "0.0.0" diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index d7a829ae08..a48c8a2baa 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -155,6 +155,10 @@ pub fn status_for_error(error: &stack_encrypt::Error) -> u32 { // children asked for as a scalar, or an altered entry. The client // cannot tell which, so neither STATUS_AUTH nor a claim of either. stack_encrypt::Error::JsonNotALeaf => STATUS_ENCODING, + // A refusal of the caller's input, reported through the crate's + // error by a path whose failure can only be that: the dynamic + // refusal it holds is classified as the dynamic path classifies it. + stack_encrypt::Error::Input(refusal) => status_for_dynamic(refusal), _ => STATUS_INTERNAL, } } @@ -422,6 +426,21 @@ mod tests { ); } + /// A refusal of the caller's input that arrives in the crate's error is + /// classified as the dynamic path classifies it. + #[test] + fn an_input_refusal_is_the_callers_input() { + use stack_encrypt::refusal::{Error, Reason}; + let refused = Error::Source { + field: None, + reason: Reason::JsonPathNoWildcard, + }; + assert_eq!( + status_for_error(&stack_encrypt::Error::Input(Box::new(refused))), + STATUS_ENCODING + ); + } + #[test] fn a_context_mismatch_is_its_own_status() { use stack_encrypt::Describe; diff --git a/mise.toml b/mise.toml index 235105e36f..05a18c465f 100644 --- a/mise.toml +++ b/mise.toml @@ -12,6 +12,7 @@ includes = [ "packages/stack-kms/tasks.toml", "packages/stack-profile/tasks.toml", "packages/stack-encrypt/tasks.toml", + "packages/stack-encrypt-jsonpath/tasks.toml", "packages/stack-guest-abi/tasks.toml", ] diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 03db2eaf9e..d6f1776e9e 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -4235,6 +4235,7 @@ dependencies = [ "serdect", "sha2 0.11.0", "stack-encrypt-derive", + "stack-encrypt-jsonpath", "stack-kms", "thiserror 1.0.69", "uuid", @@ -4256,9 +4257,22 @@ version = "0.3.0" dependencies = [ "proc-macro2", "quote", + "stack-encrypt-jsonpath", "syn 3.0.3", ] +[[package]] +name = "stack-encrypt-jsonpath" +version = "0.3.0" +dependencies = [ + "miette", + "serde", + "serde_json", + "stack-auth 0.44.0", + "thiserror 1.0.69", + "zeroize", +] + [[package]] name = "stack-kms" version = "0.2.0" diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index c9d2764d0f..412302ddb3 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -9,6 +9,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **A `JsonTreeDocument` field is queried from its field reference** (#1459, + #1687). As a field of a derived record, a `JsonTreeDocument` (and an + `Option`) has Stack Encrypt's JSON field queries, + which return the EQL query types a parameter binds as: + `EncryptedCustomer::PROFILE.contains(doc)` gives a `JsonTreeQuery`, + `at().age().gt(v)` a `JsonTreeLeafQuery`, `elements().visits()..` a + `JsonTreeElementsQuery`, `predicate(text).var(name, v)` a + `JsonTreePredicateQuery`, `at().age().selector()` a `JsonTreeSelector` + and `children(path)` a `JsonTreeToken`. A field marked + `#[stash(json(ordered = { "$.age": u32 }))]` is sealed under those + options, so its orderings compare, and each declared path has a typed + method that the compiler checks; `at_text_path(path)` and + `elements_text_path(path)` take a path built at run time. Each operand + is the one a data plan naming `JsonSearch` derives for the same column + and options. `JsonTreeDocument` implements `JsonTarget` and + `JsonQueries`. + +- **A value passed by value is sealed without a copy** (#1687). Sealing + took a copy of the value when the type had no owned form of its own. + Both copies were wiped, so nothing leaked, but the copy was not needed. + - `JsonTreeDocument` overrides `EncryptTarget::owned_encryption` and + `JsonTarget::json_owned_encryption`. `encrypt_into`, and a derived + record's `JsonTreeDocument` field, move the document out of the + `JsonPlaintext` into the seal. + - A data plan field that names `JsonSearch` moves the document it parses + into the seal. + - `Ciphertext` (`c`) has an owned form, which moves the value into the + seal and wipes it when the context is refused. So the 11 storage-only + v4 types (`Integer`, `Bigint`, `Smallint`, `Boolean`, `Date`, + `Timestamp`, `Numeric`, `Real`, `Double`, `Text` and `Json`) seal with + no copy, through `encrypt_into` and through a data plan. + - A data plan field that names an EQL type runs the type's owned form. + A type with search terms guards the value and wipes it, as before. + - The stored bytes do not change. Needs the Stack Encrypt in this + repository, which adds the owned `Encryption::storing` and + `Encryption::over_json_plaintext`. + - **The parts of a `JsonSearch` document decrypt through the owned API** (#1660). `JsonTreeExtracted`, the entry `->` returns, implements `DecryptSource`. `JsonTreeSubtree`, the rows of a subtree @@ -335,8 +372,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 gone. - A JSON document is a `JsonPlaintext`, not a `serde_json::Value`. `JsonTreeDocument`, `JsonTreeExtracted` and `JsonTreeSubtree` open to - it. A typed JSON query has no replacement yet: derive the operand - through a data plan that names `JsonSearch` (`EqlTargets`). + it. A typed JSON query is a document field's reference query (above). - `JsonTree` no longer implements `stack_encrypt::target::Layout`, which is removed. `JsonTree::encryption()`, `index()` and `specs()` are its own methods, and `index()` returns the index by value. diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 417c65f8d1..6cf6f9b975 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -114,7 +114,7 @@ use stack_encrypt::sem::{ use stack_encrypt::target::transcode::{Reader, Transcode, Visitor}; use stack_encrypt::target::{ self, AeadContext, CallerContext, ContextFromField, DecryptSource, EncryptTarget, IndexSpec, - RequiredContext, + Owned, RequiredContext, }; use stack_encrypt::{ CipherText, ContextPiece, Decrypt, DecryptField, Decryptable, Decryption, Describe, @@ -260,6 +260,10 @@ impl Reader for Ciphertext { // The canonical ciphertext, read into EQL's `c`. The declaration requires the // AEAD (authenticated encryption) half of the context, as Stack Encrypt's own // `StackCipherText` does. +// +// The borrowed form clones the plaintext to seal it. The owned form is Stack +// Encrypt's own owned form of `StackCipherText`: it moves the value into the +// seal, with no copy, and wipes it when the context is refused. impl EncryptTarget for Ciphertext { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> @@ -268,6 +272,12 @@ impl EncryptTarget for Ciphertext { { target::ciphertext().accepting().transcode() } + fn owned_encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput, Owned> + where + S: 's, + { + >::owned_encryption().transcode() + } } /// Reads a stored `c` back as the native sealed leaf it encodes. Public for diff --git a/packages/eql/crates/eql-bindings/src/encryption/targets.rs b/packages/eql/crates/eql-bindings/src/encryption/targets.rs index 44e4e3ee4d..70080f4afc 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/targets.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/targets.rs @@ -507,8 +507,8 @@ fn document(name: &str) -> Option<&'static Target> { /// Seal one `JsonSearch` value: the document the field's text holds, /// parsed by the engine's rules, laid out by the JSON index under /// `options`, under the field's context. The document stores the column -/// alone. The parsed document is wiped when this returns; the pending has -/// taken what it seals. +/// alone. The parsed document is moved into the seal, with no copy, and is +/// wiped when it has been sealed or the context is refused. fn encrypt_document<'a, K: 'static>( name: &'static str, options: &JsonOptions, @@ -523,8 +523,8 @@ fn encrypt_document<'a, K: 'static>( })?; Ok(keyset .run( - crate::v4::json_tree::JsonTree::new(options.clone()).sealing(), - document.value(), + crate::v4::json_tree::JsonTree::new(options.clone()).owned_sealing(), + document, StoredContext::from(context), ) .try_map(|value| serde_json::to_vec(&value).map_err(|error| Error::Other(Box::new(error))))) @@ -708,9 +708,9 @@ mod sealed { /// implementations are exactly the plaintext types the catalog's producible /// families name, and the generated dispatch picks one per type. /// `Zeroize`, because [`from_frame`](Self::from_frame) copies the plaintext -/// out of the frame's `Protected` buffer and the copy is wiped when it is -/// dropped (`run_target` holds it in [`zeroize::Zeroizing`]), as the frame -/// is. +/// out of the frame's `Protected` buffer, and that copy must be wiped, as +/// the frame is. `run_target` hands it to the type's owned form, which +/// wipes it. pub trait Plaintext: sealed::Sealed + Decrypt + Sized + MaybeSend + zeroize::Zeroize + 'static { @@ -882,15 +882,39 @@ where S: Plaintext + zeroize::Zeroize, K: 'static, { - // The copy lives only until the run has cloned what it seals, and is - // wiped when this returns: the frame kept its bytes in `Protected`, - // and the copy is held to the same rule. - let plaintext = zeroize::Zeroizing::new(S::from_frame(name, &plaintext)?); - Ok(keyset - .run(T::encryption(), &*plaintext, StoredContext::from(context)) + let pending = run_owned::(name, keyset, context, plaintext)?; + Ok(pending .try_map(|value| serde_json::to_vec(&value).map_err(|error| Error::Other(Box::new(error))))) } +/// Read the plaintext out of the frame and run `T`'s owned form over it. +/// +/// The frame kept its bytes in `Protected`, and the plaintext read out of it +/// is held to the same rule. The owned form takes the value: a type that +/// seals it alone, such as a storage-only type, moves it into the seal with +/// no copy. A type that derives terms too guards it, as the default owned +/// form does. Either way it is wiped. Until the owned form exists it is held +/// in `Protected`, because building the form can panic. +fn run_owned<'a, T, S, K>( + name: &'static str, + keyset: &'a KeysetCipher<'_, K>, + context: CallerContext, + plaintext: ValueFrame, +) -> Result, TargetError> +where + T: EncryptTarget>, + S: Plaintext + zeroize::Zeroize, + K: 'static, +{ + let plaintext = stack_encrypt::Protected::new(S::from_frame(name, &plaintext)?); + let description = T::owned_encryption(); + Ok(keyset.run( + description, + stack_encrypt::Controlled::risky_unwrap(plaintext), + StoredContext::from(context), + )) +} + /// Run the plan of `P`, a projection of the query twin `Q` that carries one /// term, and resolve to `Q`'s JSON bytes: the twin of a type whose query /// terms are optional, holding only the term `P` derives. The generated @@ -907,14 +931,12 @@ where S: Plaintext + zeroize::Zeroize, K: 'static, { - // Wiped when this returns, as in `run_target`. - let plaintext = zeroize::Zeroizing::new(S::from_frame(name, &plaintext)?); - Ok(keyset - .run(P::encryption(), &*plaintext, StoredContext::from(context)) - .try_map(|value| { - let query: Q = value.into(); - serde_json::to_vec(&query).map_err(|error| Error::Other(Box::new(error))) - })) + // Wiped by the owned form, as in `run_target`. + let pending = run_owned::(name, keyset, context, plaintext)?; + Ok(pending.try_map(|value| { + let query: Q = value.into(); + serde_json::to_vec(&query).map_err(|error| Error::Other(Box::new(error))) + })) } /// Parse a stored EQL value as the target and describe opening it through diff --git a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs index 36542fd979..9c38aa4973 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -12,7 +12,13 @@ //! [`EncryptTarget`] / [`DecryptSource`] impls that let a Rust program name //! [`JsonTreeDocument`] as a target: //! `document.encrypt_into_with_context(&keyset, column)` under an -//! [`Identifier`]. A query derives through a data plan that names the type +//! [`Identifier`]. As a field of a derived record, its field reference has the +//! JSON queries (`contains`, `at`, `elements`, `predicate`, `children`), +//! which return the query types here +//! ([`JsonQueries`](stack_encrypt::json::JsonQueries)), under the options +//! the field's `#[stash(json(..))]` names +//! ([`JsonTarget`](stack_encrypt::json::JsonTarget)). A document with +//! no record is queried through a data plan that names the type //! (`JsonSearch`) under the same column, and its operand converts into the //! operand types here (see [`crate::encryption`]). The //! design is `docs/plans/2026-10-17-json-tree-index.md` at @@ -22,12 +28,13 @@ use schemars::{schema_for, JsonSchema, Schema}; use serde::{Deserialize, Serialize}; use serde_json::Value; use stack_encrypt::json::{ - JsonDocument, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonQuery, - JsonSelector, JsonSubtree, JsonSubtreeKey, + JsonDocument, JsonElementsQuery, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonPlaintext, + JsonPredicateQuery, JsonQueries, JsonQuery, JsonSelector, JsonSubtree, JsonSubtreeKey, + JsonTarget, }; use stack_encrypt::target::{ json_document, AeadContext, Borrowed, DecryptSource, EncryptTarget, ExpectedContext, Index, - IndexSpec, Json, RequiredContext, StoredContext, + IndexSpec, Json, Owned, RequiredContext, StoredContext, }; use stack_encrypt::{DecryptField, Decryptable, Decryption, Encryption, Error, NonEmpty}; use ts_rs::TS; @@ -501,6 +508,10 @@ impl JsonTree { /// On its own, the document stores the column the caller passes, and /// seals under it. As a field of a record, it stores the field's own /// column, and seals under the scopes and bindings of the record too. + /// + /// The document is borrowed, so it is copied once to be sealed, and the + /// copy is wiped. [`owned_sealing`](Self::owned_sealing) moves it in + /// instead. pub(crate) fn sealing<'s, K: 'static>( &self, ) -> Encryption<'s, Value, JsonTreeDocument, K, StoredContext> { @@ -508,6 +519,24 @@ impl JsonTree { .storing(|document, column: Identifier| (column, document)) .try_map(|(column, document)| JsonTreeDocument::envelope(column, &document)) } + + /// [`sealing`](Self::sealing), for a document passed by value. The + /// document is moved out of the [`JsonPlaintext`] into the seal, with no + /// copy. + /// + /// The stored column is checked while the document is still a + /// `JsonPlaintext`, so a column that cannot be stored drops the + /// `JsonPlaintext`, which wipes the document. After that the document + /// is the seal's, which wipes it when it has been sealed, and when the + /// context is refused. + pub(crate) fn owned_sealing<'s, K: 'static>( + &self, + ) -> Encryption<'s, JsonPlaintext, JsonTreeDocument, K, StoredContext, Owned> { + json_document::(self.options.clone()) + .over_json_plaintext() + .storing(|document, column: Identifier| (column, document)) + .try_map(|(column, document)| JsonTreeDocument::envelope(column, &document)) + } } impl JsonTreeDocument { @@ -546,6 +575,11 @@ impl JsonTreeDocument { /// is then the record's scope and the field's name. A scope or a binding /// that the record lists is not stored in the document: the reader supplies /// it again. +/// +/// `encrypt_into` moves the document into the seal, with no copy, and the +/// document is wiped when it has been sealed or the context is refused. +/// Sealing a borrowed plaintext, such as an element of a collection, reads +/// the document through one copy, which is wiped too. impl EncryptTarget for JsonTreeDocument { type ContextInput = StoredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> @@ -554,11 +588,82 @@ impl EncryptTarget for JsonTreeDocument { { JsonTree::default().sealing().project(JsonPlaintext::value) } + fn owned_encryption<'s, K: 'static>( + ) -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput, Owned> + where + JsonPlaintext: 's, + { + JsonTree::default().owned_sealing() + } fn indexes() -> Vec { JsonTree::default().specs() } } +/// A document field sealed under the options its record's +/// `#[stash(json(..))]` names, which order the paths its queries compare. +/// +/// A derived record seals each such field through the owned form, which +/// moves the document into the seal, with no copy. +impl JsonTarget for JsonTreeDocument { + fn json_encryption<'s, K: 'static>( + options: JsonOptions, + ) -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> + where + JsonPlaintext: 's, + { + JsonTree::new(options) + .sealing() + .project(JsonPlaintext::value) + } + fn json_owned_encryption<'s, K: 'static>( + options: JsonOptions, + ) -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput, Owned> + where + JsonPlaintext: 's, + { + JsonTree::new(options).owned_sealing() + } +} + +/// A document field's reference queries return the EQL query types a +/// parameter binds as: `JsonTreeQuery` for `@>` and `<@` +/// (`eql_v4.query_json`), `JsonTreeLeafQuery` for an ordering at a path +/// (`eql_v4.query_json_leaf`), `JsonTreeElementsQuery` for +/// `eql_v4.json_tree_element_match`, `JsonTreePredicateQuery` for `@@`, the +/// selector `->` takes, and the token the child functions take. +impl JsonQueries for JsonTreeDocument { + type Query = JsonTreeQuery; + type LeafQuery = JsonTreeLeafQuery; + type ElementsQuery = JsonTreeElementsQuery; + type PredicateQuery = JsonTreePredicateQuery; + type Selector = JsonTreeSelector; + type Token = JsonTreeToken; + fn query(query: JsonQuery) -> Result { + JsonTreeQuery::try_from(query) + } + fn leaf_query(query: JsonLeafQuery) -> Result { + JsonTreeLeafQuery::try_from(&query) + } + fn elements_query(query: JsonElementsQuery) -> Result { + transcode(&query) + } + fn predicate_query(query: JsonPredicateQuery) -> Result { + transcode(&query) + } + fn selector(selector: JsonSelector) -> Result { + transcode(&selector) + } + fn token(key: JsonSubtreeKey) -> Result { + match key.tokens().as_slice() { + [token] => transcode(token), + _ => Err(Error::Other( + "a path with no wildcard names one node".into(), + )), + } + } +} + /// Decrypts to the plaintext document, under the stored column. /// /// - `decrypt_from_with_context(document, &keyset, column)` checks that the diff --git a/packages/eql/tests/encryption/tests/heap_hygiene.rs b/packages/eql/tests/encryption/tests/heap_hygiene.rs index 501becf536..9c6cae80b2 100644 --- a/packages/eql/tests/encryption/tests/heap_hygiene.rs +++ b/packages/eql/tests/encryption/tests/heap_hygiene.rs @@ -23,6 +23,8 @@ //! Rust slice (see [`holds_mark`]). #![cfg(unix)] +mod common; + use std::alloc::{GlobalAlloc, Layout, System}; use std::borrow::Cow; use std::cell::Cell; @@ -84,10 +86,21 @@ unsafe fn holds_mark(ptr: *const u8, len: usize) -> bool { !memmem(ptr.cast(), len, MARK.as_ptr().cast(), MARK.len()).is_null() } +/// The size of block [`allocations_of`] counts, or 0 when nothing is +/// counted; and how many blocks of that size the watched thread allocated. +static COUNT_SIZE: AtomicUsize = AtomicUsize::new(0); +static COUNTED: AtomicUsize = AtomicUsize::new(0); + struct Spy; unsafe impl GlobalAlloc for Spy { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if layout.size() == COUNT_SIZE.load(Ordering::SeqCst) + && WATCHING.with(Cell::get) + && !BUSY.with(Cell::get) + { + COUNTED.fetch_add(1, Ordering::SeqCst); + } System.alloc(layout) } @@ -128,6 +141,27 @@ static SPY: Spy = Spy; /// the marker. fn watched(what: &str, f: impl FnOnce() -> T) -> T { let _gate = GATE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + watched_in_gate(what, f) +} + +/// [`watched`], and count the blocks of exactly `size` bytes the watched +/// thread allocated meanwhile. +/// +/// A copy of a string allocates a block of the string's length. So with a +/// string of a length nothing else allocates, two runs of one operation, one +/// that copies the string and one that does not, differ by one block. +fn allocations_of(size: usize, what: &str, f: impl FnOnce()) -> usize { + assert_ne!(size, 0, "a block size to count"); + let _gate = GATE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + COUNTED.store(0, Ordering::SeqCst); + COUNT_SIZE.store(size, Ordering::SeqCst); + watched_in_gate(what, f); + COUNT_SIZE.store(0, Ordering::SeqCst); + COUNTED.load(Ordering::SeqCst) +} + +/// [`watched`], for a caller already holding [`GATE`]. +fn watched_in_gate(what: &str, f: impl FnOnce() -> T) -> T { FOUND.lock().unwrap().clear(); *EXCLUDED.lock().unwrap() = [0; 1]; WATCHING.with(|on| on.set(true)); @@ -542,10 +576,8 @@ fn a_cancelled_text_target_leaves_no_plaintext_on_the_heap() { /// can hold another test's freed bytes. stack-encrypt's `heap_hygiene`, /// run one test to a process, holds containers to the same rule. /// -/// The seal and open themselves are the JSON index's -/// (`stack_encrypt::json`), which is not held to this rule yet: its path -/// derivation frees key and leaf plaintext unwiped, so they are not -/// watched here. +/// The seal is watched in [`owned_seals`]. Opening a document is the JSON +/// index's (`stack_encrypt::json`), and is not watched here. #[test] fn a_document_leaves_no_plaintext_on_the_heap_at_the_boundary() { let mark = marked("doc"); @@ -573,6 +605,299 @@ fn a_document_leaves_no_plaintext_on_the_heap_at_the_boundary() { drop(document); } +/// The owned forms that move a plaintext into its seal, with no copy: a JSON +/// tree document ([`JsonTreeDocument`]), sealed from a `JsonPlaintext`, from a +/// data plan's frame (`JsonSearch`), and as a field under the options its +/// record names; and the storage-only types, whose one field is the +/// ciphertext. Each is watched on success and on each refusal, and each +/// refusal requests no key. +/// +/// [`JsonTreeDocument`]: eql_bindings::v4::json_tree::JsonTreeDocument +mod owned_seals { + use super::*; + + use eql_bindings::v4::json::Json; + use eql_bindings::v4::json_tree::{JsonTree, JsonTreeDocument}; + use eql_bindings::v4::text::Text; + use eql_bindings::Identifier; + use serde_json::{json, Value}; + use stack_encrypt::json::{JsonOptions, JsonPlaintext, JsonTarget}; + use stack_encrypt::plan::PlanError; + use stack_encrypt::target::{CallerContext, DeclaredContext, Scope, StoredContext}; + use stack_encrypt::{nonempty, EncryptInto, EncryptTarget, Error, NonEmpty}; + + fn column() -> NonEmpty { + Identifier::for_column("users", "profile").unwrap() + } + + /// The column, then an empty scope: the column can be stored, and the + /// empty scope is refused when the value is sealed. + fn empty_scope() -> StoredContext { + StoredContext::from( + DeclaredContext::default() + .with(CallerContext::from(Scope::new(String::new()))) + .under(nonempty!("users").with("profile")), + ) + } + + /// A context of one part, which no `Identifier` can store. + fn not_storable() -> StoredContext { + StoredContext::from(CallerContext::from(nonempty!("profile"))) + } + + /// A document with the marker in a key, in an array and in a string + /// with escapes, and a string long enough to make a short buffer grow. + fn document() -> Value { + let mut members = serde_json::Map::new(); + members.insert(marked("key"), json!([marked("in-array"), 1.5, null])); + members.insert( + "escaped".to_owned(), + Value::String(format!("{}\n\"", marked("escaped"))), + ); + members.insert("pad".to_owned(), Value::String("x".repeat(8 * 1024))); + Value::Object(members) + } + + fn generated(calls: &std::sync::Mutex) -> usize { + calls.lock().unwrap().generate.len() + } + + #[test] + fn a_document_sealed_by_value_leaves_no_plaintext_on_the_heap() { + let rt = runtime(); + let (cipher, calls) = rt.block_on(common::cipher()); + let keyset = cipher.default_keyset(); + let source = JsonPlaintext::from(document()); + watched("JsonTreeDocument, encrypt_into", || { + let _: JsonTreeDocument = rt.block_on(async { + source + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap() + }); + }); + // A record field sealed under the options its record names. + let source = JsonPlaintext::from(document()); + watched("JsonTreeDocument, as a field", || { + let description = + >::json_owned_encryption( + JsonOptions::default(), + ); + let _: JsonTreeDocument = rt.block_on(async { + keyset + .run(description, source, StoredContext::from(column())) + .await + .unwrap() + }); + }); + assert_eq!(generated(&calls), 2, "one data key for each seal"); + } + + /// A refused context. With an empty scope, the document has been moved + /// out of the `JsonPlaintext` when the scope is refused, and the seal + /// wipes it. With a column that cannot be stored, the refusal comes + /// first, and dropping the `JsonPlaintext` wipes the document. + #[test] + fn a_document_refused_leaves_no_plaintext_on_the_heap() { + let rt = runtime(); + let (cipher, calls) = rt.block_on(common::cipher()); + let keyset = cipher.default_keyset(); + let source = JsonPlaintext::from(document()); + watched("JsonTreeDocument, an empty scope", || { + let description = + >::owned_encryption(); + let refused = + rt.block_on(async { keyset.run(description, source, empty_scope()).await }); + assert!( + matches!(refused, Err(Error::Plan(PlanError::EmptyPart))), + "an empty scope is refused: {refused:?}" + ); + }); + let source = JsonPlaintext::from(document()); + watched("JsonTreeDocument, a column it cannot store", || { + let description = + >::json_owned_encryption( + JsonOptions::default(), + ); + let refused = + rt.block_on(async { keyset.run(description, source, not_storable()).await }); + assert!( + matches!( + refused, + Err(Error::Plan(PlanError::ContextNotStorable { .. })) + ), + "one part is not a column: {refused:?}" + ); + }); + assert_eq!(generated(&calls), 0, "a refusal requests no key"); + } + + /// A data plan's `JsonSearch` field: the document parsed from the + /// frame is moved into the seal. + #[test] + fn a_document_from_a_frame_leaves_no_plaintext_on_the_heap() { + let rt = runtime(); + let (cipher, calls) = rt.block_on(common::cipher()); + let keyset = cipher.default_keyset(); + let label = Label::new(["users", "profile"]).unwrap(); + let text = joined(&[ + r#"{""#, + &marked("key"), + r#"": [""#, + &marked("in-array"), + r#"\n"]}"#, + ]); + let frame = ValueFrame::of(text.as_str()).unwrap(); + drop(text); + watched("JsonSearch, encrypt", || { + rt.block_on(async { + targets::encrypt("JsonSearch", &keyset, &label, frame) + .unwrap() + .await + .unwrap() + }); + }); + assert_eq!(generated(&calls), 1, "one data key"); + } + + /// A storage-only type moves its plaintext into its ciphertext. + #[test] + fn a_storage_only_value_sealed_by_value_leaves_no_plaintext_on_the_heap() { + let rt = runtime(); + let (cipher, calls) = rt.block_on(common::cipher()); + let keyset = cipher.default_keyset(); + let source = marked("text"); + watched("Text, encrypt_into", || { + let _: Text = rt.block_on(async { + source + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap() + }); + }); + let source = JsonPlaintext::from(document()); + watched("Json, encrypt_into", || { + let _: Json = rt.block_on(async { + source + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap() + }); + }); + assert_eq!(generated(&calls), 2, "one data key for each seal"); + } + + /// A refused context wipes a storage-only type's plaintext: a column it + /// cannot store is refused before the ciphertext is reached, and an + /// empty scope is refused by the ciphertext. + #[test] + fn a_storage_only_value_refused_leaves_no_plaintext_on_the_heap() { + let rt = runtime(); + let (cipher, calls) = rt.block_on(common::cipher()); + let keyset = cipher.default_keyset(); + let source = marked("not-storable"); + watched("Text, a column it cannot store", || { + let description = >::owned_encryption(); + let refused = + rt.block_on(async { keyset.run(description, source, not_storable()).await }); + assert!( + matches!( + refused, + Err(Error::Plan(PlanError::ContextNotStorable { .. })) + ), + "one part is not a column: {:?}", + refused.err() + ); + }); + let source = marked("empty-scope"); + watched("Text, an empty scope", || { + let description = >::owned_encryption(); + let refused = + rt.block_on(async { keyset.run(description, source, empty_scope()).await }); + assert!( + matches!(refused, Err(Error::Plan(PlanError::EmptyPart))), + "an empty scope is refused: {:?}", + refused.err() + ); + }); + assert_eq!(generated(&calls), 0, "a refusal requests no key"); + } + + /// A string of a length no other block in the seal has, in a document. + const LONG: usize = 12_289; + fn long() -> Value { + let mut text = marked("long"); + text.extend(std::iter::repeat_n('y', LONG - text.len())); + json!({"long": text, "short": marked("short")}) + } + + /// The owned forms do not copy the document: each makes one block + /// fewer of the length of the document's long string than the borrowed + /// form of the same type, which copies the document once. + #[test] + fn a_document_sealed_by_value_is_not_copied() { + let rt = runtime(); + let cipher = cipher(&rt); + let keyset = cipher.default_keyset(); + + let source = long(); + let borrowed = allocations_of(LONG, "JsonTreeDocument, borrowed", || { + let _: JsonTreeDocument = rt.block_on(async { + keyset + .run(JsonTree::default().encryption(), &source, column()) + .await + .unwrap() + }); + }); + drop(source); + let source = JsonPlaintext::from(long()); + let owned = allocations_of(LONG, "JsonTreeDocument, owned", || { + let _: JsonTreeDocument = rt.block_on(async { + source + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap() + }); + }); + assert_eq!( + borrowed, + owned + 1, + "JsonTreeDocument: the borrowed form copies the document once and the owned \ + form does not (borrowed {borrowed}, owned {owned})" + ); + + let source = JsonPlaintext::from(long()); + let borrowed = allocations_of(LONG, "Json, borrowed", || { + let _: Json = rt.block_on(async { + keyset + .run( + >::encryption(), + &source, + StoredContext::from(column()), + ) + .await + .unwrap() + }); + }); + drop(source); + let source = JsonPlaintext::from(long()); + let owned = allocations_of(LONG, "Json, owned", || { + let _: Json = rt.block_on(async { + source + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap() + }); + }); + assert_eq!( + borrowed, + owned + 1, + "Json: the borrowed form copies the document once and the owned form does not \ + (borrowed {borrowed}, owned {owned})" + ); + } +} + /// `parts` joined into a string sized for them before it is written, so /// building a marked input frees no marked block that a later allocation /// could reuse and a watch then find. diff --git a/packages/eql/tests/encryption/tests/json_tree.rs b/packages/eql/tests/encryption/tests/json_tree.rs index 193f2bc4f3..eb316e2b26 100644 --- a/packages/eql/tests/encryption/tests/json_tree.rs +++ b/packages/eql/tests/encryption/tests/json_tree.rs @@ -4,8 +4,9 @@ //! (`JsonTreeDocument`, `JsonTreeExtracted`, `JsonTreeSubtree`), as a //! `JsonPlaintext`. A query's operand derives through a data plan that //! names the type `JsonSearch` under the same column and options -//! ([`contains`], [`contained_by`], [`gte_at`]), since an EQL type has no -//! typed JSON query. The unit tests need no database; the PostgreSQL test +//! ([`contains`], [`contained_by`], [`gte_at`]), the path a language SDK +//! takes. A record field's reference derives the same operands +//! (`tests/json_tree_field_references.rs`). The unit tests need no database; the PostgreSQL test //! installs nothing itself (`mise run test:encryption:postgres` installs the //! v4 bundle built from the tree) and is the oracle the design asks for: //! `@>` and `<@` over the encrypted column against PostgreSQL's own @@ -61,9 +62,9 @@ const ORDERED: [&str; 2] = ["$.hello", "$.number"]; /// The plan a query derives through: a data plan with one `json` field, /// `profile`, that names the EQL type `JsonSearch` under `users/profile`. /// That context is the identifier [`seal`] stores (the same two parts), so -/// a query's selectors are the stored document's. An EQL type has no typed -/// JSON query: a Rust program derives one through a data plan, as a -/// language SDK does. +/// a query's selectors are the stored document's. A document sealed on its +/// own, with no record, has no field reference, so it is queried through a data +/// plan, as a language SDK queries one. fn plan() -> record::Plan { let wire = json!({ "profile": { diff --git a/packages/eql/tests/encryption/tests/json_tree_field_references.rs b/packages/eql/tests/encryption/tests/json_tree_field_references.rs new file mode 100644 index 0000000000..e74550ef29 --- /dev/null +++ b/packages/eql/tests/encryption/tests/json_tree_field_references.rs @@ -0,0 +1,442 @@ +//! An encrypted JSON document field queried from its field reference: the typed +//! Rust form of the JSON operators, returning the EQL query types a +//! parameter binds as. +//! +//! The record seals the field under the options its `#[stash(json(..))]` +//! names, and the field's reference derives each query under the same column +//! and options. Each query is held to the operand a data plan of the same +//! declaration derives, which is the path the Go SDK takes and the one the +//! PostgreSQL suite checks against `jsonb`, and to the document the record +//! sealed: +//! +//! - `contains`, `contained_by` and `at().age().eq` derive the containment +//! needle (`JsonTreeQuery`), and find the documents that hold it; +//! - the orderings at a path derive `JsonTreeLeafQuery`, with the path's +//! selector, and `between` the two bounds; +//! - `elements().visits()` derives `JsonTreeElementsQuery`, +//! `predicate(text)` `JsonTreePredicateQuery`, and `children(path)` the +//! node's token; +//! - a declared path's typed accessor and the same path as text +//! (`at_text_path`, `elements_text_path`) derive the same operand; +//! - an ordering at a path the field does not order is refused before any +//! key is requested. + +mod common; + +use std::num::NonZeroU32; + +use eql_bindings::encryption::EqlTargets; +use eql_bindings::v4::json_tree::{ + JsonTreeDocument, JsonTreeElementsQuery, JsonTreeLeafQuery, JsonTreePredicateQuery, + JsonTreeQuery, JsonTreeSelector, JsonTreeToken, +}; +use serde_json::{json, Value}; +use stack_encrypt::dynamic::{self, record, ValueFrame}; +use stack_encrypt::json::{JsonDocument, JsonPlaintext, JsonQuery}; +use stack_encrypt::sem::TermError; +use stack_encrypt::target::{DecryptSource, EncryptTarget}; +use stack_encrypt::{AsProtectedRef as _, DecryptFrom, EncryptInto, Error, KeysetCipher}; +use zeroize::Zeroize; + +/// A customer, and the profile document stored for them. +#[derive(Zeroize)] +struct Customer { + profile: JsonPlaintext, +} + +/// The plan's example: the profile is stored under `customers/profile`, +/// ordering the age and each visit's time and place. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(json(ordered = { "$.age": u32, "$.visits[*].at": u64, "$.visits[*].place": String }))] + profile: JsonTreeDocument, +} + +fn profile() -> Value { + json!({ + "name": "Ada", + "age": 35, + "visits": [{"place": "home", "at": 15}, {"place": "work", "at": 9}] + }) +} + +/// The field as a data plan, under the record's options. +fn plan() -> record::Plan { + let wire = json!({ + "profile": { + "context": ["customers", "profile"], + "type": "json", + "null": "sql", + "target": { + "name": "JsonSearch", + "options": {"ordered": ["$.age", "$.visits[*].at", "$.visits[*].place"]} + } + } + }); + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &EqlTargets, + ) + .unwrap() +} + +/// The data plan's operand for `operator` and its input. +async fn data( + keyset: &KeysetCipher<'_, common::RecordingKeySource>, + operator: &str, + input: Value, +) -> dynamic::Operand { + let frame = ValueFrame::from_bytes( + dynamic::frame::serde::to_vec(&input) + .unwrap() + .as_protected_ref(), + ) + .unwrap(); + dynamic::query_term( + keyset, + &plan(), + "profile", + dynamic::Op::parse(operator).unwrap(), + frame, + &EqlTargets, + ) + .unwrap() + .await + .unwrap() + .operand() + .clone() +} + +fn one(operand: dynamic::Operand) -> Value { + match operand { + dynamic::Operand::One(bytes) => serde_json::from_slice(&bytes).unwrap(), + other => panic!("one operand: {other:?}"), + } +} + +fn text(operand: dynamic::Operand) -> String { + match operand { + dynamic::Operand::Text(text) => text, + other => panic!("text: {other:?}"), + } +} + +/// A containment needle as the engine's `JsonQuery`, which compares as +/// sets: each derivation sends its selector set in a random order of its +/// own. +fn needle(query: &JsonTreeQuery) -> JsonQuery { + serde_json::from_value(serde_json::to_value(query).unwrap()).unwrap() +} + +/// The JSON index's own document under the EQL envelope, whose selector +/// set compares as a set. +fn index_document(document: &JsonTreeDocument) -> JsonDocument { + let wire = serde_json::to_value(document).unwrap(); + serde_json::from_value(json!({"h": wire["h"], "sv": wire["sv"], "q": wire["q"]})).unwrap() +} + +/// The plan's "Query a JSON document" example, run: each query's type is +/// the EQL query type the field reference fixes. +#[tokio::test] +async fn the_plans_json_query_example_runs() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedCustomer = Customer { + profile: profile().into(), + } + .encrypt_into(&keyset) + .await + .unwrap(); + + let ada: JsonTreeQuery = EncryptedCustomer::PROFILE + .contains(json!({ "name": "Ada" })) + .encrypt(&keyset) + .await + .unwrap(); + let older: JsonTreeLeafQuery = EncryptedCustomer::PROFILE + .at() + .age() + .gt(30) + .encrypt(&keyset) + .await + .unwrap(); + let (low, high): (JsonTreeLeafQuery, JsonTreeLeafQuery) = EncryptedCustomer::PROFILE + .at() + .age() + .between(18, 65) + .encrypt(&keyset) + .await + .unwrap(); + let home: JsonTreeElementsQuery = EncryptedCustomer::PROFILE + .elements() + .visits() + .place() + .eq("home") + .and() + .at() + .gt(10) + .encrypt(&keyset) + .await + .unwrap(); + let adult: JsonTreePredicateQuery = EncryptedCustomer::PROFILE + .predicate("$.age >= $min") + .var("min", 18) + .encrypt(&keyset) + .await + .unwrap(); + let visits: JsonTreeToken = EncryptedCustomer::PROFILE + .children("$.visits") + .encrypt(&keyset) + .await + .unwrap(); + let age: JsonTreeSelector = EncryptedCustomer::PROFILE + .at() + .age() + .selector() + .encrypt(&keyset) + .await + .unwrap(); + + assert_eq!( + older.s, age, + "an ordering is compared at the path's selector" + ); + assert_eq!((&low.s, &high.s), (&age, &age)); + assert_eq!(home.m.len(), 2, "one member per condition"); + assert!(matches!(adult, JsonTreePredicateQuery::And(_)), "{adult:?}"); + assert!( + serde_json::to_value(&visits).unwrap().is_string(), + "a token is text" + ); + assert!( + needle(&ada).matches(index_document(&stored.profile).selector_set()), + "the stored document holds the needle" + ); + + let opened = Customer::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened.profile.value(), &profile()); +} + +/// Every field query derives the operand the data plan derives for the +/// same declaration, with the path typed or as text. +#[tokio::test] +async fn each_query_is_the_data_plans_operand() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + + let typed = EncryptedCustomer::PROFILE + .contains(json!({"visits": [{"place": "home"}]})) + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "contains", + json!({"json": json!({"visits": [{"place": "home"}]}).to_string()}), + ) + .await); + assert_eq!( + needle(&typed), + serde_json::from_value::(wire).unwrap() + ); + + let typed = EncryptedCustomer::PROFILE + .at_text_path("$.visits[*].place") + .eq("home") + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "eq_at", + json!({"path": "$.visits[*].place", "json": "\"home\""}), + ) + .await); + assert_eq!( + needle(&typed), + serde_json::from_value::(wire.clone()).unwrap() + ); + let declared = EncryptedCustomer::PROFILE + .at() + .visits_place() + .eq("home") + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!( + needle(&declared), + serde_json::from_value::(wire).unwrap() + ); + + let typed = EncryptedCustomer::PROFILE + .at_text_path("$.visits[*].at") + .lte(20) + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "lte_at", + json!({"path": "$.visits[*].at", "json": "20"}), + ) + .await); + assert_eq!(serde_json::to_value(&typed).unwrap(), wire); + let declared = EncryptedCustomer::PROFILE + .at() + .visits_at() + .lte(20) + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(serde_json::to_value(&declared).unwrap(), wire); + + let typed = EncryptedCustomer::PROFILE + .elements_text_path("$.visits[*]") + .eq("place", "home") + .between("at", 10, 20) + .wildcard_bound(NonZeroU32::new(8).unwrap()) + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "element_match", + json!({"path": "$.visits[*]", "wildcard_bound": 8, "predicates": [ + {"member": "place", "op": "eq", "json": "\"home\""}, + {"member": "at", "op": "between", "low": "10", "high": "20"} + ]}), + ) + .await); + assert_eq!(serde_json::to_value(&typed).unwrap(), wire); + let declared = EncryptedCustomer::PROFILE + .elements() + .visits() + .place() + .eq("home") + .and() + .at() + .between(10, 20) + .wildcard_bound(NonZeroU32::new(8).unwrap()) + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(serde_json::to_value(&declared).unwrap(), wire); + + let typed = EncryptedCustomer::PROFILE + .predicate("$.age >= $min && exists($.name)") + .var("min", 30) + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "match", + json!({"predicate": "$.age >= $min && exists($.name)", "vars": "{\"min\": 30}"}), + ) + .await); + assert_eq!(serde_json::to_value(&typed).unwrap(), wire); + + let typed = EncryptedCustomer::PROFILE + .at_text_path("$.age") + .selector() + .encrypt(&keyset) + .await + .unwrap(); + let wire = text(data(&keyset, "selector", json!({"path": "$.age"})).await); + assert_eq!(serde_json::to_value(&typed).unwrap(), json!(wire)); + let declared = EncryptedCustomer::PROFILE + .at() + .age() + .selector() + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(serde_json::to_value(&declared).unwrap(), json!(wire)); + + let typed = EncryptedCustomer::PROFILE + .children("$.visits") + .encrypt(&keyset) + .await + .unwrap(); + let wire = text(data(&keyset, "children", json!({"path": "$.visits"})).await); + assert_eq!(serde_json::to_value(&typed).unwrap(), json!(wire)); +} + +/// An ordering at a path the field does not order is refused before any +/// key is requested, as the data plan refuses it. +#[tokio::test] +async fn an_ordering_the_field_does_not_order_is_refused_before_any_key() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let refused = EncryptedCustomer::PROFILE + .at_text_path("$.name") + .gt("A") + .encrypt(&keyset) + .await; + assert!( + matches!(refused, Err(Error::Term(TermError::JsonPathNotOrdered))), + "{refused:?}" + ); + let calls = calls.lock().unwrap(); + assert!( + calls.generate.is_empty() && calls.retrieve.is_empty(), + "no key requested" + ); +} + +/// The plan's example with the name declared for equality alone: a +/// `paths` entry, which adds nothing to the field's options. +#[derive(EncryptTarget)] +#[stash(struct = Customer, scope = "customers")] +struct NamedCustomer { + #[stash(json( + ordered = { "$.age": u32, "$.visits[*].at": u64, "$.visits[*].place": String }, + paths = { "$.name": String }, + ))] + profile: JsonTreeDocument, +} + +/// A path declared for equality derives the data plan's operand, whose +/// options do not name it, finds the stored document, and is not ordered. +#[tokio::test] +async fn a_path_declared_for_equality_is_the_data_plans_operand() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: NamedCustomer = Customer { + profile: profile().into(), + } + .encrypt_into(&keyset) + .await + .unwrap(); + let typed: JsonTreeQuery = NamedCustomer::PROFILE + .at() + .name() + .eq("Ada") + .encrypt(&keyset) + .await + .unwrap(); + let wire = one(data( + &keyset, + "eq_at", + json!({"path": "$.name", "json": "\"Ada\""}), + ) + .await); + assert_eq!( + needle(&typed), + serde_json::from_value::(wire).unwrap() + ); + assert!(needle(&typed).matches(index_document(&stored.profile).selector_set())); + let refused = NamedCustomer::PROFILE + .at_text_path("$.name") + .gt("A") + .encrypt(&keyset) + .await + .unwrap_err(); + assert!( + matches!(refused, Error::Term(TermError::JsonPathNotOrdered)), + "{refused:?}" + ); +} diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index 35c4857372..ec2b7caa94 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -213,8 +213,9 @@ async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typ #[test] fn a_field_reference_answers_what_the_data_path_answers() { let mut gap = Vec::new(); - // A document has no field query: it is queried through a data plan, - // which tests/json_tree_data_plan.rs covers. + // A document's field reference answers through its JSON queries + // (`JsonQueries`), not `Answers`: tests/json_tree_field_references.rs holds them + // to the data path. for target in eql_targets::targets() .iter() .filter(|t| t.plaintext != Some("json")) diff --git a/packages/eql/tests/encryption/tests/v4_owned.rs b/packages/eql/tests/encryption/tests/v4_owned.rs index 12db90a5e4..52422fb5b6 100644 --- a/packages/eql/tests/encryption/tests/v4_owned.rs +++ b/packages/eql/tests/encryption/tests/v4_owned.rs @@ -639,3 +639,112 @@ fn the_traits_the_compile_fail_examples_refuse_exist_for_the_right_shapes() { encrypts::(); encrypts::(); } + +/// How many copies of the plaintext the ciphertext `c` makes. The owned form +/// that `encrypt_into` runs moves the plaintext into the seal. The borrowed +/// form, which a collection runs for each element, copies it once. +mod the_ciphertext { + use super::*; + + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + use eql_bindings::v4::terms::Ciphertext; + use stack_encrypt::target::{AeadContext, EncryptTarget, RequiredContext}; + use stack_encrypt::{nonempty, Encrypt}; + use vitaminc_aead::plaintext::Sink; + use zeroize::Zeroize; + + /// A `String` that counts its clones. + struct Counted { + text: String, + clones: Arc, + } + impl Clone for Counted { + fn clone(&self) -> Self { + let _ = self.clones.fetch_add(1, Ordering::SeqCst); + Self { + text: self.text.clone(), + clones: self.clones.clone(), + } + } + } + impl Encrypt for Counted { + fn visit(self, sink: S) -> Result { + self.text.visit(sink) + } + } + /// The counter is not secret. + impl Zeroize for Counted { + fn zeroize(&mut self) { + self.text.zeroize(); + } + } + + fn counted() -> (Counted, Arc) { + let clones = Arc::new(AtomicUsize::new(0)); + let value = Counted { + text: "ada@example.com".to_owned(), + clones: clones.clone(), + }; + (value, clones) + } + + fn aead() -> RequiredContext { + RequiredContext::from(AeadContext::from(nonempty!("users").with("email"))) + } + + #[tokio::test] + async fn the_owned_form_copies_nothing_and_the_borrowed_form_copies_once() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + + let (value, clones) = counted(); + let owned: Ciphertext = keyset + .run( + >::owned_encryption(), + value, + aead(), + ) + .await + .unwrap(); + assert_eq!(clones.load(Ordering::SeqCst), 0, "the owned form"); + let opened: String = String::decrypt_from_with_context(owned, &cipher, aead()) + .await + .unwrap(); + assert_eq!( + opened, "ada@example.com", + "the moved value is what is sealed" + ); + + let (value, clones) = counted(); + let _: Ciphertext = keyset + .run( + >::encryption(), + &value, + aead(), + ) + .await + .unwrap(); + assert_eq!(clones.load(Ordering::SeqCst), 1, "the borrowed form"); + } + + /// A refused context requests no key. + #[tokio::test] + async fn the_owned_form_refuses_an_empty_part_before_any_key_is_requested() { + use stack_encrypt::target::Scope; + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let (value, clones) = counted(); + let refused = keyset + .run( + >::owned_encryption(), + value, + RequiredContext::from(AeadContext::from(Scope::new(String::new()))), + ) + .await; + assert!(refused.is_err(), "an empty scope is refused"); + assert_eq!(clones.load(Ordering::SeqCst), 0); + assert!(calls.lock().unwrap().generate.is_empty(), "no key"); + } +} diff --git a/packages/stack-encrypt-derive/Cargo.toml b/packages/stack-encrypt-derive/Cargo.toml index 98b4954713..8cc735f9ca 100644 --- a/packages/stack-encrypt-derive/Cargo.toml +++ b/packages/stack-encrypt-derive/Cargo.toml @@ -20,6 +20,11 @@ proc-macro = true proc-macro2 = "1" quote = "1" syn = { version = "3", features = ["full", "extra-traits"] } +# The JSONPath grammar stack-encrypt reads paths with, so a field's declared +# paths are parsed here, at compile time, exactly as the engine parses them. +# No features: the engine's error reporting (miette, ErrorPayload) is not +# 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. # `cargo-udeps` cannot see into rustdoc, so it reports them as unused. diff --git a/packages/stack-encrypt-derive/docs/attributes.md b/packages/stack-encrypt-derive/docs/attributes.md index 196395122a..046548f015 100644 --- a/packages/stack-encrypt-derive/docs/attributes.md +++ b/packages/stack-encrypt-derive/docs/attributes.md @@ -42,6 +42,7 @@ field from the whole `User`. To encrypt a struct field by field, use | `default` or `default = expr` | The field is not derived. It is filled with `Default::default()` or `expr`. It is not encrypted and not authenticated. | | `decrypt` | Decryption opens this field. Use it only when the field types do not decide it. See [Which field decryption opens](#which-field-decryption-opens). | | `passthrough` | Owned derives, with `struct` only. The plaintext field is moved into the record as it is, and moved back on decryption. It is **not encrypted and not authenticated**. See [Passthrough fields](#passthrough-fields). Not with `identity`, `default` or `decrypt`. | +| `json(ordered = { "$.path": Type, .. }, paths = { "$.path": Type, .. }, names = { "key": word, .. }, sealed_root = false)` | Owned derives, with `struct` only, on a field whose type stores a JSON document (`JsonDocument`, or EQL's `JsonTreeDocument`). The field is sealed under the JSON index options it names: `ordered` maps each path whose numbers and strings carry an ordering term to the type of the values at it, `paths` declares a path's type for equality alone and adds nothing to the options, and `sealed_root = false` turns off the sealed root, which is on by default. The field's reference queries under the same options, and has one typed method per path: `PROFILE.at().age().gt(30)`. See [A field that stores a JSON document](#a-field-that-stores-a-json-document). Without it, the field takes the default options, which order no path. | A field cannot have a `context = ".."` of its own, on any derive. Every field of a `plaintext` record shares the caller's context. Every field of a @@ -319,6 +320,135 @@ assert_eq!(opened.len(), 1); # }).unwrap(); ``` +## A field that stores a JSON document + +`json(..)` on a field of a `struct` record names the JSON index's options +the field is sealed and queried under. Its `ordered` entry maps each path +whose values carry an ordering term to the type of those values. Its +`paths` entry maps a path compared with equality alone to its type: the +field stores no ordering term for it, so the entry changes no stored or +derived byte. + +```rust +use serde_json::json; +use stack_encrypt::json::{JsonDocument, JsonPlaintext}; +use stack_encrypt::target::EncryptTarget; +use stack_encrypt::{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, + "$.firstName": String, + "$.visits[*].at": u64, + "$.visits[*].place": String, + "$[\"ship to\"].zip": String, + }, + paths = { "$.vip": bool }, + names = { "ship to": shipping }, + ))] + 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!({ + "age": 35, + "firstName": "Ada", + "visits": [{"place": "home", "at": 15}], + "ship to": {"zip": "3000"}, + "vip": true + }) + .into(), +} +.encrypt_into(&keyset) +.await?; + +// One method per path under `at()`, taking the path's type. +let older = EncryptedCustomer::PROFILE.at().age().gt(30).encrypt(&keyset).await?; +let ada = EncryptedCustomer::PROFILE.at().first_name().eq("Ada").encrypt(&keyset).await?; +let zip = EncryptedCustomer::PROFILE.at().shipping_zip().eq("3000").encrypt(&keyset).await?; +assert!(ada.matches(stored.profile.selector_set())); +assert!(zip.matches(stored.profile.selector_set())); + +// A path under `paths` has equality, and no ordering. +let vip = EncryptedCustomer::PROFILE.at().vip().eq(true).encrypt(&keyset).await?; +assert!(vip.matches(stored.profile.selector_set())); + +// One method per array under `elements()`, and one per member: every +// condition holds of one element together. +let home = EncryptedCustomer::PROFILE + .elements() + .visits() + .place().eq("home") + .and().at().gt(10) + .encrypt(&keyset) + .await?; +assert_eq!(home.len(), 2); + +// A path built at run time is text, checked when the query is encrypted. +let same = EncryptedCustomer::PROFILE.at_text_path("$.age").gt(30).encrypt(&keyset).await?; +assert_eq!(older.selector(), same.selector()); +# Ok::<(), stack_encrypt::Error>(()) +# }).unwrap(); +``` + +The derive parses each path with the engine's grammar when it compiles the +record. A path that does not parse, has no `$`, names an array position +(`[2]`), is given twice, or is given under both `ordered` and `paths` is a +compile error at the path. An `ordered` type is `i8` to `i64`, `u8` to +`u64`, `f64` or `String`; a `paths` type is any of those or `bool`. Any +other is a compile error at the type. + +Each path, under either key, gets a method under `at()`. A path under +`paths` has `eq`, `is_null` and `selector`; an ordering of it (`lt`, +`gt`, `between` and the rest) is a compile error that says to declare it +under `ordered`. Each array whose elements have an ordered member gets a +method under `elements()`, with a method for each ordered member: an +element-scoped condition compares ordering terms, even for equality, so +a `paths` member has none. A method's name comes from the path's keys, +under either key: + +- A key gives a word: its ASCII letters in lower case, with `_` before an + upper-case letter that follows a lower-case letter or a digit, and `-` + read as `_`. `firstName` gives `first_name`, and `user-id` gives + `user_id`. +- A method's name is the words of its keys joined by `_`, with the + wildcards left out. `$.visits[*].at` is `at().visits_at()`; its array + `$.visits[*]` is `elements().visits()`, and the member is `at()`. A path + or an array with no keys is `root`. +- A name that is a Rust keyword is a raw identifier: `$.type` is + `at().r#type()`. + +A key with any other character, such as a space, gives no word, and is a +compile error until `names = { "key": word }` gives it one. Two paths, two +arrays, or two members of one array that give the same name are a compile +error too; `names` resolves that as well. + +A value of another type than the path declares does not compile, and +neither does a member of another array: after a condition, `and()` gives +the members of the same array. An element predicate has `encrypt` only +after its first condition. + +`at_text_path(path)` and `elements_text_path(path)` take a path as text, +for a filter a program builds at run time. They check the path when the +query is encrypted, before any key is requested, and derive the same +operand as the typed method for the same path and value. A field that +declares no paths has only these. + ## Which context a record takes A `CallerContext` contains two encodings of the context. A ciphertext is diff --git a/packages/stack-encrypt-derive/src/attrs.rs b/packages/stack-encrypt-derive/src/attrs.rs index 9278ddfd07..cfe2722fb2 100644 --- a/packages/stack-encrypt-derive/src/attrs.rs +++ b/packages/stack-encrypt-derive/src/attrs.rs @@ -1,6 +1,7 @@ //! Parsing of the `#[stash(...)]` container and field attributes. -use syn::{Attribute, Expr, Ident, LitStr, Member, Path, Result, Type}; +use stack_encrypt_jsonpath::JsonPath; +use syn::{Attribute, Expr, Ident, LitBool, LitStr, Member, Path, Result, Token, Type}; /// Container-level options, from `#[stash(...)]` on the struct itself. pub(crate) struct ContainerAttrs { @@ -342,6 +343,217 @@ pub(crate) struct FieldAttrs { /// an `Option` of it. On a field whose field reference has no operator method /// (a record field, a ciphertext alone), only the check applies. pub(crate) query: Option, + /// `#[stash(json(ordered = { "$.age": u32 }, sealed_root = false))]`: + /// with `struct = ..`, the JSON index's options of a field that stores a + /// document. The field is sealed under them, its field reference's JSON + /// queries derive under them, and each ordered path gets a typed + /// accessor. + pub(crate) json: Option, +} + +/// The JSON index's options a field's `json(..)` names. +#[cfg_attr(test, derive(Debug))] +pub(crate) struct JsonAttr { + /// Where `json` is written, for errors. + pub(crate) span: proc_macro2::Span, + /// `ordered = { "$.age": u32, .. }`: the paths whose leaves carry an + /// ordering term, each with the type of the values at it, in the order + /// written. Each path is parsed here, with the engine's grammar. + pub(crate) ordered: Vec, + /// `paths = { "$.name": String, .. }`: paths given a type and no + /// ordering term, in the order written: each gets a typed accessor + /// under `at()` for equality, and adds nothing to the field's options. + pub(crate) paths: Vec, + /// `names = { "first-name": first_name, .. }`: the word a JSON key + /// gives an accessor name, for a key the naming rule cannot turn into + /// one, or whose word another key gives too. + pub(crate) names: Vec<(LitStr, Ident)>, + /// `sealed_root = false`: turn off the sealed root, which is on by + /// default. + pub(crate) sealed_root: Option, +} + +/// One entry of `ordered = { .. }` or `paths = { .. }`: a path and the type +/// its values hold. +#[cfg_attr(test, derive(Debug))] +pub(crate) struct TypedPath { + /// The path as written, which the field's options are built from. + pub(crate) text: LitStr, + /// The path, parsed. + pub(crate) path: JsonPath, + /// The type of the values at the path. + pub(crate) ty: Type, + /// Whether the entry is under `ordered`: its leaves carry an ordering + /// term, and its accessor has the orderings. + pub(crate) ordered: bool, +} + +/// What `ordered` is now, for a field that still writes the list form. +const ORDERED_IS_A_MAP: &str = "`ordered` maps each path to the type of the values at it: \ + `ordered = { \"$.age\": u32, \"$.visits[*].place\": String }`. The type is a number \ + type or `String`, and gives the path a typed accessor under `at()`"; + +impl JsonAttr { + fn parse(meta: &syn::meta::ParseNestedMeta<'_>) -> Result { + let mut json = Self { + span: syn::spanned::Spanned::span(&meta.path), + ordered: Vec::new(), + paths: Vec::new(), + names: Vec::new(), + sealed_root: None, + }; + let mut ordered = false; + let mut paths = false; + let mut names = false; + meta.parse_nested_meta(|inner| { + if inner.path.is_ident("ordered") { + if ordered { + return Err(inner.error("`ordered` is given twice")); + } + ordered = true; + let value = inner.value()?; + if value.peek(syn::token::Bracket) { + return Err(value.error(ORDERED_IS_A_MAP)); + } + let content; + syn::braced!(content in value); + json.ordered = parse_typed_paths(&content, true, &json.paths)?; + return Ok(()); + } + if inner.path.is_ident("paths") { + if paths { + return Err(inner.error("`paths` is given twice")); + } + paths = true; + let value = inner.value()?; + let content; + syn::braced!(content in value); + json.paths = parse_typed_paths(&content, false, &json.ordered)?; + return Ok(()); + } + if inner.path.is_ident("names") { + if names { + return Err(inner.error("`names` is given twice")); + } + names = true; + let value = inner.value()?; + let content; + syn::braced!(content in value); + json.names = parse_names(&content)?; + return Ok(()); + } + if inner.path.is_ident("sealed_root") { + if json.sealed_root.is_some() { + return Err(inner.error("`sealed_root` is given twice")); + } + json.sealed_root = Some(inner.value()?.parse()?); + return Ok(()); + } + Err(inner.error( + "unsupported `json(..)` option; expected `ordered = { \"$.path\": Type, .. }`, \ + `paths = { \"$.path\": Type, .. }`, `names = { \"key\": name, .. }` or \ + `sealed_root = false`", + )) + })?; + Ok(json) + } +} + +/// The entries of `ordered = { .. }` (`ordered`) or `paths = { .. }`: +/// `"path": Type`, comma separated. Each path is parsed with the engine's +/// grammar. A path that does not parse, names an array position, repeats +/// an earlier path, or is one of `other`, the entries of the other key, is +/// refused at its literal. +fn parse_typed_paths( + content: syn::parse::ParseStream<'_>, + ordered: bool, + other: &[TypedPath], +) -> Result> { + let key = if ordered { "ordered" } else { "paths" }; + let other_key = if ordered { "paths" } else { "ordered" }; + let mut entries: Vec = Vec::new(); + while !content.is_empty() { + let text: LitStr = content.parse()?; + let _: Token![:] = content.parse()?; + let ty: Type = content.parse()?; + let path = JsonPath::parse(&text.value()).map_err(|error| { + syn::Error::new( + text.span(), + format!( + "{error}. A path starts with `$` and continues with `.name`, `[\"name\"]` or \ + `[*]` steps, as in `$.age` or `$.visits[*].place`" + ), + ) + })?; + if path.names_a_position() { + return Err(syn::Error::new( + text.span(), + if ordered { + "an ordered path names no array position (`[2]`): an ordering compares the \ + value its selector reads, and a selector reads every element of an array \ + alike. Write `[*]` to order every element" + } else { + "a declared path names no array position (`[2]`): a query reads every \ + element of an array alike. Write `[*]` for every element" + }, + )); + } + if let Some(earlier) = entries.iter().find(|entry| entry.path == path) { + let mut error = syn::Error::new( + text.span(), + format!("this path is given twice in `{key}`; each path is declared once"), + ); + error.combine(syn::Error::new(earlier.text.span(), "given here first")); + return Err(error); + } + if let Some(earlier) = other.iter().find(|entry| entry.path == path) { + let mut error = syn::Error::new( + text.span(), + format!( + "this path is given in `{other_key}` too; declare a path once: under \ + `ordered` to compare it, or under `paths` for equality alone" + ), + ); + error.combine(syn::Error::new(earlier.text.span(), "given here first")); + return Err(error); + } + entries.push(TypedPath { + text, + path, + ty, + ordered, + }); + if content.is_empty() { + break; + } + let _: Token![,] = content.parse()?; + } + Ok(entries) +} + +/// The entries of `names = { .. }`: `"key": name`, comma separated. +fn parse_names(content: syn::parse::ParseStream<'_>) -> Result> { + let mut names: Vec<(LitStr, Ident)> = Vec::new(); + while !content.is_empty() { + let key: LitStr = content.parse()?; + let _: Token![:] = content.parse()?; + let name: Ident = content.parse()?; + if names + .iter() + .any(|(earlier, _)| earlier.value() == key.value()) + { + return Err(syn::Error::new( + key.span(), + "this key is given twice in `names`; a key has one name", + )); + } + names.push((key, name)); + if content.is_empty() { + break; + } + let _: Token![,] = content.parse()?; + } + Ok(names) } impl FieldAttrs { @@ -421,6 +633,15 @@ impl FieldAttrs { parsed.passthrough = true; return Ok(()); } + if meta.path.is_ident("json") { + if parsed.json.is_some() { + return Err(meta.error( + "`json(..)` is given twice; a field's JSON options are one list", + )); + } + parsed.json = Some(JsonAttr::parse(&meta)?); + return Ok(()); + } if meta.path.is_ident("query") { if parsed.query.is_some() { return Err( @@ -445,7 +666,7 @@ impl FieldAttrs { Err(meta.error( "unsupported field attribute; expected `context_field`, \ `identity = \"...\"`, `from = field`, `default`, `default = expr`, \ - `decrypt`, `passthrough` or `query = Type`", + `decrypt`, `passthrough`, `query = Type` or `json(..)`", )) })?; } diff --git a/packages/stack-encrypt-derive/src/json_paths.rs b/packages/stack-encrypt-derive/src/json_paths.rs new file mode 100644 index 0000000000..8ba0de79ee --- /dev/null +++ b/packages/stack-encrypt-derive/src/json_paths.rs @@ -0,0 +1,507 @@ +//! The typed accessors of a document field's declared paths. +//! +//! A field's `#[stash(json(ordered = { "$.age": u32, .. }, paths = { +//! "$.name": String, .. }))]` names its declared paths and their types: +//! `ordered` ones, whose values carry an ordering term, and `paths` ones, +//! compared with equality alone. The derive generates, for the field +//! `profile` of the record `EncryptedCustomer`: +//! +//! - `EncryptedCustomerProfilePaths`, the type of the field's paths: the +//! fifth type parameter of `EncryptedCustomer::PROFILE`, implementing +//! `DocumentPaths`. +//! - `EncryptedCustomerProfileAt`, what `PROFILE.at()` returns: one method +//! per path, returning a `DeclaredPath` of the path's type. +//! - `EncryptedCustomerProfileElements`, what `PROFILE.elements()` returns: +//! one method per array whose elements have an ordered member. +//! - `EncryptedCustomerProfileElementsVisits`, for the array `$.visits[*]`: +//! one method per ordered member, returning an `ElementMember` of the +//! member's type. It implements `ElementArray`, so a predicate on the +//! array reaches its members again through `and()`. +//! +//! # Names +//! +//! A JSON key gives a word: its ASCII letters in lower case, with `_` +//! before an upper-case letter that follows a lower-case letter or a digit +//! (`firstName` is `first_name`), and `-` read as `_`. A key with any other +//! character gives no word. `names = { "key": word }` gives a key its word +//! instead. +//! +//! An accessor's name is the words of its keys joined by `_`, with the +//! wildcards left out: `$.visits[*].at` is `visits_at` under `at()`, the +//! array `$.visits[*]` is `visits` under `elements()`, and its member +//! `at` is `at`. A path or an array with no keys is `root`. A name that is +//! a Rust keyword is written as a raw identifier (`r#type`). A key that +//! gives no word, a name that is not an identifier, and two paths, arrays +//! or members that give one name are compile errors at the path. + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; +use stack_encrypt_jsonpath::{JsonPath, Segment}; +use syn::spanned::Spanned; +use syn::{Ident, Path, Result, Visibility}; + +use crate::attrs::{JsonAttr, TypedPath}; + +/// The type of a field's declared paths, which the field reference's type +/// names: `Paths`. +pub(crate) fn paths_type(record: &Ident, field: &Ident) -> Ident { + format_ident!("{}{}Paths", record, pascal(&unraw(field))) +} + +/// The accessors of one document field's declared paths, or nothing when +/// the field declares none. +pub(crate) fn accessors( + krate: &Path, + vis: &Visibility, + record: &Ident, + field: &Ident, + json: &JsonAttr, +) -> Result { + if json.ordered.is_empty() && json.paths.is_empty() { + return Ok(TokenStream::new()); + } + let names = Names::new(json); + let field_name = unraw(field); + let prefix = format!("{}{}", record, pascal(&field_name)); + let paths = format_ident!("{}Paths", prefix); + let at = format_ident!("{}At", prefix); + let elements = format_ident!("{}Elements", prefix); + let json_mod = quote!(#krate::field_reference::json); + let reference = quote!(#krate::FieldReference); + let bounds = quote! { + W: #krate::field_reference::Place, + T: #krate::json::JsonQueries, + C: #krate::field_reference::ScopeInput, + }; + let constant = field_name.to_uppercase(); + + // Each declared type is one a path can hold, checked at the type: an + // ordered path's a type an ordering compares, and an unordered path's + // a type equality compares. + let types = json.ordered.iter().chain(&json.paths).map(|entry| { + let ty = &entry.ty; + if entry.ordered { + quote_spanned! {ty.span()=> let _ = ordered::<#ty>; } + } else { + quote_spanned! {ty.span()=> let _ = unordered::<#ty>; } + } + }); + let checks = quote! { + const _: () = { + fn ordered() {} + fn unordered() {} + #(#types)* + }; + }; + + // One method under `at()` per path, ordered or not. + let mut at_methods = Vec::new(); + let mut at_names: Vec<(String, &TypedPath)> = Vec::new(); + for ordered in json.ordered.iter().chain(&json.paths) { + let name = names.accessor(keys(ordered.path.segments()), ordered)?; + if let Some((_, earlier)) = at_names.iter().find(|(seen, _)| *seen == name) { + return Err(collision(ordered, earlier, &format!("at().{name}()"))); + } + let method = method_ident(&name, ordered.text.span())?; + let text = &ordered.text; + let ty = &ordered.ty; + let (order, compares) = if ordered.ordered { + ( + quote!(#json_mod::OrderedPath), + "Equality and the orderings compare it", + ) + } else { + ( + quote!(#json_mod::EqualityPath), + "Equality compares it; it is not ordered", + ) + }; + let doc = format!( + "The value at `{}`, which holds a `{}`. {compares}.", + text.value(), + quote!(#ty) + ); + let output = quote_spanned!(ty.span()=> #json_mod::DeclaredPath); + at_methods.push(quote! { + #[doc = #doc] + pub fn #method(self) -> #output { + #json_mod::DeclaredPath::new(self.0, #text) + } + }); + at_names.push((name, ordered)); + } + + // One method under `elements()` per array whose elements have an + // ordered member, and one type per array holding its members. + let mut arrays: Vec> = Vec::new(); + for ordered in &json.ordered { + let segments = ordered.path.segments(); + let Some(last) = segments + .iter() + .rposition(|segment| *segment == Segment::Wildcard) + else { + continue; + }; + let (array, member) = segments.split_at(last + 1); + if member.is_empty() { + continue; + } + let array = JsonPath::from(array.to_vec()); + match arrays.iter_mut().find(|known| known.path == array) { + Some(known) => known.members.push((member.to_vec(), ordered)), + None => arrays.push(Array { + path: array, + first: ordered, + members: vec![(member.to_vec(), ordered)], + }), + } + } + let mut element_methods = Vec::new(); + let mut array_items = Vec::new(); + let mut array_types = Vec::new(); + let mut array_names: Vec<(String, &TypedPath)> = Vec::new(); + for array in &arrays { + let name = names.accessor(keys(array.path.segments()), array.first)?; + if let Some((_, earlier)) = array_names.iter().find(|(seen, _)| *seen == name) { + return Err(collision( + array.first, + earlier, + &format!("elements().{name}()"), + )); + } + let method = method_ident(&name, array.first.text.span())?; + let members_type = format_ident!("{}Elements{}", prefix, pascal(&name)); + array_types.push(members_type.clone()); + let array_text = array.path.to_string(); + let doc = format!( + "The array `{array_text}`: its ordered members are the methods of `{members_type}`." + ); + element_methods.push(quote! { + #[doc = #doc] + pub fn #method(self) -> #members_type<#json_mod::ArrayElements> { + #members_type(#json_mod::ArrayElements::new(self.0, #array_text)) + } + }); + array_names.push((name, array.first)); + + let mut member_methods = Vec::new(); + let mut member_names: Vec<(String, &TypedPath)> = Vec::new(); + for (member, ordered) in &array.members { + let name = names.accessor(keys(member), ordered)?; + if let Some((_, earlier)) = member_names.iter().find(|(seen, _)| *seen == name) { + return Err(collision( + ordered, + earlier, + &format!( + "elements().{}().{name}()", + array_names.last().map_or("", |n| &n.0) + ), + )); + } + let method = method_ident(&name, ordered.text.span())?; + // A member's text is the path below the element, as the text + // form of the query names it: `place`, or `["first name"]`. + let rendered = JsonPath::from(member.clone()).to_string(); + let member_text = rendered + .strip_prefix("$.") + .or_else(|| rendered.strip_prefix('$')) + .unwrap_or(&rendered) + .to_owned(); + let ty = &ordered.ty; + let doc = format!( + "The member `{member_text}` of each element of `{array_text}`, which holds a `{}`. A condition on it holds of one element together with the predicate's other conditions.", + quote!(#ty) + ); + let output = quote_spanned!(ty.span()=> #json_mod::ElementMember); + member_methods.push(quote! { + #[doc = #doc] + pub fn #method(self) -> #output { + #json_mod::ElementMember::new(self.0, #member_text) + } + }); + member_names.push((name, ordered)); + } + let doc = format!( + "The ordered members of each element of `{array_text}`, in the field `{field_name}`, one method each. Returned by `{record}::{constant}.elements().{}()`, and by `and()` after a condition on one of them.", + array_names.last().map_or("", |n| &n.0), + ); + array_items.push(quote! { + #[doc = #doc] + #[allow(dead_code)] + pub struct #members_type(Q); + + #[automatically_derived] + #[allow(dead_code)] + impl #members_type { + #(#member_methods)* + } + + #[automatically_derived] + impl #json_mod::ElementArray for #members_type { + type Members = #members_type; + fn members(query: Q) -> Self::Members { + #members_type(query) + } + } + }); + } + + let paths_doc = format!( + "The paths the field `{field_name}` of `{record}` declares, as a type: the last type parameter of `{record}::{constant}`, through which it has `at()` and `elements()`." + ); + let at_doc = format!( + "The ordered paths of the field `{field_name}` of `{record}`, one method each: what `{record}::{constant}.at()` returns." + ); + let elements_doc = format!( + "The arrays of the field `{field_name}` of `{record}` whose elements have an ordered member, one method each: what `{record}::{constant}.elements()` returns." + ); + // The types live in a module of their own, so that the field each + // wraps is private to it and the compiler never suggests reaching + // through it, and are re-exported beside the record. + let module = format_ident!("__stash_json_paths_{}_{}", record, field_name); + Ok(quote! { + #checks + + #[doc(hidden)] + #[allow(non_snake_case)] + mod #module { + #[allow(unused_imports)] + use super::*; + + #[doc = #paths_doc] + #[allow(dead_code)] + pub enum #paths {} + + #[doc = #at_doc] + #[allow(dead_code)] + pub struct #at(#reference); + + #[automatically_derived] + #[allow(dead_code)] + impl #at + where + #bounds + { + #(#at_methods)* + } + + #[doc = #elements_doc] + #[allow(dead_code)] + pub struct #elements(#reference); + + #[automatically_derived] + #[allow(dead_code)] + impl #elements + where + #bounds + { + #(#element_methods)* + } + + #(#array_items)* + + #[automatically_derived] + impl #json_mod::DocumentPaths for #paths { + type At = #at; + type Elements = #elements; + fn at(reference: #krate::FieldReference) -> Self::At { + #at(reference) + } + fn elements(reference: #krate::FieldReference) -> Self::Elements { + #elements(reference) + } + } + } + + #[allow(unused_imports)] + #vis use #module::{#paths, #at, #elements #(, #array_types)*}; + }) +} + +/// One array a field declares through its ordered members. +struct Array<'a> { + path: JsonPath, + /// The first entry that names it, where an error about it is reported. + first: &'a TypedPath, + /// Each member's steps below the element, with its entry. + members: Vec<(Vec, &'a TypedPath)>, +} + +/// The keys of `segments`, in order: the wildcards left out. Ordered paths +/// name no position, so every other step is a key. +fn keys(segments: &[Segment]) -> Vec<&str> { + segments + .iter() + .filter_map(|segment| match segment { + Segment::Key(key) => Some(key.as_str()), + Segment::Index(_) | Segment::Wildcard => None, + }) + .collect() +} + +/// The words a field's `names = { .. }` gives keys. +struct Names<'a> { + given: &'a [(syn::LitStr, Ident)], +} + +impl<'a> Names<'a> { + fn new(json: &'a JsonAttr) -> Self { + Self { given: &json.names } + } + + /// The word of one key: the one `names` gives it, or the naming rule's. + fn word(&self, key: &str) -> Option { + if let Some((_, name)) = self.given.iter().find(|(given, _)| given.value() == key) { + return Some(unraw(name)); + } + word(key) + } + + /// The accessor name of a path, an array or a member with these keys, + /// reported at `ordered`'s literal when a key gives no word. + fn accessor(&self, keys: Vec<&str>, ordered: &TypedPath) -> Result { + if keys.is_empty() { + return Ok("root".to_owned()); + } + let mut words = Vec::with_capacity(keys.len()); + for key in keys { + let Some(word) = self.word(key) else { + return Err(syn::Error::new( + ordered.text.span(), + format!( + "the key {key:?} gives no accessor name: a key gives one from ASCII \ + letters, digits, `_` and `-`. Name it with `names = {{ {key:?}: word }}` \ + in the field's `json(..)`" + ), + )); + }; + words.push(word); + } + Ok(words.join("_")) + } +} + +/// A key's word by the naming rule: ASCII letters in lower case, `_` before +/// an upper-case letter that follows a lower-case letter or a digit, and +/// `-` read as `_`. `None` for a key with any other character, or none. +pub(crate) fn word(key: &str) -> Option { + let mut out = String::with_capacity(key.len() + 4); + let mut previous: Option = None; + for c in key.chars() { + match c { + 'A'..='Z' => { + if matches!(previous, Some('a'..='z' | '0'..='9')) { + out.push('_'); + } + out.push(c.to_ascii_lowercase()); + } + 'a'..='z' | '0'..='9' | '_' => out.push(c), + '-' => out.push('_'), + _ => return None, + } + previous = Some(c); + } + (!out.is_empty()).then_some(out) +} + +/// The method an accessor name is: the name itself, or a raw identifier +/// for a keyword. A name that is no identifier either way is refused at +/// `span`. +fn method_ident(name: &str, span: Span) -> Result { + if syn::parse_str::(name).is_ok() { + return Ok(Ident::new(name, span)); + } + let starts_well = name.starts_with(|c: char| c.is_ascii_lowercase() || c == '_'); + let unrawable = matches!(name, "self" | "Self" | "super" | "crate" | "_"); + if starts_well && !unrawable { + return Ok(Ident::new_raw(name, span)); + } + Err(syn::Error::new( + span, + format!( + "this path gives the accessor name `{name}`, which is not a Rust identifier. Name \ + the key that starts it with `names = {{ \"key\": word }}` in the field's `json(..)`" + ), + )) +} + +/// Two entries that give one accessor name, reported at the later. +fn collision(later: &TypedPath, earlier: &TypedPath, accessor: &str) -> syn::Error { + let mut error = syn::Error::new( + later.text.span(), + format!( + "this path gives the accessor `{accessor}`, which `{}` gives too. Name a key with \ + `names = {{ \"key\": word }}` in the field's `json(..)`", + earlier.text.value() + ), + ); + error.combine(syn::Error::new( + earlier.text.span(), + "the accessor's first path", + )); + error +} + +/// An identifier's text without its `r#`. +fn unraw(ident: &Ident) -> String { + let text = ident.to_string(); + text.strip_prefix("r#").map(str::to_owned).unwrap_or(text) +} + +/// `snake_case` in `PascalCase`: `visits_at` is `VisitsAt`. +fn pascal(snake: &str) -> String { + snake + .split('_') + .filter(|word| !word.is_empty()) + .map(|word| { + let mut chars = word.chars(); + chars + .next() + .map(|first| first.to_ascii_uppercase().to_string() + chars.as_str()) + .unwrap_or_default() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_key_gives_its_word_by_the_rule() { + for (key, expected) in [ + ("age", Some("age")), + ("firstName", Some("first_name")), + ("first-name", Some("first_name")), + ("first_name", Some("first_name")), + ("userID", Some("user_id")), + ("URL", Some("url")), + ("v2Count", Some("v2_count")), + ("2fa", Some("2fa")), + ("type", Some("type")), + ("", None), + ("first name", None), + ("café", None), + ("a.b", None), + ] { + assert_eq!(word(key).as_deref(), expected, "{key:?}"); + } + } + + #[test] + fn a_keyword_is_a_raw_identifier_and_a_digit_is_refused() { + let span = Span::call_site(); + assert_eq!(method_ident("age", span).unwrap().to_string(), "age"); + assert_eq!(method_ident("type", span).unwrap().to_string(), "r#type"); + assert_eq!(method_ident("_", span).ok(), None); + assert_eq!(method_ident("self", span).ok(), None); + assert_eq!(method_ident("2fa", span).ok(), None); + } + + #[test] + fn a_name_is_pascal_cased_for_a_type() { + assert_eq!(pascal("visits_at"), "VisitsAt"); + assert_eq!(pascal("profile"), "Profile"); + assert_eq!(pascal("a__b"), "AB"); + } +} diff --git a/packages/stack-encrypt-derive/src/lib.rs b/packages/stack-encrypt-derive/src/lib.rs index 9d513f2ca9..896340a4cf 100644 --- a/packages/stack-encrypt-derive/src/lib.rs +++ b/packages/stack-encrypt-derive/src/lib.rs @@ -143,6 +143,16 @@ //! inner record lists a scope, the query needs each record's scope, //! outermost first. //! +//! `#[stash(json(ordered = { "$.age": u32 }))]` on a field whose type stores +//! a JSON document names the JSON index's options: the paths whose numbers +//! and strings carry an ordering term, each with the type of its values, +//! and `sealed_root = false` to turn the sealed root off. The field is +//! sealed under them, and its field reference's JSON queries (`contains`, +//! `at`, `elements`, `predicate`, `children`) derive under them. The derive +//! parses each path at compile time and gives it a typed method: +//! `PROFILE.at().age().gt(30)`. Without it the field takes the default +//! options, which order no path. +//! //! `#[stash(query = String)]` on a field states the type its queries take, //! so each of its field reference's methods takes that type alone. The derive checks //! it against the plaintext struct's field, which is that type or an @@ -312,6 +322,7 @@ use proc_macro::TokenStream; use syn::{parse_macro_input, DeriveInput}; mod attrs; +mod json_paths; mod owned_decrypt; mod owned_encrypt; mod shape; diff --git a/packages/stack-encrypt-derive/src/owned_encrypt.rs b/packages/stack-encrypt-derive/src/owned_encrypt.rs index 9eaad3bab9..9532c63461 100644 --- a/packages/stack-encrypt-derive/src/owned_encrypt.rs +++ b/packages/stack-encrypt-derive/src/owned_encrypt.rs @@ -31,7 +31,97 @@ pub(crate) fn derive(input: DeriveInput) -> Result { }; let contexts = contexts_fn(&input, &record); let field_references = field_references(&input, &record); - Ok(quote!(#emitted #decryptable #contexts #field_references)) + let json = json_options_fns(&input, &record); + let paths = json_path_accessors(&input, &record)?; + Ok(quote!(#emitted #decryptable #contexts #field_references #json #paths)) +} + +/// The name of the function that builds the JSON options a field's +/// `#[stash(json(..))]` names, which the field's encryption and its field reference +/// both call. +fn json_options_name(field: &Field) -> Ident { + Ident::new( + &format!("__stash_json_options_{}", field.local), + field.local.span(), + ) +} + +/// One function per `#[stash(json(..))]` field, building the options it +/// names: the paths it orders, and whether the root is sealed. A path the +/// engine refuses is an error the field's encryption and its queries meet +/// before any key is requested. +fn json_options_fns(input: &DeriveInput, record: &Record) -> TokenStream { + let krate = &record.krate; + let name = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + let fns: Vec = record + .fields + .iter() + .filter_map(|field| { + let Kind::Derived { + by_field: Some(ByField { json: Some(json), .. }), + } = &field.kind + else { + return None; + }; + let fn_name = json_options_name(field); + let paths: Vec<_> = json.ordered.iter().map(|ordered| &ordered.text).collect(); + let count = paths.len(); + let sealed_root = json.sealed_root.as_ref().map(|sealed| { + quote!(options.sealed_root = #sealed;) + }); + Some(quote_spanned! {json.span=> + #[doc(hidden)] + #[allow(dead_code)] + fn #fn_name() -> ::core::result::Result<#krate::json::JsonOptions, #krate::sem::TermError> { + let paths: [&'static str; #count] = [#(#paths),*]; + #[allow(unused_mut)] + let mut options = #krate::json::JsonOptions::new().ordering(paths)?; + #sealed_root + ::core::result::Result::Ok(options) + } + }) + }) + .collect(); + if fns.is_empty() { + return TokenStream::new(); + } + quote! { + #[automatically_derived] + impl #impl_generics #name #ty_generics #where_clause { + #(#fns)* + } + } +} + +/// The typed accessors of each document field whose `#[stash(json(..))]` +/// declares ordered paths ([`crate::json_paths`]). +fn json_path_accessors(input: &DeriveInput, record: &Record) -> Result { + if !record.by_field { + return Ok(TokenStream::new()); + } + let mut items = TokenStream::new(); + for field in &record.fields { + let Kind::Derived { + by_field: Some(ByField { + json: Some(json), .. + }), + } = &field.kind + else { + continue; + }; + let syn::Member::Named(ident) = &field.member else { + continue; + }; + items.extend(crate::json_paths::accessors( + &record.krate, + &input.vis, + &input.ident, + ident, + json, + )?); + } + Ok(items) } /// The field references of a `struct = ..` record: one associated constant @@ -61,11 +151,15 @@ fn field_references(input: &DeriveInput, record: &Record) -> TokenStream { }; let consts = record.fields.iter().filter_map(|field| { let Kind::Derived { - by_field: Some(ByField { context, query, .. }), + by_field: Some(ByField { context, query, json, .. }), } = &field.kind else { return None; }; + let json_options = json.as_ref().map(|_| { + let fn_name = json_options_name(field); + quote!(.with_json_options(Self::#fn_name)) + }); let syn::Member::Named(ident) = &field.member else { return None; }; @@ -73,6 +167,15 @@ fn field_references(input: &DeriveInput, record: &Record) -> TokenStream { Some(query) => quote!(#krate::field_reference::Takes<#query>), None => quote!(#krate::field_reference::TakesAny), }; + // A field that declares paths, ordered or not, has a type of its + // own for them, through which it has `at()` and `elements()`. + let paths_ty = json + .as_ref() + .filter(|json| !json.ordered.is_empty() || !json.paths.is_empty()) + .map(|_| { + let paths = crate::json_paths::paths_type(name, ident); + quote!(, #paths) + }); // The field reference's name is the field's as `contexts()` and the label // spell it, `r#` included; the constant's name cannot carry it. let field_name = ident.to_string(); @@ -90,8 +193,8 @@ fn field_references(input: &DeriveInput, record: &Record) -> TokenStream { Some(quote_spanned! {ty.span()=> #[doc = #doc] #[allow(dead_code, private_interfaces)] - pub const #const_name: #krate::FieldReference<#krate::field_reference::Root, #ty, #scope_ty, #query_ty> = - #krate::FieldReference::new(#field_name, #prefix, #identity, Self::contexts); + pub const #const_name: #krate::FieldReference<#krate::field_reference::Root, #ty, #scope_ty, #query_ty #paths_ty> = + #krate::FieldReference::new(#field_name, #prefix, #identity, Self::contexts)#json_options; }) }); quote! { @@ -320,7 +423,7 @@ fn struct_derive(input: &DeriveInput, record: &Record) -> TokenStream { let local = &field.local; match &field.kind { Kind::Derived { - by_field: Some(ByField { from, context, query }), + by_field: Some(ByField { from, context, query, json }), } => { let own = own_expr(krate, context); let name = field_name(field); @@ -334,9 +437,18 @@ fn struct_derive(input: &DeriveInput, record: &Record) -> TokenStream { }; } }); + // A `json(..)` field is sealed under the options it + // names, through the field type's `JsonTarget`. + let description = match json { + Some(_) => { + let fn_name = json_options_name(field); + quote_spanned!(ty.span()=> #krate::json::seal_field::<#ty, _, __K>(Self::#fn_name())) + } + None => quote_spanned!(ty.span()=> <#ty as #krate::target::EncryptTarget<_>>::encryption::<__K>()), + }; quote_spanned! {ty.span()=> #check - let #local = <#ty as #krate::target::EncryptTarget<_>>::encryption::<__K>() + let #local = #description .under_field(#own) .project(|__source: &#source| &__source.#from) .named(#name); @@ -367,14 +479,21 @@ fn struct_derive(input: &DeriveInput, record: &Record) -> TokenStream { let local = &field.local; match &field.kind { Kind::Derived { - by_field: Some(ByField { context, .. }), + by_field: Some(ByField { context, json, .. }), } => { let own = own_expr(krate, context); let name = field_name(field); + let description = match json { + Some(_) => { + let fn_name = json_options_name(field); + quote_spanned!(ty.span()=> #krate::json::seal_field_owned::<#ty, _, __K>(Self::#fn_name())) + } + None => quote_spanned!(ty.span()=> <#ty as #krate::target::EncryptTarget<_>>::owned_encryption::<__K>()), + }; // `under_field` wipes the field's plaintext when the // context is refused before the field's target runs. quote_spanned! {ty.span()=> - let #local = <#ty as #krate::target::EncryptTarget<_>>::owned_encryption::<__K>() + let #local = #description .under_field(#own) .named(#name); } @@ -516,6 +635,12 @@ fn own_expr(krate: &syn::Path, context: &OwnContext) -> TokenStream { /// are zipped. A record with a `context_field` stores its context /// (`Encryption::storing`): the `NonEmpty` the caller passes, or the /// field's own context when the record is a field of a `struct = ..` record. +/// +/// A record with exactly one field derived from the plaintext also has an +/// owned form ([`owned_form`]). Its value goes to that one field, so it can +/// be moved into the field's own owned form. A record with two or more such +/// fields keeps the default owned form: the value is guarded, and each field +/// reads it through the borrowed form. fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> TokenStream { let krate = &record.krate; let input_type = encrypt_input(record); @@ -580,6 +705,7 @@ fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> Toke } } }; + let owned = owned_form(record, fields, &source, &lifetime, &threaded, &body); impls.push(trait_impl( input, &generics, @@ -602,6 +728,7 @@ fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> Toke } __described } + #owned fn indexes() -> ::std::vec::Vec<#krate::target::IndexSpec> { let mut __indexes = ::std::vec::Vec::new(); #(#indexes)* @@ -612,3 +739,47 @@ fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> Toke } quote!(#(#impls)*) } + +/// The owned form of a `plaintext = T` record with exactly one field derived +/// from the plaintext, or nothing for any other record. +/// +/// The whole value goes to the one field, so nothing needs to share it. The +/// value is moved into the field's own owned form. A field type that only +/// reads its plaintext in place keeps the default owned form, which guards +/// the value and wipes it. A field type that seals the value, such as a +/// ciphertext, moves it into the seal, with no copy. +/// +/// `body` is the borrowed form's root, after the fields' descriptions: a +/// `map` and `accepting`, which take any source mode, or `storing`, whose +/// owned form wipes the value when the context cannot be stored. A refusal +/// of the record's indexes wipes the value too (`refused_wiping`). +fn owned_form( + record: &Record, + fields: &[&Field], + source: &Type, + lifetime: &syn::Lifetime, + threaded: &Type, + body: &TokenStream, +) -> TokenStream { + let [field] = fields else { + return TokenStream::new(); + }; + let krate = &record.krate; + let ty = &field.ty; + let local = &field.local; + let name = field_name(field); + quote! { + fn owned_encryption<#lifetime, __K: 'static>() -> #krate::target::Encryption<#lifetime, #source, Self, __K, Self::ContextInput, #krate::target::Owned> where #source: #lifetime { + let #local = <#ty as #krate::target::EncryptTarget<#source>>::owned_encryption::<__K>() + .accepting::<#threaded>() + .named(#name); + let __described = #body; + if let ::core::result::Result::Err(__error) = #krate::target::check_indexes( + &>::indexes(), + ) { + return __described.refused_wiping(__error); + } + __described + } + } +} diff --git a/packages/stack-encrypt-derive/src/shape.rs b/packages/stack-encrypt-derive/src/shape.rs index c511b64ce4..65a4691530 100644 --- a/packages/stack-encrypt-derive/src/shape.rs +++ b/packages/stack-encrypt-derive/src/shape.rs @@ -8,7 +8,7 @@ use syn::{ PathArguments, Result, Type, }; -use crate::attrs::{ContainerAttrs, FieldAttrs}; +use crate::attrs::{ContainerAttrs, FieldAttrs, JsonAttr}; /// A generated lifetime must not shadow one the record declares. Append /// underscores until the name is free, preserving the user's parameters. @@ -76,6 +76,9 @@ pub(crate) struct ByField { /// `#[stash(query = T)]`: the type a query of the field takes, for its /// field reference. pub(crate) query: Option, + /// `#[stash(json(..))]`: the JSON index's options the field is sealed + /// and queried under. + pub(crate) json: Option>, } impl Field { @@ -473,6 +476,23 @@ fn collect(fields: &Fields, prefix: Option<&LitStr>) -> Result> { )); } } + // JSON options are a sealed document field's, and only a field + // of a `struct = ..` record has a field reference to query it with. + if let Some(json) = &attrs.json { + if prefix.is_none() + || attrs.context_field + || attrs.passthrough + || attrs.default.is_some() + { + return Err(syn::Error::new( + json.span, + "`json(..)` names the JSON index's options a sealed document field is \ + sealed and queried under; only a sealed field of a `struct = ..` record \ + has them, so it does not apply to a `plaintext` record's field, or to a \ + `context_field`, `passthrough` or `default` field", + )); + } + } // An identity is one label segment: non-empty, and plain so the // descriptor names the field. if let Some(identity) = &attrs.identity { @@ -588,6 +608,7 @@ fn collect(fields: &Fields, prefix: Option<&LitStr>) -> Result> { from, context, query: attrs.query, + json: attrs.json.map(Box::new), }), } } diff --git a/packages/stack-encrypt-jsonpath/CHANGELOG.md b/packages/stack-encrypt-jsonpath/CHANGELOG.md new file mode 100644 index 0000000000..b3db900248 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- **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 + time with the same grammar. It holds `JsonPath`, `Segment`, + `JsonPathError`, and the JSON string decoder a quoted name is read with + (`json_string`). `stack-encrypt` re-exports the three types at + `stack_encrypt::json`. Three items are new to the public surface, because + the engine now builds paths across the crate boundary: `JsonPath::push`, + `From> for JsonPath`, and `JsonPath::names_a_position`. + The `diagnostics` feature gives `JsonPathError` its `miette::Diagnostic` + and `ErrorPayload`; `stack-encrypt` turns it on, and the derive leaves it + off. diff --git a/packages/stack-encrypt-jsonpath/Cargo.toml b/packages/stack-encrypt-jsonpath/Cargo.toml new file mode 100644 index 0000000000..14a3828952 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "stack-encrypt-jsonpath" +description = "The JSONPath subset stack-encrypt's JSON index addresses, shared by stack-encrypt and its derive" +version = "0.3.0" +edition.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true +keywords.workspace = true +categories.workspace = true +license-file = "LICENSE" +# Published to crates.io by release-plz.yml, in the `stack-encrypt` version +# group: stack-encrypt parses every path through this crate, and +# stack-encrypt-derive parses a field's declared paths through it at compile +# time, so the three release together. stack-encrypt re-exports the types at +# `stack_encrypt::json`. + +[dependencies] +# A path deserializes from its text and serializes as it, as a plan's +# ordered paths read on the wire. +serde = { workspace = true } +# `JsonPath::select` reads a `serde_json::Value`, and `Display` writes a +# quoted key the way serde_json escapes a string. +serde_json = { workspace = true } +thiserror = { workspace = true } +# A path's key names can be customer data: a path wipes them when it drops, +# and a quoted name is decoded into a buffer that is wiped. +zeroize = { workspace = true } +# The `diagnostics` feature: how stack-encrypt reports a refused path. +# `miette::Diagnostic` gives `JsonPathError` its code and help, and stack-auth's +# `ErrorPayload` its structured fields. Optional, so the derive, which parses +# paths at compile time and reports its own errors, builds neither into the +# compiler's process. stack-encrypt turns it on; both crates are already in +# its graph. +miette = { workspace = true, optional = true } +stack-auth = { workspace = true, optional = true } + +[features] +diagnostics = ["dep:miette", "dep:stack-auth"] + +[package.metadata.docs.rs] +all-features = true diff --git a/packages/stack-encrypt-jsonpath/LICENSE b/packages/stack-encrypt-jsonpath/LICENSE new file mode 100644 index 0000000000..2cbd67a66d --- /dev/null +++ b/packages/stack-encrypt-jsonpath/LICENSE @@ -0,0 +1,96 @@ +# PolyForm Internal Use License 1.0.0 + + + +## Acceptance + +In order to get any license under these terms, you must agree +to them as both strict obligations and conditions to all +your licenses. + +## Copyright License + +The licensor grants you a copyright license for the software +to do everything you might do with the software that would +otherwise infringe the licensor's copyright in it for any +permitted purpose. However, you may only make changes or +new works based on the software according to [Changes and New +Works License](#changes-and-new-works-license), and you may +not distribute the software. + +## Changes and New Works License + +The licensor grants you an additional copyright license to +make changes and new works based on the software for any +permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that +covers patent claims the licensor can license, or becomes able +to license, that you would infringe by using the software. + +## Fair Use + +You may have "fair use" rights for the software under the +law. These terms do not limit them. + +## Internal Business Use + +Use of the software for the internal business operations of +you and your company is use for a permitted purpose. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of +your licenses to anyone else, or prevent the licensor from +granting licenses to anyone else. These terms do not imply +any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or +contributes to infringement of any patent, your patent license +for the software granted under these terms ends immediately. If +your company makes such a claim, your patent license ends +immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have +violated any of these terms, or done anything with the software +not covered by your licenses, your licenses can nonetheless +continue if you come into full compliance with these terms, +and take practical steps to correct past violations, within +32 days of receiving notice. Otherwise, all your licenses +end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without +any warranty or condition, and the licensor will not be liable +to you for any damages arising out of these terms or the use +or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these +terms, and the **software** is the software the licensor makes +available under these terms. + +**You** refers to the individual or entity agreeing to these +terms. + +**Your company** is any legal entity, sole proprietorship, +or other kind of organization that you work for, plus all +organizations that have control over, are under the control of, +or are under common control with that organization. **Control** +means ownership of substantially all the assets of an entity, +or the power to direct its management and policies by vote, +contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the +software under these terms. + +**Use** means anything you do with the software requiring one +of your licenses. diff --git a/packages/stack-encrypt-jsonpath/src/json_string.rs b/packages/stack-encrypt-jsonpath/src/json_string.rs new file mode 100644 index 0000000000..d197fbb7e8 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/src/json_string.rs @@ -0,0 +1,313 @@ +//! JSON strings: the quoted names of a path, and the strings of every JSON +//! text `stack-encrypt` reads. +//! +//! One decoder serves both, so a quoted key in a path and the same key in a +//! document decode to the same text. The escapes are JSON's. A string's +//! decoded text is never longer than its raw text, so a caller sizes the +//! buffer to [`raw_len`] before it decodes, and the buffer never grows: a +//! key can be customer data, and a buffer that grew would free a copy of +//! it. + +use zeroize::Zeroizing; + +/// The decoder refused the text at its cursor: a control character, the +/// end of the text before the closing quote, a malformed escape, an unpaired +/// surrogate, or bytes that are not UTF-8. The cursor is left at the place +/// the refusal names, so the caller reports the offset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StringSyntaxError; + +/// Decode the string whose raw text starts at `rest`, just after its +/// opening quote, into `out`, and move `rest` past its closing quote. +/// +/// # Errors +/// +/// [`StringSyntaxError`] for text that is not the rest of one JSON string. +/// `rest` is then at the first byte refused. +pub fn decode<'t>(rest: &mut &'t [u8], out: &mut String) -> Result<(), StringSyntaxError> { + loop { + // A run of plain bytes, copied as one checked UTF-8 slice. + let current: &'t [u8] = rest; + let run = current + .iter() + .take_while(|&&b| b != b'"' && b != b'\\' && b >= 0x20) + .count(); + let (plain, tail) = current.split_at(run); + let plain = std::str::from_utf8(plain).map_err(|_| StringSyntaxError)?; + out.push_str(plain); + *rest = tail; + // Each arm that goes round again first moves `rest` past the byte + // it read, so every turn of the loop consumes at least one byte, + // whatever the escape reads after it. + match *rest { + [b'"', after @ ..] => { + *rest = after; + return Ok(()); + } + [b'\\', after @ ..] => { + *rest = after; + out.push(escape(rest)?); + } + // A control character, or the end of the text. + _ => return Err(StringSyntaxError), + } + } +} + +/// The character an escape names, after its backslash. On a refusal +/// `rest` is at the byte refused. +fn escape(rest: &mut &[u8]) -> Result { + let [first, after @ ..] = *rest else { + return Err(StringSyntaxError); + }; + let c = match first { + b'"' => '"', + b'\\' => '\\', + b'/' => '/', + b'b' => '\u{8}', + b'f' => '\u{c}', + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'u' => { + *rest = after; + return unicode(rest); + } + _ => return Err(StringSyntaxError), + }; + *rest = after; + Ok(c) +} + +/// `\uXXXX`, after its `u`: one code point, or a surrogate pair. An +/// unpaired surrogate is refused. +fn unicode(rest: &mut &[u8]) -> Result { + let high = hex4(rest)?; + let code = if (0xD800..0xDC00).contains(&high) { + let Some(tail) = rest.strip_prefix(b"\\u") else { + return Err(StringSyntaxError); + }; + *rest = tail; + let low = hex4(rest)?; + if !(0xDC00..0xE000).contains(&low) { + return Err(StringSyntaxError); + } + 0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00) + } else { + high + }; + char::from_u32(code).ok_or(StringSyntaxError) +} + +fn hex4(rest: &mut &[u8]) -> Result { + let current: &[u8] = rest; + let Some((digits, tail)) = current.split_first_chunk::<4>() else { + return Err(StringSyntaxError); + }; + let mut code = 0; + for &d in digits { + let Some(v) = char::from(d).to_digit(16) else { + return Err(StringSyntaxError); + }; + code = code * 16 + v; + } + *rest = tail; + Ok(code) +} + +/// The length of a string's raw text, from after its opening quote to +/// before its closing one (or to the end, when it has none): an escaped +/// quote does not end it. +pub fn raw_len(rest: &[u8]) -> usize { + let mut escaped = false; + rest.iter() + .take_while(|&&b| { + let end = b == b'"' && !escaped; + escaped = !escaped && b == b'\\'; + !end + }) + .count() +} + +/// The text of one JSON string, quotes included, decoded; `None` for text +/// that is not exactly one string. The decoded text is wiped when it is +/// dropped. Its buffer is sized to the raw text before anything is written, +/// so it never grows, and it is wiped on a refusal. +pub fn string_text(text: &[u8]) -> Option> { + let mut rest = text.strip_prefix(b"\"")?; + let mut decoded = Zeroizing::new(String::with_capacity(raw_len(rest))); + decode(&mut rest, &mut decoded).ok()?; + rest.is_empty().then_some(decoded) +} + +/// Where the JSON string at the front of `text` ends: the offset of its +/// closing quote. `text` starts at the opening quote. `None` for a string +/// with no closing quote. An escaped quote does not close it. +pub fn string_end(text: &[u8]) -> Option { + let end = 1 + raw_len(text.get(1..)?); + (end < text.len()).then_some(end) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn string_end_is_the_offset_of_the_closing_quote() { + for (text, end) in [ + (r#""""#, Some(1)), + (r#""ab" rest"#, Some(3)), + (r#""a\"b" rest"#, Some(5)), + (r#""a\\" rest"#, Some(4)), + (r#""a\\\"b""#, Some(7)), + (r#""unterminated"#, None), + (r#""ends in an escape\""#, None), + (r#"""#, None), + ("", None), + ] { + assert_eq!(string_end(text.as_bytes()), end, "{text:?}"); + } + } + + #[test] + fn string_text_decodes_exactly_one_json_string() { + let decoded = |text: &str| string_text(text.as_bytes()).map(|text| text.to_string()); + assert_eq!(decoded(r#""plain""#).as_deref(), Some("plain")); + assert_eq!(decoded(r#""""#).as_deref(), Some("")); + assert_eq!( + decoded(r#""a\n\"b\" é 😀""#).as_deref(), + Some("a\n\"b\" é 😀") + ); + for refused in [ + "", + "plain", + r#" "leading space""#, + r#""unterminated"#, + r#""one" "two""#, + r#""trailing" "#, + r#""bad \x escape""#, + r#""lone \ud83d surrogate""#, + "\"raw\nnewline\"", + "1", + "null", + ] { + assert_eq!(decoded(refused), None, "{refused:?}"); + } + } + + /// A predicate's literals and a path's quoted keys are JSON strings by + /// `serde_json`'s rules: every string it reads is read the same here, + /// and every one it refuses is refused. + #[test] + fn string_text_reads_what_serde_json_reads() { + for text in [ + r#""""#, + r#""a""#, + r#""\"\\\/\b\f\n\r\t""#, + r#""Aé中""#, + r#""😀""#, + r#""\ude00\ud83d""#, + r#""\ud83d""#, + r#""\u12""#, + r#""\q""#, + "\"\u{1}\"", + "\"é中😀\"", + r#""a"b""#, + ] { + let ours = string_text(text.as_bytes()).map(|text| text.to_string()); + let theirs = serde_json::from_str::(text).ok(); + assert_eq!(ours, theirs, "{text:?}"); + } + } + + /// A refusal leaves the cursor at the byte refused, which is the offset + /// a caller reports. + #[test] + fn a_refusal_leaves_the_cursor_at_the_byte_refused() { + for (text, left) in [ + (&b"ab\x01cd"[..], &b"\x01cd"[..]), + (b"ab", b""), + (br"a\qb", b"qb"), + (br"\u12g4", b"12g4"), + (br"\ud83dx", b"x"), + (br"\ud83d\u0041", b""), + (br"\ud83d\ue000x", b"x"), + (br"\udc00x", b"x"), + (br"a\", b""), + (br"\u12", b"12"), + (b"a\xffb\"", b"a\xffb\""), + ] { + let mut rest = text; + let mut out = String::new(); + assert_eq!(decode(&mut rest, &mut out), Err(StringSyntaxError)); + assert_eq!(rest, left, "{}", String::from_utf8_lossy(text)); + } + let mut rest = &br#"a\"b" tail"#[..]; + let mut out = String::new(); + assert_eq!(decode(&mut rest, &mut out), Ok(())); + assert_eq!((out.as_str(), rest), ("a\"b", &b" tail"[..])); + } + + #[test] + fn the_raw_length_runs_to_the_closing_quote_or_the_end() { + assert_eq!(raw_len(br#"abc""#), 3); + assert_eq!(raw_len(br#"a\"b\\""#), 6); + assert_eq!(raw_len(b"ab"), 2, "an unterminated string runs to the end"); + } + + /// Each escape decodes to the character JSON gives it, a surrogate + /// pair to its one code point, and the boundaries refuse what they + /// should: a control character, a lone or reversed surrogate, a short + /// or non-hex `\u`. + #[test] + fn each_escape_decodes_and_each_boundary_holds() { + let decoded = |raw: &str| { + let mut rest = raw.as_bytes(); + let mut out = String::new(); + decode(&mut rest, &mut out).map(|()| (out, rest.len())) + }; + for (raw, expected) in [ + (r#"\"""#, "\""), + (r#"\\""#, "\\"), + (r#"\/""#, "/"), + (r#"\b""#, "\u{8}"), + (r#"\f""#, "\u{c}"), + (r#"\n""#, "\n"), + (r#"\r""#, "\r"), + (r#"\t""#, "\t"), + (r#"\u0041""#, "A"), + (r#"\u00e9""#, "\u{e9}"), + (r#"\u00E9""#, "\u{e9}"), + (r#"\uffff""#, "\u{ffff}"), + (r#"\ud83d\ude00""#, "\u{1f600}"), + (r#"\ud800\udc00""#, "\u{10000}"), + (r#"\udbff\udfff""#, "\u{10ffff}"), + ("\u{20}~\"", " ~"), + ] { + assert_eq!(decoded(raw), Ok((expected.to_owned(), 0)), "{raw:?}"); + } + for raw in [ + "\u{1f}\"", + r#"\ud83d""#, + r#"\ud83d\u0041""#, + r#"\ud83d\ue000""#, + r#"\udc00""#, + r#"\u12""#, + r#"\u12g4""#, + r#"\x""#, + r#"\"#, + ] { + assert_eq!(decoded(raw).ok(), None, "{raw:?}"); + } + assert_eq!(decoded(r#"ab" tail"#), Ok(("ab".to_owned(), 5))); + } + + #[test] + fn an_escaped_backslash_does_not_escape_the_quote_after_it() { + assert_eq!(raw_len(br#"a\\"b"#), 3); + assert_eq!(raw_len(br#"a\\\"b""#), 6); + assert_eq!(string_end(br#""a\\" rest"#), Some(4)); + assert_eq!(string_end(b"\""), None, "an opening quote alone"); + assert_eq!(string_end(b"\"\""), Some(1)); + } +} diff --git a/packages/stack-encrypt-jsonpath/src/lib.rs b/packages/stack-encrypt-jsonpath/src/lib.rs new file mode 100644 index 0000000000..0b84229743 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/src/lib.rs @@ -0,0 +1,36 @@ +//! The JSONPath subset that `stack-encrypt`'s JSON index addresses. +//! +//! 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. +//! +//! 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::json`, which re-exports these types. +//! +//! ``` +//! use stack_encrypt_jsonpath::{JsonPath, Segment}; +//! +//! let path = JsonPath::parse("$.visits[*].place")?; +//! assert_eq!( +//! path.segments(), +//! &[ +//! Segment::Key("visits".into()), +//! Segment::Wildcard, +//! Segment::Key("place".into()), +//! ] +//! ); +//! assert!(!path.is_positional()); +//! assert!(JsonPath::parse("visits").is_err(), "a path starts with `$`"); +//! # Ok::<(), stack_encrypt_jsonpath::JsonPathError>(()) +//! ``` +#![forbid(unsafe_code)] + +pub mod json_string; +mod path; + +pub use path::{JsonPath, JsonPathError, Segment}; diff --git a/packages/stack-encrypt-jsonpath/src/path.rs b/packages/stack-encrypt-jsonpath/src/path.rs new file mode 100644 index 0000000000..2cebb53a91 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/src/path.rs @@ -0,0 +1,509 @@ +//! JSON paths: how a caller names a node of a document. +//! +//! A [`JsonPath`] is parsed from the JSONPath subset the JSON index +//! addresses: `$`, 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. +//! +//! `stack-encrypt`'s JSON index derives two things from a path, and they +//! differ on arrays: +//! +//! - A **selector** names a path with every array position replaced by the +//! wildcard, because every element of an array shares one selector. +//! `$.a[2].x` and `$.a[*].x` have the same selector. +//! - A **token** names a path positionally, so a path with a wildcard has +//! none: the token chain addresses one node. +use std::fmt; +use std::str::FromStr; + +use zeroize::{Zeroize, Zeroizing}; + +/// One step of a [`JsonPath`]. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Segment { + /// An object member, by key. + Key(String), + /// One array element, by position. + Index(u64), + /// Every element of an array. + Wildcard, +} + +/// A path into a JSON document, from the root (`$`) down. +/// +/// A key step's name can be customer data (the walk builds a path for every +/// node of a document it seals or queries), so a path wipes its key names +/// when it drops. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Default, PartialOrd, Ord)] +pub struct JsonPath { + segments: Vec, +} + +impl Drop for JsonPath { + fn drop(&mut self) { + for segment in &mut self.segments { + if let Segment::Key(key) = segment { + key.zeroize(); + } + } + } +} + +/// Why text is not a [`JsonPath`]. The message names the position of the +/// first character the parser refused and nothing else of the text: a path +/// can name a key that is customer data. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[cfg_attr(feature = "diagnostics", derive(miette::Diagnostic))] +#[error("not a JSON path: {reason} at byte {at}")] +#[cfg_attr( + feature = "diagnostics", + diagnostic( + code(stack_encrypt::json_path), + help("A path starts with `$` and continues with `.name`, `[\"name\"]`, `[2]` or `[*]` steps, as in `$.address.city` or `$.tags[*]`.") + ) +)] +pub struct JsonPathError { + /// What was expected, or what was found. + pub reason: &'static str, + /// The byte offset in the text the parser stopped at. + pub at: usize, +} + +/// The reason and the offset, as fields. Never the text. +#[cfg(feature = "diagnostics")] +impl stack_auth::ErrorPayload for JsonPathError { + fn payload(&self) -> serde_json::Map { + stack_auth::diagnostic::payload([ + ("reason", self.reason.into()), + ("at", (self.at as u64).into()), + ]) + } +} + +impl JsonPath { + /// The root, `$`. + pub fn root() -> Self { + Self::default() + } + + /// Parse the JSONPath subset the index addresses: `$`, `.name`, + /// `["name"]`, `[2]` and `[*]` steps. + /// + /// # Errors + /// + /// [`JsonPathError`] for text that is not one. + pub fn parse(text: &str) -> Result { + // The parser walks a cursor, `rest`: the text not yet read. Every + // step strips at least one byte from its front, so the loop ends on + // any input, and a refusal names the offset of what was left. + let at = |rest: &str| text.len() - rest.len(); + let refuse = |reason, rest: &str| { + Err(JsonPathError { + reason, + at: at(rest), + }) + }; + let Some(mut rest) = text.strip_prefix('$') else { + return refuse("expected `$`", text); + }; + // The steps are read into the path itself, so a refusal part way + // drops a path, which wipes the keys already read. + let mut path = Self::default(); + let segments = &mut path.segments; + while !rest.is_empty() { + if let Some(after) = rest.strip_prefix('.') { + let end = after.find(['.', '[']).unwrap_or(after.len()); + if end == 0 { + return refuse("expected a member name after `.`", after); + } + // `end` is at an ASCII delimiter or the end of the text, so + // the split falls on a character boundary. + let (name, next) = after.split_at(end); + segments.push(Segment::Key(name.to_owned())); + rest = next; + } else if let Some(after) = rest.strip_prefix('[') { + if let Some(star) = after.strip_prefix('*') { + let Some(next) = star.strip_prefix(']') else { + return refuse("expected `]` after `*`", star); + }; + segments.push(Segment::Wildcard); + rest = next; + } else if after.starts_with('"') { + let (mut key, next) = match quoted(after) { + Ok(parts) => parts, + Err(reason) => return refuse(reason, after), + }; + let Some(next) = next.strip_prefix(']') else { + return refuse("expected `]` after the quoted name", next); + }; + segments.push(Segment::Key(std::mem::take(&mut *key))); + rest = next; + } else if after.starts_with(|c: char| c.is_ascii_digit()) { + let end = after + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(after.len()); + let (digits, next) = after.split_at(end); + let Some(next) = next.strip_prefix(']') else { + return refuse("expected `]` after the position", next); + }; + let Ok(index) = digits.parse::() else { + return refuse("the position does not fit 64 bits", after); + }; + segments.push(Segment::Index(index)); + rest = next; + } else { + return refuse("expected `*`, a quoted name or a position after `[`", after); + } + } else { + return refuse("expected `.` or `[`", rest); + } + } + Ok(path) + } + + /// The steps, from the root down. Empty for the root itself. + pub fn segments(&self) -> &[Segment] { + &self.segments + } + + /// Whether some step is an array position (`[2]`), which a selector + /// reads as the wildcard. + pub fn names_a_position(&self) -> bool { + self.segments.iter().any(|s| matches!(s, Segment::Index(_))) + } + + /// Whether this path names one node: no step is the wildcard. + pub fn is_positional(&self) -> bool { + !self.segments.iter().any(|s| matches!(s, Segment::Wildcard)) + } + + /// Whether this path, read as a pattern, covers `path`: the same + /// steps, except that a wildcard here covers any array step there, a + /// position or the wildcard. A position here covers that position + /// alone, not the wildcard, since the wildcard names elements the + /// position does not. How the JSON index's ordered paths are matched + /// against a node's path when a document is sealed, and against a + /// query's path when an ordering is asked. + /// + /// ``` + /// use stack_encrypt_jsonpath::JsonPath; + /// + /// let wild = JsonPath::parse("$.orders[*].total").unwrap(); + /// assert!(wild.covers(&JsonPath::parse("$.orders[3].total").unwrap())); + /// assert!(wild.covers(&JsonPath::parse("$.orders[*].total").unwrap())); + /// let third = JsonPath::parse("$.orders[3].total").unwrap(); + /// assert!(third.covers(&JsonPath::parse("$.orders[3].total").unwrap())); + /// assert!(!third.covers(&JsonPath::parse("$.orders[2].total").unwrap())); + /// assert!(!third.covers(&JsonPath::parse("$.orders[*].total").unwrap())); + /// assert!(!wild.covers(&JsonPath::parse("$.orders[*]").unwrap())); + /// ``` + pub fn covers(&self, path: &JsonPath) -> bool { + self.segments.len() == path.segments.len() + && self + .segments + .iter() + .zip(&path.segments) + .all(|(pattern, step)| match (pattern, step) { + (Segment::Key(a), Segment::Key(b)) => a == b, + (Segment::Wildcard, Segment::Index(_) | Segment::Wildcard) => true, + (Segment::Index(a), Segment::Index(b)) => a == b, + _ => false, + }) + } + + /// The values at this path in `value`, in document order: at most one + /// for a positional path, one per element a wildcard reaches, none when + /// the path names nothing. A key step into an array, or a position + /// into an object, reaches nothing, as the token chain reaches nothing + /// there. What a client takes over a whole document when a walk + /// returned the sealed root in place of the subtree. + pub fn select<'a>(&self, value: &'a serde_json::Value) -> Vec<&'a serde_json::Value> { + let mut current = vec![value]; + for segment in &self.segments { + let mut next = Vec::new(); + for node in current { + match segment { + Segment::Key(key) => next.extend(node.as_object().and_then(|o| o.get(key))), + Segment::Index(index) => next.extend( + usize::try_from(*index) + .ok() + .and_then(|i| node.as_array().and_then(|a| a.get(i))), + ), + Segment::Wildcard => next.extend(node.as_array().into_iter().flatten()), + } + } + current = next; + } + current + } + + /// Add one step to the end of this path. A parser reads its steps + /// into a path with this, so the keys it has read are wiped if it + /// refuses the text part way. + pub fn push(&mut self, segment: Segment) { + self.segments.push(segment); + } +} + +/// The JSON string at the front of `text`, which starts at its opening +/// quote: its value and the text after its closing quote. The escapes are +/// JSON's. The refusal is the reason; the caller names the offset. +/// +/// A key is plaintext. Its value is decoded into a buffer sized for it and +/// is wiped when it is dropped, so a caller that refuses the text after it +/// leaves nothing behind. A caller that keeps the key takes it out into a +/// path, which wipes it. +fn quoted(text: &str) -> Result<(Zeroizing, &str), &'static str> { + let end = crate::json_string::string_end(text.as_bytes()).ok_or("unterminated quoted name")?; + let key = crate::json_string::string_text(&text.as_bytes()[..=end]) + .ok_or("the quoted name is not a JSON string")?; + Ok((key, &text[end + 1..])) +} + +/// The path of these steps, from the root down. +impl From> for JsonPath { + fn from(segments: Vec) -> Self { + Self { segments } + } +} + +impl FromStr for JsonPath { + type Err = JsonPathError; + + fn from_str(text: &str) -> Result { + Self::parse(text) + } +} + +/// Renders the path as it parses: a plain key as `.key`, any other as +/// `["…"]`, a position as `[2]`, the wildcard as `[*]`. +impl fmt::Display for JsonPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("$")?; + for segment in &self.segments { + match segment { + Segment::Key(key) if !key.is_empty() && !key.contains(['.', '[', ']', '"']) => { + write!(f, ".{key}")?; + } + Segment::Key(key) => { + write!(f, "[{}]", serde_json::Value::String(key.clone()))?; + } + Segment::Index(index) => write!(f, "[{index}]")?, + Segment::Wildcard => f.write_str("[*]")?, + } + } + Ok(()) + } +} + +/// A path serializes as its text, as [`Display`](fmt::Display) renders it, +/// so a plan's ordered paths read as `["$.age"]` on the wire. +impl serde::Serialize for JsonPath { + fn serialize(&self, s: S) -> Result { + s.collect_str(self) + } +} + +/// A path deserializes from its text through [`JsonPath::parse`], so a +/// string that is not a path is refused where it is read, with the +/// [`JsonPathError`]'s message. +impl<'de> serde::Deserialize<'de> for JsonPath { + fn deserialize>(d: D) -> Result { + let text = >::deserialize(d)?; + Self::parse(&text).map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(k: &str) -> Segment { + Segment::Key(k.to_owned()) + } + + #[test] + fn parses_the_subset_the_index_addresses() { + let path = JsonPath::parse("$.a[2].b[*][\"c.d\"]").unwrap(); + assert_eq!( + path.segments(), + &[ + key("a"), + Segment::Index(2), + key("b"), + Segment::Wildcard, + key("c.d") + ] + ); + assert_eq!(path.to_string(), "$.a[2].b[*][\"c.d\"]"); + assert_eq!(JsonPath::parse("$").unwrap(), JsonPath::root()); + assert_eq!(JsonPath::parse("$").unwrap().to_string(), "$"); + assert!(!path.is_positional()); + assert!(JsonPath::parse("$.a[2]").unwrap().is_positional()); + } + + #[test] + fn selects_what_the_chain_would_reach() { + let doc = serde_json::json!({ + "a": [{"x": 1}, {"x": 2, "y": [3, 4]}, 5], + "b": {"c": "d"}, + }); + let at = |text: &str| JsonPath::parse(text).unwrap().select(&doc); + assert_eq!(at("$"), vec![&doc]); + assert_eq!(at("$.b.c"), vec![&serde_json::json!("d")]); + assert_eq!(at("$.a[1].x"), vec![&serde_json::json!(2)]); + assert_eq!( + at("$.a[*].x"), + vec![&serde_json::json!(1), &serde_json::json!(2)] + ); + assert_eq!( + at("$.a[*].y[*]"), + vec![&serde_json::json!(3), &serde_json::json!(4)] + ); + assert!(at("$.a.x").is_empty(), "a key step into an array"); + assert!(at("$.b[0]").is_empty(), "a position into an object"); + assert!(at("$.a[3]").is_empty(), "past the end"); + assert!(at("$.b[*]").is_empty(), "the wildcard over an object"); + assert!(at("$.z").is_empty()); + assert!(JsonPath::parse("$[18446744073709551615]") + .unwrap() + .select(&doc) + .is_empty()); + } + + #[test] + fn refuses_what_it_does_not_address() { + for (text, at) in [ + ("", 0), + ("a.b", 0), + ("$.", 2), + ("$..a", 2), + ("$[", 2), + ("$[1", 3), + ("$[-1]", 2), + ("$[\"a]", 2), + ("$.a[x]", 4), + ("$[*x", 3), + ("$[*", 3), + ("$[\"a\"x", 5), + ("$[\"a\"", 5), + ("$[\"\\q\"]", 2), + ("$[18446744073709551616]", 2), + ] { + let error = JsonPath::parse(text).unwrap_err(); + assert_eq!(error.at, at, "{text:?}: {error}"); + } + // A plain key runs to the next `.` or `[`, so it may hold a space. + assert_eq!(JsonPath::parse("$.a b").unwrap().segments(), &[key("a b")]); + } + + #[test] + fn a_quoted_name_takes_json_escapes() { + assert_eq!( + JsonPath::parse(r#"$["a\"b"]"#).unwrap().segments(), + &[key("a\"b")], + "an escaped quote does not end the name" + ); + assert_eq!( + JsonPath::parse(r#"$["a\\"].b"#).unwrap().segments(), + &[key("a\\"), key("b")], + "an escaped backslash does not escape the closing quote" + ); + assert_eq!( + JsonPath::parse(r#"$["\u0041"][0]"#).unwrap().segments(), + &[key("A"), Segment::Index(0)] + ); + assert_eq!( + JsonPath::parse("$[18446744073709551615]") + .unwrap() + .segments(), + &[Segment::Index(u64::MAX)] + ); + } + + #[test] + fn a_path_parses_through_from_str() { + let path: JsonPath = "$.a[*]".parse().unwrap(); + assert_eq!(path, JsonPath::parse("$.a[*]").unwrap()); + assert_eq!("$.".parse::().unwrap_err().at, 2); + } + + #[test] + fn a_position_covers_its_own_position_only() { + let path = |text: &str| JsonPath::parse(text).unwrap(); + let third = path("$.orders[3].total"); + assert!(third.covers(&path("$.orders[3].total"))); + assert!(!third.covers(&path("$.orders[2].total"))); + assert!(!third.covers(&path("$.orders[*].total"))); + assert!(path("$.orders[*].total").covers(&third)); + assert!(!path("$.orders[3]").covers(&third), "the same steps only"); + } + + #[test] + fn a_path_round_trips_through_serde_as_its_text() { + for text in ["$", "$.a[*].b", r#"$["a.b"][2]"#, r#"$["say \"hi\""]"#] { + let path = JsonPath::parse(text).unwrap(); + let wire = serde_json::to_value(&path).unwrap(); + assert_eq!(wire, serde_json::Value::String(path.to_string())); + assert_eq!(serde_json::from_value::(wire).unwrap(), path); + } + let refused = serde_json::from_value::(serde_json::json!("a.b")).unwrap_err(); + assert_eq!( + refused.to_string(), + "not a JSON path: expected `$` at byte 0" + ); + assert!(serde_json::from_value::(serde_json::json!(1)).is_err()); + } + + #[test] + fn a_path_built_step_by_step_is_the_path_parsed() { + let mut built = JsonPath::root(); + built.push(key("visits")); + built.push(Segment::Wildcard); + built.push(key("place")); + let parsed = JsonPath::parse("$.visits[*].place").unwrap(); + assert_eq!(built, parsed); + assert_eq!( + JsonPath::from(vec![key("visits"), Segment::Wildcard, key("place")]), + parsed + ); + } + + #[test] + fn a_position_is_named_and_a_wildcard_is_not() { + let path = |text: &str| JsonPath::parse(text).unwrap(); + assert!(path("$.a[2].b").names_a_position()); + assert!(!path("$.a[*].b").names_a_position()); + assert!(!path("$").names_a_position()); + } + + /// The payload stack-encrypt reports a refusal with: the reason and + /// the offset, and nothing of the text. + #[cfg(feature = "diagnostics")] + #[test] + fn a_refusal_reports_its_reason_and_offset_as_its_payload() { + use stack_auth::ErrorPayload; + let payload = JsonPath::parse("$.secret[x]").unwrap_err().payload(); + assert_eq!( + payload.get("reason"), + Some(&serde_json::json!( + "expected `*`, a quoted name or a position after `[`" + )) + ); + assert_eq!(payload.get("at"), Some(&serde_json::json!(9))); + assert_eq!(payload.len(), 2, "{payload:?}"); + } + + /// A refusal names its reason and offset, never the text: a key in it + /// can be customer data. + #[test] + fn a_refusal_does_not_quote_the_text() { + let error = JsonPath::parse("$.secret[x]").unwrap_err(); + assert_eq!( + error.reason, + "expected `*`, a quoted name or a position after `[`" + ); + assert_eq!(error.at, 9); + assert!(!error.to_string().contains("secret")); + } +} diff --git a/packages/stack-encrypt-jsonpath/tasks.toml b/packages/stack-encrypt-jsonpath/tasks.toml new file mode 100644 index 0000000000..b34d3e8306 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/tasks.toml @@ -0,0 +1,8 @@ +# Tasks for stack-encrypt-jsonpath, the JSONPath grammar stack-encrypt and its +# derive share. Included from the root mise.toml. + +# Rustdoc with warnings as errors, which the root `doc` task fans out to. +["doc:stack-encrypt-jsonpath"] +description = "Build docs for stack-encrypt-jsonpath with all features (warnings are errors)" +env = { RUSTDOCFLAGS = "-D warnings" } +run = "cargo doc -p stack-encrypt-jsonpath --no-deps --all-features" diff --git a/packages/stack-encrypt-jsonpath/tests/wipe.rs b/packages/stack-encrypt-jsonpath/tests/wipe.rs new file mode 100644 index 0000000000..7b8ecadaf3 --- /dev/null +++ b/packages/stack-encrypt-jsonpath/tests/wipe.rs @@ -0,0 +1,102 @@ +//! A path's key names can be customer data, so a path wipes them when it +//! drops, and a parse that refuses its text part way wipes the keys it has +//! read. Checked with an allocator that looks inside every block it frees. +//! +//! Unix only: the allocator scans a freed block with libc's `memmem`. + +#![cfg(unix)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use stack_encrypt_jsonpath::JsonPath; + +/// A key name no other allocation in this test holds. +const MARK: &[u8] = b"kq7markzv"; + +/// Freed blocks that still held [`MARK`], while [`WATCHING`]. +static FOUND: AtomicUsize = AtomicUsize::new(0); +static WATCHING: AtomicBool = AtomicBool::new(false); + +struct Spy; + +/// Whether the `len` bytes at `ptr` hold [`MARK`]. A freed block can hold +/// bytes Rust never initialised (a `Vec`'s spare capacity, a struct's +/// padding), and reading those through a `&[u8]` is undefined behaviour, so +/// the scan is libc's `memmem`, which reads the block as plain memory. +/// +/// # Safety +/// +/// `ptr` must point to `len` allocated bytes. +unsafe fn holds_mark(ptr: *const u8, len: usize) -> bool { + extern "C" { + fn memmem( + haystack: *const c_void, + haystack_len: usize, + needle: *const c_void, + needle_len: usize, + ) -> *mut c_void; + } + !memmem(ptr.cast(), len, MARK.as_ptr().cast(), MARK.len()).is_null() +} + +// SAFETY: every call is forwarded to `System`; `dealloc` only reads the +// block it is given before freeing it. +unsafe impl GlobalAlloc for Spy { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + System.alloc(layout) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + if WATCHING.load(Ordering::SeqCst) { + // SAFETY: `ptr` is a live block of `layout.size()` bytes until + // the `System.dealloc` below. + if holds_mark(ptr, layout.size()) { + let _ = FOUND.fetch_add(1, Ordering::SeqCst); + } + } + System.dealloc(ptr, layout); + } +} + +#[global_allocator] +static ALLOCATOR: Spy = Spy; + +/// The freed blocks that held the mark while `run` ran. +fn leaked(run: impl FnOnce()) -> usize { + FOUND.store(0, Ordering::SeqCst); + WATCHING.store(true, Ordering::SeqCst); + run(); + WATCHING.store(false, Ordering::SeqCst); + FOUND.load(Ordering::SeqCst) +} + +#[test] +fn a_path_and_a_refused_parse_leave_no_key_behind() { + let mark = std::str::from_utf8(MARK).unwrap(); + let text = format!("$.{mark}[*].b"); + let quoted = format!("$[\"{mark}\"].b"); + let refused = format!("$.{mark}[x]"); + assert_eq!( + leaked(|| { + let path = JsonPath::parse(&text).unwrap(); + assert_eq!(path.segments().len(), 3); + drop(path); + }), + 0, + "a plain key" + ); + assert_eq!( + leaked(|| drop(JsonPath::parse("ed).unwrap())), + 0, + "a quoted key" + ); + assert_eq!( + leaked(|| assert!(JsonPath::parse(&refused).is_err())), + 0, + "a refused parse" + ); + // The control: the spy finds a key that is not wiped. + assert_eq!(leaked(|| drop(mark.to_owned())), 1, "an unwiped copy"); +} diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 333aaad601..94bdd02597 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -57,6 +57,131 @@ 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 +- **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 + query, in place of the operator methods: + + | Field reference method | Returns, for `JsonDocument` | + | --- | --- | + | `contains(doc)`, `contained_by(doc)`, `at().age().eq(v)` | `JsonQuery` | + | `at().age().lt(v)`, `.lte`, `.gt`, `.gte` | `JsonLeafQuery` | + | `at().age().between(lo, hi)` | `(JsonLeafQuery, JsonLeafQuery)`, low then high | + | `at().age().is_null()` | `JsonQuery` | + | `at().age().selector()` | `JsonSelector` | + | `elements().visits().place().eq(v).and().at().gt(v)` | `JsonElementsQuery` | + | `predicate(text).var(name, v)` | `JsonPredicateQuery` | + | `children(path)` | `JsonSubtreeKey`, which holds the node's one token | + + `EncryptedCustomer::PROFILE.at().age().gt(30).encrypt(&keyset)` derives + under the field's column and options, as a scalar field's query does, + and takes a scope with `.scope(..)`. Each query derives the operand the + dynamic interface derives for the same declaration: the field reference + and the data plan read one definition of each input, which no longer + needs the `dynamic` feature. + - **Typed paths.** `#[stash(json(ordered = { "$.age": u32, + "$.visits[*].place": String }, sealed_root = false))]` on the field + names the JSON index's options and the type of the values at each + ordered path. The derive seals the field under them, and the field + queries under them. It parses each path at compile time with the + engine's grammar (`stack-encrypt-jsonpath`): a path that does not + parse, has no `$`, names an array position or is given twice is a + compile error at the path, and a type other than an integer type, + `f64` or `String` (`JsonPathType`) is one at the type. Each path gets + a method under `at()`, returning a `DeclaredPath` of its type, and + each array whose elements have an ordered member gets one under + `elements()`, whose methods are the members (`ElementMember`). A + path, member or array the field does not declare has no method, a + value of another type does not compile (`PathValue`), and `and()` + after a condition gives the same array's members, so a member of + another array cannot be given. A method is named after the path's + keys (`$.visits[*].at` is `visits_at()`); `names = { "key": word }` + names a key the rule cannot. `paths = { "$.name": String, "$.vip": + bool }` declares a path for equality alone: its type is any + `JsonScalarType` (a `JsonPathType` or `bool`), it adds nothing to the + field's options, so no stored or derived byte changes, and its + `DeclaredPath` (kind `EqualityPath`, where an `ordered` path's is + `OrderedPath`) has `eq`, `is_null` and `selector`; an ordering of it + does not compile (`OrderedPathKind`). A path under both keys is a + compile error. An element-scoped condition compares ordering terms, + so `elements()` has ordered members only. The field reference has a fifth type + parameter, the field's paths (`DocumentPaths`); a field that declares + none has `TextPaths`. A field reached through an outer record + (`field`) keeps its paths. + - **Paths as text.** `at_text_path(path)` and `elements_text_path(path)` + take JSONPath text, for a filter built at run time, and check it when + the query is encrypted, before any key is requested, by the dynamic + interface's rules: an ordering at a path the field does not order is + `TermError::JsonPathNotOrdered`. They derive the operand the typed + method derives for the same path and value. A field with no declared + paths has only these. A document type that seals under other options + when its field names none says so with `JsonQueries::default_options`, + which its field queries under. + - **Typed values.** An ordering at a text path takes a number or a + string (`field_reference::json::JsonOrdered`), equality there a scalar + (`JsonScalar`), and containment a document. A boolean ordering, or + equality with an object, does not compile. An element predicate with + no condition has no `encrypt`. A NaN or an infinity, which no JSON + number is, is refused with the new `TermError::JsonNumberNotFinite` + (`stack_encrypt::json_number_not_finite`) before any key is requested, + rather than becoming `null`. There is no `f32` value: serde_json widens + an `f32` when it builds a document, so the query takes the `f64` the + document holds (`f64::from(x)` for one built from `x`). A NaN or an + infinity inside a `serde_json::Value` given to `contains` is already + `null`, and is queried as `null`. + - **Predicate variables.** `predicate(text).var("min", 30)` names one + variable, which the predicate reads as `$min`; `var_null(name)` names + a JSON `null`. A value is a `JsonScalar`. A NaN or an infinity is + refused with `TermError::JsonNumberNotFinite`, and a name given twice + with `Error::Input` and `Reason::JsonDuplicateKey`, each before any + key is requested. The predicate text is checked when the query is + encrypted. + - **Refusals.** A refusal of the input's own shape (an + `elements_text_path` path with no wildcard, a predicate the grammar + does not read) is the new `Error::Input`, below. + - **New public items.** `json::JsonTarget`, which seals a document under + options; `json::JsonQueries`, which converts each operand into the + field type's query type; `json::JsonElementsQuery` and + `json::JsonPredicateQuery`, the typed element and predicate operands; + and `field_reference::json`, the query types: `DeclaredPath`, + `ArrayElements`, `ElementMember`, `DocumentPaths`, `ElementArray`, + `TextPaths`, `JsonPathType` and `PathValue` among them. + +- **A value passed by value is sealed without a copy** (#1687). Sealing + a value took a copy of it when the target had no owned form of its own. + Both copies were wiped, so nothing leaked, but the copy was not needed. + - A `JsonDocument` field marked `#[stash(json(..))]` moves the document + out of the `JsonPlaintext` into the seal + (`JsonTarget::json_owned_encryption`), as `encrypt_into` already did. + - A derived `plaintext = T` record with exactly one field derived from + the plaintext has its own `owned_encryption`. It moves the value into + the owned form of that field's target. So a record whose one field is a + `StackCipherText` seals the value with no copy. When the record's + context cannot be stored, or its indexes are refused, the value is + wiped. A record with two or more such fields is unchanged. + - Three items for generated and binding code, hidden from the docs: + `Encryption::storing` in `Owned` mode (requires `S: Zeroize`, and + wipes the value when the context cannot be stored), + `Encryption::refused_wiping` (requires `S: Zeroize`), and + `Encryption::over_json_plaintext`, which turns an owned description of + a `serde_json::Value` into one of a `JsonPlaintext` by moving the + document across. No item returns the document to its caller. + - The stored bytes do not change. A target with search terms keeps its + behaviour. + +- **`Error::Input`: a refusal of the caller's input** (#1459). A field + field reference's JSON query whose input has the wrong shape, and a data plan run + through `dynamic::Planned` whose source does not fit it, now fail with + `Error::Input`, which holds the dynamic interface's error. Its message, + code (`stack_encrypt::dynamic_source`, `stack_encrypt::dynamic_predicate` + and the rest) and payload (`reason`, and `field`, `construct` and `at` + where it has them) are that error's, so a refusal reports the same way + on both paths. They used to be `Error::Other`, whose code + (`stack_encrypt::other`) a caller could not tell from an engine fault. + The error type is now public without the `dynamic` feature too, as + `stack_encrypt::refusal::Error` and `refusal::Reason` (the same types as + `dynamic::Error` and `dynamic::Reason`). This module's own bug + (`Internal`) and a target resolver's own failure stay `Error::Other`. - **Two more records derive** (#1661). The owned derives did not accept these shapes, and the removed derives did: - A `plaintext = T` record can have a `struct = ..` record as a field. @@ -193,8 +318,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 them. The caller's scope and bindings are the one context argument, after the plan's own. A query takes scopes alone, and refuses a binding before any key is requested, as `PlanError::BindInQuery`. A refused - term keeps its kind (`Error::Term`); other dynamic refusals are - `Error::Other`. `Planned::contexts()` shows every field's context with + term keeps its kind (`Error::Term`); a refusal of the caller's input is + `Error::Input`. `Planned::contexts()` shows every field's context with a placeholder for the caller's scope and one for the caller's binding, before any value is encrypted. - **Query plans and the dynamic field handle** (#1486). `Plan::query(field, @@ -266,6 +391,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 jiff has no leap seconds, so the error now says only what is wrong: `Timestamp::new` was given nanoseconds of one second or more. +- **An index run over a `ValueFrame` refuses a value as `Error::Input`** + (#1459). An `IndexSpec` run directly over a `ValueFrame` it has no term + for (a boolean under equality, a container under ORE) failed with the + dynamic `Error::Term` boxed in `Error::Other`. It is now in + `Error::Input`, matched as `Error::Input(refusal)` with + `refusal.as_ref()` the `dynamic::Error::Term`, and its code is + `stack_encrypt::dynamic_term` rather than `stack_encrypt::other`. - **The structural API is removed** (#1661, #1662). Stack Encrypt had two ways to encrypt a record and two ways to query one. The owned API stays: `EncryptTarget`, `DecryptSource`, `EncryptInto`, `DecryptFrom`, field @@ -303,12 +435,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 | `plan::all((a, b))` | `a.zip(b)` on two `Pending` values, or `Pending::all`. Both wipe the plaintext a decrypt recovered if a later item fails. | | A hand-written `impl EncryptFrom for T` | `impl EncryptTarget for T` with `type ContextInput = RequiredContext`, and `DecryptSource` in place of `DecryptInto` | + A typed JSON query, `cipher.query(op::Contains, ..).on(&plan)` and + `op::AtPath(..)`, is the document field's reference query: see "Typed JSON + queries from a field reference", above. + What has no replacement yet: - - **A typed JSON query.** `cipher.query(op::Contains, ..)` and - `op::AtPath(..)` on a plan were the only typed way to query a JSON - document. Until the document's field reference has methods for them, a - JSON query goes through a plan that is data (`dynamic::query_term`, or - `Planned` with a query plan). - **Naming another index for a query** (`.via(index)`). A field reference answers through the index its field's type declares. - **A keyset chosen by name on a call** (`.keyset("tenant")`). Load the @@ -331,6 +462,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 target that calls `open` for its own plaintext type is unaffected. A caller that opens a type that is not `Zeroize` wraps it in one that is, or implements `Zeroize` for it. +- **The JSON index answers no typed operator through `Supports`** (#1459). + `Json`'s `Supports` impls for `op::Contains`, `op::ContainedBy` and + `op::AtPath`, `JsonDocument`'s `Answers` and `LabelledTarget` impls, the + `Input` impls of a path and a value, and `json::AtPathTerms` are + removed. Only the removed query chain reached them; a field reference's + JSON queries replace them. The operator types stay: the dynamic `Op` + enum is generated from them. - **A set of terms holds one index for each operator.** `Encrypted` and a derived `plaintext = T` record now refuse a set @@ -848,6 +986,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **The JSON path grammar is its own crate, `stack-encrypt-jsonpath`** + (#1687). `JsonPath`, `Segment` and `JsonPathError` moved there unchanged, + so that the derive can parse a field's declared paths at compile time + with the engine's own grammar. `stack_encrypt::json` re-exports all + three at the same paths, and `JsonPathError` keeps its code, help and + payload. The JSON text parser decodes strings with the same decoder as a + path's quoted names, which also moved. No stored byte changes: the + selector and token encodings of a path stay in this crate. - **A data plan lowers to the combinators directly** (#1488, first part). `dynamic::planned::compose` and `opening` build each field's combinator from the parsed plan, and the dynamic entry points run them: diff --git a/packages/stack-encrypt/CONTEXT.md b/packages/stack-encrypt/CONTEXT.md index cdddec8d3f..d370c9fee6 100644 --- a/packages/stack-encrypt/CONTEXT.md +++ b/packages/stack-encrypt/CONTEXT.md @@ -294,9 +294,21 @@ operator through the one index that answers it. A nullable field answers what a present value answers. A record field's reference reaches the inner record's field references with `.field(..)`, under the outer field's context. `#[stash(query = T)]` gives a field reference the type its queries take. -_Avoid_: marker (its old name), field handle (that is the dynamic form), +_Avoid_: field reference (its old name), field handle (that is the dynamic form), column, accessor +**Declared path**: +A path into a JSON document field that the field's +`#[stash(json(ordered = { "$.age": u32 }, paths = { "$.name": String }))]` +names, with the type of the values at it. An `ordered` path's values carry +an ordering term; a `paths` path is compared with equality alone and adds +nothing to the field's options. The derive parses it at compile time and +gives it a method under the field reference's `at()`, and, for an ordered +member of an array, one under `elements()` (`DeclaredPath`, +`ElementMember`). A path given as text at run time (`at_text_path`) is not +a declared path. +_Avoid_: typed path (that is the target-directed form), static path + **Planned**: A value under a plan that is data, `Planned::new(&plan, value)`. The value is a `ValueFrame` under a record plan or a query plan, or a stored diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 6e90024771..b7ac63b6e8 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -23,6 +23,9 @@ stack-kms = { path = "../stack-kms", version = "0.2.0", default-features = false stack-auth = { workspace = true, optional = true } # `#[derive(EncryptTarget)]` / `#[derive(DecryptSource)]`, re-exported from `target`. stack-encrypt-derive = { path = "../stack-encrypt-derive", version = "0.3.0" } +# The JSONPath grammar the JSON index addresses, re-exported at +# `stack_encrypt::json`. The derive reads declared paths with the same crate. +stack-encrypt-jsonpath = { path = "../stack-encrypt-jsonpath", version = "0.3.0", features = ["diagnostics"] } # The workspace vitaminc: one canonical context encoding shared by # the AEAD and PRF derivations (`IntoContext`, cipherstash/vitaminc#339), diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index dd789294c7..1943a2dc4d 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2089,6 +2089,7 @@ dependencies = [ "serdect", "sha2 0.11.0", "stack-encrypt-derive", + "stack-encrypt-jsonpath", "stack-kms", "thiserror 1.0.69", "uuid", @@ -2110,6 +2111,7 @@ version = "0.3.0" dependencies = [ "proc-macro2", "quote", + "stack-encrypt-jsonpath", "syn 3.0.3", ] @@ -2126,6 +2128,18 @@ dependencies = [ "vitaminc-protected 0.10.0", ] +[[package]] +name = "stack-encrypt-jsonpath" +version = "0.3.0" +dependencies = [ + "miette", + "serde", + "serde_json", + "stack-auth", + "thiserror 1.0.69", + "zeroize", +] + [[package]] name = "stack-kms" version = "0.2.0" diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index a4a85643f1..5d5884a331 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -288,6 +288,22 @@ pub enum Error { #[error(transparent)] #[diagnostic(code(stack_encrypt::other))] Other(Box), + /// The caller's input was refused before any key was requested: a + /// field marker's JSON query whose input has the wrong shape (an + /// `elements` path with no wildcard, a predicate the grammar does not + /// read), or a data plan's source that does not fit the plan, run + /// through `dynamic::Planned`. + /// + /// The refusal is the dynamic interface's own + /// ([`refusal::Error`](crate::refusal::Error)), and it shows through: + /// its message, its code (`stack_encrypt::dynamic_source`, + /// `stack_encrypt::dynamic_predicate` and the rest) and its payload + /// (`reason`, and `field`, `construct` and `at` where it has them) are + /// the ones the dynamic interface reports. It is always the caller's + /// input at fault, never the engine. + #[error(transparent)] + #[diagnostic(transparent)] + Input(Box), /// A [`transcode::Visitor`](crate::target::transcode::Visitor) was handed /// an encrypted output shape its destination does not accept: a scalar /// destination offered a sequence, say. Raised by the visitor's default @@ -461,6 +477,7 @@ impl crate::ErrorPayload for Error { .unwrap_or_default(), #[cfg(not(feature = "http"))] Self::Config(_) => serde_json::Map::new(), + Self::Input(refusal) => refusal.payload(), Self::Aead | Self::JsonNotALeaf | Self::Other(_) diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 3e5a43fdb6..fc31c56b0d 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -68,6 +68,11 @@ mod tests { Error::Config(_) => Error::Config(cause()), Error::Term(_) => Error::Term(TermError::EmptyTermText), Error::Other(_) => Error::Other(cause()), + // The same refusal as the dynamic `Error::Source` row, whose + // code it shows through. + Error::Input(_) => Error::Input(Box::new(crate::refusal::Error::bad_source( + crate::refusal::Reason::FieldMissing, + ))), Error::UnsupportedShape => Error::UnsupportedShape, Error::ContextMismatch { .. } => Error::ContextMismatch { stored: Descriptor::of("users"), @@ -123,6 +128,7 @@ mod tests { TermError::JsonPathNotOrdered => TermError::JsonPathNotOrdered, TermError::JsonOrderingAtPosition => TermError::JsonOrderingAtPosition, TermError::JsonValueNotScalar => TermError::JsonValueNotScalar, + TermError::JsonNumberNotFinite => TermError::JsonNumberNotFinite, ])); errors.extend(boxed(variants![ TermBytesError::WrongEqualityTermLength(_) => { @@ -405,6 +411,15 @@ mod tests { })), json!({ "field": "age" }), ), + ( + Box::new(Error::Input(Box::new(crate::refusal::Error::Predicate { + field: None, + reason: crate::refusal::Reason::JsonPredicateSyntax, + construct: "a path", + at: 3, + }))), + json!({ "reason": "json_predicate_syntax", "construct": "a path", "at": 3 }), + ), ( Box::new(Error::KeyCountMismatch { expected: 2, diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index f5b3928cd8..a749b1446f 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -204,13 +204,13 @@ use zeroize::Zeroizing; use super::query::{Op, Operand}; use super::{Error, Reason, ValueFrame}; -use crate::json::{ - parse_text, wipe_value, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonPlaintext, - JsonQuery, JsonSubtreeKey, +pub(super) use crate::json::inputs::Under; +use crate::json::inputs::{ + elements_base, json_reason, leaf, member_path, node_path, ordered_path, path, scalar, + selector_path, wildcard_bound, Bounds, Compare, Derived, Input, Parsed, Predicate, }; -use crate::sem::TermError; -use crate::target::{AeadContext, CallerContext, DeclaredContext, Index, Json, Owned}; -use crate::{ContextPiece, DecryptFrom, KeysetCipher, Label, NonEmpty, Pending}; +use crate::json::{parse_text, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSubtreeKey}; +use crate::{DecryptFrom, KeysetCipher, Pending}; /// The SQL type a JSON operand binds as. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -310,20 +310,10 @@ impl<'de> Deserialize<'de> for PathText { } } -/// A document parsed from an input, wiped when it drops. -#[derive(PartialEq)] -pub(super) struct Parsed(pub(super) Value); - -impl Drop for Parsed { - fn drop(&mut self) { - wipe_value(&mut self.0); - } -} - impl JsonText { pub(super) fn parse(&self) -> Result { parse_text(&self.0) - .map(Parsed) + .map(Parsed::of) .map_err(|error| Error::Source { field: None, reason: json_reason(error), @@ -331,16 +321,6 @@ impl JsonText { } } -/// The reason a JSON text refusal is reported with. -pub(super) fn json_reason(error: crate::json::JsonTextError) -> Reason { - use crate::json::JsonTextError as E; - match error { - E::Syntax { .. } => Reason::JsonSyntax, - E::DuplicateKey { .. } => Reason::JsonDuplicateKey, - E::IntegerRange => Reason::JsonIntegerRange, - } -} - #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct DocumentInput { @@ -408,47 +388,6 @@ struct MatchInput { wildcard_bound: Option, } -/// How a predicate of `element_match` compares its field with one value. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Compare { - Eq, - Lt, - Lte, - Gt, - Gte, -} - -/// A predicate's bounds, as its input gives them. -#[derive(PartialEq)] -pub(super) enum Bounds { - /// One value, compared by the predicate's `op`. - One(Compare, Parsed), - /// `between`: the low bound then the high, both inclusive. - Between(Parsed, Parsed), -} - -/// One predicate of `element_match`, checked: the full path of the -/// element's field, which the field orders, and its bounds. -#[derive(PartialEq)] -pub(super) struct Predicate { - pub(super) path: JsonPath, - pub(super) bounds: Bounds, -} - -/// An operator's input, read from its frame and checked: everything -/// [`derive`] would refuse before it derives anything. `match`'s is its -/// predicate compiled to a tree of the other operators' inputs. -#[derive(PartialEq)] -pub(super) enum Input { - Document(Parsed), - At(JsonPath, Parsed), - Between(JsonPath, Parsed, Parsed), - Path(JsonPath), - Read(JsonPath, u32), - Elements(u32, Vec), - Predicate(Box), -} - fn read_frame Deserialize<'de>>(input: &ValueFrame) -> Result { vitaminc_aead_frame::serde::from_slice(input.risky_ref()).map_err(|_| Error::Source { field: None, @@ -456,59 +395,25 @@ fn read_frame Deserialize<'de>>(input: &ValueFrame) -> Result Result { - let path = - JsonPath::parse(text).map_err(|error| Error::Cipher(TermError::JsonPath(error).into()))?; - if path.segments().len() > crate::json::MAX_DEPTH { - return Err(term(TermError::JsonTooDeep)); - } - Ok(path) -} - -/// A path whose operand is a selector, which reads a position as the -/// wildcard. -fn selector_path(text: &str) -> Result { - let path = path(text)?; - if path.names_a_position() { - return Err(Error::bad_source(Reason::JsonPathPosition)); - } - Ok(path) -} - -/// A path that names one node: no wildcard. -fn node_path(text: &str) -> Result { - let path = path(text)?; - // `is_positional`: every array step names a position, so the path - // has no wildcard and names at most one node. - if path.is_positional() { - Ok(path) - } else { - Err(Error::bad_source(Reason::JsonPathWildcard)) - } -} - -fn term(error: TermError) -> Error { - Error::Cipher(error.into()) -} - -/// Read and check an operator's input against the field's options. +/// Read and check an operator's input against the field's options: the +/// frame read into the input the operator takes ([`Input`]), checked with +/// the rules a field reference's typed JSON queries apply, and in the order a +/// binding has always met them. fn read_input(op: Op, options: &JsonOptions, input: &ValueFrame) -> Result { match op { Op::Contains | Op::ContainedBy => Ok(Input::Document( read_frame::(input)?.json.parse()?, )), Op::EqAt => read_eq_at(input), - Op::LtAt | Op::LteAt | Op::GtAt | Op::GteAt => read_ordering(options, input), + Op::LtAt => read_ordering(options, Compare::Lt, input), + Op::LteAt => read_ordering(options, Compare::Lte, input), + Op::GtAt => read_ordering(options, Compare::Gt, input), + Op::GteAt => read_ordering(options, Compare::Gte, input), Op::BetweenAt => read_between(options, input), - Op::Selector => Ok(Input::Path(selector_path( + Op::Selector => Ok(Input::Selector(selector_path( &read_frame::(input)?.path, )?)), - Op::Children | Op::ChildCount => Ok(Input::Path(node_path( + Op::Children | Op::ChildCount => Ok(Input::Node(node_path( &read_frame::(input)?.path, )?)), Op::Subtree => { @@ -524,15 +429,6 @@ fn read_input(op: Op, options: &JsonOptions, input: &ValueFrame) -> Result) -> Result { - match bound.unwrap_or(JsonSubtreeKey::DEFAULT_BOUND) { - 0 => Err(Error::bad_source(Reason::JsonWildcardBoundZero)), - bound => Ok(bound), - } -} - /// `match`'s input: a jsonpath predicate, its variables as one JSON object /// (the `vars` jsonb `jsonb_path_match` takes, `{}` when absent) and the /// bound its element-scoped leaves are read to. The predicate is compiled @@ -542,29 +438,21 @@ fn read_match(options: &JsonOptions, input: &ValueFrame) -> Result let bound = wildcard_bound(input.wildcard_bound)?; let vars = match &input.vars { Some(vars) => vars.parse()?, - None => Parsed(Value::Object(serde_json::Map::new())), + None => Parsed::of(Value::Object(serde_json::Map::new())), }; if !vars.0.is_object() { return Err(Error::bad_source(Reason::JsonInput)); } let text = std::str::from_utf8(&input.predicate.0) .map_err(|_| Error::bad_source(Reason::JsonInput))?; - Ok(Input::Predicate(Box::new(super::json_predicate::compile( - text, &vars.0, options, bound, - )?))) + Input::predicate(options, text, &vars.0, Some(bound)) } /// `element_match`'s input: an array's elements, by a path with a wildcard /// and no position, and one or more predicates on their fields. fn read_elements(options: &JsonOptions, input: &ValueFrame) -> Result { let elements: ElementsInput = read_frame(input)?; - let base = path(&elements.path)?; - if base.is_positional() { - return Err(Error::bad_source(Reason::JsonPathNoWildcard)); - } - if base.names_a_position() { - return Err(term(TermError::JsonOrderingAtPosition)); - } + let base = elements_base(&elements.path)?; let bound = wildcard_bound(elements.wildcard_bound)?; if elements.predicates.is_empty() { return Err(Error::bad_source(Reason::JsonNoPredicates)); @@ -574,7 +462,7 @@ fn read_elements(options: &JsonOptions, input: &ValueFrame) -> Result, _>>()?; - Ok(Input::Elements(bound, predicates)) + Input::elements(Some(bound), predicates) } /// One predicate of `element_match`: its member's full path below `base`, @@ -607,67 +495,26 @@ fn read_predicate( Ok(Predicate { path, bounds }) } -/// A member's full path: `base` and then the member's steps, read as a -/// path relative to an element (`name`, `address.city`, `["a b"]`). A -/// member names one field of each element, so it has no wildcard of its -/// own, and the full path is an ordering's: no position, and ordered. A -/// member that does not parse is refused at an offset into the member's -/// own text. -fn member_path(options: &JsonOptions, base: &JsonPath, member: &str) -> Result { - let prefix = if member.starts_with('[') { "$" } else { "$." }; - // Sized before it is written, and wiped: the member names keys. - let mut rooted = Zeroizing::new(String::with_capacity(prefix.len() + member.len())); - rooted.push_str(prefix); - rooted.push_str(member); - let relative = JsonPath::parse(&rooted).map_err(|error| { - let error = crate::json::JsonPathError { - at: error.at.saturating_sub(prefix.len()), - ..error - }; - Error::Cipher(TermError::JsonPath(error).into()) - })?; - member_of(options, base, relative) -} - -/// A member's full path, from the steps already parsed: the checks -/// [`member_path`] makes past parsing, which `match` makes of the members -/// of an element-scoped filter. -pub(super) fn member_of( - options: &JsonOptions, - base: &JsonPath, - relative: JsonPath, -) -> Result { - if !relative.is_positional() { - return Err(Error::bad_source(Reason::JsonPathWildcard)); - } - let full = relative - .segments() - .iter() - .fold(base.clone(), |at, segment| at.then(segment.clone())); - if full.segments().len() > crate::json::MAX_DEPTH { - return Err(term(TermError::JsonTooDeep)); - } - ordered_path_of(options, full) -} - /// `eq_at`'s input: a scalar at a path read through a selector. fn read_eq_at(input: &ValueFrame) -> Result { let at: AtInput = read_frame(input)?; let path = selector_path(&at.path)?; let value = at.json.parse()?; - if matches!(value.0, Value::Object(_) | Value::Array(_)) { - return Err(term(TermError::JsonValueNotScalar)); - } - Ok(Input::At(path, value)) + scalar(&value.0)?; + Ok(Input::EqAt(path, value)) } /// An ordering's input: a leaf the index orders at an ordered path. -fn read_ordering(options: &JsonOptions, input: &ValueFrame) -> Result { +fn read_ordering( + options: &JsonOptions, + compare: Compare, + input: &ValueFrame, +) -> Result { let at: AtInput = read_frame(input)?; let path = ordered_path(options, &at.path)?; let value = at.json.parse()?; leaf(&value.0)?; - Ok(Input::At(path, value)) + Ok(Input::Ordering(compare, path, value)) } /// `between_at`'s input: two leaves the index orders at an ordered path. @@ -680,117 +527,23 @@ fn read_between(options: &JsonOptions, input: &ValueFrame) -> Result Result { - ordered_path_of(options, path(text)?) -} - -/// [`ordered_path`] of a path already parsed. -pub(super) fn ordered_path_of(options: &JsonOptions, path: JsonPath) -> Result { - if path.names_a_position() { - Err(term(TermError::JsonOrderingAtPosition)) - } else if options.orders(&path) { - Ok(path) - } else { - Err(term(TermError::JsonPathNotOrdered)) - } -} - -/// A leaf the index orders: a number or a string. -pub(super) fn leaf(value: &Value) -> Result<(), Error> { - match value { - Value::Number(_) | Value::String(_) => Ok(()), - _ => Err(term(TermError::JsonLeafNotOrdered)), - } -} - -/// Check a JSON operator's input without a cipher: what [`derive`] -/// refuses from the input alone (its shape, its paths and values, a path -/// deeper than a document). The limits a subtree read's key hits as it is -/// built, a wildcard expanding too wide or a path too deep for its -/// tokens (`JsonWildcardTooWide`, `JsonTooWide`, `JsonTooDeep`), are -/// [`derive`]'s, after the keyset is resolved. +/// Check a JSON operator's input without a cipher: what [`derive`] refuses +/// from the input alone (its shape, its paths and values, a path deeper +/// than a document). The limits a subtree read's key hits as it is built, +/// a wildcard expanding too wide or a path too deep for its tokens +/// (`JsonWildcardTooWide`, `JsonTooWide`, `JsonTooDeep`), are [`derive`]'s, +/// after the keyset is resolved. pub(super) fn check(op: Op, options: &JsonOptions, input: &ValueFrame) -> Result<(), Error> { read_input(op, options, input).map(drop) } -/// Where a document field's queries and reads run: under the field's -/// label, then the scopes and the bindings of its plan, as the document -/// was sealed. -/// -/// For example, take the field `profile` of the table `users`, in a plan -/// whose caller added the tenant 7 as a scope and the row 9 as a binding. -/// A selector, a read key and every other term derive under -/// `users/profile`, then 7: the query context. An entry that a read -/// returns opens under `users/profile`, then 7, then 9: the stored -/// context. -#[derive(Clone)] -pub(super) struct Under<'p> { - label: &'p Label, - /// The plan's scopes, then its bindings. - parts: DeclaredContext, -} - -impl<'p> Under<'p> { - /// The field with the label `label`, in a plan whose scopes and - /// bindings are `parts`. - pub(super) fn new(label: &'p Label, parts: DeclaredContext) -> Self { - Self { label, parts } - } - - fn column(&self) -> NonEmpty