diff --git a/AGENTS.md b/AGENTS.md index 9a2716575b..9065c2333d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -712,6 +712,14 @@ monorepo, which is where the silent failures are. `jsonb @>` over the plaintexts, is `packages/eql/tests/encryption/tests/json_tree.rs`, run by `mise run test:encryption:postgres`. The design and its implementation notes are `docs/plans/2026-10-17-json-tree-index.md`. + Tests that read a stored document without PostgreSQL use + `stack_encrypt::eql_simulator`, Rust copies of the EQL read functions + (`json_tree_children`, `json_tree_subtree`). Production code never calls + them. The functions are behind the `eql-simulator` feature. + stack-encrypt's own tests turn it on with a dev-dependency on the crate + itself. The EQL encryption test crate turns it on in its `Cargo.toml`. A + change to how a read finds or walks entries changes the SQL and the + simulator together. In v4 it carries v3's names for the searchable JSON document: the target `JsonSearch` stores `public.eql_v4_json_search`, queried with `eql_v4.query_json` and `eql_v4.query_json_leaf`, with entries diff --git a/Cargo.lock b/Cargo.lock index a1f237c8bc..1ffec6803f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3470,6 +3470,7 @@ dependencies = [ "serdect", "sha2 0.11.0", "stack-auth", + "stack-encrypt", "stack-encrypt-derive", "stack-encrypt-jsonpath", "stack-kms", diff --git a/docs/plans/2026-10-17-json-tree-index.md b/docs/plans/2026-10-17-json-tree-index.md index a28a05707e..6390f7fd31 100644 --- a/docs/plans/2026-10-17-json-tree-index.md +++ b/docs/plans/2026-10-17-json-tree-index.md @@ -386,7 +386,7 @@ The index, the SQL and the live oracle landed in the pull request stacked on thi - *`AtPath` is the containment of the needle document that holds the value at the path*, with a position in the path read as the wildcard, rather than a single `{vs}` entry: a leaf inside an array element sits in that element's group of the projection, and the needle has to say which group. Containment of that needle is equality only for a scalar, so a container value is refused (`TermError::JsonValueNotScalar`; `op::Contains` asks the containment question), and the needle carries no `alt`, so `("$", 1)` does not match a stored `[1]`. - *The data-plan form and the catalog are not done.* The Go guest, `stashgen`, the target table and `v4::all()` do not know the family; `IndexSpec::Json` crosses the wire and is refused with a reason. The family is hand-written in `eql-bindings` as the SteVec structs are. Both are the next bindings issue. - *A document is at most 127 levels deep*, under either root option. The sealed root's plaintext is the document as JSON, and `serde_json` parses JSON back only to 128 levels of nesting, so the 512 levels the walk first admitted sealed documents that then never opened. The bound is the reader's, so a document too deep fails when it is sealed, while the caller still holds it, and not when it is read. -- *A stored document is read as untrusted input.* Its chain fields are not authenticated, and whoever holds a token can write tags that form a cycle or a chain deeper than any sealed document. `JsonDocument::children` checks each entry at its own ordinal instead of looping over a fan-out the document chooses; `JsonDocument::subtree` and the SQL walks stop below 127 levels, and the Rust walk also stops once it has returned as many entries as the document holds; the rebuild of a subtree's rows refuses a repeated row and a nesting deeper than 127 levels as `OpenedType`. Each would otherwise have overflowed the stack, looped, or allocated what the document asked for. (Phase 3b replaced `children` with a probe from ordinal 0 to the first miss, bounded by the entry count, and derives a child's token from its ordinal by hash, so no stored chain can form a cycle and the SQL walks need no depth bound; the Rust walk keeps both of its bounds and the rebuild keeps its own.) +- *A stored document is read as untrusted input.* Its chain fields are not authenticated, and whoever holds a token can write tags that form a cycle or a chain deeper than any sealed document. `eql_simulator::json_tree_children` checks each entry at its own ordinal instead of looping over a fan-out the document chooses; `eql_simulator::json_tree_subtree` and the SQL walks stop below 127 levels, and the Rust walk also stops once it has returned as many entries as the document holds; the rebuild of a subtree's rows refuses a repeated row and a nesting deeper than 127 levels as `OpenedType`. Each would otherwise have overflowed the stack, looped, or allocated what the document asked for. (Phase 3b replaced `children` with a probe from ordinal 0 to the first miss, bounded by the entry count, and derives a child's token from its ordinal by hash, so no stored chain can form a cycle and the SQL walks need no depth bound; the Rust walk keeps both of its bounds and the rebuild keeps its own. #1755 moved these two Rust copies of the SQL reads out of `JsonDocument` and into the `stack_encrypt::eql_simulator` module, behind the `eql-simulator` feature.) - *Nothing wipes the plaintext copies the walk makes* (the per-node scalars it clones before sealing), where the scalar paths hold theirs in `Zeroizing`. A `serde_json::Value` does not zeroize; a follow-up should walk the caller's value without copying scalars out of it. (2026-10-23: done. The JSON plaintext is held under vitaminc's `Protected` as the scalar paths hold theirs. The walk no longer copies a scalar or a key out of the caller's value: it encodes each node's plaintext straight into a `Protected>`, sized before it is written so it never reallocates, and hands that to the cipher, which takes a `Protected` anyway; the sealed root's JSON is measured first and written once into its own. On the way back, the bytes the cipher opens stay in its `Protected>` while they are parsed, and every key, scalar and sealed-root document read out of them is wrapped as it is made (`zip_ref` over the bytes), in `Protected` for a value: `PlainJson` is a newtype over `serde_json::Value` whose `Zeroize` wipes every string, values and object keys alike, and overwrites numbers and booleans in place. A subtree is rebuilt inside a `Protected`, each member moved in from its own, and a value leaves the wrapper only where it is handed to the caller. The sealed-root fallback selects the walked path inside the document's `Protected`, so the whole document is wiped when the selection is made and only the selected nodes come out. What remains: numbers and booleans have no volatile overwrite without unsafe code, which this crate denies, so theirs is best-effort; and outside the decrypted plaintext, the query and term side still holds plaintext in places vitaminc does not reach from here: an accessor's needle document (`JsonPath::needle`), the canonical bytes of a value selector inside vitaminc's PAE `Context`, and the key names in each term node's positional path.) ## Implementation notes (2026-10-21, Phase 3: first measurements and the fixes they forced) diff --git a/packages/eql/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index fd3161bd37..03d27ecf84 100644 --- a/packages/eql/tests/encryption/Cargo.toml +++ b/packages/eql/tests/encryption/Cargo.toml @@ -44,7 +44,9 @@ eql-domains = { path = "../../crates/eql-domains" } # `dynamic`: `ValueFrame`, the runtime plaintext the target dispatch takes, # as eql-bindings names it. # `testing`: `assert_context!`, which pins the contexts of the EQL types. -stack-encrypt = { path = "../../../stack-encrypt", default-features = false, features = ["dynamic", "testing"] } +# `eql-simulator`: Rust copies of the EQL reads of a stored JSON document, so +# the tests that need no PostgreSQL read one without it. +stack-encrypt = { path = "../../../stack-encrypt", default-features = false, features = ["dynamic", "testing", "eql-simulator"] } # `plaintext::Sink`, for a plaintext type with its own `Encrypt` impl; and # jiff's and rust_decimal's own sources, which seal the leaf a date, # timestamp or decimal from any other producer seals. diff --git a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs index 423f37f81c..485a9d78b7 100644 --- a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs +++ b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs @@ -36,6 +36,7 @@ use eql_bindings::v4::json_tree::{JsonTree, JsonTreeDocument, JsonTreeLeafQuery, use eql_bindings::Identifier; use serde_json::{json, Value}; use stack_encrypt::dynamic::{self, record, TargetError, ValueFrame}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{JsonDocument, JsonOptions, JsonPlaintext, JsonQuery}; use stack_encrypt::{CipherText, DecryptFrom, Encrypt, KeysetCipher, Label, NonEmpty}; @@ -883,10 +884,10 @@ fn subtree_rows(doc: &stack_encrypt::json::JsonDocument, tokens: &[String]) -> V .unwrap() }) .collect(); - doc.subtree(&tokens) + eql_simulator::json_tree_subtree(doc, &tokens) .into_iter() .map(|(j, _, d)| { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); wire["d"] = json!(d); wire.to_string() }) @@ -907,7 +908,7 @@ fn extracted_row(doc: &stack_encrypt::json::JsonDocument, selector: &str) -> Opt .iter() .position(|e| e.selector() == &selector)?; Some( - serde_json::to_value(doc.node(j).unwrap()) + serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()) .unwrap() .to_string(), ) diff --git a/packages/eql/tests/encryption/tests/json_tree_field_references.rs b/packages/eql/tests/encryption/tests/json_tree_field_references.rs index 9eb5d03a6d..f45d101ad0 100644 --- a/packages/eql/tests/encryption/tests/json_tree_field_references.rs +++ b/packages/eql/tests/encryption/tests/json_tree_field_references.rs @@ -33,6 +33,7 @@ use eql_bindings::v4::json_tree::{ use eql_bindings::Identifier; use serde_json::{json, Value}; use stack_encrypt::dynamic::{self, record, ValueFrame}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{JsonChildPlaintext, JsonDocument, JsonPlaintext, JsonQuery}; use stack_encrypt::sem::TermError; use stack_encrypt::target::{DecryptSource, EncryptTarget}; @@ -255,7 +256,8 @@ async fn the_children_token_comes_with_the_key_that_opens_each_child() { // depth below the node. let document = &stored.profile; let mut members = Vec::new(); - for (slot, _, _) in index_document(document).children(&key.token_bytes()[0]) { + let indexed = index_document(document); + for (slot, _, _) in eql_simulator::json_tree_children(&indexed, &key.token_bytes()[0]) { let mut entry = document.sv[slot].clone(); entry.h = Some(document.h.clone()); entry.j = Some(slot as u64); diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index fe57fdcac2..0dcd252ed6 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -501,6 +501,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `operation`. That index would compile. The index's queries would then send the stored value's tokens, and miss rows. No stored byte changes. +- **The JSON document read helpers moved to `eql_simulator`** (#1755). + `JsonDocument` had four methods that copy, in Rust, what the database + (EQL) does when your app reads part of a document. Production code does + not call them, because the database does that work. The four methods are + now functions in the module `stack_encrypt::eql_simulator`. The module is + behind a new feature, `eql-simulator`. The feature is off by default. Use + it in tests and examples that run without PostgreSQL. + + | Removed method | Replacement | What it copies | + |---|---|---| + | `doc.children(token)` | `eql_simulator::json_tree_children(&doc, token)` | `eql_v4.json_tree_children` | + | `doc.subtree(tokens)` | `eql_simulator::json_tree_subtree(&doc, tokens)` | `eql_v4.json_tree_subtree(doc, tokens, 0)` | + | `doc.find(token)` | `eql_simulator::find_by_token(&doc, token)` | How EQL finds the entry a token names | + | `doc.node(slot)` | `eql_simulator::entry_row(&doc, slot)` | The row EQL returns for one entry | + + Pass the document first, then the method's argument. Each function + returns what its method returned. To upgrade: + + 1. Turn the feature on in your dev-dependencies: + `stack-encrypt = { version = "0.4", features = ["eql-simulator"] }`. + 2. Change each call to the function in the table. + + No stored byte changes. + - **Seven `PlanError` variants that nothing raised are removed** (#1671). Only the plan builder and `plan::all` raised them, and both are gone, so no call returned them: `IdentityWithoutField`, `IndexNotDeclared`, diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 45c3ac72c9..6a2a2f74f7 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -155,8 +155,19 @@ test-support = ["stack-kms/test-support"] # declaration or a call in a test. No dependency; a dev-dependency on this # crate with the feature on is enough. testing = [] +# `stack_encrypt::eql_simulator`: Rust copies of what the database (EQL) +# does to read a stored JSON document, so tests and examples run without +# PostgreSQL. Production code does not use it. No dependency; turn it on in +# a dev-dependency. +eql-simulator = [] [dev-dependencies] +# This crate's own tests and doc examples read stored JSON documents through +# `eql_simulator`. A dev-dependency on the crate itself turns the feature on +# for them under every feature set, and adds nothing else: +# `default-features = false` keeps `--no-default-features` builds free of +# `http`. A path-only dev-dependency is dropped when the crate is published. +stack-encrypt = { path = ".", default-features = false, features = ["eql-simulator"] } # The types `value::{Date, Timestamp, Decimal}` are built from, for the # tests and doc examples that build one. jiff = { version = "1.0.0", default-features = false } diff --git a/packages/stack-encrypt/src/eql_simulator.rs b/packages/stack-encrypt/src/eql_simulator.rs new file mode 100644 index 0000000000..93f9ca5360 --- /dev/null +++ b/packages/stack-encrypt/src/eql_simulator.rs @@ -0,0 +1,227 @@ +//! Rust copies of the EQL functions that read a stored JSON document, for +//! tests and examples. Behind the `eql-simulator` feature. +//! +//! These functions copy what the database (EQL) does in PostgreSQL when +//! your app reads part of a [`JsonDocument`]. Production code does not use +//! them. In production, the database runs the EQL function and returns the +//! encrypted entries. The `eql-simulator` feature exists so that tests and +//! examples can read a document without PostgreSQL. +//! +//! Reading part of a stored document takes three steps: +//! +//! 1. Your app derives a token for the path to read, for example with +//! [`KeysetCipher::json_subtree_key`](crate::KeysetCipher::json_subtree_key). +//! The token tells the database which node to find. +//! 2. The database (EQL) runs an EQL function with that token, such as +//! `eql_v4.json_tree_children`. The function returns the matching +//! encrypted entries. The database never decrypts anything. +//! 3. Your app checks each entry and decrypts it. A subtree read checks +//! its entries with [`JsonSubtreeKey::open`](crate::json::JsonSubtreeKey::open). +//! A read of one level checks each entry with +//! [`JsonSubtreeKey::open_child`](crate::json::JsonSubtreeKey::open_child). +//! +//! This module does step 2 in Rust. Each function copies one part of EQL: +//! +//! | Function | What it copies | +//! |---|---| +//! | [`json_tree_children`] | `eql_v4.json_tree_children` | +//! | [`json_tree_subtree`] | `eql_v4.json_tree_subtree`, with a budget of `0` | +//! | [`find_by_token`] | How the EQL functions find the entry a token names | +//! | [`entry_row`] | The row an EQL function returns for one entry | +//! +//! Turn the feature on in your dev-dependencies only, so that it stays out +//! of your production build: +//! +//! ```toml +//! [dev-dependencies] +//! stack-encrypt = { version = "0.4", features = ["eql-simulator"] } +//! ``` +//! +//! This example reads the members of one object in a stored document: +//! +//! ``` +//! # async fn example() -> Result<(), stack_encrypt::Error> { +//! use serde_json::json; +//! use stack_encrypt::eql_simulator; +//! use stack_encrypt::json::{JsonDocument, JsonOptions, JsonPath, JsonPlaintext}; +//! use stack_encrypt::target::{AeadContext, CallerContext}; +//! use stack_encrypt::{nonempty, DecryptFrom, EncryptInto, StackCipher}; +//! +//! let cipher = StackCipher::builder() +//! # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +//! .init() +//! .await?; +//! let keyset = cipher.default_keyset(); +//! let stored: JsonDocument = JsonPlaintext::from(json!({"tags": ["admin"]})) +//! .encrypt_into_with_context( +//! &keyset, +//! CallerContext::from(nonempty!("users").with("profile")), +//! ) +//! .await?; +//! +//! // Step 1, your app: derive the parent's key, which holds its token. +//! let parent = keyset +//! .json_subtree_key( +//! &JsonPath::parse("$.tags").unwrap(), +//! &JsonOptions::default(), +//! nonempty!("users").with("profile"), +//! ) +//! .await?; +//! +//! // Step 2, the database. In production, this query returns the entries: +//! // SELECT eql_v4.json_tree_children(profile, $1::text) FROM users WHERE id = $2 +//! let token = &parent.token_bytes()[0]; +//! let entries = eql_simulator::json_tree_children(&stored, token) +//! .into_iter() +//! .filter_map(|(slot, _, _)| eql_simulator::entry_row(&stored, slot)); +//! +//! // Step 3, your app: check each entry against the parent, and decrypt it. +//! for entry in entries { +//! let tag = JsonPlaintext::decrypt_from_with_context( +//! parent.open_child(entry), +//! &cipher, +//! AeadContext::from(nonempty!("users").with("profile")), +//! ) +//! .await?; +//! assert_eq!(tag.value(), &json!("admin")); +//! } +//! # Ok(()) +//! # } +//! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); +//! ``` + +use crate::json::derive::{hit_token, parent_tag}; +use crate::json::{JsonDocument, JsonEntry, JsonNode, Tag, MAX_DEPTH}; + +/// The entry whose token is `token`, with the slot it is stored at. `None` +/// when `token` names no node of the document. +/// +/// Copies how the EQL functions find the node a token names. The database +/// matches the token's self tag (`eql_v4_internal.json_tree_self_tag`) +/// against the index `eql_v4_internal.json_tree_index` builds. EQL has no +/// function that returns this entry alone. +/// +/// If several entries have the same self tag, this function returns the +/// last of them, as the index does. A sealed document never has two such +/// entries. +pub fn find_by_token<'d>( + document: &'d JsonDocument, + token: &Tag, +) -> Option<(usize, &'d JsonEntry)> { + document.find(token) +} + +/// The children of the node whose token is `token`: each child's slot, +/// entry, and token. Copies `eql_v4.json_tree_children`. +/// +/// The children come in ordinal order, as the database returns them. That +/// puts an array's elements in index order, and an object's members in the +/// random order drawn when the document was sealed. The child's token is +/// `None` when the entry's self tag is neither a member's token nor an +/// element's token under this node. A token that names no node returns no +/// children. +/// +/// Pass each slot to [`entry_row`] to get the row the database returns. +pub fn json_tree_children<'d>( + document: &'d JsonDocument, + token: &Tag, +) -> Vec<(usize, &'d JsonEntry, Option)> { + let iv = document.header().iv(); + let entries = document.entries(); + let mut children = Vec::new(); + if document.find(token).is_none() { + return children; + } + // Probe the ordinals 0, 1, 2, … until one has no entry. A node has at + // most as many children as the document has entries, so the loop ends + // whatever the entries say. + let most = u32::try_from(entries.len()).unwrap_or(u32::MAX); + for ordinal in 0..most { + let wanted = parent_tag(iv, token, ordinal); + // The last entry with the parent tag, as `find_by_token` picks. + let Some((slot, entry)) = entries + .iter() + .enumerate() + .rev() + .find(|(_, entry)| entry.parent_tag() == Some(&wanted)) + else { + break; + }; + children.push((slot, entry, hit_token(iv, token, entry, ordinal))); + } + children +} + +/// The node each token names, and every entry beneath it: each entry's +/// slot, the entry, and its depth below the node its token named. Copies +/// `eql_v4.json_tree_subtree(doc, tokens, 0)`. A budget of `0` reads the +/// whole subtree, whatever its size. +/// +/// The rows come token by token, in the order of `tokens`. For each token, +/// the node comes first at depth `0`. After each entry come its own +/// children, in ordinal order. A token that names no node returns no rows. +/// +/// The database returns one token's rows in slot order instead. Opening the +/// rows does not depend on their order. +/// +/// A stored document can be forged, so its tags need not form a tree. This +/// function stops below the deepest level a sealed document has. The +/// function also stops after as many rows as the document has entries. +pub fn json_tree_subtree<'d>( + document: &'d JsonDocument, + tokens: &[Tag], +) -> Vec<(usize, &'d JsonEntry, u32)> { + let mut rows = Vec::new(); + for token in tokens { + let Some((slot, entry)) = document.find(token) else { + continue; + }; + let mut token_rows = vec![(slot, entry, 0)]; + walk(document, token, 1, &mut token_rows); + rows.extend(token_rows); + } + rows +} + +/// Appends the entries beneath the node whose token is `token` to `rows`, +/// each at its depth, starting at `depth` for the node's children. +fn walk<'d>( + document: &'d JsonDocument, + token: &Tag, + depth: u32, + rows: &mut Vec<(usize, &'d JsonEntry, u32)>, +) { + // The walk returns each entry at most once in a tree. So when the tags + // form a cycle, it stops once it has returned as many rows as the + // document has entries. No sealed document nests deeper than + // `MAX_DEPTH`, so a longer chain stops there, and the recursion stays + // bounded. + let most = document.entries().len(); + if rows.len() >= most || depth as usize > MAX_DEPTH { + return; + } + for (slot, entry, child) in json_tree_children(document, token) { + if rows.len() >= most { + return; + } + rows.push((slot, entry, depth)); + if let Some(child) = child { + walk(document, &child, depth + 1, rows); + } + } +} + +/// The row an EQL function returns for the entry stored at `slot`: the +/// entry, with the document's header and the slot added. `None` when the +/// document has no entry at `slot`. +/// +/// Copies `eql_v4_internal.json_tree_graft`. That function builds the row +/// for one entry. The `->` operator returns this row. The row has no depth (`d`). +/// `eql_v4.json_tree_children` and `eql_v4.json_tree_subtree` build the +/// same row and add the entry's depth. +pub fn entry_row(document: &JsonDocument, slot: usize) -> Option { + document + .entries() + .get(slot) + .map(|entry| JsonNode::new(entry.clone(), document.header().clone(), slot as u64)) +} diff --git a/packages/stack-encrypt/src/json/derive.rs b/packages/stack-encrypt/src/json/derive.rs index 99e21bd617..731a61e3be 100644 --- a/packages/stack-encrypt/src/json/derive.rs +++ b/packages/stack-encrypt/src/json/derive.rs @@ -428,7 +428,7 @@ pub(super) fn self_tag(iv: &[u8], token: &Tag) -> super::SelfTag { /// is inside `c`), so the self tag is what chooses. An entry that matches /// neither is still a child, and is returned, but the walk does not descend /// into it. -pub(super) fn hit_token( +pub(crate) fn hit_token( iv: &[u8], parent: &Tag, entry: &super::JsonEntry, @@ -447,7 +447,7 @@ pub(super) fn hit_token( /// document, so the same position in two rows is too. Eight bytes, since a /// parent tag only has to be distinct within its document /// ([`ParentTag`](super::ParentTag)). -pub(super) fn parent_tag(iv: &[u8], parent: &Tag, ordinal: u32) -> super::ParentTag { +pub(crate) fn parent_tag(iv: &[u8], parent: &Tag, ordinal: u32) -> super::ParentTag { let full = h16(&[b"p", iv, parent, &ordinal.to_le_bytes()]); let mut tag = super::ParentTag::default(); tag.copy_from_slice(&full[..8]); diff --git a/packages/stack-encrypt/src/json/mod.rs b/packages/stack-encrypt/src/json/mod.rs index e095f16f0f..21aec47f79 100644 --- a/packages/stack-encrypt/src/json/mod.rs +++ b/packages/stack-encrypt/src/json/mod.rs @@ -138,7 +138,7 @@ use vitaminc_protected::OpaqueDebug; use crate::target::{DecryptField, DecryptSource, Decryptable, Decryption}; mod cascade; -mod derive; +pub(crate) mod derive; pub(crate) mod inputs; mod path; mod plain; @@ -502,8 +502,8 @@ impl JsonDocument { /// The entries, in their stored order: the root first, the rest in a /// uniformly random order drawn when the document was sealed, which says - /// nothing of the tree. A node's children are found by the chain - /// ([`children`](Self::children)), not by position. + /// nothing of the tree. The database finds a node's children through + /// the chain, not by position. pub fn entries(&self) -> &[JsonEntry] { &self.entries } @@ -517,16 +517,15 @@ impl JsonDocument { &self.selectors } - /// The entry whose self tag is `token`'s, as the server finds the node - /// a token names: its ordinal and the entry. `None` for a token that - /// names no node of this document. - /// - /// Where several entries carry the tag, which no sealing produces, the - /// last of them, as the server's index keeps it - /// (`eql_v4_internal.json_tree_index` builds it with - /// `jsonb_object_agg`, which keeps the last value of a repeated key). - pub fn find(&self, token: &Tag) -> Option<(usize, &JsonEntry)> { + /// The entry whose self tag matches `token`, with the slot it is stored + /// at. Decrypting a whole document uses it to check that the root's + /// token enters the document's chain. `eql_simulator::find_by_token` + /// is the public form, and its docs say which entry this returns. + pub(crate) fn find(&self, token: &Tag) -> Option<(usize, &JsonEntry)> { let x = derive::self_tag(&self.header.iv, token); + // The last entry with the tag. `eql_v4_internal.json_tree_index` + // builds its index with `jsonb_object_agg`. That function keeps the + // last value of a repeated key. self.entries .iter() .enumerate() @@ -534,101 +533,6 @@ impl JsonDocument { .find(|(_, e)| e.x == x) } - /// The children of the node whose token is `token`, as the server - /// enumerates them: the entries at the ordinals `0, 1, 2, …` under it, - /// probed until the first miss, each with the token the server derives - /// for it, by the member rule or the element rule, whichever the entry's - /// self tag matches, and `None` when it matches neither. A token that - /// names no node yields nothing. - /// - /// What `json_tree_children(doc, token)` returns; one level of the - /// walk [`subtree`](Self::subtree) runs to the bottom. - pub fn children(&self, token: &Tag) -> Vec<(usize, &JsonEntry, Option)> { - let iv = &self.header.iv; - let mut out = Vec::new(); - if self.find(token).is_none() { - return out; - } - // A node has at most as many children as the document has entries, - // so the probe loop is bounded whatever the entries say. - let most = u32::try_from(self.entries.len()).unwrap_or(u32::MAX); - for o in 0..most { - let tag = derive::parent_tag(iv, token, o); - // The last entry carrying the tag, as the server's index keeps - // it ([`find`](Self::find)). - let Some((j, entry)) = self - .entries - .iter() - .enumerate() - .rev() - .find(|(_, e)| e.p.as_ref() == Some(&tag)) - else { - break; - }; - out.push((j, entry, derive::hit_token(iv, token, entry, o))); - } - out - } - - /// The rows the server's read returns for `tokens` with no budget: - /// for each token in order, the node it names at depth `0` and every - /// entry beneath it with its depth below that node, each node followed - /// by its children in ordinal order. (The SQL returns the rows of a - /// token by slot instead, which the client does not rely on.) - /// A token that names no node yields nothing. What - /// `json_tree_subtree(doc, tokens, 0)` returns. - /// - /// A stored document is untrusted, and its tags need not form a tree: - /// whoever holds a token can write a chain deeper than any document the - /// index seals, or a cycle. Each token's walk stops descending below the - /// deepest level a sealed document has, and stops once it has returned - /// as many entries as the document holds, which a tree never exceeds, - /// so it ends, and in bounded stack, on any document. - pub fn subtree(&self, tokens: &[Tag]) -> Vec<(usize, &JsonEntry, u32)> { - let mut out = Vec::new(); - for token in tokens { - let Some((j, entry)) = self.find(token) else { - continue; - }; - let mut rows = vec![(j, entry, 0)]; - self.walk(token, 1, &mut rows); - out.extend(rows); - } - out - } - - fn walk<'a>(&'a self, token: &Tag, depth: u32, out: &mut Vec<(usize, &'a JsonEntry, u32)>) { - // A walk finds each entry at most once, so a document whose tags do - // not form a tree (which no sealing produces) ends the walk once it - // has returned as many entries as the document holds, instead of - // looping; and no sealed document nests deeper than MAX_DEPTH, so a - // chain of tags longer than that stops there, in bounded stack. - if out.len() >= self.entries.len() || depth as usize > derive::MAX_DEPTH { - return; - } - for (j, entry, child) in self.children(token) { - if out.len() >= self.entries.len() { - return; - } - out.push((j, entry, depth)); - if let Some(child) = child { - self.walk(&child, depth + 1, out); - } - } - } - - /// The node stored at `slot` as an extraction returns it: the entry - /// with the header beside it. A scalar or an empty container opens on - /// its own; a container with children opens only with its subtree. - pub fn node(&self, slot: usize) -> Option { - self.entries.get(slot).map(|entry| JsonNode { - entry: entry.clone(), - header: self.header.clone(), - slot: slot as u64, - depth: None, - }) - } - pub(crate) fn new( header: JsonHeader, entries: Vec, @@ -696,6 +600,17 @@ impl JsonNode { pub fn depth(&self) -> Option { self.depth } + + /// The row for `entry`, stored at `slot`, with no depth. + #[cfg(any(test, feature = "eql-simulator"))] + pub(crate) fn new(entry: JsonEntry, header: JsonHeader, slot: u64) -> Self { + Self { + entry, + header, + slot, + depth: None, + } + } } /// The entry `->` returned, with the selector the client asked for: what @@ -1147,7 +1062,7 @@ mod tests { entries, JsonSelectorSet::default(), ); - let walked = chain.subtree(&[token]); + let walked = crate::eql_simulator::json_tree_subtree(&chain, &[token]); assert_eq!( walked.len(), derive::MAX_DEPTH + 1, diff --git a/packages/stack-encrypt/src/json/plaintext.rs b/packages/stack-encrypt/src/json/plaintext.rs index d4dc0f5566..f925f83252 100644 --- a/packages/stack-encrypt/src/json/plaintext.rs +++ b/packages/stack-encrypt/src/json/plaintext.rs @@ -252,7 +252,9 @@ impl fmt::Debug for JsonPlaintext { /// JsonChildPlaintext, JsonDocument, JsonOptions, JsonPath, JsonPlaintext, /// }; /// use stack_encrypt::target::{AeadContext, CallerContext}; -/// use stack_encrypt::{nonempty, DecryptFrom, EncryptInto, StackCipher}; +/// // `eql_simulator` needs this crate's `eql-simulator` feature. The +/// // feature is off by default. +/// use stack_encrypt::{eql_simulator, nonempty, DecryptFrom, EncryptInto, StackCipher}; /// /// let cipher = StackCipher::builder() /// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) @@ -276,15 +278,12 @@ impl fmt::Debug for JsonPlaintext { /// ) /// .await?; /// -/// // In production, the entries come from the database: +/// // The database returns the entries. In production, this query does it: /// // SELECT eql_v4.json_tree_children(profile, $1::text) FROM users WHERE id = $2 -/// // Here the example reads the same entries from the stored document, so -/// // it runs without a database. /// let token = &parent.token_bytes()[0]; -/// let entries = stored -/// .children(token) +/// let entries = eql_simulator::json_tree_children(&stored, token) /// .into_iter() -/// .filter_map(|(slot, _, _)| stored.node(slot)); +/// .filter_map(|(slot, _, _)| eql_simulator::entry_row(&stored, slot)); /// /// // Your app decrypts each entry. The key says which member it is. /// let mut limits = serde_json::Map::new(); diff --git a/packages/stack-encrypt/src/json/query.rs b/packages/stack-encrypt/src/json/query.rs index a552a72f73..2631d315ef 100644 --- a/packages/stack-encrypt/src/json/query.rs +++ b/packages/stack-encrypt/src/json/query.rs @@ -637,7 +637,9 @@ impl JsonSubtreeKey { /// use serde_json::json; /// use stack_encrypt::json::{JsonDocument, JsonOptions, JsonPath, JsonPlaintext}; /// use stack_encrypt::target::{AeadContext, CallerContext}; - /// use stack_encrypt::{nonempty, DecryptFrom, EncryptInto, StackCipher}; + /// // `eql_simulator` needs this crate's `eql-simulator` feature. The + /// // feature is off by default. + /// use stack_encrypt::{eql_simulator, nonempty, DecryptFrom, EncryptInto, StackCipher}; /// /// let cipher = StackCipher::builder() /// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) @@ -662,15 +664,12 @@ impl JsonSubtreeKey { /// ) /// .await?; /// - /// // Step 2, the database. In production, the entries come from: + /// // Step 2, the database. In production, this query returns the entries: /// // SELECT eql_v4.json_tree_children(profile, $1::text) FROM users WHERE id = $2 - /// // Here the example reads the same entries from the stored document, so - /// // it runs without a database. /// let token = &parent.token_bytes()[0]; - /// let entries = stored - /// .children(token) + /// let entries = eql_simulator::json_tree_children(&stored, token) /// .into_iter() - /// .filter_map(|(slot, _, _)| stored.node(slot)); + /// .filter_map(|(slot, _, _)| eql_simulator::entry_row(&stored, slot)); /// /// // Step 3, your app: pair each entry with the parent's key, and decrypt. /// for entry in entries { diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index ec27fe80ef..320a92fd9c 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -320,6 +320,11 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! # }).unwrap(); //! ``` //! +//! To read part of a stored JSON document without PostgreSQL, turn on this +//! crate's `eql-simulator` feature in your `[dev-dependencies]`. The module +//! `stack_encrypt::eql_simulator` copies, in Rust, the EQL functions that +//! the database runs for that read. Production code does not use it. +//! //! # Seeing the context //! //! A wrong context loses data silently: a query under the wrong context @@ -712,6 +717,8 @@ mod codes; pub mod descriptor; #[cfg(feature = "dynamic")] pub mod dynamic; +#[cfg(any(test, feature = "eql-simulator"))] +pub mod eql_simulator; pub mod field_reference; pub mod json; pub mod keyset; diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index fc3414ff29..a86b5a2958 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -57,6 +57,7 @@ use std::sync::{Arc, Mutex}; use common::frames::{frame, object}; use stack_encrypt::dynamic::{query_term, record, verify, NoTargets, Op, ValueFrame}; +use stack_encrypt::eql_simulator; use stack_encrypt::nonempty; use vitaminc_aead::plaintext::{Physical, Raw}; use vitaminc_aead::Frame; @@ -2495,11 +2496,11 @@ mod json_index { }) .unwrap(); // The rows as the SQL returns them, built before the watch. - let rows: Vec = doc - .subtree(&key.token_bytes()) + let rows: Vec = eql_simulator::json_tree_subtree(&doc, &key.token_bytes()) .iter() .map(|(j, _, d)| { - let mut wire = serde_json::to_value(doc.node(*j).unwrap()).unwrap(); + let mut wire = + serde_json::to_value(eql_simulator::entry_row(&doc, *j).unwrap()).unwrap(); wire["d"] = json!(d); serde_json::from_value(wire).unwrap() }) @@ -2527,8 +2528,8 @@ mod json_index { .await }) .unwrap(); - let (j, _) = doc.find(&key.token_bytes()[0]).unwrap(); - let node = selector.open(doc.node(j).unwrap()); + let (j, _) = eql_simulator::find_by_token(&doc, &key.token_bytes()[0]).unwrap(); + let node = selector.open(eql_simulator::entry_row(&doc, j).unwrap()); watched(&format!("-> (sealed_root: {sealed_root})"), || { let opened = rt.block_on(async { JsonPlaintext::decrypt_from_with_context(node, &cipher, aead()) @@ -2736,7 +2737,8 @@ mod json_index { let tag = |text: &str| -> [u8; 16] { Base64::decode_vec(text).unwrap().try_into().unwrap() }; let row = |j: usize, d: Option| { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = + serde_json::to_value(eql_simulator::entry_row(&doc, j).unwrap()).unwrap(); if let Some(d) = d { wire["d"] = json!(d); } @@ -2759,8 +2761,7 @@ mod json_index { panic!("a subtree read's tokens are a text array") }; let tokens: Vec<[u8; 16]> = tokens.iter().map(|t| tag(t)).collect(); - let read = vec![doc - .subtree(&tokens) + let read = vec![eql_simulator::json_tree_subtree(&doc, &tokens) .into_iter() .map(|(j, _, d)| row(j, Some(u64::from(d)))) .collect::>()]; diff --git a/packages/stack-encrypt/tests/json_field_references.rs b/packages/stack-encrypt/tests/json_field_references.rs index 6e90375a17..ba6d9630a6 100644 --- a/packages/stack-encrypt/tests/json_field_references.rs +++ b/packages/stack-encrypt/tests/json_field_references.rs @@ -15,6 +15,7 @@ use std::num::NonZeroU32; use std::sync::atomic::Ordering; use serde_json::{json, Value}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{ JsonChildPlaintext, JsonDocument, JsonLeafQuery, JsonPlaintext, JsonQuery, }; @@ -234,7 +235,7 @@ mod the_fields_options { doc: &'d JsonDocument, key: &JsonSubtreeKey, ) -> Option<&'d stack_encrypt::json::JsonEntry> { - doc.find(&key.token_bytes()[0]).map(|(_, entry)| entry) + eql_simulator::find_by_token(doc, &key.token_bytes()[0]).map(|(_, entry)| entry) } /// `encrypt_keyed` gives `encrypt`'s token and the key that holds it, @@ -258,9 +259,9 @@ mod the_fields_options { assert_eq!(key.tokens(), alone.tokens(), "the key holds the token"); assert_eq!(key.path().to_string(), "$.visits[0]", "the key's path"); let mut members = Vec::new(); - for (slot, _, _) in doc.children(&key.token_bytes()[0]) { + for (slot, _, _) in eql_simulator::json_tree_children(&doc, &key.token_bytes()[0]) { let child = JsonChildPlaintext::decrypt_from_with_context( - key.open_child(doc.node(slot).unwrap()), + key.open_child(eql_simulator::entry_row(&doc, slot).unwrap()), &keyset, AeadContext::from(nonempty!("customers").with("profile")), ) diff --git a/packages/stack-encrypt/tests/json_index.rs b/packages/stack-encrypt/tests/json_index.rs index 5760330e1c..824666a2fa 100644 --- a/packages/stack-encrypt/tests/json_index.rs +++ b/packages/stack-encrypt/tests/json_index.rs @@ -31,6 +31,7 @@ mod common; use common::stack_cipher; use serde_json::{json, Map, Value}; +use stack_encrypt::eql_simulator; #[cfg(feature = "dynamic")] use stack_encrypt::json::JsonQuery; use stack_encrypt::json::{ @@ -252,7 +253,7 @@ async fn keyed(cipher: &Cipher, path: &str, rows: Vec) -> JsonSubtree /// option of `options`. async fn at_with(cipher: &Cipher, doc: &JsonDocument, path: &str, options: JsonOptions) -> usize { let key = subtree_key(cipher, path, options).await.unwrap(); - doc.find(&key.token_bytes()[0]) + eql_simulator::find_by_token(doc, &key.token_bytes()[0]) .unwrap_or_else(|| panic!("the document has {path}")) .0 } @@ -295,12 +296,15 @@ fn base64(bytes: &[u8]) -> String { /// The ordinals the read of `tokens` finds. fn subtree_ordinals(doc: &JsonDocument, tokens: &[Tag]) -> Vec { - doc.subtree(tokens).iter().map(|(j, _, _)| *j).collect() + eql_simulator::json_tree_subtree(doc, tokens) + .iter() + .map(|(j, _, _)| *j) + .collect() } /// Node `j` as a walk returns it, `d` levels below where it started. fn with_depth(doc: &JsonDocument, j: usize, d: u32) -> JsonNode { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); wire["d"] = json!(d); serde_json::from_value(wire).unwrap() } @@ -309,7 +313,7 @@ fn with_depth(doc: &JsonDocument, j: usize, d: u32) -> JsonNode { /// read here as the SQL reads them, each with its depth below the node its /// token named. fn read_rows(doc: &JsonDocument, key: &JsonSubtreeKey) -> Vec { - doc.subtree(&key.token_bytes()) + eql_simulator::json_tree_subtree(doc, &key.token_bytes()) .iter() .map(|(j, _, d)| with_depth(doc, *j, *d)) .collect() @@ -1037,7 +1041,7 @@ mod given_the_fixture_document { tokens.len() <= doc.entries().len(), "the chain is a tree: no token is reached twice" ); - for (_, _, child) in doc.children(&token) { + for (_, _, child) in eql_simulator::json_tree_children(&doc, &token) { let child = child.expect("every child of a sealed node takes a rule"); tokens.push(child); frontier.push(child); @@ -1194,7 +1198,7 @@ mod given_a_subtree_key { &JsonPath::parse("$.nested").unwrap(), "the key carries the path it was derived from" ); - let under = doc.subtree(&key.token_bytes()); + let under = eql_simulator::json_tree_subtree(&doc, &key.token_bytes()); let mut expected = Vec::new(); for (path, d) in [ ("$.nested", 0), @@ -1220,7 +1224,7 @@ mod given_a_subtree_key { "nested, deep, list, both elements and both leaves, each at its depth below $.nested" ); assert!( - doc.subtree(&[[7; 16]]).is_empty(), + eql_simulator::json_tree_subtree(&doc, &[[7; 16]]).is_empty(), "a wrong token finds nothing" ); } @@ -1253,8 +1257,7 @@ mod given_a_subtree_key { let list = subtree_key(&cipher, "$.nested.list", JsonOptions::default()) .await .unwrap(); - let (_, entry, list_token) = doc - .children(&key.token_bytes()[0]) + let (_, entry, list_token) = eql_simulator::json_tree_children(&doc, &key.token_bytes()[0]) .into_iter() .find(|(j, _, _)| *j == list_at) .expect("the list is a child of nested"); @@ -1264,13 +1267,12 @@ mod given_a_subtree_key { "the server derives the token the client sends" ); assert_eq!( - doc.find(&list.token_bytes()[0]).map(|(j, _)| j), + eql_simulator::find_by_token(&doc, &list.token_bytes()[0]).map(|(j, _)| j), Some(list_at), "the list's token finds the list" ); assert_eq!(entry.selector(), doc.entries()[list_at].selector()); - let children: Vec = doc - .children(&list.token_bytes()[0]) + let children: Vec = eql_simulator::json_tree_children(&doc, &list.token_bytes()[0]) .iter() .map(|(j, _, _)| *j) .collect(); @@ -1282,7 +1284,10 @@ mod given_a_subtree_key { ], "the children of a node, by ordinal: the list's two elements" ); - assert!(doc.children(&[7; 16]).is_empty(), "no node, no children"); + assert!( + eql_simulator::json_tree_children(&doc, &[7; 16]).is_empty(), + "no node, no children" + ); } /// `$` is a read under either root. Under the sealed root its token @@ -1297,7 +1302,7 @@ mod given_a_subtree_key { .await .unwrap(); assert_eq!( - doc.subtree(&sealed_root.token_bytes()) + eql_simulator::json_tree_subtree(&doc, &sealed_root.token_bytes()) .iter() .map(|(j, _, d)| (*j, *d)) .collect::>(), @@ -1307,7 +1312,7 @@ mod given_a_subtree_key { let open_doc = seal_with(&cipher, &fixture(), &open_root()).await; let root = subtree_key(&cipher, "$", open_root()).await.unwrap(); assert_eq!( - open_doc.subtree(&root.token_bytes()).len(), + eql_simulator::json_tree_subtree(&open_doc, &root.token_bytes()).len(), 10, "the root and every entry beneath it" ); @@ -1358,7 +1363,7 @@ mod given_a_position { ] { let doc = seal(&cipher, &object).await; assert!( - doc.subtree(&first.token_bytes()).is_empty(), + eql_simulator::json_tree_subtree(&doc, &first.token_bytes()).is_empty(), "{path} in {object}: an object member is not an element" ); } @@ -1381,7 +1386,7 @@ mod given_an_extracted_node { let cipher = &cipher; let doc = &doc; async move { - let node = doc.node(at(cipher, doc, path).await).unwrap(); + let node = eql_simulator::entry_row(doc, at(cipher, doc, path).await).unwrap(); open_extracted(cipher, extracted(cipher, path, node).await).await } }; @@ -1442,7 +1447,7 @@ mod given_an_extracted_node { let Scenario { cipher, .. } = scenario().await; let doc = seal(&cipher, &fixture()).await; let x = at(&cipher, &doc, "$.nested.list[0].x").await; - let mut wire = serde_json::to_value(doc.node(x).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(&doc, x).unwrap()).unwrap(); wire["i"] = json!({"t": "users", "c": "profile"}); wire["v"] = json!(4); let back: JsonNode = serde_json::from_value(wire).unwrap(); @@ -1466,11 +1471,11 @@ mod given_an_extracted_node { let Scenario { cipher, .. } = scenario().await; let doc = seal(&cipher, &fixture()).await; assert_eq!( - doc.node(6).unwrap().depth(), + eql_simulator::entry_row(&doc, 6).unwrap().depth(), None, "an extracted node has no depth" ); - let mut wire = serde_json::to_value(doc.node(6).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(&doc, 6).unwrap()).unwrap(); assert!( wire.get("d").is_none(), "an extracted node writes no `d`: {wire}" @@ -1575,7 +1580,12 @@ mod given_a_derived_record { let Scenario { cipher, .. } = scenario().await; let doc = seal(&cipher, &fixture()).await; let hello = at(&cipher, &doc, "$.hello").await; - let node = extracted(&cipher, "$.hello", doc.node(hello).unwrap()).await; + let node = extracted( + &cipher, + "$.hello", + eql_simulator::entry_row(&doc, hello).unwrap(), + ) + .await; let list = subtree_key(&cipher, "$.nested.list", JsonOptions::default()) .await .unwrap(); @@ -1799,7 +1809,7 @@ mod given_rows_the_server_chose { async fn refuses_a_repeated_row_or_a_line_of_containers() { let Scenario { cipher, .. } = scenario().await; let doc = seal(&cipher, &fixture()).await; - let node = |j: usize| doc.node(j).unwrap(); + let node = |j: usize| eql_simulator::entry_row(&doc, j).unwrap(); let repeated = keyed(&cipher, "$.nested", vec![node(1), node(1)]).await; assertions::refused_as_wrong_entry(&open_list(&cipher, repeated).await, "a repeated row"); @@ -1815,11 +1825,12 @@ mod given_rows_the_server_chose { let mut containers = Vec::new(); for i in 0..200 { containers.push( - doc.node(at(&cipher, &doc, &format!("$.k{i:03}")).await) + eql_simulator::entry_row(&doc, at(&cipher, &doc, &format!("$.k{i:03}")).await) .unwrap(), ); } - containers.push(doc.node(at(&cipher, &doc, "$.k199.x").await).unwrap()); + containers + .push(eql_simulator::entry_row(&doc, at(&cipher, &doc, "$.k199.x").await).unwrap()); assert_eq!(containers.len(), 201, "200 objects and the last leaf"); assertions::refused_as_tampered( &open_list(&cipher, keyed(&cipher, "$.k000", containers).await).await, @@ -1834,14 +1845,16 @@ mod given_rows_the_server_chose { .collect(), ); let doc = seal(&cipher, &wide).await; - let mut arrays = vec![doc.node(at(&cipher, &doc, "$.k000").await).unwrap()]; + let mut arrays = + vec![eql_simulator::entry_row(&doc, at(&cipher, &doc, "$.k000").await).unwrap()]; for i in 0..200 { arrays.push( - doc.node(at(&cipher, &doc, &format!("$.k{i:03}[0]")).await) + eql_simulator::entry_row(&doc, at(&cipher, &doc, &format!("$.k{i:03}[0]")).await) .unwrap(), ); } - arrays.push(doc.node(at(&cipher, &doc, "$.k199[0][0]").await).unwrap()); + arrays + .push(eql_simulator::entry_row(&doc, at(&cipher, &doc, "$.k199[0][0]").await).unwrap()); assert_eq!( arrays.len(), 202, @@ -1907,7 +1920,8 @@ mod given_a_tampered_document { // `JsonNotALeaf`, which names both. let sealed = seal(&cipher, &value).await; let a = at(&cipher, &sealed, "$.a").await; - let mut lifted = serde_json::to_value(sealed.node(a).unwrap()).unwrap(); + let mut lifted = + serde_json::to_value(eql_simulator::entry_row(&sealed, a).unwrap()).unwrap(); lifted["j"] = json!(3 - a); let lifted: JsonNode = serde_json::from_value(lifted).unwrap(); assertions::refused_as_not_a_leaf( @@ -2639,7 +2653,8 @@ mod given_a_float_at_full_precision { .await .unwrap(); let rows = read_rows(&sealed, &key); - let element = sealed.node(at(cipher, &sealed, "$.list[0]").await).unwrap(); + let element = + eql_simulator::entry_row(&sealed, at(cipher, &sealed, "$.list[0]").await).unwrap(); vec![ ( "the document, from the sealed root", diff --git a/packages/stack-encrypt/tests/json_leakage/calibration.rs b/packages/stack-encrypt/tests/json_leakage/calibration.rs index 2f86516a81..c56d318d8b 100644 --- a/packages/stack-encrypt/tests/json_leakage/calibration.rs +++ b/packages/stack-encrypt/tests/json_leakage/calibration.rs @@ -6,6 +6,7 @@ use std::collections::BTreeSet; use proptest::test_runner::{Config, RngAlgorithm, TestCaseError, TestRng, TestRunner}; use serde_json::json; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{JsonOptions, JsonPath}; use stack_encrypt::StackCipher; use stack_kms::FakeDataKeySource; @@ -428,8 +429,8 @@ mod the_harness { /// The harness's hash chain is the crate's: reading a sealed /// document's observed bytes with a subtree key's tokens finds exactly - /// the entries `JsonDocument::subtree` does, at the same depths, for - /// paths through members, positions and wildcards, and `$`. + /// the entries `eql_simulator::json_tree_subtree` does, at the same + /// depths, for paths through members, positions, wildcards, and `$`. #[test] fn chain_is_the_crates_chain() { let runtime = runtime(); @@ -479,11 +480,11 @@ mod the_harness { }) .expect("derives"); let tokens = key.token_bytes(); - let crates: Vec<(usize, usize)> = sealed - .subtree(&tokens) - .iter() - .map(|(j, _, d)| (*j, *d as usize)) - .collect(); + let crates: Vec<(usize, usize)> = + eql_simulator::json_tree_subtree(&sealed, &tokens) + .iter() + .map(|(j, _, d)| (*j, *d as usize)) + .collect(); assert_eq!( walk_positions(&observed.rows[0], &tokens), crates, diff --git a/packages/stack-encrypt/tests/json_leakage/chain.rs b/packages/stack-encrypt/tests/json_leakage/chain.rs index 45096e2096..ca84c1703e 100644 --- a/packages/stack-encrypt/tests/json_leakage/chain.rs +++ b/packages/stack-encrypt/tests/json_leakage/chain.rs @@ -10,7 +10,7 @@ //! selectors, head tokens, member ranks, the OPE key) stays on the client //! and is replaced by randomness in the simulator. //! `chain_is_the_crates_chain` (in `calibration.rs`) holds them to the -//! crate's own walk, `JsonDocument::subtree`. +//! crate's own walk, `eql_simulator::json_tree_subtree`. use sha2::{Digest, Sha256}; diff --git a/packages/stack-encrypt/tests/json_leakage/distinguishers.rs b/packages/stack-encrypt/tests/json_leakage/distinguishers.rs index 32f5b4b896..4543781c8b 100644 --- a/packages/stack-encrypt/tests/json_leakage/distinguishers.rs +++ b/packages/stack-encrypt/tests/json_leakage/distinguishers.rs @@ -558,9 +558,9 @@ fn children(row: &ObservedRow, index: &RowIndex, token: &Tag16) -> Vec { } /// The node `token` names in `row`, found by its self tag, then everything -/// below it, depth first, bounded as the crate's walk (`JsonDocument::subtree`) -/// and the SQL's are: no deeper than the index seals, and no more hits than -/// entries. +/// below it, depth first, bounded as the crate's walk +/// (`eql_simulator::json_tree_subtree`) and the SQL's are. That is, no +/// deeper than the index seals, and no more hits than entries. pub(super) fn walk_with(row: &ObservedRow, index: &RowIndex, token: &Tag16) -> Vec { fn go( row: &ObservedRow, @@ -1472,7 +1472,7 @@ pub fn ordering_matches(world: &ObservedWorld) -> Vec>> { } /// The positions and depths a read of `tokens` reaches in `row`, token by -/// token in the walk's order: what `JsonDocument::subtree` returns. +/// token in the walk's order: what `eql_simulator::json_tree_subtree` returns. pub fn walk_positions(row: &ObservedRow, tokens: &[Tag16]) -> Vec<(usize, usize)> { let index = row_index(row); tokens diff --git a/packages/stack-encrypt/tests/json_leakage/mod.rs b/packages/stack-encrypt/tests/json_leakage/mod.rs index 6f2dba7699..172bd16f66 100644 --- a/packages/stack-encrypt/tests/json_leakage/mod.rs +++ b/packages/stack-encrypt/tests/json_leakage/mod.rs @@ -112,8 +112,8 @@ //! none today. This is what shows the distinguishers can see what the //! clauses describe, so that the positive control passing means something. //! - **The harness itself.** The chain functions agree with the crate's own -//! walk (`JsonDocument::subtree`) for reads through members, positions, -//! wildcards and `$`; one document sealed four times stores its root at +//! walk (`eql_simulator::json_tree_subtree`) for reads through members, +//! positions, wildcards, and `$`; one document sealed four times stores its root at //! slot `0` each time and the rest of its entries, and `q`'s pairs, in a //! fresh order each time (`the_order_is_drawn_afresh_with_the_root_first`); //! and on the real scheme a wildcard read's token list gives its bound and diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index b6e9be3452..ef7e258b1a 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -21,6 +21,7 @@ use stack_encrypt::dynamic::{ self, record, Op, Operand, QueryTerm, Reason, TargetDescriptor, TargetError, TargetOptions, TargetResolver, ValueFrame, ValueKind, }; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{JsonDocument, Tag}; use stack_encrypt::target::{Borrowed, IndexSpec}; use stack_encrypt::{CipherText, Encrypt, KeysetCipher, Label, NonEmpty, Pending, StackCipher}; @@ -244,7 +245,7 @@ fn extracted(doc: &JsonDocument, selector: &str) -> Vec { .iter() .position(|entry| entry.selector() == &selector) .map(|j| { - serde_json::to_value(doc.node(j).unwrap()) + serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()) .unwrap() .to_string() }) @@ -255,10 +256,10 @@ fn extracted(doc: &JsonDocument, selector: &str) -> Vec { /// The rows `json_tree_children(doc, token)` returns, one group each: the /// children of the node the token names, in ordinal order, at depth 1. fn children(doc: &JsonDocument, token: &str) -> Vec> { - doc.children(&tag(token)) + eql_simulator::json_tree_children(doc, &tag(token)) .into_iter() .map(|(j, _, _)| { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); wire["d"] = json!(1); vec![wire.to_string()] }) @@ -269,10 +270,10 @@ fn children(doc: &JsonDocument, token: &str) -> Vec> { /// its depth grafted. fn subtree(doc: &JsonDocument, tokens: &[String]) -> Vec { let tokens: Vec = tokens.iter().map(|t| tag(t)).collect(); - doc.subtree(&tokens) + eql_simulator::json_tree_subtree(doc, &tokens) .into_iter() .map(|(j, _, d)| { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); wire["d"] = json!(d); wire.to_string() }) @@ -1576,8 +1577,8 @@ fn a_malformed_read_is_refused_before_any_key() { /// `element_match`: a predicate on one element of an array, its operand the /// members' subtree reads and their bounds, as the `subtree` operator and /// the orderings derive them. `json_tree_element_match` is modelled over -/// the rows `JsonDocument::subtree` returns, as the subtree tests model -/// `json_tree_subtree`; `packages/eql/tests/encryption` runs the SQL. +/// the rows `eql_simulator::json_tree_subtree` returns, as the subtree tests +/// model `json_tree_subtree`; `packages/eql/tests/encryption` runs the SQL. mod element_match { use super::*; @@ -1676,7 +1677,10 @@ mod element_match { .collect(); let selector = tag(bounds[0].1["s"].as_str().unwrap()); let token = tag(member["t"][k].as_str().unwrap()); - let Some((j, entry, _)) = doc.subtree(&[token]).into_iter().next() else { + let Some((j, entry, _)) = eql_simulator::json_tree_subtree(doc, &[token]) + .into_iter() + .next() + else { all = false; continue; }; @@ -1685,7 +1689,7 @@ mod element_match { all = false; continue; } - let node = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let node = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); if node.get("op").is_none() { all = false; continue; diff --git a/packages/stack-encrypt/tests/json_owned.rs b/packages/stack-encrypt/tests/json_owned.rs index c8234972ea..f9b550b56e 100644 --- a/packages/stack-encrypt/tests/json_owned.rs +++ b/packages/stack-encrypt/tests/json_owned.rs @@ -16,6 +16,7 @@ use std::sync::Arc; use common::CountingSource; use serde_json::{json, Value}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{ JsonDocument, JsonExtracted, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSelector, JsonSubtree, JsonSubtreeKey, @@ -86,7 +87,7 @@ async fn key(cipher: &Cipher, path: &str) -> JsonSubtreeKey { /// server finds it: by the self tag of the path's token. async fn slot(cipher: &Cipher, doc: &JsonDocument, path: &str) -> usize { let key = key(cipher, path).await; - doc.find(&key.token_bytes()[0]) + eql_simulator::find_by_token(doc, &key.token_bytes()[0]) .unwrap_or_else(|| panic!("the document has {path}")) .0 } @@ -94,7 +95,7 @@ async fn slot(cipher: &Cipher, doc: &JsonDocument, path: &str) -> usize { /// The entry at `j` as an extractor returns it, at depth `d` when a walk /// returned it. fn row(doc: &JsonDocument, j: usize, d: Option) -> JsonNode { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); if let Some(d) = d { wire["d"] = json!(d); } @@ -104,7 +105,7 @@ fn row(doc: &JsonDocument, j: usize, d: Option) -> JsonNode { /// The rows a subtree read returns for `key`: for each token, the node it /// names at depth 0 and everything beneath it. fn walk(doc: &JsonDocument, key: &JsonSubtreeKey) -> Vec { - doc.subtree(&key.token_bytes()) + eql_simulator::json_tree_subtree(doc, &key.token_bytes()) .iter() .map(|(j, _, d)| row(doc, *j, Some(*d))) .collect() diff --git a/packages/stack-encrypt/tests/json_properties.rs b/packages/stack-encrypt/tests/json_properties.rs index 3b5e9807e2..996080c050 100644 --- a/packages/stack-encrypt/tests/json_properties.rs +++ b/packages/stack-encrypt/tests/json_properties.rs @@ -1,7 +1,8 @@ //! Properties of the JSON index's reads over random documents, with no //! database: the rows the server's read returns are modelled by -//! `JsonDocument::subtree`, the Rust twin of `json_tree_subtree`, and -//! opened through the key, as a caller opens what PostgreSQL returns. +//! `eql_simulator::json_tree_subtree`, the Rust copy of +//! `eql_v4.json_tree_subtree`, and opened through the key, as a caller opens +//! what PostgreSQL returns. //! //! - **Metamorphic.** A read of `$.a` with `.b` applied on the client is the //! read of `$.a.b`; a read of `$` (the open root walked, the sealed root @@ -29,6 +30,7 @@ use common::stack_cipher; use proptest::prelude::*; use proptest::test_runner::TestCaseError; use serde_json::{json, Map, Value}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{ JsonDocument, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSubtree, Segment, }; @@ -88,14 +90,14 @@ async fn key( /// The rows the server's read returns for `key`, in full. fn rows(doc: &JsonDocument, key: &stack_encrypt::json::JsonSubtreeKey) -> Vec { - doc.subtree(&key.token_bytes()) + eql_simulator::json_tree_subtree(doc, &key.token_bytes()) .iter() .map(|(j, _, d)| with_depth(doc, *j, *d)) .collect() } fn with_depth(doc: &JsonDocument, j: usize, d: u32) -> JsonNode { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); wire["d"] = json!(d); serde_json::from_value(wire).unwrap() } @@ -168,7 +170,7 @@ async fn slot( options: &JsonOptions, ) -> Option { let k = key(cipher, path, options, 0).await; - doc.find(&k.token_bytes()[0]).map(|(j, _)| j) + eql_simulator::find_by_token(doc, &k.token_bytes()[0]).map(|(j, _)| j) } /// `items` in the order a Fisher–Yates shuffle driven by `seed` puts them: @@ -336,7 +338,7 @@ proptest! { for path in node_paths(&value) { let node = path.select(&value)[0].clone(); let k = key(&cipher, &path, &options, 4).await; - let children = doc.children(&k.token_bytes()[0]).len(); + let children = eql_simulator::json_tree_children(&doc, &k.token_bytes()[0]).len(); let count = match &node { Value::Object(m) => m.len(), Value::Array(a) => a.len(), @@ -353,7 +355,7 @@ proptest! { .await .unwrap(); let j = doc.entries().iter().position(|e| e.selector() == selector.as_bytes()).unwrap(); - let entry = selector.open(doc.node(j).unwrap()); + let entry = selector.open(eql_simulator::entry_row(&doc, j).unwrap()); let arrow = JsonPlaintext::decrypt_from_with_context(entry, &cipher, aead()) .await .map(held) @@ -556,7 +558,7 @@ proptest! { let mut found = Vec::new(); for siblings in [&left, &right] { let doc = seal(&cipher, &row(siblings), &options(true)).await; - let (j, entry) = doc.find(&k.token_bytes()[0]).expect("found by its token"); + let (j, entry) = eql_simulator::find_by_token(&doc, &k.token_bytes()[0]).expect("found by its token"); found.push(*entry.selector()); prop_assert_eq!(read(&cipher, &doc, &path, &options(true)).await, Some(json!(1))); prop_assert!(j > 0); @@ -625,7 +627,7 @@ proptest! { let found: Vec = k .token_bytes() .iter() - .map(|t| doc.find(t).map(|(j, _)| j).expect("every token names a node of the witness")) + .map(|t| eql_simulator::find_by_token(&doc, t).map(|(j, _)| j).expect("every token names a node of the witness")) .collect(); // Where each node of the witness is stored, by its own path's // key: the slots are random, so the read's tokens are checked @@ -740,7 +742,7 @@ async fn every_seal_draws_its_own_member_ordinals() { let mut orders = BTreeSet::new(); for _ in 0..10 { let doc = seal(&cipher, &value, &options).await; - let children = doc.children(&root.token_bytes()[0]); + let children = eql_simulator::json_tree_children(&doc, &root.token_bytes()[0]); assert_eq!(children.len(), 6, "every member at an ordinal from 0 to 5"); let order: Vec> = children .iter() diff --git a/packages/stack-encrypt/tests/json_read_checks.rs b/packages/stack-encrypt/tests/json_read_checks.rs index c18662d014..4cf841e9ca 100644 --- a/packages/stack-encrypt/tests/json_read_checks.rs +++ b/packages/stack-encrypt/tests/json_read_checks.rs @@ -23,6 +23,7 @@ use std::sync::atomic::Ordering; use common::CountingSource; use serde_json::{json, Value}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{ JsonChild, JsonChildPlaintext, JsonDocument, JsonExtracted, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSelector, JsonSubtree, JsonSubtreeKey, @@ -126,7 +127,7 @@ async fn slot_with( options: &JsonOptions, ) -> usize { let key = key_with(cipher, path, options).await; - doc.find(&key.token_bytes()[0]) + eql_simulator::find_by_token(doc, &key.token_bytes()[0]) .unwrap_or_else(|| panic!("the document has {path}")) .0 } @@ -134,7 +135,7 @@ async fn slot_with( /// The entry at `j` as an extractor returns it, at depth `d` when a walk /// returned it. fn row(doc: &JsonDocument, j: usize, d: Option) -> JsonNode { - let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + let mut wire = serde_json::to_value(eql_simulator::entry_row(doc, j).unwrap()).unwrap(); if let Some(d) = d { wire["d"] = json!(d); } @@ -145,7 +146,7 @@ fn row(doc: &JsonDocument, j: usize, d: Option) -> JsonNode { /// read as the SQL reads them: for each token, the node it names at depth /// 0 and everything beneath it. fn walk(doc: &JsonDocument, key: &JsonSubtreeKey) -> Vec { - doc.subtree(&key.token_bytes()) + eql_simulator::json_tree_subtree(doc, &key.token_bytes()) .iter() .map(|(j, _, d)| row(doc, *j, Some(*d))) .collect() @@ -297,7 +298,8 @@ mod given_the_entry_arrow_returned { // Passing the check by rewriting `s` breaks the ciphertext's // binding to its own selector instead. let number = slot(&cipher, &doc, "$.number").await; - let mut wire = serde_json::to_value(doc.node(number).unwrap()).unwrap(); + let mut wire = + serde_json::to_value(eql_simulator::entry_row(&doc, number).unwrap()).unwrap(); wire["s"] = json!(hello.to_string()); let relabelled: JsonNode = serde_json::from_value(wire).unwrap(); let opened = open_extracted(&cipher, hello.open(relabelled)).await; @@ -858,7 +860,7 @@ mod given_one_child_of_a_node { /// The rows `json_tree_children(doc, key.tokens()[0])` returns: one per /// child, in ordinal order, each at depth 1. fn children(doc: &JsonDocument, key: &JsonSubtreeKey) -> Vec { - doc.children(&key.token_bytes()[0]) + eql_simulator::json_tree_children(doc, &key.token_bytes()[0]) .iter() .map(|(j, _, _)| row(doc, *j, Some(1))) .collect() @@ -1323,12 +1325,11 @@ async fn the_model_keeps_the_last_entry_carrying_a_tag_as_the_sql_index_does() { sv.push(copy); let forged: JsonDocument = serde_json::from_value(wire).unwrap(); assert_eq!( - forged.find(&hello.token_bytes()[0]).map(|(j, _)| j), + eql_simulator::find_by_token(&forged, &hello.token_bytes()[0]).map(|(j, _)| j), Some(10), "the last entry with the self tag" ); - let children: Vec = forged - .children(&root.token_bytes()[0]) + let children: Vec = eql_simulator::json_tree_children(&forged, &root.token_bytes()[0]) .iter() .map(|(j, _, _)| *j) .collect(); @@ -1342,7 +1343,8 @@ async fn the_model_keeps_the_last_entry_carrying_a_tag_as_the_sql_index_does() { /// The self tag the stored node at `key`'s only token carries, as the /// database could write it on any entry: it holds the token and the `iv`. fn x_of(doc: &JsonDocument, key: &JsonSubtreeKey) -> String { - let (j, _) = doc.find(&key.token_bytes()[0]).expect("the node is there"); + let (j, _) = + eql_simulator::find_by_token(doc, &key.token_bytes()[0]).expect("the node is there"); base64(doc.entries()[j].self_tag()) } diff --git a/packages/stack-encrypt/tests/json_tree_vectors.rs b/packages/stack-encrypt/tests/json_tree_vectors.rs index 467a973ec3..1755f3f11c 100644 --- a/packages/stack-encrypt/tests/json_tree_vectors.rs +++ b/packages/stack-encrypt/tests/json_tree_vectors.rs @@ -36,6 +36,7 @@ use std::ffi::OsStr; use std::path::PathBuf; use serde_json::{json, Value}; +use stack_encrypt::eql_simulator; use stack_encrypt::json::{JsonDocument, JsonOptions, JsonPath}; use stack_encrypt::nonempty; use stack_encrypt::target::CallerContext; @@ -124,8 +125,7 @@ async fn vectors(options: &JsonOptions) -> Value { ) .await .unwrap(); - let (j, _) = doc - .find(&key.token_bytes()[0]) + let (j, _) = eql_simulator::find_by_token(&doc, &key.token_bytes()[0]) .expect("every node is stored"); order[j] = json!(path); }