diff --git a/.changeset/eql-json-tree-open-one-child.md b/.changeset/eql-json-tree-open-one-child.md new file mode 100644 index 0000000000..90ecf96fd1 --- /dev/null +++ b/.changeset/eql-json-tree-open-one-child.md @@ -0,0 +1,12 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package, can now decrypt one child of a JSON node on its own. A read of one child no longer needs the parent's whole subtree. + +- Your app pairs each entry that `eql_v4.json_tree_children` returned with the parent's `JsonSubtreeKey`, through `JsonTreeChild::from_key(&key, entry)`. +- Decrypting checks that the entry is a child of that parent. +- Your app decrypts into a `JsonPlaintext` for the child's value. Decrypt into a `JsonChildPlaintext` for its key or index too. +- A child with members of its own does not decrypt alone. Read it through `JsonTreeSubtree`. + +The EQL v4 JSON tree reference describes the child read. The stored format and the SQL bundle do not change. diff --git a/.plain-language.json b/.plain-language.json new file mode 100644 index 0000000000..ef6dfc8efd --- /dev/null +++ b/.plain-language.json @@ -0,0 +1 @@ +{ "names": ["CipherStash", "ZeroKMS", "EQL", "PostgreSQL"] } diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 9e73f4c8cb..b811546583 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -110,9 +110,10 @@ cleanup gaps and unobserved behavior alongside the passing requirements. ## EQL and JSON operations The [EQL/JSON contract](eql-json-contract.md) enrolls resolver capabilities, -document writes, queries, extraction/subtree reads, element-match and predicate -matching. It reuses the native, Go and independent PostgreSQL suites and shares -write/predicate case data. Run `mise run test:conformance:eql` and the separate +document writes, queries, extraction reads, subtree reads, reads of one +child checked against its parent, element-match, and predicate matching. The +contract reuses the native, Go, and independent PostgreSQL suites. The +contract also shares write and predicate case data. Run `mise run test:conformance:eql` and the separate required `test:conformance:eql:postgres` task; see the contract for guest builds, disposable database setup, intentional SQL differences and version reports. diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index a35bb18e6b..71c70208c4 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -115,8 +115,8 @@ unsupported feature silently advertised by the Go/dynamic record profile. The [EQL/JSON contract](eql-json-contract.md) and its enrollment index cover resolver/catalog capabilities, JSON writes and queries, request-bound reads, -element-match and predicate-match. Existing Rust, Go and PostgreSQL suites stay -in place. The common document and predicate-refusal tables now live in +reads of one child checked against its parent, element-match, and +predicate-match. Existing Rust, Go, and PostgreSQL suites stay in place. The common document and predicate-refusal tables now live in `v1/eql-json-v1.cases.json`: Rust and Go execute them, retaining native key-call checks, Go diagnostic mapping and all extra cases from the original suites. diff --git a/conformance/stack-encrypt/eql-json-contract.md b/conformance/stack-encrypt/eql-json-contract.md index af4ddbcdea..ed25f0e23b 100644 --- a/conformance/stack-encrypt/eql-json-contract.md +++ b/conformance/stack-encrypt/eql-json-contract.md @@ -16,6 +16,7 @@ native Rust and Go. Python and TypeScript have no enrolled runner yet. | `json-request-bound-reads-v1` | Extraction and subtree/wildcard reads open against the prepared path, column, position and bounds. Wrong requests and detectable tampering fail. | Native adversarial read suite, EQL request/open tests, Go selector reads, PostgreSQL extraction/subtree and hostile-row suites | | `json-extraction-v1` | Single-node extraction opens the requested scalar. | Native scalar extraction, Go selectors and PostgreSQL plaintext extraction oracle | | `json-subtree-v1` | Complete bounded subtrees and wildcard reads match plaintext queries. | Native/EQL prepared reads and Go/PostgreSQL read paths | +| `json-child-v1` | Your app opens one entry that `json_tree_children` returned, checked against the parent path that prepared the read. The check covers the entry's selector, depth, parent tag, and self tag: the one its decrypted key or index gives under the parent's token. The entry opens to its value and its authenticated key or index. The check refuses another node's child, an entry at another depth, a top-level field under a sealed root, and a parent path with a wildcard. A child with members does not open alone. | Native child reads and data-path reads, EQL typed child open, Go raw and generated `Children` (with and without a binding), PostgreSQL `json_tree_children` oracle | | `json-tamper-v1` | Detectable mixed-document, truncated-chain and substituted-column answers are refused. | Native and PostgreSQL adversarial suites; Go observes wrong-column rejection | | `json-element-match-v1` | Every condition must hold on one element. Ordering paths and resolver capability are required; a probe beyond the declared bound raises rather than silently truncating. | Native operator/capability tests, Go generated member APIs, SQL domain and independent plaintext predicate tests | | `json-predicate-match-v1` | Supported text compiles to existing operators; refusals preserve reason, construct and byte offset, with no caller text in diagnostics. Missing and null paths obey the documented truth rules. | Shared negative corpus, native compiler/property tests, Go generated `Match`, SQL `jsonb_path_match` and handwritten-operator oracles | diff --git a/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json b/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json index dc955c3127..54109d735a 100644 --- a/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json +++ b/conformance/stack-encrypt/v1/eql-json-v1.enrollment.json @@ -249,6 +249,35 @@ "go-postgres": ["TestJSONDocumentsQueryAndReadInPostgres"] } }, + { + "id": "json-child-v1", + "evidence": { + "engine-reads": [ + "given_one_child_of_a_node::each_leaf_member_opens_to_its_key_and_value", + "given_one_child_of_a_node::each_element_opens_to_its_index_and_value_in_position_order", + "given_one_child_of_a_node::a_child_of_another_node_is_refused_by_its_selector", + "given_one_child_of_a_node::an_element_read_as_another_position_is_refused", + "given_one_child_of_a_node::a_member_under_the_element_rule_is_refused_by_its_label", + "given_one_child_of_a_node::a_row_at_another_depth_is_refused", + "given_one_child_of_a_node::a_chain_head_is_refused_before_any_key_is_retrieved", + "given_one_child_of_a_node::a_key_with_a_wildcard_is_refused_before_any_key_is_retrieved" + ], + "engine-queries": [ + "a_child_opens_against_the_parent_its_request_names", + "a_malformed_read_is_refused_before_any_key" + ], + "eql-typed": ["a_child_opens_through_the_key_of_its_parent"], + "postgres": ["postgres_each_child_opens_against_its_parent"], + "go": [ + "TestJSONChildrenOpenAgainstTheirParent", + "TestTheReadOperatorsAreTheOnesTheEngineOpens", + "TestACustomersDocumentReadsThroughACipherWithABinding", + "TestAnOlderGeneratedChildrenTokenIsAQueryOperand", + "TestJSONReadTypesPrintAndLogRedacted" + ], + "go-postgres": ["TestJSONDocumentsQueryAndReadInPostgres"] + } + }, { "id": "json-tamper-v1", "evidence": { 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 0b374c370c..640137bfda 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -963,16 +963,23 @@ The generated file builds its declaration through `gensupport` calls, and the module builds the frames it sends to the engine. So a change to the serialised `Planned`'s shape is a change inside the module. A program generates again only to adopt a new -declaration, such as a scope or binding on a field. The generator keeps its output identical for unchanged input. So an -upgrade alone does not change a committed `*_stash.go` file, apart from -the one regeneration the handle rename needs. +declaration, such as a scope or binding on a field, or a new generated +method. The generator keeps its output identical for unchanged input. So +an upgrade alone does not change a committed `*_stash.go` file. -Two parts of the target state are not in Go yet: +A regeneration picks up two changes to the generated code. The handle +rename is the one a program needs. The other is the new `Children`. The +new `Children` returns `encrypt.JSONChildren`, and that type opens each +child. + +A file generated before this change still compiles and runs. That file's +`Children` returns the token alone. + +One part of the target state is not in Go yet: - A Go program cannot set match options. -- A Go program cannot open one child of a JSON node, bound to its parent. -Both are in [Remaining work](#remaining-work). +[Remaining work](#remaining-work) lists it. ### Rules in the target state @@ -1284,8 +1291,22 @@ release leaves behind. - **Why.** Today a program must read and open the parent's whole subtree to see one child. That transfers more data and reveals a different set of tokens. -- **Done already.** Nothing. -- **Tracked in.** Issue #1677 is open. Pull request #1353, the Go JSON plan document, lists it as remaining. +- **Done already.** + - The engine opens one entry that `json_tree_children` returned. The + engine checks the entry against the key of the parent's path, with + the same parent-link checks as a subtree read + (`JsonSubtreeKey::open_child`, a `JsonChild`). + - A child opens to its value (`JsonPlaintext`). A child also opens to + its value with its authenticated key or index (`JsonChildPlaintext`; + Go's `JSONChildValue`). + - `eql-bindings` has `JsonTreeChild`. `children(path).encrypt_keyed` + returns the token with the key that opens what the query returns. + - The dynamic interface's `json_open` takes the `children` operation. + - Go's generated `Children` returns an `encrypt.JSONChildren`. + `JSONChildren.Open` opens each entry. + - The `eql-json-v1` profile enrolls the read as `json-child-v1`, with + Rust, Go, and PostgreSQL evidence. +- **Tracked in.** Issue #1677. Pull request #1353, the Go JSON plan document, lists it as remaining. - **Finished when** Go can open one child, and the `eql-json-v1` conformance profile covers it. @@ -1644,7 +1665,9 @@ Base64. program runs it is `predicate(text).var(..)`, so the operand is the text form's and the data plan's `match` operand. - **Tracked in.** Issue #1459 closes with the `predicate!` pull request. - Issue #1677 is open for opening one child. Issue #1486 is closed. + Issue #1677, for opening one child, closes with its pull request: a + `JsonDocument` field's `children(path)` key opens each child + (`open_child`). Issue #1486 is closed. - **Finished when** these are all true: - the [JSON query example](#query-a-json-document) compiles; - a path, a member or a value type the field does not declare does not @@ -1751,7 +1774,8 @@ Decided on 7 November 2026, as area one of the query design review. `Planned` with the engine's expected answer beside it; - a Go program generated for rc.3 runs against the module that sends serialised `Planned` values, apart from the one regeneration the - handle rename needs; + handle rename needs. That regeneration also changes `Children` to + return `encrypt.JSONChildren`. That type still binds as the token; - the chain in `plan/chain.rs` and the builder in `plan/build.rs` are gone. diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 37b86fc91e..959799136f 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -15,6 +15,44 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Added +- **Read one child of a JSON node** (#1677). Your app can now read one + level of a `JsonSearch` document without fetching the parent's whole + subtree. The read takes three steps. + 1. Your app calls `Children(ctx, c, path)` on the field. `Children` now + returns an `encrypt.JSONChildren`. + 2. The database (EQL) runs `eql_v4.json_tree_children(col, $1::text)`, + with `Token()` as `$1`. The database returns the parent's direct + children as encrypted entries. + 3. Your app passes the entries to `Open(ctx, entries)`. `Open` checks + each entry, then decrypts it. + + More detail: + + - Each entry opens to an `encrypt.JSONChildValue`. `Key()` gives a + member's key, and `Index()` gives an element's index. `JSON` is the + child's value as JSON text, or `{}` or `[]` for an empty object or + array. + - The key or index is encrypted with the value, and authenticated. The + database returns an object's members in a random order. So the key is + how your app tells the members apart. + - `Open` checks each entry against the node at `path`. The entry's + selector must be that path extended by its key or index. The entry's + self tag must be the one that key or index gives under the parent's + token. + - An entry that is not a child of that node is `ErrEncoding`, with code + `stack_encrypt::json_wrong_entry`. + - A child that is an object or an array with members does not open + alone. `Open` refuses it as `ErrEncoding`, with code + `stack_encrypt::json_not_a_leaf`. Read such a child with `Subtree` at + its own path. + - No guest export is added. `se_json_open` takes the operation + `"children"`, and returns each child's key or index with its value. + `Cipher.JSONOpen` refuses that operation. Open a children read with + `JSONChildren.Open`. + - `JSONChildren` prints and logs with the path and the token redacted, + as `JSONSelection` and `JSONRead` do. `JSONChildValue` prints and logs + redacted, since a key can be a customer's data. + - **Audit metadata for the ZeroKMS audit log** (#1067). ZeroKMS logs every data-key request with the identity that made it. `encrypt.AuditMetadata` adds facts about the call to that log, such as its purpose or a request @@ -92,8 +130,24 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. in the database until the row is written again or the column is dropped. +- **`Children` returns `encrypt.JSONChildren`, not `encrypt.JSONToken`** + (#1677). The new type contains the token and opens the children. + Regenerate with `stashgen` to get it. + - Code that passes the result to a query keeps working, because + `JSONChildren` binds as its token. + - Code that keeps the result as a `JSONToken` takes `.Token()`. + - `ChildCount` still returns a `JSONToken`. + - A `*_stash.go` file generated before this release still compiles and + runs. Its `Children` returns a `JSONToken`, and a cipher with a binding + still refuses it. + ### Changed +- `Children` through a cipher with a binding now prepares the read, as + `Selector` and `Subtree` do (#1677). Before, the cipher refused it. The + token derives under the cipher's scopes alone. The children open under + the scopes and the binding. A cipher with a binding still refuses + `ChildCount`, since a count opens nothing. - `vcffi` and `vcvalue` move to vitaminc `f1fc9ae74`, the commit vitaminc 0.10.0 was released from. The host now checks the same date and timestamp range as the guests. diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 12c50c265b..8c6c392f86 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -201,7 +201,8 @@ The field's `Fields` entry has a method per operation: | `At.Age.Lt(ctx, c, v)`, `Lte`, `Gt`, `Gte`, `Between` | `eql.JSONSearchLeafQuery` | `(col -> $sel::text) < $1::eql_v4.query_json_leaf`, `$sel` from `At.Age.Selector(ctx, c)` | | `Selector(ctx, c, path)` | `encrypt.JSONSelection`: `Selector()` and `Open` | `col -> $1::text` | | `Subtree(ctx, c, path, opts)` | `encrypt.JSONRead`: `Tokens()`, `Open` and `OpenOne` | `eql_v4.json_tree_subtree(col, $1::text[], 64)` | -| `Children(ctx, c, path)`, `ChildCount(ctx, c, path)` | `encrypt.JSONToken` | `eql_v4.json_tree_children(col, $1::text)`, `eql_v4.json_tree_child_count(col, $1::text)` | +| `Children(ctx, c, path)` | `encrypt.JSONChildren`: `Token()`, and `Open` to each child's key or index and value | `eql_v4.json_tree_children(col, $1::text)` | +| `ChildCount(ctx, c, path)` | `encrypt.JSONToken` | `eql_v4.json_tree_child_count(col, $1::text)` | | `Elements.Visits.Match(ctx, c, opts, predicates...)` | `eql.JSONSearchElementsQuery` | `eql_v4.json_tree_element_match(col, $1::eql_v4.query_json_elements)` | | `Match(ctx, c, predicate, vars, opts)` | `eql.JSONSearchPredicateQuery` | `col @@ $1::eql_v4.query_json_predicate`, or `eql_v4.json_tree_match(col, $1::eql_v4.query_json_predicate)` | diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 1303aa23d8..f90e23a747 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -737,12 +737,12 @@ The EQL value stores the table and the column alone, in `i`, so: - open the value through a cipher with the same scope and binding; - query it through a cipher with the same scope. A binding is in no query; -- read part of a `JsonSearch` document (`Selector`, `Subtree`) through a - cipher with the same scope and binding. The selector or the tokens derive - under the scope alone, as a query does, and the entries open under the - scope and the binding. Every row of one `Open` call opens under that - binding, so a read through a cipher with a binding reads that binding's - row. +- read part of a `JsonSearch` document (`Selector`, `Subtree`, `Children`) + through a cipher with the same scope and binding. The selector or the + tokens derive under the scope alone, as a query does, and the entries + open under the scope and the binding. Every row of one `Open` call opens + under that binding, so a read through a cipher with a binding reads that + binding's row. ### Encrypted JSON documents @@ -798,15 +798,56 @@ and a selector or token as `text`; cast each parameter, as above, so PostgreSQL picks EQL's operator and not `jsonb`'s; a zero one is refused rather than bound. A token is a capability over its node's subtree in every row of the column, and a path's keys can be your customer's data, so -`JSONToken`, `JSONTokens`, `JSONSelection` and `JSONRead` print and log with -the tokens, the selector and the path redacted. A `JSONValue` holds the -plaintext a read opened, and prints it. Numbers order as `float64`, -so integers past 2^53 can tie at an ordered path; containment and `EqAt` +`JSONToken`, `JSONTokens`, `JSONSelection`, `JSONRead`, and `JSONChildren` +print and log with the tokens, the selector, and the path redacted. A +`JSONValue` contains the plaintext a read opened, and prints it. A +`JSONChildValue` contains a child's key or index and its value. A +`JSONChildValue` prints and logs redacted, since a key can be your +customer's data. Numbers order as +`float64`, so integers past 2^53 can tie at an ordered path; containment and `EqAt` compare them exactly. At a wildcard path, `->` returns an unspecified element of each row, so an ordering over every element is written over `eql_v4.json_tree_path_query(col, $sel)`, its matches (the stashgen README shows the SQL). +#### Read the children of one node + +`Children` reads one level of a document, without fetching the parent's +whole subtree. It takes three steps. + +1. **Your app** calls `Children` with the parent's path, a path with no + wildcard. `Children` derives the parent's token. A token is a value the + database uses to find a node's entry. Deriving it asks ZeroKMS for + nothing. +2. **The database (EQL)** runs `eql_v4.json_tree_children(profile, $1::text)`, + with `children.Token()` as `$1`. In each row, it finds the parent's + entry and returns the parent's direct children as encrypted entries. It + never decrypts anything, and it never receives a key. +3. **Your app** passes the returned entries to `children.Open`. The engine + checks that each entry is a child of the parent. Then it fetches the + data keys from ZeroKMS and decrypts each child. + +```go +// Step 1: derive the parent's token. +children, err := users.Fields.Profile.Children(ctx, cipher, "$.address") + +// Step 2: run this query with children.Token() as $1, and collect every entry. +// SELECT e FROM users, eql_v4.json_tree_children(profile, $1::text) AS e WHERE id = $2 + +// Step 3: decrypt the entries. +members, err := children.Open(ctx, entries) +for _, member := range members { + key, _ := member.Key() // "city", "street", ... + value, err := encrypt.DecodeJSON[string](member.JSON) +} +``` + +Each child has a key, for a member of an object, or an index, for an +element of an array. The database returns an object's members in a random +order, so the key is how your app tells them apart. A child that is an +object or an array with members does not decrypt alone. Read it with +`Subtree` at its own path. + #### Choosing a JSON query | To find rows where… | Use | Engages an index | diff --git a/languages/golang/encrypt/cipher.go b/languages/golang/encrypt/cipher.go index d6bf27c5f4..6f4a1b77ab 100644 --- a/languages/golang/encrypt/cipher.go +++ b/languages/golang/encrypt/cipher.go @@ -84,11 +84,14 @@ func (cph *Cipher) Scope(parts ...any) *Cipher { // through cipher.Bind(rowID) opens only through a cipher with the same // binding. It is in no query context, so a query through a cipher with a // binding is refused as [ErrEncoding]: a query by column or by tenant still -// finds the row. A read of part of a JSON document (a field's Selector or -// Subtree) is not refused: it prepares under the scopes alone and opens -// under the binding, so it reads that binding's row. The parts are those -// [Cipher.Scope] takes, and an empty string or byte slice is refused: an -// unassigned row ID would bind every such row to one context. +// finds the row. A cipher with a binding does not refuse a read of part of +// a JSON document, through a field's Selector, Subtree, or Children. The +// read prepares under the scopes alone and opens under the binding, so it +// reads that binding's row. +// +// The parts are those [Cipher.Scope] takes. Bind refuses an empty string +// or byte slice. An unassigned row ID would bind every such row to one +// context. func (cph *Cipher) Bind(parts ...any) *Cipher { next := cph.copy() for _, part := range parts { diff --git a/languages/golang/encrypt/doc.go b/languages/golang/encrypt/doc.go index 18d7b37afa..fee2bb8955 100644 --- a/languages/golang/encrypt/doc.go +++ b/languages/golang/encrypt/doc.go @@ -244,14 +244,21 @@ // the query. // // A selection or a subtree read opens values as JSON text ([JSONValue], -// [JSONRead.Open]). [DecodeJSON] reads one into a Go type. +// [JSONRead.Open]). [DecodeJSON] reads JSON text into a Go type. +// +// A children read ([JSONChildren]) reads one level of a document. Your app +// derives the parent's token. The database (EQL) returns the parent's +// direct children as encrypted entries. Your app then opens each entry to +// the child's key or index and its JSON text ([JSONChildValue]). // // A document sealed through a cipher with a binding ([Cipher.Bind]) is read -// through a cipher with the same scopes and binding. Selector and Subtree -// take such a cipher: the selector or the tokens derive under its scopes -// alone, as a query's term does, and the entries open under the scopes and -// the binding. Every row of one Open call opens under that binding, so a -// read through a cipher with a binding reads that binding's row. A query +// through a cipher with the same scopes and binding. Selector, Subtree, and +// Children take such a cipher. The selector or the tokens derive under its +// scopes alone, as a query's term does. The entries open under the scopes +// and the binding. +// +// Every row of one Open call opens under that binding, so a read through a +// cipher with a binding reads that binding's row. A query // (Contains, EqAt, Match and the rest) opens nothing, so it takes no // binding, and a query through a cipher with one is refused. // diff --git a/languages/golang/encrypt/example/json/customer_stash.go b/languages/golang/encrypt/example/json/customer_stash.go index 9dfdf67dc6..f0a1cbc703 100644 --- a/languages/golang/encrypt/example/json/customer_stash.go +++ b/languages/golang/encrypt/example/json/customer_stash.go @@ -193,11 +193,14 @@ func (f ProfileField) Subtree(ctx context.Context, c *encrypt.Cipher, path strin return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f ProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f ProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which diff --git a/languages/golang/encrypt/export_test.go b/languages/golang/encrypt/export_test.go index 2712fbd39a..9af6686d12 100644 --- a/languages/golang/encrypt/export_test.go +++ b/languages/golang/encrypt/export_test.go @@ -14,6 +14,7 @@ import ( "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -52,6 +53,14 @@ func withZeroKMSURL(url string) ClientOption { // WithZeroKMSURL is withZeroKMSURL for the external tests. func WithZeroKMSURL(url string) ClientOption { return withZeroKMSURL(url) } +// JSONOpensForTest asks se_json_open to open no rows of a read whose request +// names operator as its operation, at path: nil when the engine opens a +// read of that operation. +func (cph *Cipher) JSONOpensForTest(ctx context.Context, plan *record.Plan, field, operator, path string) error { + _, err := cph.jsonOpen(ctx, plan, field, vcvalue.Object{{Key: "operation", Value: operator}, {Key: "path", Value: path}}, nil) + return err +} + // Sends is how many ZeroKMS requests the client has made. func Sends(c *Client) int64 { return c.transport.sends.Load() } diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index 844b75390a..5a27261849 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -434,7 +434,7 @@ func (f Field[T]) elementMembers(path string) []string { // JSONSelect prepares `->` at a path on a JSON field: the selector to // bind, and what opens the entries it returns. E is the field's entry type. func JSONSelect[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, path string) (encrypt.JSONSelection[E], error) { - term, err := f.jsonTerm(ctx, c, "selector", "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + term, err := f.jsonTerm(ctx, c, record.JSONSelector, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) if err != nil { return encrypt.JSONSelection[E]{}, err } @@ -450,18 +450,39 @@ func JSONSubtree[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.C if opts.WildcardBound != 0 { input = append(input, vcvalue.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) } - term, err := f.jsonTerm(ctx, c, "subtree", "text_array", 0, input) + term, err := f.jsonTerm(ctx, c, record.JSONSubtree, "text_array", 0, input) if err != nil { return encrypt.JSONRead[E]{}, err } return encrypt.NewJSONRead[E](c, f.plan, f.name, input, term.Text), nil } -// JSONNodeToken derives the token of the node at a path with no wildcard -// (children, child_count), which json_tree_children and -// json_tree_child_count take. +// JSONChildren prepares a children read of a JSON field at path, a path +// with no wildcard. It returns the parent's token to bind, and what opens +// each entry eql_v4.json_tree_children returns. E is the field's entry +// type. +func JSONChildren[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, path string) (encrypt.JSONChildren[E], error) { + term, err := f.jsonTerm(ctx, c, record.JSONChildren, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + if err != nil { + return encrypt.JSONChildren[E]{}, err + } + return encrypt.NewJSONChildren[E](c, f.plan, f.name, path, term.Text[0]), nil +} + +// JSONNodeToken derives the token of the node at path, a path with no +// wildcard, for eql_v4.json_tree_child_count. operator is child_count. The +// token is a query's operand and opens nothing. So a cipher with a binding +// is refused, as [encrypt.Cipher.QueryTerm] refuses a query. +// +// A file generated by an older stashgen calls JSONNodeToken with children, +// for json_tree_children. The token is the same, so JSONNodeToken derives +// it as child_count's. Such a file is still refused through a cipher with a +// binding. Any other operator is refused. func JSONNodeToken[T any](ctx context.Context, f Field[T], c *encrypt.Cipher, operator, path string) (encrypt.JSONToken, error) { - term, err := f.jsonTerm(ctx, c, operator, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + if operator != record.JSONChildCount && operator != record.JSONChildren { + return "", fmt.Errorf("%w: gensupport: %s: %s derives no node token", encrypt.ErrEncoding, f.name, operator) + } + term, err := f.jsonTerm(ctx, c, record.JSONChildCount, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) if err != nil { return "", err } diff --git a/languages/golang/encrypt/guest/src/ops.rs b/languages/golang/encrypt/guest/src/ops.rs index d599bac8ec..e50c381aa1 100644 --- a/languages/golang/encrypt/guest/src/ops.rs +++ b/languages/golang/encrypt/guest/src/ops.rs @@ -303,18 +303,22 @@ where } /// Open the rows a read of a document field returned -/// ([`dynamic::json_open`]): a codec-encoded list per database row of the +/// ([`dynamic::json_open`]). In: a codec-encoded list of groups of the /// entries the SQL returned (`public.eql_v4_json_entry` JSON, text or /// bytes), the plan, the field's name and the codec-encoded read request -/// (`{"operation": "selector" | "subtree", "path", "wildcard_bound"?}`) in; -/// a codec-encoded list per row of JSON texts (bytes) out, which is -/// **plaintext**. The selector or the read key is derived again from the -/// request under `keyset`, which the host names as it named it to prepare -/// the read, and the rows open through that keyset only: a document sealed -/// under another is refused before any key is retrieved. One batched key -/// request for every row, sent with `audit`: the audit metadata from the -/// options object's `audit` key (see [`crate::options`]). Empty metadata -/// sends nothing. +/// (`{"operation": "selector" | "subtree" | "children", "path", +/// "wildcard_bound"?}`). Out: a codec-encoded list per group. The list is +/// **plaintext**. For `selector` and `subtree`, each list contains JSON +/// texts (bytes). For `children`, each list contains one map per child, +/// `{"key" | "index", "json"}`. +/// +/// The selector or the read key is derived again from the request under +/// `keyset`. The host names `keyset` as it named it to prepare the read. +/// The rows open through that keyset only, so a document sealed under another +/// is refused before any key is retrieved. One batched key request serves +/// every group, sent with `audit`: the audit metadata from the options +/// object's `audit` key (see [`crate::options`]). Empty metadata sends +/// nothing. pub async fn json_open( keyset: &KeysetCipher<'_, K>, rows: &Bytes, diff --git a/languages/golang/encrypt/internal/testusers/customer_stash.go b/languages/golang/encrypt/internal/testusers/customer_stash.go index 6c16c05d5c..797cf23cd3 100644 --- a/languages/golang/encrypt/internal/testusers/customer_stash.go +++ b/languages/golang/encrypt/internal/testusers/customer_stash.go @@ -199,11 +199,14 @@ func (f CustomerProfileField) Subtree(ctx context.Context, c *encrypt.Cipher, pa return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f CustomerProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f CustomerProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which @@ -442,11 +445,14 @@ func (f CustomerPrefsField) Subtree(ctx context.Context, c *encrypt.Cipher, path return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f CustomerPrefsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f CustomerPrefsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which diff --git a/languages/golang/encrypt/internal/testusers/entity_stash.go b/languages/golang/encrypt/internal/testusers/entity_stash.go index bb6cdbbe21..ce8457593b 100644 --- a/languages/golang/encrypt/internal/testusers/entity_stash.go +++ b/languages/golang/encrypt/internal/testusers/entity_stash.go @@ -186,11 +186,14 @@ func (f EntityCustomFieldValuesField) Subtree(ctx context.Context, c *encrypt.Ci return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f EntityCustomFieldValuesField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f EntityCustomFieldValuesField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which diff --git a/languages/golang/encrypt/internal/testusers/subscriber_stash.go b/languages/golang/encrypt/internal/testusers/subscriber_stash.go index 1743e8183c..44a3c12898 100644 --- a/languages/golang/encrypt/internal/testusers/subscriber_stash.go +++ b/languages/golang/encrypt/internal/testusers/subscriber_stash.go @@ -212,11 +212,14 @@ func (f SubscriberProfileField) Subtree(ctx context.Context, c *encrypt.Cipher, return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f SubscriberProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f SubscriberProfileField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which @@ -459,11 +462,14 @@ func (f SubscriberPrefsField) Subtree(ctx context.Context, c *encrypt.Cipher, pa return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f SubscriberPrefsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f SubscriberPrefsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which @@ -580,11 +586,14 @@ func (f SubscriberLabelsField) Subtree(ctx context.Context, c *encrypt.Cipher, p return gensupport.JSONSubtree[eql.JSONEntry](ctx, f.field, c, path, opts) } -// Children derives the token of the node at path, a path with no wildcard, -// which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted -// entries one level down. -func (f SubscriberLabelsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) { - return gensupport.JSONNodeToken(ctx, f.field, c, "children", path) +// Children prepares a read of the children of the node at path, a path with no +// wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). +// Pass the entries the database returns to Open. Open decrypts each one to the +// child's key or index and its value. encrypt.DecodeJSON reads a value into a +// Go type. A child with members of its own does not decrypt alone: read it with +// Subtree. +func (f SubscriberLabelsField) Children(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[eql.JSONEntry], error) { + return gensupport.JSONChildren[eql.JSONEntry](ctx, f.field, c, path) } // ChildCount derives the token of the node at path, which diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index 8de2479c16..20d6e110ac 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -16,13 +16,20 @@ import ( "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) -// JSONOpen opens the rows a read of a field that stores a JSON document -// returned (the guest's se_json_open), against the request that prepared -// the read: {"operation": "selector" | "subtree", "path", "wildcard_bound"}. -// rows holds one group per database row: for selector, the entry col -> -// selector returned, or none for SQL NULL; for subtree, the rows -// eql_v4.json_tree_subtree returned. Each entry is the -// public.eql_v4_json_entry JSON the database sent. +// JSONOpen opens the rows that a read of a JSON document field returned. +// It calls the guest's se_json_open, and checks the rows against the +// request that prepared the read. The request is +// `{"operation": "selector" | "subtree", "path", "wildcard_bound"}`. The +// rows argument has one group per database row: +// +// - for selector, the entry that `col -> selector` returned, or none for +// SQL NULL; +// - for subtree, the rows that eql_v4.json_tree_subtree returned. +// +// Each entry is the public.eql_v4_json_entry JSON the database sent. +// JSONOpen refuses a children read as [ErrEncoding]. Open a children read +// with [JSONChildren.Open]. That method returns each child's key or index +// with its value. // // The engine derives the selector or the read's key again from the request, // the field's declaration and this cipher's keyset, and checks every row @@ -43,13 +50,45 @@ import ( // of one call opens under that one binding: a read through a cipher with a // binding is a read of that binding's row. The selector or the key derives // under the scope alone, as a query's term does, so the read can be -// prepared through this cipher ([Cipher.QueryTerm] takes a binding for -// selector and subtree) or through one with the same scope and no binding. +// prepared through this cipher or through one with the same scope and no +// binding. [Cipher.QueryTerm] takes a binding for selector, subtree, and +// children. // // Opening does not prove the database returned every row the read asked // for, or rows of the database row the caller meant: see the EQL json_tree // leakage reference. func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string, request vcvalue.Object, rows [][][]byte) ([][][]byte, error) { + for _, f := range request { + if f.Key == "operation" && f.Value == record.JSONChildren { + return nil, fmt.Errorf("%w: a children read opens with JSONChildren.Open, which returns each child's key or index", ErrEncoding) + } + } + list, err := cph.jsonOpen(ctx, plan, field, request, rows) + if err != nil { + return nil, err + } + opened := make([][][]byte, len(list)) + for i, item := range list { + values, ok := item.([]any) + if !ok { + return nil, fmt.Errorf("%w: se_json_open group %d is %T", ErrInternal, i, item) + } + opened[i] = make([][]byte, len(values)) + for j, v := range values { + text, ok := v.([]byte) + if !ok { + return nil, fmt.Errorf("%w: se_json_open value %d.%d is %T", ErrInternal, i, j, v) + } + opened[i][j] = text + } + } + return opened, nil +} + +// jsonOpen calls se_json_open with the request and the rows. It returns the +// decoded list, with one item per group of rows. Each read's Open reads its +// values from that list. +func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string, request vcvalue.Object, rows [][][]byte) ([]any, error) { p, err := cph.readPlan(plan, field) if err != nil { return nil, err @@ -85,7 +124,7 @@ func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string return nil, err } // The output is plaintext: wiped once it is decoded into the caller's - // slices. + // values. defer wipe(out) decoded, err := vcffi.Unmarshal(out) if err != nil { @@ -95,22 +134,7 @@ func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string if !ok || len(list) != len(rows) { return nil, fmt.Errorf("%w: se_json_open returned %T for %d groups", ErrInternal, decoded, len(rows)) } - opened := make([][][]byte, len(list)) - for i, item := range list { - values, ok := item.([]any) - if !ok { - return nil, fmt.Errorf("%w: se_json_open group %d is %T", ErrInternal, i, item) - } - opened[i] = make([][]byte, len(values)) - for j, v := range values { - text, ok := v.([]byte) - if !ok { - return nil, fmt.Errorf("%w: se_json_open value %d.%d is %T", ErrInternal, i, j, v) - } - opened[i][j] = text - } - } - return opened, nil + return list, nil } // JSONSelector is a JSON path's selector: what `->`, `->>` and the path @@ -148,6 +172,83 @@ func (t JSONToken) Value() (driver.Value, error) { // read types print and log. It also stands in for a [Secret]. const redacted = "[redacted]" +// readKind names a prepared read's type and the operand it binds. Both are +// what [redactedRead] prints. +type readKind interface { + typeName() string + // operand is the name of what the read binds: its selector, its token, + // or its tokens. + operand() string + // counted reports whether the read prints how many tokens it binds. + // The other reads print [redacted] for their operand. + counted() bool +} + +// The kinds of prepared read: [JSONSelection], [JSONRead] and +// [JSONChildren]. +type ( + selectionRead struct{} + subtreeRead struct{} + childrenRead struct{} +) + +func (selectionRead) typeName() string { return "encrypt.JSONSelection" } +func (selectionRead) operand() string { return "selector" } +func (selectionRead) counted() bool { return false } +func (subtreeRead) typeName() string { return "encrypt.JSONRead" } +func (subtreeRead) operand() string { return "tokens" } +func (subtreeRead) counted() bool { return true } +func (childrenRead) typeName() string { return "encrypt.JSONChildren" } +func (childrenRead) operand() string { return "token" } +func (childrenRead) counted() bool { return false } + +// redactedRead is embedded in each prepared read of a JSONSearch field, and +// prints and logs it. The output names the read's type and its field. +// +// The output hides the path, because a path's keys can be a customer's +// data. The operand is a capability, so the output hides it too. A subtree +// read shows how many tokens it binds instead. A zero read prints as its +// type with nothing in it. +type redactedRead[K readKind] struct { + field string + // count is how many tokens a subtree read binds. + count int +} + +// String names the read's type and field, and hides its path and operand. +func (r redactedRead[K]) String() string { + var kind K + if r.field == "" { + return kind.typeName() + "{}" + } + return fmt.Sprintf("%s{field: %q, path: %s, %s: %s}", kind.typeName(), r.field, redacted, kind.operand(), r.operandValue()) +} + +// GoString is what %#v prints: String. +func (r redactedRead[K]) GoString() string { return r.String() } + +// Format prints String for every verb fmt hands it. +func (r redactedRead[K]) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, r.String()) } + +// LogValue is what slog records: the field, [redacted] for the path, and +// the operand as String shows it. +func (r redactedRead[K]) LogValue() slog.Value { + if r.field == "" { + return slog.GroupValue() + } + var kind K + return slog.GroupValue(slog.String("field", r.field), slog.String("path", redacted), slog.Attr{Key: kind.operand(), Value: r.operandValue()}) +} + +// operandValue is what the read shows for its operand. +func (r redactedRead[K]) operandValue() slog.Value { + var kind K + if kind.counted() { + return slog.IntValue(r.count) + } + return slog.StringValue(redacted) +} + // String hides the token: it is a capability, so it does not print. func (t JSONToken) String() string { if t == "" { @@ -250,9 +351,9 @@ type JSONRange[Q ~[]byte] struct { // scopes and no binding derives, and the entries open under the scopes and // the binding. type JSONSelection[E ~[]byte] struct { + redactedRead[selectionRead] cipher *Cipher plan *record.Plan - field string path string selector JSONSelector } @@ -261,36 +362,12 @@ type JSONSelection[E ~[]byte] struct { // selector operator on field of the record type that declaration // declares, at path. For generated code. func NewJSONSelection[E ~[]byte](c *Cipher, declaration *record.Plan, field, path, selector string) JSONSelection[E] { - return JSONSelection[E]{cipher: c, plan: declaration, field: field, path: path, selector: JSONSelector(selector)} + return JSONSelection[E]{redactedRead: redactedRead[selectionRead]{field: field}, cipher: c, plan: declaration, path: path, selector: JSONSelector(selector)} } // Selector is the selector to bind: `col -> $1::text`. func (s JSONSelection[E]) Selector() JSONSelector { return s.selector } -// String names the field and hides the path and the selector: a path's -// keys can be a customer's data. -func (s JSONSelection[E]) String() string { - if s.cipher == nil { - return "encrypt.JSONSelection{}" - } - return fmt.Sprintf("encrypt.JSONSelection{field: %q, path: %s, selector: %s}", s.field, redacted, redacted) -} - -// GoString is what %#v prints: [JSONSelection.String]. -func (s JSONSelection[E]) GoString() string { return s.String() } - -// Format prints [JSONSelection.String] for every verb fmt hands it. -func (s JSONSelection[E]) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, s.String()) } - -// LogValue is what slog records: the field, and [redacted] for the path -// and the selector. -func (s JSONSelection[E]) LogValue() slog.Value { - if s.cipher == nil { - return slog.GroupValue() - } - return slog.GroupValue(slog.String("field", s.field), slog.String("path", redacted), slog.String("selector", redacted)) -} - // Open opens the entries `col -> selector` returned, one per database row, // nil for a row where it returned SQL NULL, with one ZeroKMS request. Each // opens to the scalar it holds (Found), or for the sealed root at "$" the @@ -319,7 +396,7 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err if !entries { return make([]JSONValue, len(rows)), nil } - opened, err := s.cipher.JSONOpen(ctx, s.plan, s.field, vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: s.path}}, groups) + opened, err := s.cipher.JSONOpen(ctx, s.plan, s.field, vcvalue.Object{{Key: "operation", Value: record.JSONSelector}, {Key: "path", Value: s.path}}, groups) if err != nil { return nil, err } @@ -348,9 +425,9 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err // those of the cipher's scopes alone, and the rows open under the scopes // and the binding. type JSONRead[E ~[]byte] struct { + redactedRead[subtreeRead] cipher *Cipher plan *record.Plan - field string // input is the subtree operator's input the tokens were derived from; // opening sends it back as the read's request, unchanged. input vcvalue.Object @@ -361,38 +438,13 @@ type JSONRead[E ~[]byte] struct { // on field of the record type that declaration declares, from input, its // {"path", "wildcard_bound"?} object. For generated code. func NewJSONRead[E ~[]byte](c *Cipher, declaration *record.Plan, field string, input vcvalue.Object, tokens []string) JSONRead[E] { - return JSONRead[E]{cipher: c, plan: declaration, field: field, input: input, tokens: JSONTokens(tokens)} + return JSONRead[E]{redactedRead: redactedRead[subtreeRead]{field: field, count: len(tokens)}, cipher: c, plan: declaration, input: input, tokens: JSONTokens(tokens)} } // Tokens are the tokens to bind: // `eql_v4.json_tree_subtree(col, $1::text[], 64)`. func (r JSONRead[E]) Tokens() JSONTokens { return r.tokens } -// String names the field and counts the tokens, and hides the path and -// the tokens: a path's keys can be a customer's data, and a token is a -// capability. -func (r JSONRead[E]) String() string { - if r.cipher == nil { - return "encrypt.JSONRead{}" - } - return fmt.Sprintf("encrypt.JSONRead{field: %q, path: %s, tokens: %d}", r.field, redacted, len(r.tokens)) -} - -// GoString is what %#v prints: [JSONRead.String]. -func (r JSONRead[E]) GoString() string { return r.String() } - -// Format prints [JSONRead.String] for every verb fmt hands it. -func (r JSONRead[E]) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, r.String()) } - -// LogValue is what slog records: the field, [redacted] for the path, and -// how many tokens. -func (r JSONRead[E]) LogValue() slog.Value { - if r.cipher == nil { - return slog.GroupValue() - } - return slog.GroupValue(slog.String("field", r.field), slog.String("path", redacted), slog.Int("tokens", len(r.tokens))) -} - // Open opens the rows the read returned, one group per database row, with // one ZeroKMS request: per row, the value at each concrete path the read // named that the row has, in document order. A row with no node there @@ -422,7 +474,7 @@ func (r JSONRead[E]) Open(ctx context.Context, rows [][]E) ([][]json.RawMessage, groups[i][j] = []byte(entry) } } - request := append(vcvalue.Object{{Key: "operation", Value: "subtree"}}, r.input...) + request := append(vcvalue.Object{{Key: "operation", Value: record.JSONSubtree}}, r.input...) opened, err := r.cipher.JSONOpen(ctx, r.plan, r.field, request, groups) if err != nil { return nil, err @@ -470,6 +522,215 @@ func (r JSONRead[E]) OpenOne(ctx context.Context, entries []E) (JSONValue, error } } +// JSONChildren reads the children of one node of a JSONSearch document, +// without fetching the node's whole subtree. A field's generated Children +// method returns one. Reading takes three steps. +// +// 1. Your app calls Children with the parent's path, a path with no +// wildcard. Children derives the parent's token. A token is a value the +// database uses to find a node's entry. Deriving it asks ZeroKMS for +// nothing. +// 2. The database (EQL) runs eql_v4.json_tree_children(col, $1::text), with +// [JSONChildren.Token] as $1. In each row, it finds the parent's entry +// and returns the parent's direct children as encrypted entries. It +// never decrypts anything, and it never receives a key. +// 3. Your app passes the returned entries to [JSONChildren.Open]. The engine +// checks that each entry is a child of the parent. Then it fetches the +// data keys from ZeroKMS and decrypts each child. +// +// An entry is one encrypted node of a stored document: an object, an array, +// or a scalar. E is the column's entry type, eql.JSONEntry. +// +// A JSONChildren keeps the request it was prepared from: the field's +// declaration, the parent's path, and the cipher. Open derives the parent's +// token again from that request. So your app never relies on the database +// to say which path an entry is for. Through a cipher with a binding, the +// token derives under the cipher's scopes alone. The entries open under the +// scopes and the binding, as for a [JSONSelection]. +type JSONChildren[E ~[]byte] struct { + redactedRead[childrenRead] + cipher *Cipher + plan *record.Plan + path string + token JSONToken +} + +// NewJSONChildren builds a [JSONChildren] from token. The children operator +// of [Cipher.QueryTerm] derived that token. The read is of field, of the +// record type that declaration declares, at path. For generated code. +func NewJSONChildren[E ~[]byte](c *Cipher, declaration *record.Plan, field, path, token string) JSONChildren[E] { + return JSONChildren[E]{redactedRead: redactedRead[childrenRead]{field: field}, cipher: c, plan: declaration, path: path, token: JSONToken(token)} +} + +// Token is the parent's token. Bind it as $1 in +// `eql_v4.json_tree_children(col, $1::text)`. It is a capability, so it +// prints and logs redacted. +func (c JSONChildren[E]) Token() JSONToken { return c.token } + +// Value binds the parent's token as text, as [JSONChildren.Token] does. So +// a JSONChildren can be passed to the query where the token goes. A zero +// JSONChildren is refused, as a zero [JSONToken] is. +func (c JSONChildren[E]) Value() (driver.Value, error) { return c.token.Value() } + +// Open decrypts the entries eql_v4.json_tree_children returned for the +// token, with one ZeroKMS request for all of them. The entries can come +// from many database rows. Each entry decrypts to one [JSONChildValue]. +// That value contains the child's value as JSON text. It also contains the +// key of a member of an object, or the index of an element of an array. +// +// The database returns an object's members in a random order, so the key +// is how your app tells them apart. +// +// Open refuses an entry that is not a child of the node at the path. The +// error is [ErrEncoding], with code stack_encrypt::json_wrong_entry. Open +// checks these values that each entry stores: +// +// - The entry must have a parent tag, the tag the database finds a +// parent's children by. +// - The selector, a keyed hash of the entry's path, must be the parent's +// path extended by the child's key or index. +// - The self tag, the tag the database finds an entry by, must be the one +// the child's key or index gives under the parent's token. +// +// A child that is an object or an array with members does not decrypt +// alone. Open refuses it as [ErrEncoding], with code +// stack_encrypt::json_not_a_leaf. An altered entry gets the same code, +// because Open cannot tell the two apart. Read such a child with Subtree at +// its own path. +// +// Every entry of one call opens under the binding of the cipher the read +// was prepared through. So through a cipher with a binding, pass only the +// entries of the row that binding names. An entry encrypted under another +// binding, or under none, does not open: ZeroKMS refuses its data key. +// +// Open does not check that the database returned every child, or which row +// an entry came from. +// +// Open does not check which array element the parent is either. The tags +// are not authenticated. The database has the parent's token, so it can +// compute them. So a database that forges tags can return the children of +// $.items[0] for a read of $.items[1]. See the EQL json_tree leakage +// reference. +func (c JSONChildren[E]) Open(ctx context.Context, entries []E) ([]JSONChildValue, error) { + if c.cipher == nil { + return nil, fmt.Errorf("%w: a zero JSONChildren has no request to open against", ErrEncoding) + } + if len(entries) == 0 { + return []JSONChildValue{}, nil + } + groups := make([][][]byte, len(entries)) + for i, entry := range entries { + groups[i] = [][]byte{[]byte(entry)} + } + request := vcvalue.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: c.path}} + list, err := c.cipher.jsonOpen(ctx, c.plan, c.field, request, groups) + if err != nil { + return nil, err + } + out := make([]JSONChildValue, len(list)) + for i, item := range list { + children, ok := item.([]any) + if !ok || len(children) != 1 { + return nil, fmt.Errorf("%w: se_json_open opened %T for child %d", ErrInternal, item, i) + } + if out[i], err = jsonChildValue(children[0]); err != nil { + return nil, fmt.Errorf("%w: se_json_open child %d: %v", ErrInternal, i, err) + } + } + return out, nil +} + +// JSONChildValue is one child that [JSONChildren.Open] decrypted: its value, +// and which child of the parent it is. A member of an object has a key +// ([JSONChildValue.Key]). An element of an array has an index +// ([JSONChildValue.Index]). The key or index is encrypted with the value, +// and Open checks it. +// +// The key, the index, and the value are plaintext. The caller owns them. A +// member's key can be a customer's data, so a JSONChildValue prints and logs +// redacted. Read its parts through its methods and its JSON field. +type JSONChildValue struct { + // JSON is the child's value as JSON text: a scalar, or {} or [] for an + // empty object or array. [DecodeJSON] reads it into a Go type. + JSON json.RawMessage + + label childLabel + key string + index uint64 +} + +// childLabel says which of a JSONChildValue's key and index is set. A zero +// JSONChildValue has neither. +type childLabel uint8 + +const ( + noLabel childLabel = iota + memberKey + elementIndex +) + +// Key is the member's key and true, for a child of an object. It is "" and +// false for an element of an array. +func (v JSONChildValue) Key() (string, bool) { return v.key, v.label == memberKey } + +// Index is the element's index and true, for a child of an array. It is 0 +// and false for a member of an object. +func (v JSONChildValue) Index() (uint64, bool) { return v.index, v.label == elementIndex } + +// String hides the key, the index, and the value, since each is plaintext. +func (v JSONChildValue) String() string { + if v.label == noLabel && v.JSON == nil { + return "encrypt.JSONChildValue{}" + } + return "encrypt.JSONChildValue{" + redacted + "}" +} + +// GoString is what %#v prints: [JSONChildValue.String]. +func (v JSONChildValue) GoString() string { return v.String() } + +// Format prints [JSONChildValue.String] for every verb fmt hands it. +func (v JSONChildValue) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, v.String()) } + +// LogValue is what slog records: [redacted], never the key, the index, or +// the value. +func (v JSONChildValue) LogValue() slog.Value { return slog.StringValue(redacted) } + +// jsonChildValue reads one child as se_json_open writes it: +// {"key": string, "json": bytes} for a member, or {"index": uint64, "json": +// bytes} for an element. An error names what is wrong, never a value. +func jsonChildValue(item any) (JSONChildValue, error) { + fields, ok := item.(vcvalue.Object) + if !ok || len(fields) != 2 { + return JSONChildValue{}, fmt.Errorf("a child is %T, not a map of a key or an index and json", item) + } + var child JSONChildValue + for _, field := range fields { + switch value := field.Value.(type) { + case string: + if field.Key != "key" { + return JSONChildValue{}, fmt.Errorf("text at %q", field.Key) + } + child.label, child.key = memberKey, value + case uint64: + if field.Key != "index" { + return JSONChildValue{}, fmt.Errorf("an integer at %q", field.Key) + } + child.label, child.index = elementIndex, value + case []byte: + if field.Key != "json" { + return JSONChildValue{}, fmt.Errorf("bytes at %q", field.Key) + } + child.JSON = value + default: + return JSONChildValue{}, fmt.Errorf("a %T at %q", value, field.Key) + } + } + if child.label == noLabel || child.JSON == nil { + return JSONChildValue{}, errors.New("a child has no key or index, or no json") + } + return child, nil +} + // DecodeJSON reads JSON text a read opened, a [JSONValue]'s JSON or one // value of [JSONRead.Open], into a value of the caller's type T, with // encoding/json's rules: a number reads into a declared integer field diff --git a/languages/golang/encrypt/json_fields_test.go b/languages/golang/encrypt/json_fields_test.go index 8ea000cd7d..9312d57a95 100644 --- a/languages/golang/encrypt/json_fields_test.go +++ b/languages/golang/encrypt/json_fields_test.go @@ -14,6 +14,7 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/eql" + "github.com/cipherstash/stack/languages/golang/encrypt/gensupport" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" ) @@ -113,9 +114,6 @@ func TestACustomersFieldsDeriveEachQuery(t *testing.T) { if v, err := read.Tokens().Value(); err != nil || !strings.HasPrefix(fmt.Sprint(v), `{"`) { t.Fatalf("Tokens bind as a text[] literal: %v %v", v, err) } - if _, err := f.Children(ctx, cipher, "$.visits"); err != nil { - t.Fatal(err) - } // An ordered path's own selector is the field's at that path. pathSel, err := f.At.VisitsAt.Selector(ctx, cipher) if err != nil { @@ -151,6 +149,40 @@ func TestACustomersFieldsDeriveEachQuery(t *testing.T) { if _, err := (encrypt.JSONRead[eql.JSONEntry]{}).Tokens().Value(); !errors.Is(err, encrypt.ErrEncoding) { t.Fatalf("a zero read's tokens bind: %v", err) } + // A children read binds as its token, and a zero one binds nothing and + // opens nothing. + children, err := f.Children(ctx, cipher, "$.visits") + if err != nil { + t.Fatal(err) + } + if v, err := children.Value(); err != nil || v != string(children.Token()) || children.Token() == "" { + t.Fatalf("a children read binds as %v (%v), not its token", v, err) + } + var zero encrypt.JSONChildren[eql.JSONEntry] + if _, err := zero.Value(); !errors.Is(err, encrypt.ErrEncoding) { + t.Fatalf("a zero children read binds: %v", err) + } + if _, err := zero.Open(ctx, []eql.JSONEntry{eql.JSONEntry(`{}`)}); !errors.Is(err, encrypt.ErrEncoding) { + t.Fatalf("a zero children read opens: %v", err) + } + if fmt.Sprint(zero) != "encrypt.JSONChildren{}" || zero.LogValue().String() != "[]" { + t.Fatalf("a zero children read prints %v and logs %v", zero, zero.LogValue()) + } + // A zero child has neither a key nor an index, and prints as nothing. + var zeroChild encrypt.JSONChildValue + if _, ok := zeroChild.Key(); ok { + t.Fatal("a zero child has a key") + } + if _, ok := zeroChild.Index(); ok { + t.Fatal("a zero child has an index") + } + if fmt.Sprint(zeroChild) != "encrypt.JSONChildValue{}" { + t.Fatalf("a zero child prints %v", zeroChild) + } + // No entries open to no values without a request. + if values, err := children.Open(ctx, nil); err != nil || values == nil || len(values) != 0 { + t.Fatalf("no entries: %d values, %v", len(values), err) + } // A selection over rows with no entry opens to no value without a // request. none, err := sel.Open(ctx, make([]*eql.JSONEntry, 3)) @@ -179,7 +211,10 @@ func TestACustomersFieldsDeriveEachQuery(t *testing.T) { } // A token is a capability and a path's keys can be a customer's data: the -// read types print and log neither, under any verb or through slog. +// read types print and log neither, under any fmt verb, or through slog. A +// child a read opened is plaintext, its key included, and prints and logs +// redacted too. The three prepared reads print through one embedded type, +// each with its own name and operand. func TestJSONReadTypesPrintAndLogRedacted(t *testing.T) { c := deterministicEQLClient(t) ctx := context.Background() @@ -193,14 +228,42 @@ func TestJSONReadTypesPrintAndLogRedacted(t *testing.T) { if err != nil { t.Fatal(err) } - token, err := f.Children(ctx, cipher, "$.secretkey") + children, err := f.Children(ctx, cipher, "$.secretkey") if err != nil { t.Fatal(err) } - hidden := append([]string{"secretkey", string(sel.Selector()), string(token)}, read.Tokens()...) + for name, got := range map[string]string{ + `encrypt.JSONSelection{field: "profile", path: [redacted], selector: [redacted]}`: fmt.Sprint(sel), + `encrypt.JSONRead{field: "profile", path: [redacted], tokens: 3}`: fmt.Sprint(read), + `encrypt.JSONChildren{field: "profile", path: [redacted], token: [redacted]}`: fmt.Sprint(children), + } { + if got != name { + t.Errorf("printed %s, want %s", got, name) + } + } + // A child of $.secretkey, opened: a member whose key and value are + // both plaintext. + encrypted, err := testusers.EncryptCustomer(ctx, cipher, []testusers.Customer{{ID: 1, Profile: json.RawMessage(`{"secretkey":{"swordfishkey":"hunter2secret"}}`)}}) + if err != nil { + t.Fatal(err) + } + member, err := f.Selector(ctx, cipher, "$.secretkey.swordfishkey") + if err != nil { + t.Fatal(err) + } + entry := jsonEntry(t, []byte(encrypted[0].Profile), string(member.Selector())) + opened, err := children.Open(ctx, []eql.JSONEntry{eql.JSONEntry(entry)}) + if err != nil || len(opened) != 1 { + t.Fatalf("the child of $.secretkey: %d values, %v", len(opened), err) + } + child := opened[0] + if key, ok := child.Key(); !ok || key != "swordfishkey" || string(child.JSON) != `"hunter2secret"` { + t.Fatalf("the child opened to the key %q (%v)", key, ok) + } + hidden := append([]string{"secretkey", "swordfishkey", "hunter2secret", string(sel.Selector()), string(children.Token())}, read.Tokens()...) var logged bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logged, nil)) - for name, v := range map[string]any{"selection": sel, "read": read, "token": token, "tokens": read.Tokens()} { + for name, v := range map[string]any{"selection": sel, "read": read, "children": children, "token": children.Token(), "tokens": read.Tokens(), "child": child} { logger.Info(name, "v", v) for _, verb := range []string{"%v", "%+v", "%#v", "%s", "%q", "%x", "%d"} { out := fmt.Sprintf(verb, v) @@ -224,6 +287,36 @@ func TestJSONReadTypesPrintAndLogRedacted(t *testing.T) { } } +// A file generated before gensupport.JSONChildren derives a children token +// with JSONNodeToken. It is the token Children binds, and still a query's +// operand: refused through a cipher with a binding, as ChildCount is. +func TestAnOlderGeneratedChildrenTokenIsAQueryOperand(t *testing.T) { + c := deterministicEQLClient(t) + ctx := context.Background() + cipher := c.DefaultKeyset() + // The customer's profile field, declared as its generated file declares + // it. + declaration := gensupport.Declare("customers"). + Passthrough("id"). + EncryptInto("profile", gensupport.JSON, "JsonSearch"). + Options("profile", gensupport.TargetOptions{Ordered: []string{"$.age", "$.visits[*].at"}}) + field := gensupport.NewField[json.RawMessage](declaration, "profile") + token, err := gensupport.JSONNodeToken(ctx, field, cipher, "children", "$.visits") + if err != nil { + t.Fatal(err) + } + children, err := testusers.CustomerFields.Profile.Children(ctx, cipher, "$.visits") + if err != nil || children.Token() != token { + t.Fatalf("the older file's token is not the one Children binds: %v", err) + } + if _, err := gensupport.JSONNodeToken(ctx, field, cipher.Bind(uint64(9)), "children", "$.visits"); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("an older file's children token through a cipher with a binding: %v, want ErrEncoding", err) + } + if _, err := gensupport.JSONNodeToken(ctx, field, cipher, "selector", "$.visits"); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("a selector as a node token: %v, want ErrEncoding", err) + } +} + // subtreeLeafRow is the one row eql_v4.json_tree_subtree returns for a // read of a scalar: the scalar's entry, at depth 0 below the node its token // names. @@ -242,17 +335,19 @@ func subtreeLeafRow(t *testing.T, entry []byte) eql.JSONEntry { } // A document sealed through a cipher with a binding is read in part through -// the same cipher: Selector and Subtree prepare the read under the cipher's -// scopes alone, so their selector and tokens are those of a cipher with the -// same scopes and no binding, and open what the database returns under the -// scopes and the binding. A cipher with another binding, or none, finds the -// same entries and does not open them. A document sealed with no binding -// reads through a cipher with no binding, as before. +// the same cipher. Selector, Subtree, and Children prepare the read under +// the cipher's scopes alone. So their selector and tokens are those of a +// cipher with the same scopes and no binding. The read opens what the +// database returns under the scopes and the binding. +// +// A cipher with another binding, or none, finds the same entries and does +// not open them. A document sealed with no binding reads through a cipher +// with no binding, as before. func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { c := deterministicEQLClient(t) ctx := context.Background() f := testusers.CustomerFields.Profile - in := []testusers.Customer{{ID: 1, Profile: json.RawMessage(`{"name":"Alice","age":34}`)}} + in := []testusers.Customer{{ID: 1, Profile: json.RawMessage(`{"name":"Alice","age":34,"tags":["vip"]}`)}} const path = "$.name" // selectorRead opens the entry `col -> selector` returns through @@ -304,6 +399,36 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { return read.Tokens(), nil } + // childrenRead opens the one child json_tree_children returns for + // $.tags through cipher. + childrenRead := func(cipher *encrypt.Cipher, document []byte) (encrypt.JSONToken, error) { + t.Helper() + children, err := f.Children(ctx, cipher, "$.tags") + if err != nil { + return "", err + } + // The element's entry is the one carrying the elements' selector. + sel, err := f.Selector(ctx, cipher, "$.tags[*]") + if err != nil { + return "", err + } + entry := jsonEntry(t, document, string(sel.Selector())) + if entry == nil { + t.Fatal("the selector names no element of the document") + } + values, err := children.Open(ctx, []eql.JSONEntry{eql.JSONEntry(entry)}) + if err != nil { + return children.Token(), err + } + if len(values) != 1 || string(values[0].JSON) != `"vip"` { + t.Fatalf("the child opened %d values", len(values)) + } + if index, ok := values[0].Index(); !ok || index != 0 { + t.Fatalf("the child is not the first element: %d %v", index, ok) + } + return children.Token(), nil + } + plain := c.DefaultKeyset() for _, scoped := range []struct { name string @@ -328,6 +453,10 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { if err != nil { t.Fatalf("Subtree through the cipher that sealed the document: %v", err) } + token, err := childrenRead(bound, document) + if err != nil { + t.Fatalf("Children through the cipher that sealed the document: %v", err) + } // The operands are those of the cipher's scopes alone. unbound, err := f.Selector(ctx, scoped.cipher, path) if err != nil || unbound.Selector() != selector { @@ -345,6 +474,13 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { if _, err := f.Subtree(ctx, scoped.cipher.Bind(""), path, encrypt.JSONReadOptions{}); !errors.Is(err, encrypt.ErrEncoding) { t.Errorf("Subtree through a cipher with an empty binding: %v, want ErrEncoding", err) } + unboundChildren, err := f.Children(ctx, scoped.cipher, "$.tags") + if err != nil || unboundChildren.Token() != token { + t.Errorf("the bound cipher's children token is not its scopes' own: %v", err) + } + if _, err := f.Children(ctx, scoped.cipher.Bind(""), "$.tags"); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("Children through a cipher with an empty binding: %v, want ErrEncoding", err) + } // An ordered path's accessor prepares its selection the same way. atAge, err := f.At.Age.Selector(ctx, bound) @@ -369,11 +505,14 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { if _, err := subtreeRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { t.Errorf("%s: Subtree opened the row, or not as ErrForbidden: %v", whose, err) } + if _, err := childrenRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("%s: Children opened the child, or not as ErrForbidden: %v", whose, err) + } } // A query opens nothing, so it has no use for a binding, and a // query through a cipher with one is still refused. So is a - // node's token, which is a query's operand too. + // child count's token. That token is a query's operand too. for name, err := range map[string]error{ "Contains": func() error { _, err := f.Contains(ctx, bound, json.RawMessage(`{"name":"Alice"}`)); return err }(), "ContainedBy": func() error { _, err := f.ContainedBy(ctx, bound, json.RawMessage(`{"name":"Alice"}`)); return err }(), @@ -387,7 +526,6 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { _, err := f.Elements.Visits.Match(ctx, bound, encrypt.JSONReadOptions{}, encrypt.AtPath(testusers.CustomerPaths.Profile.Visits.At).Gt(1)) return err }(), - "Children": func() error { _, err := f.Children(ctx, bound, path); return err }(), "ChildCount": func() error { _, err := f.ChildCount(ctx, bound, path); return err }(), } { if !errors.Is(err, encrypt.ErrEncoding) { @@ -408,6 +546,12 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { if _, err := subtreeRead(scoped.cipher, plainDocument); err != nil { t.Errorf("Subtree of a document sealed with no binding: %v", err) } + if _, err := childrenRead(scoped.cipher, plainDocument); err != nil { + t.Errorf("Children of a document sealed with no binding: %v", err) + } + if _, err := childrenRead(bound, plainDocument); !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("a bound cipher's Children opened a document sealed with no binding: %v", err) + } if _, err := selectorRead(bound, plainDocument); !errors.Is(err, encrypt.ErrForbidden) { t.Errorf("a bound cipher's Selector opened a document sealed with no binding: %v", err) } diff --git a/languages/golang/encrypt/json_postgres_test.go b/languages/golang/encrypt/json_postgres_test.go index f9e2a130ac..c8fa61a99e 100644 --- a/languages/golang/encrypt/json_postgres_test.go +++ b/languages/golang/encrypt/json_postgres_test.go @@ -340,7 +340,56 @@ func TestJSONDocumentsQueryAndReadInPostgres(t *testing.T) { if err != nil { t.Fatal(err) } - want("children rows", ids(`SELECT id FROM customers, eql_v4.json_tree_children(profile, $1::text) AS e ORDER BY id`, children), 1, 1, 2) + want("children rows", ids(`SELECT id FROM customers, eql_v4.json_tree_children(profile, $1::text) AS e ORDER BY id`, children.Token()), 1, 1, 2) + + // Each child json_tree_children returns opens on its own, checked + // against the parent the read was prepared for: the one member of each + // row's first visit. A child with members of its own does not open + // alone, and another parent's children are refused. + childEntries := func(c encrypt.JSONChildren[eql.JSONEntry]) []eql.JSONEntry { + t.Helper() + rows, err := conn.QueryContext(ctx, `SELECT e FROM customers, eql_v4.json_tree_children(profile, $1::text) AS e ORDER BY id`, c.Token()) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var out []eql.JSONEntry + for rows.Next() { + var e eql.JSONEntry + if err := rows.Scan(&e); err != nil { + t.Fatal(err) + } + out = append(out, e) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return out + } + firstVisit, err := f.Children(ctx, cipher, "$.visits[0]") + if err != nil { + t.Fatal(err) + } + ats, err := firstVisit.Open(ctx, childEntries(firstVisit)) + if err != nil || len(ats) != 2 || string(ats[0].JSON) != "3" || string(ats[1].JSON) != "5" { + t.Errorf("the children of $.visits[0]: %d values, %v", len(ats), err) + } + for _, at := range ats { + if key, ok := at.Key(); !ok || key != "at" { + t.Errorf("a child of $.visits[0] opened with the key %q (%v), not at", key, ok) + } + } + var d *encrypt.Diagnostic + if _, err := children.Open(ctx, childEntries(children)); !errors.As(err, &d) || d.Code != "stack_encrypt::json_not_a_leaf" { + t.Errorf("the children of $.visits, each with a member: %v, want json_not_a_leaf", err) + } + tags, err := f.Children(ctx, cipher, "$.tags") + if err != nil { + t.Fatal(err) + } + if _, err := firstVisit.Open(ctx, childEntries(tags)); !errors.As(err, &d) || d.Code != "stack_encrypt::json_wrong_entry" { + t.Errorf("the children of $.tags opened as $.visits[0]'s: %v, want json_wrong_entry", err) + } // Sorting by an ordered path, in the form EQL documents: // ORDER BY eql_v4.ord_term(col -> sel) at a path with no array step. diff --git a/languages/golang/encrypt/json_tree_test.go b/languages/golang/encrypt/json_tree_test.go index a206ef04f9..6b693101cc 100644 --- a/languages/golang/encrypt/json_tree_test.go +++ b/languages/golang/encrypt/json_tree_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "math" "reflect" "slices" @@ -280,6 +281,172 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { } } +// A child read through the guest: each entry eql_v4.json_tree_children +// returns opens on its own against the parent the read names, to its key +// or index and its value. Another parent's child, a child with members of +// its own, and a parent path with a wildcard are refused. Cipher.JSONOpen +// refuses a children request: its values carry no key or index. +func TestJSONChildrenOpenAgainstTheirParent(t *testing.T) { + c := deterministicEQLClient(t) + ctx := context.Background() + cipher := c.DefaultKeyset() + sealed, err := cipher.Seal(ctx, jsonPlan(), []record.Source{{"profile": []byte(`{"name":"Alice","tags":["a","b"],"visits":[{"at":3},{"at":1,"where":"x"}]}`)}}) + if err != nil { + t.Fatal(err) + } + document := sealed[0]["profile"].EQL + term := func(operator, path string) string { + t.Helper() + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", operator, vcvalue.Object{{Key: "path", Value: path}}) + if err != nil { + t.Fatal(err) + } + return term.Text[0] + } + // The read of the children of the node at path, prepared as the + // generated Children prepares it. + read := func(path, token string) encrypt.JSONChildren[eql.JSONEntry] { + return encrypt.NewJSONChildren[eql.JSONEntry](cipher, jsonPlan(), "profile", path, token) + } + // The children of $.tags, of $.visits and of $.visits[1], as + // json_tree_children returns them: every entry carrying the children's + // selector. + entries := func(selector string, want int) []eql.JSONEntry { + t.Helper() + found := jsonEntries(t, document, term(record.JSONSelector, selector)) + if len(found) != want { + t.Fatalf("%s names %d entries, want %d", selector, len(found), want) + } + out := make([]eql.JSONEntry, len(found)) + for i, entry := range found { + out[i] = eql.JSONEntry(entry) + } + return out + } + // Each child as its index or key and its JSON text, sorted: the + // entries come in the document's stored order. + labelled := func(children []encrypt.JSONChildValue) []string { + var out []string + for _, child := range children { + if key, ok := child.Key(); ok { + out = append(out, fmt.Sprintf("%q: %s", key, child.JSON)) + } else if index, ok := child.Index(); ok { + out = append(out, fmt.Sprintf("[%d] %s", index, child.JSON)) + } + } + slices.Sort(out) + return out + } + tags := read("$.tags", term(record.JSONChildren, "$.tags")) + opened, err := tags.Open(ctx, entries("$.tags[*]", 2)) + if err != nil { + t.Fatal(err) + } + if got := labelled(opened); !slices.Equal(got, []string{`[0] "a"`, `[1] "b"`}) { + t.Fatalf("the children of $.tags opened %q", got) + } + second := read("$.visits[1]", term(record.JSONChildren, "$.visits[1]")) + members := append(entries("$.visits[*].at", 2), entries("$.visits[*].where", 1)...) + // Of the two at members, the one under $.visits[1] opens; the other is + // $.visits[0]'s, and is refused. + var children []encrypt.JSONChildValue + for _, entry := range members { + child, err := second.Open(ctx, []eql.JSONEntry{entry}) + if err == nil { + children = append(children, child...) + } + } + if got := labelled(children); !slices.Equal(got, []string{`"at": 1`, `"where": "x"`}) { + t.Fatalf("the children of $.visits[1] opened %q", got) + } + diagnostic := func(name string, err error, code string) { + t.Helper() + var d *encrypt.Diagnostic + if !errors.Is(err, encrypt.ErrEncoding) || !errors.As(err, &d) || d.Code != code { + t.Fatalf("%s: %v, want ErrEncoding with %s", name, err, code) + } + } + visits := read("$.visits", term(record.JSONChildren, "$.visits")) + _, err = visits.Open(ctx, entries("$.tags[*]", 2)) + diagnostic("$.tags' children under $.visits", err, "stack_encrypt::json_wrong_entry") + _, err = visits.Open(ctx, entries("$.visits[*]", 2)) + diagnostic("a child with members", err, "stack_encrypt::json_not_a_leaf") + _, err = read("$.tags[*]", "unused").Open(ctx, entries("$.tags[*]", 2)) + var d *encrypt.Diagnostic + if !errors.Is(err, encrypt.ErrEncoding) || !errors.As(err, &d) || d.Reason() != "json_path_wildcard" || d.Field() != "profile" { + t.Fatalf("a parent path with a wildcard: %v", err) + } + request := vcvalue.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: "$.tags"}} + if _, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", request, [][][]byte{{[]byte(entries("$.tags[*]", 2)[0])}}); !errors.Is(err, encrypt.ErrEncoding) || errors.As(err, &d) { + t.Fatalf("JSONOpen of a children read: %v, want ErrEncoding before the guest", err) + } +} + +// The operators that prepare a read, which a cipher with a binding prepares +// under its scopes alone, are exactly the operators the engine opens a read +// of: every operator the engine answers for a document field opens as a +// read when record.IsJSONRead names it, and is refused when it does not. +func TestTheReadOperatorsAreTheOnesTheEngineOpens(t *testing.T) { + c := deterministicEQLClient(t) + ctx := context.Background() + wasm, err := encrypt.EmbeddedGuest() + if err != nil { + t.Fatal(err) + } + checker, err := encrypt.NewCheckerOver(ctx, wasm) + if err != nil { + t.Fatal(err) + } + defer func() { _ = checker.Close() }() + operators, err := checker.Operators(ctx, jsonPlan(), "profile") + if err != nil { + t.Fatal(err) + } + reads := 0 + for _, op := range operators { + err := c.DefaultKeyset().JSONOpensForTest(ctx, jsonPlan(), "profile", op.Name, "$.name") + switch { + case record.IsJSONRead(op.Name) && err != nil: + t.Errorf("%s is a read here, and the engine does not open it: %v", op.Name, err) + case !record.IsJSONRead(op.Name) && !errors.Is(err, encrypt.ErrEncoding): + t.Errorf("%s is no read here, and the engine opens it: %v", op.Name, err) + } + if record.IsJSONRead(op.Name) { + reads++ + } + } + if reads != 3 { + t.Errorf("the engine answers %d of the three read operators: %v", reads, operators) + } +} + +// jsonEntries are the entries of a sealed document that carry selector, as +// eql_v4.json_tree_graft writes each: every element of an array shares its +// selector, so these are an array's elements, in the document's stored +// order. +func jsonEntries(t *testing.T, document []byte, selector string) [][]byte { + t.Helper() + var doc struct { + H string `json:"h"` + SV []map[string]json.RawMessage `json:"sv"` + } + if err := json.Unmarshal(document, &doc); err != nil { + t.Fatal(err) + } + var out [][]byte + for j, entry := range doc.SV { + var s string + _ = json.Unmarshal(entry["s"], &s) + if s == selector { + entry["h"], _ = json.Marshal(doc.H) + entry["j"], _ = json.Marshal(j) + row, _ := json.Marshal(entry) + out = append(out, row) + } + } + return out +} + // jsonEntry is the entry `col -> selector` returns for a sealed document, // as eql_v4.json_tree_graft writes it, or nil when no entry of the document // carries the selector. @@ -398,9 +565,9 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { }) } - // A cipher with a binding prepares a read: its selector and its subtree - // tokens derive under the scope alone, so they are the tenant's. A query, - // and a node's token, take no binding. + // A cipher with a binding prepares a read: its selector, its subtree + // tokens and its children's token derive under the scope alone, so they + // are the tenant's. A query, and a child count's token, take no binding. if got := selector(bound); got != selector(tenant) { t.Errorf("a selector through a cipher with a binding is not the tenant's") } @@ -415,7 +582,18 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { if tenantTokens, err := subtree(tenant); err != nil || !slices.Equal(boundTokens, tenantTokens) { t.Errorf("a subtree read's tokens through a cipher with a binding are not the tenant's: %v", err) } - for _, operator := range []string{"children", "child_count", "eq_at"} { + children := func(cipher *encrypt.Cipher) ([]string, error) { + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "children", vcvalue.Object{{Key: "path", Value: "$.name"}}) + return term.Text, err + } + boundToken, err := children(bound) + if err != nil { + t.Fatalf("a children read through a cipher with a binding: %v", err) + } + if tenantToken, err := children(tenant); err != nil || !slices.Equal(boundToken, tenantToken) { + t.Errorf("a children read's token through a cipher with a binding is not the tenant's: %v", err) + } + for _, operator := range []string{"child_count", "eq_at"} { input := vcvalue.Object{{Key: "path", Value: "$.name"}} if operator == "eq_at" { input = append(input, vcvalue.Field{Key: "json", Value: []byte(`"Alice"`)}) diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index e73b2948c7..2d831d8d73 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -130,10 +130,11 @@ func (l Limit) FetchOr(page uint64) uint64 { // refused: it matches no row, as SQL's BETWEEN does. // // A query through a cipher with a binding is refused as [ErrEncoding]: a -// binding is in no query context. The two operators that prepare a read of -// a document, selector and subtree, are not refused. Their operand derives -// under the cipher's scopes alone, as a query's term does, and the cipher's -// binding is used when the read opens ([Cipher.JSONOpen]). +// binding is in no query context. Three operators prepare a read of a +// document: selector, subtree, and children. A cipher with a binding does +// not refuse them. Their operand derives under the cipher's scopes alone, +// as a query's term does. The read uses the cipher's binding when it opens +// ([Cipher.JSONOpen]). // No data key is minted. For generated code. func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, operator string, input any) (QueryTerm, error) { p, err := cph.operandPlan(plan, field, operator) diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index e7ce7a3c59..6072b2e995 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -190,16 +190,17 @@ func (cph *Cipher) queryPlan(plan *record.Plan, field string) (*record.Plan, err return cph.underNamedContext(p, field) } -// operandPlan is the plan operator's operand on field derives under. A -// read's operand (selector, subtree) derives under this cipher's scopes -// alone, and its bindings are left out: the read opens what the database -// returns through the same cipher, bindings included ([Cipher.JSONOpen]). -// So a cipher with a binding prepares a read, and its operand is the one a -// cipher with the same scopes and no binding derives. Every other operator -// is a query's, which opens nothing: [Cipher.queryPlan] refuses it through -// a cipher with a binding. +// operandPlan is the plan operator's operand on field derives under. The +// operand of a read (selector, subtree, or children) derives under this +// cipher's scopes alone, with its bindings left out. The read opens what +// the database returns through the same cipher, bindings included +// ([Cipher.JSONOpen]). So a cipher with a binding prepares a read, and its +// operand is the one a cipher with the same scopes and no binding derives. +// +// Every other operator is a query's operator. A query opens nothing, so +// [Cipher.queryPlan] refuses it through a cipher with a binding. func (cph *Cipher) operandPlan(plan *record.Plan, field, operator string) (*record.Plan, error) { - if operator == "selector" || operator == "subtree" { + if record.IsJSONRead(operator) { // The copy keeps the cipher's error, so a binding part Bind refused // is reported here, before the read is prepared. scopes := cph.copy() diff --git a/languages/golang/internal/record/record.go b/languages/golang/internal/record/record.go index 7fc5e51a12..fd3d908870 100644 --- a/languages/golang/internal/record/record.go +++ b/languages/golang/internal/record/record.go @@ -664,6 +664,30 @@ const ( Probabilistic Fidelity = "probabilistic" ) +// The operators of a JSON document field that derive a node's selector or +// token. The spellings are wire format: stack-encrypt's dynamic::Op. +// +// The first three prepare a read. A read's operand derives under a cipher's +// scopes alone. se_json_open takes the operator's name as the "operation" +// of the read it opens. JSONChildCount derives the same token as +// JSONChildren, but for a query. A query opens nothing. +const ( + JSONSelector = "selector" + JSONSubtree = "subtree" + JSONChildren = "children" + JSONChildCount = "child_count" +) + +// IsJSONRead reports whether operator prepares a read of a JSON document: +// [JSONSelector], [JSONSubtree] or [JSONChildren]. +func IsJSONRead(operator string) bool { + switch operator { + case JSONSelector, JSONSubtree, JSONChildren: + return true + } + return false +} + // Operator is one operator the engine answers for a field: for an EQL type, // as se_targets lists it, and for any field of a plan, as se_operators // lists it. diff --git a/languages/golang/stashgen/emit.go b/languages/golang/stashgen/emit.go index a977c66ac5..b15e849de8 100644 --- a/languages/golang/stashgen/emit.go +++ b/languages/golang/stashgen/emit.go @@ -1402,9 +1402,9 @@ func (w *writer) jsonEntry(g genField, pathsVar string) { } if answered["children"] { w.nl() - w.b.WriteString(wrapComment("Children derives the token of the node at path, a path with no wildcard, which eql_v4.json_tree_children(col, $1::text) takes. Its rows are encrypted entries one level down.", 80)) - w.p("%sChildren(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONToken, error) {", recv) - w.p("\treturn gensupport.JSONNodeToken(ctx, f.field, c, \"children\", path)") + w.b.WriteString(wrapComment("Children prepares a read of the children of the node at path, a path with no wildcard. Bind Token() as $1 in eql_v4.json_tree_children(col, $1::text). Pass the entries the database returns to Open. Open decrypts each one to the child's key or index and its value. encrypt.DecodeJSON reads a value into a Go type. A child with members of its own does not decrypt alone: read it with Subtree.", 80)) + w.p("%sChildren(ctx context.Context, c *encrypt.Cipher, path string) (encrypt.JSONChildren[%s], error) {", recv, entry) + w.p("\treturn gensupport.JSONChildren[%s](ctx, f.field, c, path)", entry) w.p("}") } if answered["child_count"] { diff --git a/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go b/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go index 26821e83c1..e15eb2e040 100644 --- a/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go +++ b/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go @@ -174,6 +174,15 @@ type JSONSelection[E ~[]byte] struct{ _ E } func (JSONSelection[E]) Selector() JSONSelector { return "" } func (JSONSelection[E]) Open(context.Context, []*E) ([]JSONValue, error) { return nil, nil } +// JSONChildren is a prepared json_tree_children on a JSONSearch field. +type JSONChildren[E ~[]byte] struct{ _ E } + +func (JSONChildren[E]) Token() JSONToken { return "" } +func (JSONChildren[E]) Open(context.Context, []E) ([]JSONChildValue, error) { return nil, nil } + +// JSONChildValue is one child a JSONChildren read opened. +type JSONChildValue struct{ JSON json.RawMessage } + // JSONRead is a prepared subtree read on a JSONSearch field. type JSONRead[E ~[]byte] struct{ _ E } diff --git a/languages/golang/stashgen/testdata/stubsdk/encrypt/gensupport/gensupport.go b/languages/golang/stashgen/testdata/stubsdk/encrypt/gensupport/gensupport.go index bae751a8b6..722305f571 100644 --- a/languages/golang/stashgen/testdata/stubsdk/encrypt/gensupport/gensupport.go +++ b/languages/golang/stashgen/testdata/stubsdk/encrypt/gensupport/gensupport.go @@ -256,6 +256,11 @@ func JSONSubtree[E ~[]byte, T any](context.Context, Field[T], *encrypt.Cipher, s return encrypt.JSONRead[E]{}, nil } +// JSONChildren prepares json_tree_children at a path on a JSON field. +func JSONChildren[E ~[]byte, T any](context.Context, Field[T], *encrypt.Cipher, string) (encrypt.JSONChildren[E], error) { + return encrypt.JSONChildren[E]{}, nil +} + // JSONNodeToken derives the token of the node at a path. func JSONNodeToken[T any](context.Context, Field[T], *encrypt.Cipher, string, string) (encrypt.JSONToken, error) { return "", nil diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 1ce2e2930f..5af8e98297 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -9,6 +9,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Read one child of a JSON tree node** (#1677). Your app can now decrypt + one entry that `eql_v4.json_tree_children` returned, without fetching + the parent's whole subtree. + - `JsonTreeChild::from_key(&key, entry)` pairs the entry with the + `JsonSubtreeKey` of the parent's path. + - A `JsonTreeChild` decrypts into a `JsonPlaintext` for the child's + value. A `JsonTreeChild` also decrypts into a `JsonChildPlaintext` for + the value with its key or index. + - The database returns an object's members in a random order. So the key + is how your app tells the members apart. + - Decrypting checks the entry against the parent, as Stack Encrypt's + `JsonSubtreeKey::open_child` does. + - A child with members of its own does not decrypt alone. Read it + through `JsonTreeSubtree`. + - A field reference's `children(path).encrypt_keyed(&keyset)` returns + the `JsonTreeToken` to send. The call also returns the key that + decrypts what the query returns. + - The stored format and the SQL do not change. + - **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, 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 9c38aa4973..4b9b2f6c62 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -28,9 +28,9 @@ use schemars::{schema_for, JsonSchema, Schema}; use serde::{Deserialize, Serialize}; use serde_json::Value; use stack_encrypt::json::{ - JsonDocument, JsonElementsQuery, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonPlaintext, - JsonPredicateQuery, JsonQueries, JsonQuery, JsonSelector, JsonSubtree, JsonSubtreeKey, - JsonTarget, + JsonChild, JsonChildPlaintext, 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, @@ -109,11 +109,17 @@ pub struct JsonTreeDocument { /// `h`, `j`, `d`, `v` and `i` are what the extractors graft onto an entry /// they return, so that it can be opened. /// -/// An entry a query returned is the database's word and does not open on -/// its own: open the entry `->` returned through the selector that asked -/// for it ([`JsonTreeExtracted::from_selector`]), and a read's rows through -/// the key that keyed it ([`JsonTreeSubtree::from_key`]). Each checks that -/// the rows are the ones it asked for. +/// An entry a query returned comes from the database, so it does not +/// decrypt on its own. Pair it with what your app derived for the query: +/// +/// - the entry `->` returned, with the selector +/// ([`JsonTreeExtracted::from_selector`]); +/// - the entries of a subtree read, with the read's key +/// ([`JsonTreeSubtree::from_key`]); +/// - one entry `json_tree_children` returned, with the key of its parent +/// ([`JsonTreeChild::from_key`]). +/// +/// Decrypting checks that each entry is one the query asked for. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TS, JsonSchema)] #[serde(deny_unknown_fields)] pub struct JsonTreeEntry { @@ -357,6 +363,73 @@ impl JsonTreeSubtree { } } +/// One entry that `eql_v4.json_tree_children` returned, paired with the key +/// of its parent node. Decrypt it into a [`JsonPlaintext`] for the child's +/// value. Decrypt it into a [`JsonChildPlaintext`] for its key or index too. +/// +/// Reading a node's children takes three steps. +/// +/// 1. **Your app** derives the parent's token and key. A field reference's +/// `children(path).encrypt_keyed(&keyset)` returns the [`JsonTreeToken`] +/// and the [`JsonSubtreeKey`] together. The call asks ZeroKMS for +/// nothing. Your app keeps the key and sends the token. +/// 2. **The database (EQL)** runs `eql_v4.json_tree_children(doc, $1)`, +/// with the token as `$1`. The database returns the parent's direct +/// children as encrypted entries. The database never decrypts anything, +/// and it never receives a key. +/// 3. **Your app** pairs each returned entry with the key, through +/// [`from_key`](Self::from_key), and decrypts the result. Decrypting +/// checks that the entry is a child of that parent. Then it fetches the +/// data key from ZeroKMS and decrypts the child. +/// +/// [`JsonSubtreeKey::open_child`] lists what decrypting checks, and what it +/// does not. A child that has children of its own does not decrypt alone +/// ([`Error::JsonNotALeaf`]). Read it with a [`JsonTreeSubtree`] instead. +#[derive(Clone, Debug, PartialEq)] +pub struct JsonTreeChild { + entry: JsonTreeEntry, + parent: JsonSubtreeKey, +} + +impl JsonTreeChild { + /// Pairs `entry`, as the database returned it, with `key`, the key of + /// the parent's path. + pub fn from_key(key: &JsonSubtreeKey, entry: JsonTreeEntry) -> Self { + Self { + entry, + parent: key.clone(), + } + } + + /// The entry, as the database returned it. + pub fn entry(&self) -> &JsonTreeEntry { + &self.entry + } + + /// The path of the parent node that decrypting checks the entry + /// against. + pub fn parent_path(&self) -> &JsonPath { + self.parent.path() + } + + /// The one way a child decrypts, into either plaintext: the entry, with + /// the header and slot the database added, paired with the parent's + /// key. + fn decryption_into( + self, + context: RequiredContext, + ) -> Decryption + where + T: zeroize::Zeroize + 'static, + JsonChild: DecryptSource>, + { + match self.entry.node() { + Ok(node) => DecryptSource::decryption(self.parent.open_child(node), context), + Err(error) => Decryption::failed(error), + } + } +} + macro_rules! json_tree_domain_type { ($ty:ident, $sql:literal) => { impl DomainType for $ty { @@ -716,6 +789,35 @@ impl DecryptSource for JsonTreeExtracted { } } +/// Decrypts the child to its value and its key or index. All three are +/// wiped when they are dropped. +/// +/// The context is required. The context must be the one the document was +/// encrypted under. An entry with no parent tag is refused before any key +/// is fetched. So is a key for a path with a wildcard. +impl DecryptSource for JsonTreeChild { + type ContextInput = RequiredContext; + fn decryption( + self, + context: Self::ContextInput, + ) -> Decryption { + self.decryption_into(context) + } +} + +/// Decrypts the child to its value alone. The value is wiped when it is +/// dropped. This decryption runs the same checks as a +/// [`JsonChildPlaintext`] does. Then it wipes the key or index. +/// +/// The context is required. The context must be the one the document was +/// encrypted under. +impl DecryptSource for JsonTreeChild { + type ContextInput = RequiredContext; + fn decryption(self, context: Self::ContextInput) -> Decryption { + self.decryption_into(context) + } +} + /// The rows of a read open to the value at its path, as a /// [`JsonPlaintext`], which is wiped when it is dropped. No node at the /// path is an error: open as an `Option` to read that as diff --git a/packages/eql/docs/reference/json-tree-leakage.md b/packages/eql/docs/reference/json-tree-leakage.md index 4389f2a8ad..78ecf6727e 100644 --- a/packages/eql/docs/reference/json-tree-leakage.md +++ b/packages/eql/docs/reference/json-tree-leakage.md @@ -77,11 +77,12 @@ The consequence to design around: tampering with the unauthenticated fields chan - **`->`.** The entry must carry the selector the client derived for the path. Another path's entry, such as the row's `$.bonus` returned for `$.salary`, is refused, and so is the sealed root returned for a field (it opens to the whole document); the root is accepted only when `$` itself was asked for. A container with children does not open alone, since its AAD covers tags `->` does not return; the client reports that the entry did not open as a leaf (`JsonNotALeaf`), which is also what an altered entry looks like through `->`, since nothing outside the ciphertext says which it was; a container's value is read with a subtree read. - **A subtree read.** The node each token names, returned at depth 0, must carry that path's selector and, in its decrypted label, the key or position the path ends in (the root, for `$`): nothing above it is read, so these checks are all that place it. Beneath it the cascade places every row. The client also refuses, before the cipher is asked, rows of two documents and an entry returned twice; and after it, a row no token's subtree reaches, a depth the server reports that is not the one the chain gives the row, and a child whose self tag fits neither the member nor the element rule, or not the one its decrypted label names. The self tags and parent tags are not authenticated, and the database holds every token a read sends and every row's `iv`, so it can write any tag it likes: the tags say where to try each row, and the cipher decides. A read of a wildcard whose array is longer than the bound fails rather than return part of the list, both when the rows are walked and when they fall back to the sealed root. +- **A child read.** The client checks each entry `json_tree_children` returns against the path whose token it sent. The entry must have a parent tag. The entry's selector must be that path extended by its decrypted key or index. The entry's self tag must be the one that key or index gives under the parent's token. A depth the database reports must be one. The entry decrypts to its key or index and its value, so the key says which member it is, whatever order the rows come in. A child with children of its own does not decrypt alone (`JsonNotALeaf`). Nothing above the parent is read. So where the parent sits is the database's word, as it is for the node at the top of a subtree read. What the checks do not cover, by design: - **Which row an entry comes from.** Nothing in an entry names its row, so another row's `$.salary`, returned with that row's header, opens; that is the rule every EQL stored value follows (ADR 0010). -- **Which element the node at the top of a read sits under.** Every element of an array shares its selector, and nothing the node binds says which element it belongs to, so a read of `$.items[1].price` can be answered with `$.items[0].price` of the same row (its self tag rewritten), and opens to that element's price. Beneath the top of a read the cascade rules this out; at the top, ruling it out would mean checking the node against its ancestors, which the read does not return. +- **Which element the node at the top of a read sits under.** Every element of an array shares its selector, and nothing the node binds says which element it belongs to, so a read of `$.items[1].price` can be answered with `$.items[0].price` of the same row (its self tag rewritten), and opens to that element's price. A child read of `$.items[1]` can be answered with the children of `$.items[0]` the same way. Beneath the top of a read the cascade rules this out; at the top, ruling it out would mean checking the node against its ancestors, which the read does not return. - **Which nodes a row holds.** Nothing in a row says how many nodes a read should find, so a database can withhold rows: a read answered with none opens as no node at the path (`None`), and a wildcard read answered with some elements' rows left out opens to the rest. That includes a probe's rows, so an array longer than the bound can open as its first `N` elements instead of failing. A node it does return comes with its whole subtree or is refused. A query's result is not integrity-protected as a whole: each decrypted value is genuine, at a path with the selector asked for and with everything beneath it as sealed, but which row it came from, under which element, and whether anything was left out, is the database's word. diff --git a/packages/eql/docs/reference/json-tree.md b/packages/eql/docs/reference/json-tree.md index 4ce81d8d49..9ed303a97e 100644 --- a/packages/eql/docs/reference/json-tree.md +++ b/packages/eql/docs/reference/json-tree.md @@ -234,6 +234,41 @@ chain from nothing. Do not convert NULL to `0`. The count is a count of stored entries: it is not an authenticated proof that no child was withheld. +### Reading one child + +Your app can read one level of a document without fetching the parent's +whole subtree. It takes three steps. + +1. **Your app** derives the parent node's token and key from the parent's + path, through the SDK. A token is a value the database uses to find a + node's entry. Deriving it asks ZeroKMS for nothing. Your app keeps the + key and sends the token. +2. **The database (EQL)** runs `eql_v4.json_tree_children(e, $1::text)`, + with the token as `$1`. In each row, it finds the parent's entry and + returns the parent's direct children as encrypted entries. It never + decrypts anything, and it never receives a key. +3. **Your app** passes each returned entry to the SDK, with the parent's + key. The SDK checks that the entry is a child of that parent. Then it + fetches the data key from ZeroKMS and decrypts the child. + +Each child decrypts to its value. Your app can also get the child's key, +for a member of an object, or its index, for an element of an array. The +key or index is encrypted with the value, so the check covers it too. The +database returns an object's members in a random order, so the key is how +your app tells them apart. + +The SDK checks two values stored in each entry: + +- The selector, a keyed hash of the entry's path, must be the parent's + path extended by the child's key or index. +- The self tag, the tag the database finds an entry by, must be the one + the child's key or index gives under the parent's token. + +A scalar child decrypts to the scalar. An empty object or array decrypts +to `{}` or `[]`. A child with members of its own does not decrypt alone, +because its ciphertext is sealed over its children's. Read it with a +subtree read of its own path. + ## One array element, and a whole predicate Two containment needles, or two comparisons, on one array can be @@ -252,11 +287,6 @@ why no index serves it. ## What the SQL cannot do -- **Open a child bound to its parent.** The SQL returns children, but - opening one child scalar so that it is checked against its parent is - not implemented. To inspect one child, the client fetches the parent's - subtree and opens it. That transfers more data, and reveals a different - set of tokens. - **Return plaintext of every match.** `json_tree_path_query` returns encrypted entries. The supported way to grouped plaintext for a path through an array is a subtree read with a wildcard bound. diff --git a/packages/eql/tests/encryption/tests/json_tree.rs b/packages/eql/tests/encryption/tests/json_tree.rs index eb316e2b26..a4d85063d7 100644 --- a/packages/eql/tests/encryption/tests/json_tree.rs +++ b/packages/eql/tests/encryption/tests/json_tree.rs @@ -20,15 +20,15 @@ mod common; use eql_bindings::encryption::EqlTargets; use eql_bindings::v4::json_tree::{ - JsonTree, JsonTreeDocument, JsonTreeEntry, JsonTreeExtracted, JsonTreeLeafQuery, JsonTreeQuery, - JsonTreeSubtree, + JsonTree, JsonTreeChild, JsonTreeDocument, JsonTreeEntry, JsonTreeExtracted, JsonTreeLeafQuery, + JsonTreeQuery, JsonTreeSubtree, }; use eql_bindings::Identifier; use serde_json::{json, Map, Value}; use stack_encrypt::dynamic::{self, record, Op, Operand, ValueFrame}; use stack_encrypt::json::{ - JsonDocument, JsonLeafQuery, JsonOptions, JsonPath, JsonPlaintext, JsonQuery, JsonSelector, - JsonSubtreeKey, Segment, + JsonChildPlaintext, JsonDocument, JsonLeafQuery, JsonOptions, JsonPath, JsonPlaintext, + JsonQuery, JsonSelector, JsonSubtreeKey, Segment, }; use stack_encrypt::target::{json_document, Borrowed, CallerContext}; use stack_encrypt::{AsProtectedRef as _, DecryptFrom, Label, NonEmpty}; @@ -197,6 +197,41 @@ async fn read_list( .map(|opened| opened.iter().map(|value| value.value().clone()).collect()) } +/// What one entry `json_tree_children` returned opens to under the column, +/// through the key of its parent's path. +async fn open_child( + cipher: &Cipher, + parent: &JsonSubtreeKey, + entry: JsonTreeEntry, +) -> Result { + JsonChildPlaintext::decrypt_from_with_context( + JsonTreeChild::from_key(parent, entry), + cipher, + column(), + ) + .await + .map(|opened| Child::of(&opened)) +} + +/// An opened child: an object's member by its key, or an array's element +/// by its index, with its value. +#[derive(Clone, Debug, PartialEq)] +enum Child { + Member(String, Value), + Element(u64, Value), +} + +impl Child { + fn of(opened: &JsonChildPlaintext) -> Self { + let value = opened.value().clone(); + match (opened.key(), opened.index()) { + (Some(key), None) => Child::Member(key.to_owned(), value), + (None, Some(index)) => Child::Element(index, value), + other => panic!("a child has a key or an index, not {other:?}"), + } + } +} + /// Padded standard base64, as the wire spells a selector. /// A projection with every list sorted: `q` as the sets `jsonb @>` reads. fn as_set(q: &Value) -> Value { @@ -301,6 +336,101 @@ async fn a_document_round_trips_through_the_typed_target() { assert!(extract(&cipher, &hello, bare).await.is_err()); } +/// An entry lifted from the stored document as `json_tree_children` returns +/// it (the header, its slot and depth 1 grafted) opens on its own through +/// the key of its parent's path, and is refused under another parent's. +#[tokio::test] +async fn a_child_opens_through_the_key_of_its_parent() { + let (cipher, calls) = common::cipher().await; + let stored = seal(&cipher, &fixture()).await; + let keyset = cipher.default_keyset(); + let key = |path: &str| { + let path = JsonPath::parse(path).unwrap(); + let keyset = keyset.clone(); + async move { + keyset + .json_subtree_key(&path, &options(), column()) + .await + .unwrap() + } + }; + // `$.nested.deep` is the one entry carrying its selector. + let deep = keyset + .json_selector(&JsonPath::parse("$.nested.deep").unwrap(), column()) + .await + .unwrap(); + let at = stored + .sv + .iter() + .position(|e| serde_json::to_value(&e.s).unwrap() == json!(deep.to_string())) + .expect("the document has $.nested.deep"); + let mut entry = stored.sv[at].clone(); + entry.h = Some(stored.h.clone()); + entry.j = Some(at as u64); + entry.d = Some(1); + entry.i = Some(stored.i.clone()); + entry.v = Some(stored.v); + + let nested = key("$.nested").await; + let child = JsonTreeChild::from_key(&nested, entry.clone()); + assert_eq!(child.entry(), &entry, "the entry as the server sent it"); + assert_eq!( + child.parent_path().to_string(), + "$.nested", + "the parent it is checked against" + ); + let opened = open_child(&cipher, &nested, entry.clone()).await.unwrap(); + assert_eq!( + opened, + Child::Member("deep".into(), json!("constant")), + "the child's key and value" + ); + + let alone = JsonPlaintext::decrypt_from_with_context( + JsonTreeChild::from_key(&nested, entry.clone()), + &cipher, + column(), + ) + .await + .unwrap(); + assert_eq!( + alone.value(), + &json!("constant"), + "the child's value alone, after the same checks" + ); + + let hello = key("$.hello").await; + let refused = open_child(&cipher, &hello, entry.clone()).await; + assert!( + matches!(refused, Err(stack_encrypt::Error::JsonWrongEntry { .. })), + "a child of another node: {refused:?}" + ); + let refused_alone = JsonPlaintext::decrypt_from_with_context( + JsonTreeChild::from_key(&hello, entry.clone()), + &cipher, + column(), + ) + .await; + assert!( + matches!( + refused_alone, + Err(stack_encrypt::Error::JsonWrongEntry { .. }) + ), + "a child of another node, decrypted to its value alone: {refused_alone:?}" + ); + let retrieved = calls.lock().unwrap().retrieve.len(); + let bare = stored.sv[at].clone(); + assert!( + open_child(&cipher, &nested, bare).await.is_err(), + "an entry with no header or slot does not open" + ); + assert_eq!( + calls.lock().unwrap().retrieve.len(), + retrieved, + "the bare entry retrieved no key" + ); +} + #[tokio::test] async fn the_query_operands_are_the_engines_terms_in_the_sql_contract() { let (cipher, _) = common::cipher().await; @@ -1787,6 +1917,158 @@ fn postgres_every_subtree_read_answers_as_jsonb_does() { ); } +/// The entries `json_tree_children(doc, token)` returns in row `id` for the +/// token of `key`, in the order the SQL returns them. +fn children_rows( + db: &mut postgres::Client, + table: &str, + id: i32, + key: &JsonSubtreeKey, +) -> Vec { + db.query( + &format!("SELECT e::jsonb::text FROM {table}, eql_v4.json_tree_children(doc, $1::text) e WHERE id = $2"), + &[&key.tokens()[0], &id], + ) + .unwrap_or_else(|error| panic!("{table} {}: {error}", key.path())) + .iter() + .map(|r| serde_json::from_str(&r.get::<_, String>(0)).unwrap()) + .collect() +} + +/// Needs an EQL v4 installation. Every entry `json_tree_children` returns +/// for a node's token opens on its own through the key of the node's path, +/// to the value `jsonb` holds there: an array's elements in position +/// order, an object's members in any order. A child with children of its +/// own does not open alone ([`stack_encrypt::Error::JsonNotALeaf`]) and is +/// read with a subtree read. Every node of every document of the read +/// oracle is a parent here, with the root sealed and open; the sealed root +/// has no children to return. An array's elements opened against the key +/// of another array that holds them too (`$.l` for `$.h.l`) are refused. +#[test] +#[ignore = "requires EQL_TEST_DATABASE_URL pointing to an EQL v4 database"] +fn postgres_each_child_opens_against_its_parent() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let (cipher, _) = wait(&runtime, common::cipher()); + let keyset = cipher.default_keyset(); + let mut db = connect(); + let documents = read_documents(); + // The wide object's members are scalars, with no children: its own + // path reads all 300 of them. + let mut paths: Vec = documents + .iter() + .flat_map(node_paths) + .filter(|p| !matches!(p.segments(), [Segment::Key(w), Segment::Key(_)] if w == "wide")) + .collect(); + paths.sort(); + paths.dedup(); + // What a child opens to: its value, or `None` for a container with + // children, which does not open alone. + let leaf = |value: &Value| match value { + Value::Object(members) if !members.is_empty() => None, + Value::Array(items) if !items.is_empty() => None, + other => Some(other.clone()), + }; + // What a child opens to: its key or index with its value, or `None`. + let member = |(key, value): (&String, &Value)| { + leaf(value).map(|value| Child::Member(key.clone(), value)) + }; + let element = |(index, value): (usize, &Value)| { + leaf(value).map(|value| Child::Element(index as u64, value)) + }; + let mut opened = [0usize; 2]; + for sealed_root in [true, false] { + let options = JsonOptions { + sealed_root, + ..JsonOptions::default() + }; + let table = if sealed_root { + "json_tree_children_sealed" + } else { + "json_tree_children_open" + }; + store(&mut db, &runtime, &cipher, table, &options, &documents); + let key = |path: &JsonPath| { + wait(&runtime, keyset.json_subtree_key(path, &options, column())).unwrap() + }; + for path in &paths { + let parent = key(path); + for id in 1..=documents.len() as i32 { + let at = format!("{table} {path}, row {id}"); + let rows = children_rows(&mut db, table, id, &parent); + if sealed_root && path.segments().is_empty() { + assert!( + rows.is_empty(), + "{at}: the sealed root's members chain from nothing" + ); + continue; + } + let plain = jsonb_first(&mut db, table, id, path); + let mut expected: Vec> = match &plain { + Some(Value::Array(items)) => items.iter().enumerate().map(element).collect(), + Some(Value::Object(members)) => members.iter().map(member).collect(), + _ => Vec::new(), + }; + let mut got: Vec> = rows + .into_iter() + .map( + |entry| match wait(&runtime, open_child(&cipher, &parent, entry)) { + Ok(value) => { + opened[0] += 1; + Some(value) + } + Err(stack_encrypt::Error::JsonNotALeaf) => { + opened[1] += 1; + None + } + Err(error) => panic!("{at}: {error}"), + }, + ) + .collect(); + // An object's members come back in the random order their + // ordinals were drawn in, each with its key. A member with + // children does not open, so its key is not known: those + // are compared by count. + if matches!(plain, Some(Value::Object(_))) { + expected.sort_by_key(|child| format!("{child:?}")); + got.sort_by_key(|child| format!("{child:?}")); + } + assert_eq!( + got, expected, + "{at}: each child opens to its key or index and its value" + ); + } + } + + // `$.l`'s elements, offered as `$.h.l`'s: each carries `$.l[*]`'s + // selector, not `$.h.l[*]`'s, and is refused, or does not open + // alone if it has children of its own. + let (outer, inner) = ( + key(&JsonPath::parse("$.l").unwrap()), + key(&JsonPath::parse("$.h.l").unwrap()), + ); + let rows = children_rows(&mut db, table, 1, &outer); + assert!(!rows.is_empty(), "{table}: row 1 has elements at $.l"); + for entry in rows { + let refused = wait(&runtime, open_child(&cipher, &inner, entry)); + assert!( + matches!( + refused, + Err(stack_encrypt::Error::JsonWrongEntry { .. } + | stack_encrypt::Error::JsonNotALeaf) + ), + "{table}: a child of $.l under $.h.l: {refused:?}" + ); + } + } + assert!( + opened.iter().all(|n| *n > 0), + "the corpus opens children and refuses containers with children: {opened:?}" + ); +} + /// Whether a read of `pattern` at `bound` over `value` finds an array longer /// than the bound at a wildcard level it reaches, which is when one of its /// probes names a node. 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 6cc7676472..9eb5d03a6d 100644 --- a/packages/eql/tests/encryption/tests/json_tree_field_references.rs +++ b/packages/eql/tests/encryption/tests/json_tree_field_references.rs @@ -27,12 +27,13 @@ use std::num::NonZeroU32; use eql_bindings::encryption::EqlTargets; use eql_bindings::v4::json_tree::{ - JsonTreeDocument, JsonTreeElementsQuery, JsonTreeLeafQuery, JsonTreePredicateQuery, - JsonTreeQuery, JsonTreeSelector, JsonTreeToken, + JsonTreeChild, JsonTreeDocument, JsonTreeElementsQuery, JsonTreeLeafQuery, + JsonTreePredicateQuery, JsonTreeQuery, JsonTreeSelector, JsonTreeToken, }; +use eql_bindings::Identifier; use serde_json::{json, Value}; use stack_encrypt::dynamic::{self, record, ValueFrame}; -use stack_encrypt::json::{JsonDocument, JsonPlaintext, JsonQuery}; +use stack_encrypt::json::{JsonChildPlaintext, JsonDocument, JsonPlaintext, JsonQuery}; use stack_encrypt::sem::TermError; use stack_encrypt::target::{DecryptSource, EncryptTarget}; use stack_encrypt::{AsProtectedRef as _, DecryptFrom, EncryptInto, Error, KeysetCipher}; @@ -220,6 +221,64 @@ async fn the_plans_json_query_example_runs() { assert_eq!(opened.profile.value(), &profile()); } +/// `children(path).encrypt_keyed` gives the token `encrypt` gives, to +/// bind, with the key that holds it, which opens each entry +/// `json_tree_children` returns for that token to its key and value. +#[tokio::test] +async fn the_children_token_comes_with_the_key_that_opens_each_child() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedCustomer = Customer { + profile: profile().into(), + } + .encrypt_into(&keyset) + .await + .unwrap(); + let (token, key): (JsonTreeToken, _) = EncryptedCustomer::PROFILE + .children("$.visits[0]") + .encrypt_keyed(&keyset) + .await + .unwrap(); + let alone: JsonTreeToken = EncryptedCustomer::PROFILE + .children("$.visits[0]") + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(token, alone, "the token encrypt derives"); + assert_eq!( + serde_json::to_value(&token).unwrap(), + json!(key.tokens()[0]), + "the key holds the token sent" + ); + // The entries `json_tree_children(profile, token)` returns: each child + // of the token's node, with the document's header, its slot and its + // 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 mut entry = document.sv[slot].clone(); + entry.h = Some(document.h.clone()); + entry.j = Some(slot as u64); + entry.d = Some(1); + entry.i = Some(document.i.clone()); + entry.v = Some(document.v); + let child = JsonChildPlaintext::decrypt_from_with_context( + JsonTreeChild::from_key(&key, entry), + &keyset, + Identifier::for_column("customers", "profile").unwrap(), + ) + .await + .unwrap(); + members.push((child.key().unwrap().to_owned(), child.value().clone())); + } + members.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!( + members, + [("at".into(), json!(15)), ("place".into(), json!("home"))], + "each member of the first visit, with its key" + ); +} + /// Every field query derives the operand the data plan derives for the /// same declaration, with the path typed or as text. #[tokio::test] diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index b99eb690b6..17d1861ef9 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Read one child of a JSON node, checked against its parent** (#1677). + Your app can now read one level of a document without fetching the + parent's whole subtree. The read takes three steps. + 1. Your app derives the parent's token and key, for example with + `children(path).encrypt_keyed(&keyset)`. Deriving asks ZeroKMS for + nothing. + 2. The database (EQL) runs `eql_v4.json_tree_children(doc, $1)` with the + token. The database returns the parent's direct children as encrypted + entries. + 3. Your app passes each entry to `JsonSubtreeKey::open_child(node)`, and + decrypts the `JsonChild` it gets back. + + More detail: + + - A `JsonChild` decrypts into a `JsonPlaintext` for the child's value + alone. A `JsonChild` also decrypts into a `JsonChildPlaintext` for the + value with the member's `key()` or the element's `index()`. + - The database returns an object's members in a random order. So use + `JsonChildPlaintext` when your app needs to know which member a value + is. + - The key or index is encrypted with the value, and authenticated. The + key, the index, and the value are wiped on drop. `Debug` hides all + three. + - Decrypting checks the entry's link to its parent, as a subtree read + does. The entry must have a parent tag and sit one level down. The + entry's selector must be the parent's path extended by its key or + index. The entry's self tag must be the one that key or index gives + under the parent's token. + - An entry that fails a check is `Error::JsonWrongEntry`. A child with + children of its own does not decrypt alone (`Error::JsonNotALeaf`). + - Two refusals come before any key is fetched. A key for a path with a + wildcard is `Error::Input`, with reason `JsonPathWildcard`. An entry + with no parent tag is `JsonWrongEntry`. + - For a `JsonDocument` field, the field reference's `children(path)` + returns the key, so the token sent and the key are one value. For a + field of another type, `children(path).encrypt_keyed` returns the + token and the key from one derivation. + - `dynamic::json_open` takes the operation `"children"`, with the + parent's path and one entry or none per group. Each child opens to a + map: `{"key", "json"}` for a member, or `{"index", "json"}` for an + element. `dynamic::check_json_open` checks the request. + - The stored format is unchanged. + - **A credential with each call** (#1708). A server that decrypts as the end user who signed in had to build its cipher inside the first request, because `init` needs a token and a server starting up has no user. It also diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index 8dd8ea24c3..b6d2c0fe75 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -220,19 +220,25 @@ pub enum Error { help("A wildcard read expands to the positions below its bound and fails when an array is longer, so it never returns part of the answer. Derive the key with a larger bound (`json_subtree_key_with_bound`), or read the array itself.") )] JsonWildcardTruncated { bound: u32 }, - /// The JSON index entry `->` returned did not open on its own. An entry - /// opens alone only if it is a scalar, an empty container or the sealed - /// root: a container with children is sealed over its children's - /// ciphertexts, which `->` does not return. So the path named a container - /// with children, which is read with a subtree read - /// ([`KeysetCipher::json_subtree_key`](crate::KeysetCipher::json_subtree_key)), - /// or the entry was altered, or sealed under another key or column. The - /// client cannot tell which before the entry opens, so this names both - /// and claims neither. + /// A JSON entry that `->` or `json_tree_children` returned did not + /// decrypt on its own. + /// + /// An entry decrypts alone only if it is a scalar, an empty container, + /// or the sealed root. A container with children is sealed over + /// its children's ciphertexts, and neither query returns those. So one + /// of two things happened: + /// + /// - The path or the child is a container with children. Read it with + /// a subtree read + /// ([`KeysetCipher::json_subtree_key`](crate::KeysetCipher::json_subtree_key)). + /// - The entry was altered, or encrypted under another key or column. + /// + /// Your app cannot tell which before the entry decrypts, so this error + /// names both. #[error("the JSON index entry at the path did not open on its own")] #[diagnostic( code(stack_encrypt::json_not_a_leaf), - help("If the path names an object or an array with members, read it with a subtree read (`json_subtree_key`): `->` returns one entry, and a container's entry is sealed over its children. If the path names a scalar, the entry was altered, or sealed under another key or column.") + help("If the path names an object or an array with members, read it with a subtree read (`json_subtree_key`). `->` and `json_tree_children` return one entry for a node, and a container's entry is sealed over its children. If the path names a scalar, the entry was altered, or encrypted under another key or column.") )] JsonNotALeaf, /// ZeroKMS returned a different number of keys than were requested. diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index b9130fec12..6838db9718 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -185,10 +185,13 @@ //! prepared the read: the operator, the path and the bound. The engine //! derives the selector or the read key again from that request, the //! field's definition and the keyset, and checks every row against it with -//! the index's own checks ([`JsonSelector::open`], -//! [`JsonSubtreeKey::open`](crate::json::JsonSubtreeKey::open)). The rows -//! never say which path they are for. Each group of rows is one database -//! row's, and opens on its own: entries of two documents are never one walk. +//! the index's own checks: [`JsonSelector::open`], +//! [`JsonSubtreeKey::open`](crate::json::JsonSubtreeKey::open), and +//! [`JsonSubtreeKey::open_child`](crate::json::JsonSubtreeKey::open_child). +//! For a `children` read, each entry must be a child of the node at the +//! request's path. The rows never say which path they are for. Each group +//! of rows opens on its own, so entries of two documents are never one +//! walk. //! //! What opening proves is limited, as the index documents: a row of the //! column other than the one asked for can answer, an element under one @@ -199,7 +202,9 @@ use serde::de::{self, Deserializer, Visitor}; use serde::Deserialize; use serde_json::Value; -use vitaminc_protected::Protected; +use vitaminc_aead::plaintext::visit_map; +use vitaminc_aead::Sink; +use vitaminc_protected::{Controlled, Protected}; use zeroize::Zeroizing; use super::query::{Op, Operand}; @@ -209,8 +214,11 @@ 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::json::{parse_text, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSubtreeKey}; -use crate::{DecryptFrom, KeysetCipher, Pending}; +use crate::json::{ + parse_text, ChildLabel, JsonChildPlaintext, JsonNode, JsonOptions, JsonPath, JsonPlaintext, + JsonSubtreeKey, +}; +use crate::{DecryptFrom, Encrypt, KeysetCipher, Pending}; /// The SQL type a JSON operand binds as. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -602,11 +610,13 @@ struct Groups(Vec>); enum Read { Selector(JsonPath), Subtree(JsonPath, u32), + /// `children`: the parent's path. The path names one node. + Child(JsonPath), } -/// Read and check a read's request and its rows: everything [`open`] -/// refuses before it derives anything. A selector's group holds one entry -/// or none. +/// Reads and checks a read's request and its rows: everything [`open`] +/// refuses before it derives anything. A `selector` group and a `children` +/// group each contain one entry or none. fn read_open(request: &ValueFrame, rows: &ValueFrame) -> Result<(Read, Vec>), Error> { let request: ReadRequest = read_frame(request)?; let read = match Op::parse(&request.operation) { @@ -619,6 +629,9 @@ fn read_open(request: &ValueFrame, rows: &ValueFrame) -> Result<(Read, Vec { + Read::Child(node_path(&request.path)?) + } _ => return Err(Error::bad_source(Reason::JsonInput)), }; let groups: Groups = read_frame(rows)?; @@ -633,7 +646,7 @@ fn read_open(request: &ValueFrame, rows: &ValueFrame) -> Result<(Read, Vec, _>>()?; - if matches!(read, Read::Selector(_)) && groups.iter().any(|group| group.len() > 1) { + if !matches!(read, Read::Subtree(..)) && groups.iter().any(|group| group.len() > 1) { return Err(Error::bad_source(Reason::JsonInput)); } Ok((read, groups)) @@ -648,7 +661,8 @@ pub(super) fn check_open(request: &ValueFrame, rows: &ValueFrame) -> Result<(), } /// What a read opens with: the selector or the subtree key, derived again -/// from the request. +/// from the request. A `children` read opens with its parent's key +/// instead ([`open_children`]). enum Opener { Selector(crate::json::JsonSelector), Subtree(JsonSubtreeKey), @@ -660,26 +674,29 @@ enum Opener { /// sealed under another is refused before any key is retrieved. The /// selector or the read key derives under the field's query context, and /// every entry opens under its stored context, so under the plan's -/// bindings too. Each -/// group of rows is one database row's: for `selector`, the entry `->` -/// returned or none (SQL `NULL`); for `subtree`, the rows -/// `json_tree_subtree` returned. Every group opens to a list of JSON -/// texts: for `selector`, the scalar or none, and for `subtree`, one value -/// per concrete path the read named that the row has, in document order. -/// One key request for every group. +/// bindings too. [`json_open`](super::json_open) lists what each group +/// contains, and what each group opens to. One key request serves every +/// group. /// /// # Errors /// -/// [`Error::Source`] ([`Reason::JsonInput`]) for a request or rows that -/// do not parse, an operation that is not `selector` or `subtree`, a -/// `wildcard_bound` on a `selector`, or a selector group of more than one -/// entry; [`Error::Cipher`] for the read's own refusals (a path that does -/// not parse, a wildcard that expands too far). A row that is not the one -/// the read asked for fails the pending -/// ([`crate::Error::JsonWrongEntry`]), as does a wildcard read of an array -/// longer than the bound ([`crate::Error::JsonWildcardTruncated`]). A -/// `selector` entry that does not open alone, a container with members or -/// an altered entry, is [`crate::Error::JsonNotALeaf`]. +/// [`Error::Source`] with [`Reason::JsonInput`] for: +/// +/// - a request or rows that do not parse; +/// - an operation that is not `selector`, `subtree`, or `children`; +/// - a `wildcard_bound` on a `selector` or a `children`; +/// - a `selector` or `children` group of more than one entry. +/// +/// [`Reason::JsonPathWildcard`] for a `children` path with a wildcard. +/// [`Error::Cipher`] for the read's own refusals, such as a path that does +/// not parse, or a wildcard that expands too far. +/// +/// The pending fails with [`crate::Error::JsonWrongEntry`] for an entry +/// the read did not ask for. It fails with +/// [`crate::Error::JsonWildcardTruncated`] for a wildcard read of an array +/// longer than the bound. It fails with [`crate::Error::JsonNotALeaf`] for +/// a `selector` or `children` entry that does not decrypt alone: a +/// container with members, or an altered entry. pub(super) fn open<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, under: &Under<'_>, @@ -729,6 +746,7 @@ fn open_read<'a, K: 'static>( Read::Subtree(path, bound) => { Opener::Subtree(keyset.json_subtree_key_now(&path, options, bound, under.query()?)?) } + Read::Child(path) => return open_children(keyset, under, options, &path, groups), }; let context = || under.stored(); // Opened through the client, confined to the deriving keyset, as a @@ -762,6 +780,108 @@ fn open_read<'a, K: 'static>( Ok(Pending::all(keyset, pendings).try_map(opened_frame)) } +/// [`open_read`] for `children`. Each group's one entry opens against the +/// key of the parent at `path`. It opens to the child's key or index and +/// its value. +fn open_children<'a, K: 'static>( + keyset: &KeysetCipher<'a, K>, + under: &Under<'_>, + options: &JsonOptions, + path: &JsonPath, + groups: Vec>, +) -> Result, Error> { + // The path has no wildcard, so the key holds one token, the parent's. + // The bound is never used. + let parent = keyset.json_subtree_key_now( + path, + options, + JsonSubtreeKey::DEFAULT_BOUND, + under.query()?, + )?; + let opener_cipher = keyset.cipher(); + let confine = keyset.selector(); + let mut pendings: Vec, K>> = + Vec::with_capacity(groups.len()); + for nodes in groups { + pendings.push(match <[JsonNode; 1]>::try_from(nodes) { + Ok([node]) => JsonChildPlaintext::decrypt_from_with_context( + parent.open_child(node), + opener_cipher, + under.stored(), + ) + .map(|child| vec![child]) + .confined_to(&confine), + // `read_open` allows a `children` group one entry or none. + Err(_) => Pending::ready(keyset, Ok(Vec::new())), + }); + } + Ok(Pending::all(keyset, pendings).try_map(children_frame)) +} + +/// The opened children as a frame, with one list per group. Each list +/// contains one map per child, either `{"key", "json"}` or +/// `{"index", "json"}`. Each child is +/// wiped when it is dropped here, once its text is written. Each text is +/// wiped once the frame holds it. +fn children_frame(groups: Vec>) -> Result { + let opened: Result>>, crate::Error> = groups + .iter() + .map(|group| group.iter().map(OpenedChild::of).collect()) + .collect(); + let frame = ValueFrame::of(&opened?).map_err(|error| crate::Error::Other(Box::new(error))); + drop(groups); + frame +} + +/// One opened child as the frame carries it: its key or index, and its +/// value's JSON text. The text is wiped when it is dropped. +struct OpenedChild<'c> { + child: &'c JsonChildPlaintext, + json: Protected>, +} + +impl<'c> OpenedChild<'c> { + fn of(child: &'c JsonChildPlaintext) -> Result { + let json = crate::json::to_text(child.value()) + .map(Protected::new) + .map_err(|error| crate::Error::Other(Box::new(error)))?; + Ok(Self { child, json }) + } +} + +/// One entry of an [`OpenedChild`]'s map. +enum ChildField<'c> { + Key(&'c str), + Index(u64), + Json(&'c Protected>), +} + +impl Encrypt for ChildField<'_> { + fn visit(self, sink: S) -> Result { + match self { + ChildField::Key(key) => key.visit(sink), + ChildField::Index(index) => index.visit(sink), + ChildField::Json(json) => json.visit(sink), + } + } +} + +/// `{"key": text, "json": bytes}` for a member, `{"index": u64, "json": +/// bytes}` for an element. +impl Encrypt for &OpenedChild<'_> { + fn visit(self, sink: S) -> Result { + let label = match self.child.label() { + ChildLabel::Key(key) => ("key", ChildField::Key(key.risky_ref())), + ChildLabel::Index(index) => ("index", ChildField::Index(*index.risky_ref())), + }; + visit_map( + sink, + Some(2), + [label, ("json", ChildField::Json(&self.json))], + ) + } +} + /// The opened groups as a frame: a list per group of each value's JSON /// text, as bytes. Each value is wiped when it is dropped, here, once its /// text is written, and each text once the frame holds it. diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 9ff3072d19..9955d1f961 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -908,22 +908,44 @@ pub fn check_json_open( super::json_query::check_open(&request, &rows).map_err(|error| error.in_field(field)) } -/// Open the rows a read of a document field returned, against the request -/// that prepared it: the runtime form of [`JsonSelector::open`] and -/// [`JsonSubtreeKey::open`], for a binding. `request` is the read as the -/// binding prepared it, `{"operation": "selector" | "subtree", "path", -/// "wildcard_bound"?}`, and `rows` a list per database row of the entries -/// the SQL returned for it (`public.eql_v4_json_entry` JSON, as text -/// or bytes): for `selector`, the one entry `->` returned or none, and for -/// `subtree`, the rows `json_tree_subtree` returned. The engine derives -/// the selector or the read key again, under `cipher`'s keyset and the -/// field's column and options, and checks every row against it; the rows -/// open through that keyset alone, so a document sealed under another is -/// refused before any key is retrieved. The result is a list per database -/// row of JSON -/// texts, as bytes: for `selector` the scalar or nothing, for `subtree` -/// one value per concrete path the read named that the row has, in -/// document order. One key request for every row. +/// Opens the entries a read of a document field returned, against the +/// request that prepared the read. It is the runtime form of +/// [`JsonSelector::open`], [`JsonSubtreeKey::open`] and +/// [`JsonSubtreeKey::open_child`], for a language binding. +/// +/// `request` is the read as the binding prepared it: +/// `{"operation": "selector" | "subtree" | "children", "path", +/// "wildcard_bound"?}`. `rows` is a list of groups of entries. Each entry +/// is `public.eql_v4_json_entry` JSON, as text or bytes. +/// +/// - For `selector`, a group is one database row: the entry `->` +/// returned, or nothing for SQL `NULL`. +/// - For `subtree`, a group is one database row: the entries +/// `json_tree_subtree` returned. +/// - For `children`, a group is one entry `json_tree_children` returned, +/// or nothing. +/// +/// The engine derives the selector or the read's key again, from the +/// request, `cipher`'s keyset, and the field's column and options. Then +/// the engine checks every entry against that selector or key. For +/// `children`, the engine checks that each entry is a child of the node at +/// the path. +/// +/// Entries decrypt through that keyset alone. So a document encrypted under +/// another keyset is refused before any key is fetched. +/// +/// The result is a list with one item per group: +/// +/// - For `selector`, the scalar's JSON text as bytes, or nothing. +/// - For `subtree`, the JSON text, as bytes, of each value the read +/// reached in that row, in document order. +/// - For `children`, the child, or nothing. A child is a map: +/// `{"key": text, "json": bytes}` for a member of an object, or +/// `{"index": u64, "json": bytes}` for an element of an array. `json` is +/// the child's value as JSON text. The engine checked the key or index +/// with the value. +/// +/// All the groups share one key request. /// /// The read runs under the contexts the document was sealed under. The /// selector or the read key derives under the field's column, then the @@ -937,6 +959,7 @@ pub fn check_json_open( /// /// [`JsonSelector::open`]: crate::json::JsonSelector::open /// [`JsonSubtreeKey::open`]: crate::json::JsonSubtreeKey::open +/// [`JsonSubtreeKey::open_child`]: crate::json::JsonSubtreeKey::open_child /// /// # Errors /// @@ -945,15 +968,15 @@ pub fn check_json_open( /// ([`Reason::QueryContextField`]): a read names no record, so it has no /// context to derive under. A plan with a binding is not refused. /// [`Error::Source`] names the field for a -/// request or rows that do not parse ([`Reason::JsonInput`]). A row that -/// is not one the read asked for fails the pending -/// ([`Error::JsonWrongEntry`](crate::Error::JsonWrongEntry)), as does a +/// request or rows that do not parse ([`Reason::JsonInput`]). An entry +/// that is not one the read asked for fails the pending +/// ([`Error::JsonWrongEntry`](crate::Error::JsonWrongEntry)). So does a /// wildcard read of an array longer than its bound /// ([`Error::JsonWildcardTruncated`](crate::Error::JsonWildcardTruncated)). -/// A `selector` entry that does not open alone, a container with members -/// or an altered entry, fails it as -/// [`Error::JsonNotALeaf`](crate::Error::JsonNotALeaf); a container is read -/// with `subtree`. +/// A `selector` or `children` entry that does not decrypt alone fails it +/// as [`Error::JsonNotALeaf`](crate::Error::JsonNotALeaf). That entry is a +/// container with members, or an altered entry. Read a container with +/// `subtree`. pub fn json_open<'a, K>( cipher: &'a KeysetCipher<'_, K>, plan: &Plan, diff --git a/packages/stack-encrypt/src/field_reference/json.rs b/packages/stack-encrypt/src/field_reference/json.rs index b0bd2bf192..eacac77fde 100644 --- a/packages/stack-encrypt/src/field_reference/json.rs +++ b/packages/stack-encrypt/src/field_reference/json.rs @@ -188,7 +188,7 @@ use crate::json::inputs::{ self, elements_base, member_predicate, node_path, selector_path, Bounds, Compare, Derived, Input, Parsed, Under, }; -use crate::json::{FieldOptions, JsonOptions, JsonPlaintext, JsonQueries}; +use crate::json::{FieldOptions, JsonOptions, JsonPlaintext, JsonQueries, JsonSubtreeKey}; use crate::op::{AtPath, Between, ContainedBy, Contains, Eq, Gt, Gte, Lt, Lte}; use crate::sem::TermError; use crate::target::Pending; @@ -850,9 +850,19 @@ impl FieldReference JsonFieldQuery { self.json(Body::Children(path_text(path))) } @@ -1457,6 +1467,30 @@ json_encrypt! { }; } +impl JsonFieldQuery { + /// Derives the node's token and its key together. The token is the one + /// [`encrypt`](Self::encrypt) returns, in the field's own token type. + /// Your app sends the token to the database, and keeps the key to + /// decrypt each child the database returns + /// ([`JsonSubtreeKey::open_child`]). Both come from one derivation, so + /// the key always matches the token sent. + /// + /// The query is checked against the field's options first. The query's + /// path is wiped when the query is derived, refused, or dropped. The + /// derivation runs in your app and asks ZeroKMS for nothing. + /// + /// [`JsonSubtreeKey::open_child`]: crate::json::JsonSubtreeKey::open_child + pub fn encrypt_keyed<'a, K: 'static>( + mut self, + keyset: &'a KeysetCipher<'_, K>, + ) -> Pending<'a, (T::Token, JsonSubtreeKey), K> { + self.derive_json(keyset).try_map(|derived| match derived { + Derived::Node(key) => Ok((T::token(key.clone())?, key)), + _ => Err(mismatched()), + }) + } +} + impl JsonFieldQuery, Ready> { /// Derives the element-scoped predicate. /// diff --git a/packages/stack-encrypt/src/json/derive.rs b/packages/stack-encrypt/src/json/derive.rs index c277314a40..99e21bd617 100644 --- a/packages/stack-encrypt/src/json/derive.rs +++ b/packages/stack-encrypt/src/json/derive.rs @@ -31,7 +31,10 @@ use super::plain::{ use super::plaintext::JsonPlaintext; use super::query::{group_of, JsonSelector, JsonSelectorSet, JsonSubtreeKey, Read}; use super::shuffle; -use super::{JsonDocument, JsonEntry, JsonExtracted, JsonHeader, JsonOptions, JsonSubtree, Tag}; +use super::{ + JsonChild, JsonChildPlaintext, JsonDocument, JsonEntry, JsonExtracted, JsonHeader, JsonOptions, + JsonSubtree, Tag, +}; use crate::keyset::KeysetState; use crate::sem::TermError; use crate::target::{AeadContext, Decryption, Pending, Request, RequiredContext}; @@ -1328,6 +1331,16 @@ fn hand_over(value: Protected) -> JsonPlaintext { JsonPlaintext::from(value.risky_unwrap().into_value()) } +/// An opened child as the caller receives it: its value, with its key or +/// index. The root has neither, so it is refused as no child. +fn child_plaintext(label: Label, value: JsonPlaintext) -> Result { + match label { + Label::Key(key) => Ok(JsonChildPlaintext::member(key, value)), + Label::Index(index) => Ok(JsonChildPlaintext::element(index, value)), + Label::Root => Err(wrong("a child of the node the key names")), + } +} + /// What opening a document's entries under the caller's context needs /// from ZeroKMS and from the context: the request that retrieves the /// document's one data key (its `iv`, its tag and its keyset from the @@ -1554,6 +1567,90 @@ impl DecryptSource for JsonExtracted { } } +/// Opens one child's entry to its key or index and its value. See +/// [`JsonSubtreeKey::open_child`] for what opening checks. The key, the +/// index, and the value are wiped when they are dropped. +/// +/// The context is required. The context must be the one the document was +/// encrypted under. +impl DecryptSource for JsonChild { + type ContextInput = RequiredContext; + fn decryption( + self, + context: Self::ContextInput, + ) -> Decryption { + open_child(self, context, |child| child) + } +} + +/// Opens one child's entry to its value alone. This opening runs the same +/// checks as [`DecryptSource`], including the check of +/// the key or index. Then the key or index is wiped. Only the value is +/// returned. See [`JsonSubtreeKey::open_child`] for what opening checks. +/// +/// The context is required. The context must be the one the document was +/// encrypted under. +impl DecryptSource for JsonChild { + type ContextInput = RequiredContext; + fn decryption(self, context: Self::ContextInput) -> Decryption { + open_child(self, context, JsonChildPlaintext::into_value) + } +} + +/// The one way a [`JsonChild`] opens, whatever it opens to. `finish` turns +/// the opened child into what the caller asked for, after every check has +/// passed. +fn open_child( + child: JsonChild, + context: RequiredContext, + finish: fn(JsonChildPlaintext) -> T, +) -> Decryption { + let context = context.into_inner(); + let (node, key) = child.into_parts(); + // A path with no wildcard has exactly one token, the parent's, and no + // probe token. + let parent = match key.reads.as_slice() { + [read] if !read.probe => read.clone(), + _ => { + return Decryption::failed( + crate::refusal::Error::bad_source(crate::refusal::Reason::JsonPathWildcard) + .into_crate(), + ) + } + }; + // The root has no parent tag. Under a sealed root, the top-level fields + // have none either. So neither can be a child of the node the key names. + if node.entry.p.is_none() { + return Decryption::failed(wrong("a child of the node the key names")); + } + let selectors = key.selectors; + Decryption::from_open(move |cipher| { + let shown = context.piece().clone(); + let (request, aad) = match key_retrieval(&node.header, context.into_context()) { + Ok(parts) => parts, + Err(error) => return Pending::failed(cipher, error), + }; + Pending::request(cipher, vec![request], move |responses| { + let retrieved = responses.next_retrieved_key()?; + let aes = leaf_cipher(&retrieved)?; + let opening = Opening { + header: &node.header, + aad: &aad, + aes: &aes, + }; + let row = ReturnedRow { + entry: node.entry, + slot: node.slot, + depth: node.depth, + }; + let (value, label) = + ChainWalk::new(vec![row], &selectors, &opening).lone_child(&parent)?; + child_plaintext(label, hand_over(value)).map(finish) + }) + .under_context(shown.clone(), shown) + }) +} + /// Open the rows of a read into the values of the nodes its tokens named, /// in the key's order, each still under its `Protected`. Shared by the /// three openings below, so they agree on every row and on the fallback: @@ -1875,16 +1972,45 @@ impl<'k> ChainWalk<'k> { expected: ExpectedSelector<'_>, depth: u32, ) -> Result<(Protected, Label), Error> { - let refused = || wrong("a node the walked path reaches"); - // No row is placed twice: below a node the chain follows only - // children that open under its digest, which are the ones sealed - // there, and a key's paths are disjoint, so no row is both a read's - // node and beneath another's. + self.place_row(at, depth)?; + let children = self.children(token)?; + let (opened, label, bytes) = self.open_row(at, &children, expected)?; + let value = self.value(opened, token, children, &bytes, depth)?; + Ok((value, label)) + } + + /// Marks the row at `at` as placed, `depth` levels below the node the + /// read named. If the database reported a depth for the row, it must be + /// `depth`. + fn place_row(&mut self, at: usize, depth: u32) -> Result<(), Error> { + // No row is placed twice. Below a node, the walk follows only the + // children that decrypt under that node's digest. Those are the + // children sealed there. A key's paths never overlap, so no row is + // both one read's node and below another's. self.placed[at] = true; if self.rows[at].depth.is_some_and(|got| got != depth) { return Err(wrong("a row at the depth the chain gives it")); } - let children = self.children(token)?; + Ok(()) + } + + /// Decrypts the row at `at` under the digest of `children`, the rows the + /// walk found below it. Then it checks the row is the node `expected` + /// names: + /// + /// - the sealed root appears only when the read is of `$`; + /// - the row has as many children as its plaintext records; + /// - its selector is the one its decrypted label gives it. + /// + /// Returns the decrypted node, its label, and its selector bytes. The + /// selectors of the node's children extend those bytes. + fn open_row( + &self, + at: usize, + children: &[(usize, Tag)], + expected: ExpectedSelector<'_>, + ) -> Result<(Opened, Label, Protected>), Error> { + let refused = || wrong("a node the walked path reaches"); let digest = cascade::children_digest( children .iter() @@ -1919,42 +2045,55 @@ impl<'k> ChainWalk<'k> { if self.selectors.of(bytes.clone())? != row.entry.s { return Err(refused()); } + Ok((opened, label, bytes)) + } + + /// The value of a decrypted node whose token is `token`. For the sealed + /// root, that is the whole document. For a scalar, it is the scalar. For + /// a container, it is built from `children`, each placed and decrypted + /// in turn. + fn value( + &mut self, + opened: Opened, + token: &Tag, + children: Vec<(usize, Tag)>, + bytes: &Protected>, + depth: u32, + ) -> Result, Error> { if let Some(whole) = opened.whole { - return Ok((whole, label)); + return Ok(whole); } match opened.kind { Kind::Object => { let mut object = protected_object(); for (child, child_token) in children { let (value, child_label) = - self.child(child, token, &child_token, &bytes, depth)?; + self.child(child, token, &child_token, bytes, depth)?; let Label::Key(key) = child_label else { return Err(shape("an object member")); }; insert_member(&mut object, key, value); } - Ok((object, label)) + Ok(object) } Kind::Array => { let mut array = protected_array(children.len()); for (i, (child, child_token)) in children.into_iter().enumerate() { let (value, child_label) = - self.child(child, token, &child_token, &bytes, depth)?; + self.child(child, token, &child_token, bytes, depth)?; if !matches!(child_label, Label::Index(at) if at == i as u64) { return Err(shape("an array element in order")); } push_element(&mut array, value); } - Ok((array, label)) + Ok(array) } - _ => Ok((opened.scalar.ok_or_else(|| shape("a JSON scalar"))?, label)), + _ => opened.scalar.ok_or_else(|| shape("a JSON scalar")), } } - /// Place and open a child, and check that the token its self tag chose - /// (the member or the element rule) is the one its decrypted label - /// derives under its parent's: a member's by its key, an element's by - /// its index. + /// Places and decrypts a child, then checks its link to its parent + /// ([`check_parent_link`]). fn child( &mut self, child: usize, @@ -1969,14 +2108,71 @@ impl<'k> ChainWalk<'k> { ExpectedSelector::UnderParent(parent_bytes), depth + 1, )?; - let s = self.rows[child].entry.s; - if labelled_token(parent_token, &s, &label).as_ref() != Some(child_token) { - return Err(wrong("a child under the rule its label names")); - } + check_parent_link(parent_token, &self.rows[child].entry.s, &label, child_token)?; + Ok((value, label)) + } + + /// Decrypts the walk's one row as a child of the node `parent` names. + /// The row is one entry `json_tree_children` returned for that node's + /// token. + /// + /// The row is placed one level below the parent. The row is decrypted + /// under the digest of no children. So a scalar or an empty container + /// decrypts. A container with children does not + /// ([`Error::JsonNotALeaf`]). + /// + /// The row's selector must be the parent's + /// path extended by the row's label. The row's self tag must match the + /// token the label gives under the parent's token + /// ([`check_parent_link`]). + /// + /// Returns the child's value and its label: its key or index. + fn lone_child(&mut self, parent: &Read) -> Result<(Protected, Label), Error> { + let parent_bytes = parent.path.protected_selector_bytes(); + self.place_row(0, 1)?; + let (opened, label, bytes) = self + .open_row(0, &[], ExpectedSelector::UnderParent(&parent_bytes)) + .map_err(|error| match error { + Error::Aead => Error::JsonNotALeaf, + other => other, + })?; + let entry = &self.rows[0].entry; + // An element's ordinal is its index. The element's label contains + // that index. A member's ordinal is random. The row does not + // contain it. A member's token does not use its ordinal + // (`member_token`), so any ordinal finds a member. + let ordinal = match &label { + Label::Index(index) => u32::try_from(*index).unwrap_or(u32::MAX), + _ => 0, + }; + let child_token = hit_token(&self.opening.header.iv, &parent.token, entry, ordinal) + .ok_or_else(|| wrong("a child the member or element rule names"))?; + check_parent_link(&parent.token, &entry.s, &label, &child_token)?; + let value = self.value(opened, &child_token, Vec::new(), &bytes, 1)?; Ok((value, label)) } } +/// Checks the link from a child to its parent. `child_token` is the token +/// the child's self tag matched ([`hit_token`]). That token must equal the +/// token the child's `label` gives under `parent_token`: a member's from +/// its key, an element's from its index. +/// +/// The label is authenticated. The self tag is not. So this check refuses a +/// self tag that points at another index, or at a member where the label +/// is an index. +fn check_parent_link( + parent_token: &Tag, + selector: &Tag, + label: &Label, + child_token: &Tag, +) -> Result<(), Error> { + if labelled_token(parent_token, selector, label).as_ref() != Some(child_token) { + return Err(wrong("a child under the rule its label names")); + } + Ok(()) +} + /// Whether a node with `label` is the one the concrete `path` names by its /// last step: the key, the position, or the root for `$`. fn names(path: &JsonPath, label: &Label) -> bool { diff --git a/packages/stack-encrypt/src/json/mod.rs b/packages/stack-encrypt/src/json/mod.rs index 9779f7226e..e095f16f0f 100644 --- a/packages/stack-encrypt/src/json/mod.rs +++ b/packages/stack-encrypt/src/json/mod.rs @@ -69,6 +69,12 @@ //! nothing above it is read. The entries are stored in a random order, root //! first, and no check reads a slot as a position in the document. //! +//! Your app can also read one level of a document. It passes each entry +//! `json_tree_children` returns to [`JsonSubtreeKey::open_child`], with the +//! parent's key. The [`JsonChild`] it gets back decrypts to the child's +//! value ([`JsonPlaintext`]). The child can also decrypt to its value with +//! its key or index ([`JsonChildPlaintext`]). +//! //! # A document with no index //! //! [`JsonPlaintext`] is a JSON document as a plaintext that is wiped when @@ -146,7 +152,9 @@ mod text; pub use derive::JsonTerms; pub(crate) use path::IndexPath; pub use path::{JsonPath, JsonPathError, Segment}; -pub use plaintext::JsonPlaintext; +#[cfg(feature = "dynamic")] +pub(crate) use plaintext::ChildLabel; +pub use plaintext::{JsonChildPlaintext, JsonPlaintext}; pub(crate) use query::JsonElementsMember; pub use query::{ JsonElementsQuery, JsonLeafQuery, JsonPredicateQuery, JsonQuery, JsonSelector, JsonSelectorSet, @@ -738,6 +746,40 @@ where } } +/// One entry that `eql_v4.json_tree_children` returned, paired with the key +/// of its parent node. Decrypt it into a [`JsonPlaintext`] for the child's +/// value. Decrypt it into a [`JsonChildPlaintext`] for its key or index too. +/// +/// [`JsonSubtreeKey::open_child`] is the only way to build one, so a +/// `JsonChild` always contains the parent's key. That method shows the +/// whole read, step by step. It also lists what decrypting checks. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct JsonChild { + node: JsonNode, + parent: JsonSubtreeKey, +} + +impl JsonChild { + pub(crate) fn keyed(node: JsonNode, parent: JsonSubtreeKey) -> Self { + Self { node, parent } + } + + /// The entry, as the database returned it. + pub fn node(&self) -> &JsonNode { + &self.node + } + + /// The path of the parent node that decrypting checks the entry + /// against. + pub fn parent_path(&self) -> &JsonPath { + &self.parent.path + } + + pub(crate) fn into_parts(self) -> (JsonNode, JsonSubtreeKey) { + (self.node, self.parent) + } +} + /// The entries the server returned for one subtree read, ready to open: /// what `json_tree_subtree(doc, key.tokens(), budget)` yields, collected, /// and what [`DecryptSource`] opens into the value at diff --git a/packages/stack-encrypt/src/json/plaintext.rs b/packages/stack-encrypt/src/json/plaintext.rs index 624e62f203..d4dc0f5566 100644 --- a/packages/stack-encrypt/src/json/plaintext.rs +++ b/packages/stack-encrypt/src/json/plaintext.rs @@ -5,6 +5,7 @@ use std::fmt; use serde_json::Value; use vitaminc_aead::plaintext::{depth, Error as _, Scalar, SourceError}; use vitaminc_aead::{FixedType, FromScalar, Logical, Physical, Sink}; +use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; use zeroize::{Zeroize, ZeroizeOnDrop}; use super::text::{nests_within, parse_text, to_wiped_text, MAX_DEPTH}; @@ -230,6 +231,163 @@ impl fmt::Debug for JsonPlaintext { } } +/// One child of a JSON node, decrypted: its value, and its key or index in +/// its parent. Decrypt a [`JsonChild`](super::JsonChild) into this type when +/// your app needs to know which child each value is. +/// +/// A member of an object has a [`key`](Self::key) and no +/// [`index`](Self::index). An element of an array has an index and no key. +/// +/// The database returns an object's members in a random order. So the +/// value alone does not say which member it is: the key does. The key or +/// index was encrypted with the value, and decrypting checks it against the +/// parent's path. [`JsonSubtreeKey::open_child`](super::JsonSubtreeKey::open_child) +/// describes the whole read. To get the value alone, decrypt into a +/// [`JsonPlaintext`] instead. +/// +/// ``` +/// # async fn example() -> Result<(), stack_encrypt::Error> { +/// use serde_json::json; +/// use stack_encrypt::json::{ +/// JsonChildPlaintext, 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 profile = json!({"limits": {"seats": 5, "projects": 20}}); +/// let stored: JsonDocument = JsonPlaintext::from(profile) +/// .encrypt_into_with_context( +/// &keyset, +/// CallerContext::from(nonempty!("users").with("profile")), +/// ) +/// .await?; +/// +/// // Your app derives the parent's key, and sends its token as $1. +/// let parent = keyset +/// .json_subtree_key( +/// &JsonPath::parse("$.limits").unwrap(), +/// &JsonOptions::default(), +/// nonempty!("users").with("profile"), +/// ) +/// .await?; +/// +/// // In production, the entries come from the database: +/// // 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) +/// .into_iter() +/// .filter_map(|(slot, _, _)| stored.node(slot)); +/// +/// // Your app decrypts each entry. The key says which member it is. +/// let mut limits = serde_json::Map::new(); +/// for entry in entries { +/// let child = JsonChildPlaintext::decrypt_from_with_context( +/// parent.open_child(entry), +/// &cipher, +/// AeadContext::from(nonempty!("users").with("profile")), +/// ) +/// .await?; +/// limits.insert(child.key().unwrap().to_owned(), child.value().clone()); +/// } +/// assert_eq!(limits, json!({"seats": 5, "projects": 20}).as_object().unwrap().clone()); +/// # Ok(()) +/// # } +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); +/// ``` +/// +/// The key, the index, and the value are plaintext. Each is wiped when the +/// child is dropped. `Debug` hides all three. The type has no `PartialEq`, +/// like [`JsonPlaintext`]. +#[derive(OpaqueDebug)] +pub struct JsonChildPlaintext { + label: ChildLabel, + value: JsonPlaintext, +} + +/// A child's place in its parent: a member's key or an element's index. +/// Each variant wipes its value when it is dropped. +pub(crate) enum ChildLabel { + Key(Protected), + Index(Protected), +} + +impl JsonChildPlaintext { + /// A member of an object, with its key. + pub(crate) fn member(key: Protected, value: JsonPlaintext) -> Self { + Self { + label: ChildLabel::Key(key), + value, + } + } + + /// An element of an array, with its index. + pub(crate) fn element(index: u64, value: JsonPlaintext) -> Self { + Self { + label: ChildLabel::Index(Protected::new(index)), + value, + } + } + + /// The member's key, for a child of an object. `None` for an element of + /// an array. + pub fn key(&self) -> Option<&str> { + match &self.label { + ChildLabel::Key(key) => Some(key.risky_ref()), + ChildLabel::Index(_) => None, + } + } + + /// The element's index, for a child of an array. `None` for a member of + /// an object. + pub fn index(&self) -> Option { + match &self.label { + ChildLabel::Index(index) => Some(*index.risky_ref()), + ChildLabel::Key(_) => None, + } + } + + /// The child's value: a scalar, or `{}` or `[]` for an empty object or + /// array. + pub fn value(&self) -> &Value { + self.value.value() + } + + /// The value alone. The key or index is wiped when it is dropped here. + pub(crate) fn into_value(self) -> JsonPlaintext { + self.value + } + + /// The key or the index, for the dynamic interface to write out. + #[cfg(feature = "dynamic")] + pub(crate) fn label(&self) -> &ChildLabel { + &self.label + } +} + +impl Zeroize for JsonChildPlaintext { + /// Wipes the key or the index, and the value. What is left is an empty + /// key or the index 0, and a JSON `null`. + fn zeroize(&mut self) { + match &mut self.label { + ChildLabel::Key(key) => key.zeroize(), + ChildLabel::Index(index) => index.zeroize(), + } + self.value.zeroize(); + } +} + +/// Every field wipes itself when it is dropped. The key and the index are +/// `Protected`. The value is a [`JsonPlaintext`]. +impl ZeroizeOnDrop for JsonChildPlaintext {} + /// The refusal of a document nested deeper than the parser reads. const TOO_DEEP: &str = "a JSON document nested deeper than 127 levels"; @@ -458,4 +616,73 @@ mod tests { let document = JsonPlaintext::from(json!({"secret": "hunter2"})); assert_eq!(format!("{document:?}"), "JsonPlaintext()"); } + + mod given_an_opened_child { + use super::*; + + fn member() -> JsonChildPlaintext { + JsonChildPlaintext::member( + Protected::new("secret".to_owned()), + JsonPlaintext::from(json!("hunter2")), + ) + } + + fn element() -> JsonChildPlaintext { + JsonChildPlaintext::element(7, JsonPlaintext::from(json!(1234))) + } + + #[test] + fn a_member_has_its_key_and_no_index() { + let child = member(); + assert_eq!(child.key(), Some("secret"), "the member's key"); + assert_eq!(child.index(), None, "a member has no index"); + assert_eq!(child.value(), &json!("hunter2"), "the member's value"); + } + + #[test] + fn an_element_has_its_index_and_no_key() { + let child = element(); + assert_eq!(child.index(), Some(7), "the element's index"); + assert_eq!(child.key(), None, "an element has no key"); + assert_eq!(child.value(), &json!(1234), "the element's value"); + } + + #[test] + fn zeroize_wipes_the_key_and_the_value() { + let mut child = member(); + child.zeroize(); + assert_eq!(child.key(), Some(""), "the key is wiped"); + assert_eq!(child.value(), &Value::Null, "the value is wiped"); + } + + #[test] + fn zeroize_wipes_the_index_and_the_value() { + let mut child = element(); + child.zeroize(); + assert_eq!(child.index(), Some(0), "the index is wiped"); + assert_eq!(child.value(), &Value::Null, "the value is wiped"); + } + + #[test] + fn debug_shows_neither_label_nor_value() { + for child in [member(), element()] { + assert_eq!( + format!("{child:?}"), + "stack_encrypt::json::plaintext::JsonChildPlaintext { label: \"***\", value: \"***\" }", + "the key, the index and the value are plaintext" + ); + } + } + + #[test] + fn into_value_keeps_the_value_alone() { + for (child, value) in [(member(), json!("hunter2")), (element(), json!(1234))] { + assert_eq!( + child.into_value().value(), + &value, + "the value, without its key or index" + ); + } + } + } } diff --git a/packages/stack-encrypt/src/json/query.rs b/packages/stack-encrypt/src/json/query.rs index e9672be75e..a552a72f73 100644 --- a/packages/stack-encrypt/src/json/query.rs +++ b/packages/stack-encrypt/src/json/query.rs @@ -14,7 +14,7 @@ use serde_json::Value; use super::derive::{JsonTerms, Selectors, TermNode}; use super::path::JsonPath; -use super::{base64, JsonExtracted, JsonNode, JsonOptions, JsonSubtree, Tag}; +use super::{base64, JsonChild, JsonExtracted, JsonNode, JsonOptions, JsonSubtree, Tag}; use crate::op::{Op, QueryTerm}; use crate::target::Json; use vitaminc_protected::{Choice, OpaqueDebug, TimingSafeEq}; @@ -606,6 +606,153 @@ impl JsonSubtreeKey { pub fn open(&self, rows: Vec) -> JsonSubtree { JsonSubtree::keyed(rows, self.clone()) } + + /// Pairs one entry that `eql_v4.json_tree_children` returned with this + /// key, the key of the entry's parent node. Decrypt the [`JsonChild`] it + /// returns to read that child. Your app reads one level of a document + /// this way, without fetching the parent's whole subtree. + /// + /// An **entry** is one encrypted node of a stored document: an object, + /// an array, or a scalar. Reading a node's children takes three steps. + /// + /// 1. **Your app** derives the parent's token and key from the parent's + /// path. A **token** is a value the database uses to find a node's + /// entry. [`KeysetCipher::json_subtree_key`](crate::KeysetCipher::json_subtree_key) + /// returns this key. The key contains the token. A field reference's + /// `children(path).encrypt_keyed(&keyset)` returns the token and the + /// key together. Neither call asks ZeroKMS for anything. Your app + /// keeps the key and sends the token. + /// 2. **The database (EQL)** runs `eql_v4.json_tree_children(doc, $1)`, + /// with the token as `$1`. In each stored document, it finds the + /// parent's entry and returns the parent's direct children as + /// entries. The database never decrypts anything, and it never + /// receives a key. + /// 3. **Your app** deserializes each returned entry into a [`JsonNode`], + /// and passes it to `open_child`. Decrypting the result checks that + /// the entry is a child of this parent. Then it fetches the data key + /// from ZeroKMS and decrypts the child. + /// + /// ``` + /// # async fn example() -> Result<(), stack_encrypt::Error> { + /// 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}; + /// + /// let cipher = StackCipher::builder() + /// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) + /// .init() + /// .await?; + /// let keyset = cipher.default_keyset(); + /// let profile = json!({"tags": ["admin"]}); + /// let stored: JsonDocument = JsonPlaintext::from(profile) + /// .encrypt_into_with_context( + /// &keyset, + /// CallerContext::from(nonempty!("users").with("profile")), + /// ) + /// .await?; + /// + /// // Step 1, your app: derive the parent's key. Send `parent.tokens()[0]` + /// // as $1. + /// let parent = keyset + /// .json_subtree_key( + /// &JsonPath::parse("$.tags").unwrap(), + /// &JsonOptions::default(), + /// nonempty!("users").with("profile"), + /// ) + /// .await?; + /// + /// // Step 2, the database. In production, the entries come from: + /// // 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) + /// .into_iter() + /// .filter_map(|(slot, _, _)| stored.node(slot)); + /// + /// // Step 3, your app: pair each entry with the parent's key, and decrypt. + /// 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(); + /// ``` + /// + /// # Choosing what to decrypt into + /// + /// - Decrypt into a [`JsonPlaintext`](super::JsonPlaintext) to get the + /// child's value alone. + /// - Decrypt into a [`JsonChildPlaintext`](super::JsonChildPlaintext) to + /// also get the member's key or the element's index. + /// + /// The database returns an object's members in a random order. The + /// database returns an array's elements in index order, but nothing + /// checks that order. So with a `JsonPlaintext`, your app cannot tell + /// which member or element a value is. Use a `JsonChildPlaintext` when + /// that matters. + /// Both run the same checks. + /// + /// # What decrypting checks + /// + /// Each entry stores four things that decrypting checks: + /// + /// - a **selector**: a keyed hash of the entry's path, with array + /// indexes left out; + /// - a **self tag**: the tag the database computes from the entry's own + /// token, to find the entry; + /// - a **parent tag**: the tag the database computes from the parent's + /// token, to find the parent's children; + /// - a **label**: the member's key, or the element's index. The label is + /// encrypted with the value. + /// + /// Decrypting refuses the entry with + /// [`Error::JsonWrongEntry`](crate::Error::JsonWrongEntry) unless every + /// one of these checks passes: + /// + /// - The entry has a parent tag. The root has none. Under a sealed root, + /// the top-level fields have none either. + /// - If the database reported a depth, it is one level below the parent. + /// - The entry's selector is the parent's path extended by the label. + /// - The entry's self tag is the one its label gives. Your app computes + /// that tag from the parent's token and the label. + /// + /// The label is encrypted and authenticated with the value. So the + /// database cannot pass off one element as another index, or a member + /// as an element. A missing parent tag is refused before any key is + /// fetched. + /// + /// # Limits + /// + /// - A child that has children of its own does not decrypt alone. + /// Decrypting refuses it with + /// [`Error::JsonNotALeaf`](crate::Error::JsonNotALeaf). + /// Read it with a subtree read of its own path ([`open`](Self::open)). + /// - A key for a path with a wildcard names no single parent. Decrypting + /// refuses it with [`Error::Input`](crate::Error::Input), reason + /// `JsonPathWildcard`, before any key is fetched. + /// + /// Decrypting does not check these things: + /// + /// - the database row the entry came from, unless the context names the + /// row; + /// - that the database returned every child; + /// - the array element the parent is. The self tags and parent tags are + /// not authenticated. The database has the parent's token, so it can + /// compute them. So a database that forges tags can return the children of + /// `$.items[0]` for a read of `$.items[1]`. A subtree read has the + /// same limit for the node it starts at. + pub fn open_child(&self, node: JsonNode) -> JsonChild { + JsonChild::keyed(node, self.clone()) + } } /// The tokens are capabilities: the key prints as its shape, not its bytes. diff --git a/packages/stack-encrypt/src/op/mod.rs b/packages/stack-encrypt/src/op/mod.rs index bf6c1eef27..9485a63f58 100644 --- a/packages/stack-encrypt/src/op/mod.rs +++ b/packages/stack-encrypt/src/op/mod.rs @@ -402,7 +402,9 @@ operators! { /// ([`KeysetCipher::json_subtree_key_with_bound`](crate::KeysetCipher::json_subtree_key_with_bound)). Subtree = "subtree", /// `"children"`: the token of the node at a path with no wildcard, - /// which `json_tree_children` takes. + /// which `json_tree_children` takes. Your app decrypts each entry + /// it returns on its own, checked against that node + /// ([`JsonSubtreeKey::open_child`](crate::json::JsonSubtreeKey::open_child)). Children = "children", /// `"child_count"`: the same token, which `json_tree_child_count` /// takes. diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 191c1b0a43..0938af82b0 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -560,7 +560,7 @@ reasons! { /// object the operator takes ([`json_open`](crate::dynamic::json_open), the JSON operators of /// [`Op`](crate::dynamic::Op)): a missing or unknown key, a value of another kind, /// a row that is not an entry, or more than one entry for a - /// selector. + /// selector or a child. JsonInput => "json_input", "the input is not the object the JSON operator takes"; /// A JSON value in an input is not JSON text the engine reads. JsonSyntax => "json_syntax", "a JSON value is not JSON text"; diff --git a/packages/stack-encrypt/tests/json_field_references.rs b/packages/stack-encrypt/tests/json_field_references.rs index 8aac08ab29..6e90375a17 100644 --- a/packages/stack-encrypt/tests/json_field_references.rs +++ b/packages/stack-encrypt/tests/json_field_references.rs @@ -15,11 +15,13 @@ use std::num::NonZeroU32; use std::sync::atomic::Ordering; use serde_json::{json, Value}; -use stack_encrypt::json::{JsonDocument, JsonLeafQuery, JsonPlaintext, JsonQuery}; +use stack_encrypt::json::{ + JsonChildPlaintext, JsonDocument, JsonLeafQuery, JsonPlaintext, JsonQuery, +}; use stack_encrypt::refusal::Reason; use stack_encrypt::sem::TermError; -use stack_encrypt::target::{DecryptSource, EncryptTarget, Scope}; -use stack_encrypt::{DecryptFrom, EncryptInto, Error, KeysetCipher, StackCipher}; +use stack_encrypt::target::{AeadContext, DecryptSource, EncryptTarget, Scope}; +use stack_encrypt::{nonempty, DecryptFrom, EncryptInto, Error, KeysetCipher, StackCipher}; use stack_kms::FakeDataKeySource; use zeroize::Zeroize; @@ -235,6 +237,45 @@ mod the_fields_options { doc.find(&key.token_bytes()[0]).map(|(_, entry)| entry) } + /// `encrypt_keyed` gives `encrypt`'s token and the key that holds it, + /// and the key opens each child the token finds, with its key. + #[tokio::test] + async fn encrypt_keyed_gives_the_token_with_the_key_that_opens_its_children() { + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + let doc = stored(&keyset).await.profile; + let (token, key) = EncryptedCustomer::PROFILE + .children("$.visits[0]") + .encrypt_keyed(&keyset) + .await + .unwrap(); + let alone = EncryptedCustomer::PROFILE + .children("$.visits[0]") + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(token.tokens(), alone.tokens(), "encrypt's token"); + 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]) { + let child = JsonChildPlaintext::decrypt_from_with_context( + key.open_child(doc.node(slot).unwrap()), + &keyset, + AeadContext::from(nonempty!("customers").with("profile")), + ) + .await + .unwrap(); + members.push((child.key().unwrap().to_owned(), child.value().clone())); + } + members.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!( + members, + [("at".into(), json!(15)), ("place".into(), json!("home"))], + "each member of the first visit, with its key" + ); + } + #[tokio::test] async fn an_ordered_paths_entry_carries_an_ordering_term_at_the_field_references_selector() { let cipher = cipher().await; diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index c2b9d27125..b6e9be3452 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -252,6 +252,19 @@ fn extracted(doc: &JsonDocument, selector: &str) -> Vec { .collect() } +/// 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)) + .into_iter() + .map(|(j, _, _)| { + let mut wire = serde_json::to_value(doc.node(j).unwrap()).unwrap(); + wire["d"] = json!(1); + vec![wire.to_string()] + }) + .collect() +} + /// The rows `json_tree_subtree(doc, tokens, 0)` returns: each node with /// its depth grafted. fn subtree(doc: &JsonDocument, tokens: &[String]) -> Vec { @@ -308,6 +321,51 @@ fn opened_values(opened: &ValueFrame) -> Vec> { .collect() } +/// A `children` read of the `profile` field over `groups`: per group, the +/// children it opened. +async fn open_children( + keyset: &KeysetCipher<'_, K>, + plan: &record::Plan, + request: Value, + groups: Vec>, +) -> Result>, stack_encrypt::Error> { + let opened = open_pending(keyset, plan, &request, &groups).await?; + let groups: Vec> = dynamic::frame::serde::from_slice(opened.risky_ref()).unwrap(); + Ok(groups + .into_iter() + .map(|group| group.into_iter().map(ChildMap::opened).collect()) + .collect()) +} + +/// One child as the frame carries it: its key or its index, and its +/// value's JSON text. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ChildMap { + key: Option, + index: Option, + json: bytes::Bytes, +} + +impl ChildMap { + fn opened(self) -> Opened { + let value = serde_json::from_slice(&self.json.0).unwrap(); + match (self.key, self.index) { + (Some(key), None) => Opened::Member(key, value), + (None, Some(index)) => Opened::Element(index, value), + (key, index) => panic!("a child has a key or an index: {key:?}, {index:?}"), + } + } +} + +/// What a child opened to: an object's member by its key, or an array's +/// element by its index, with its value. +#[derive(Debug, PartialEq)] +enum Opened { + Member(String, Value), + Element(u64, Value), +} + /// A byte string read out of a frame. mod bytes { pub struct Bytes(pub Vec); @@ -730,6 +788,106 @@ async fn reads_open_against_the_request_that_prepared_them() { ); } +/// `children`: each entry `json_tree_children` returned for the token the +/// `children` operator derived opens on its own, one group each, against +/// the parent the request's path names; an entry of another parent is +/// refused. +#[tokio::test] +async fn a_child_opens_against_the_parent_its_request_names() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan(); + let doc = seal( + &keyset, + &plan, + &json!({"name": "Alice", "visits": [{"at": 3}, {"at": 1, "where": "x"}], "tags": ["a", "b"]}), + ) + .await; + let token = |t: QueryTerm| match t.operand() { + Operand::Text(text) => text.clone(), + other => panic!("{other:?}"), + }; + let tags = token(term(&keyset, &plan, "children", json!({"path": "$.tags"})).await); + let opened = open_children( + &keyset, + &plan, + json!({"operation": "children", "path": "$.tags"}), + children(&doc, &tags), + ) + .await + .unwrap(); + assert_eq!( + opened, + [ + vec![Opened::Element(0, json!("a"))], + vec![Opened::Element(1, json!("b"))] + ], + "each element with its index, in position order" + ); + let second = token(term(&keyset, &plan, "children", json!({"path": "$.visits[1]"})).await); + let mut members: Vec = open_children( + &keyset, + &plan, + json!({"operation": "children", "path": "$.visits[1]"}), + children(&doc, &second), + ) + .await + .unwrap() + .into_iter() + .flatten() + .collect(); + // The members come back in their random ordinal order; each names + // itself. + members.sort_by_key(|child| format!("{child:?}")); + assert_eq!( + members, + [ + Opened::Member("at".into(), json!(1)), + Opened::Member("where".into(), json!("x")) + ], + "each member of the second visit, with its key" + ); + let none = open_children( + &keyset, + &plan, + json!({"operation": "children", "path": "$.tags"}), + vec![vec![]], + ) + .await + .unwrap(); + assert_eq!( + none, + [Vec::::new()], + "a group with no entry opens to none" + ); + + // `$.tags`' elements answered for `$.visits[1]`'s members. + let wrong = open_children( + &keyset, + &plan, + json!({"operation": "children", "path": "$.visits[1]"}), + children(&doc, &tags), + ) + .await; + assert!( + matches!(wrong, Err(stack_encrypt::Error::JsonWrongEntry { .. })), + "{wrong:?}" + ); + // A container with children does not open on its own. + let visits = token(term(&keyset, &plan, "children", json!({"path": "$.visits"})).await); + let container = open_children( + &keyset, + &plan, + json!({"operation": "children", "path": "$.visits"}), + children(&doc, &visits), + ) + .await; + assert!( + matches!(container, Err(stack_encrypt::Error::JsonNotALeaf)), + "{container:?}" + ); +} + /// A read made with a credential sends that credential with its key /// request. Each group of rows opens through the client, and the groups /// are gathered into one call, which is made with the credential the call @@ -1342,17 +1500,57 @@ fn a_malformed_read_is_refused_before_any_key() { json!([]), "engine", ), + ( + json!({"operation": "children", "path": "$.a", "wildcard_bound": 2}), + json!([]), + "json_input", + ), + ( + json!({"operation": "children", "path": "$.a[*]"}), + json!([]), + "json_path_wildcard", + ), + ( + json!({"operation": "child_count", "path": "$.a"}), + json!([]), + "json_input", + ), ] { assert_eq!(refused(request.clone(), rows), want, "{request}"); } - // A selector group holds one entry or none: `->` returns one. - let entry = json!({"s": "AAAAAAAAAAAAAAAAAAAAAA==", "c": "AA=="}).to_string(); - let two = check( - json!({"operation": "selector", "path": "$.a"}), - json!([[entry.clone(), entry]]), + // A selector group holds one entry or none: `->` returns one. So does + // a child's: one entry `json_tree_children` returned. + // An entry as the SQL returns it, with the header (version 1, no tag) + // and the slot grafted: it parses, and nothing here opens it. + let entry = json!({ + "s": "AAAAAAAAAAAAAAAAAAAAAA==", + "c": "AA==", + "x": "AAAAAAAAAAA=", + "h": "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", + "j": 1, + }) + .to_string(); + for operation in ["selector", "children"] { + let request = json!({"operation": operation, "path": "$.a"}); + assert!( + check(request.clone(), json!([[entry.clone()]])).is_ok(), + "{operation}: one entry" + ); + assert_eq!( + refused(request, json!([[entry.clone(), entry.clone()]])), + "json_input", + "{operation}: two entries in one group" + ); + } + assert!( + check( + json!({"operation": "subtree", "path": "$.a"}), + json!([[entry.clone(), entry]]) + ) + .is_ok(), + "a subtree group holds many rows" ); - assert!(two.is_err()); // A field that does not store a document has no reads. let wire = diff --git a/packages/stack-encrypt/tests/json_read_checks.rs b/packages/stack-encrypt/tests/json_read_checks.rs index e9cfe5af66..c18662d014 100644 --- a/packages/stack-encrypt/tests/json_read_checks.rs +++ b/packages/stack-encrypt/tests/json_read_checks.rs @@ -1,7 +1,8 @@ //! What the client checks when it opens the rows a JSON index read //! returned, with no database: the entry `->` returns must carry the -//! selector the client derived for the path, and the rows of a subtree read -//! must be the subtree of the node the key's token names. The cascade +//! selector the client derived for the path, the rows of a subtree read +//! must be the subtree of the node the key's token names, and an entry +//! `json_tree_children` returns must be a child of that node. The cascade //! refuses, at the cipher ([`Error::Aead`]), any change to the rows beneath //! that node: a row swapped, dropped, added, reordered or moved under //! another parent changes a tag on the way up. The client's own checks @@ -23,9 +24,10 @@ use std::sync::atomic::Ordering; use common::CountingSource; use serde_json::{json, Value}; use stack_encrypt::json::{ - JsonDocument, JsonExtracted, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonSelector, - JsonSubtree, JsonSubtreeKey, + JsonChild, JsonChildPlaintext, JsonDocument, JsonExtracted, JsonNode, JsonOptions, JsonPath, + JsonPlaintext, JsonSelector, JsonSubtree, JsonSubtreeKey, }; +use stack_encrypt::refusal::Reason; use stack_encrypt::target::{AeadContext, CallerContext}; use stack_encrypt::{nonempty, DecryptFrom, EncryptInto, Error, StackCipher}; @@ -206,6 +208,22 @@ mod assertions { } } + /// Both reads were refused, with the same error: `case` names the entry. + pub(crate) fn same_refusal( + case: &str, + alone: Result, + labelled: Result, + ) { + match (alone, labelled) { + (Err(alone), Err(labelled)) => assert_eq!( + format!("{alone:?}"), + format!("{labelled:?}"), + "{case}: the value alone and the labelled child are refused alike" + ), + other => panic!("{case}: expected two refusals, got {other:?}"), + } + } + /// The read was refused by the cipher: some node did not open under the /// digest of the children the chain gave it, or under its own AAD. pub(crate) fn aead(result: Result) { @@ -816,6 +834,384 @@ mod given_the_rows_of_a_read { } } +/// One entry `json_tree_children` returned, opened on its own against the +/// key of the node whose token found it: the parent's path and token, and +/// nothing of the parent's subtree. +mod given_one_child_of_a_node { + use super::*; + + const REACHED: &str = "a node the walked path reaches"; + const RULE: &str = "a child the member or element rule names"; + const LABEL: &str = "a child under the rule its label names"; + const DEPTH: &str = "a row at the depth the chain gives it"; + + /// A member of each kind under `$.a`, a container with children among + /// them, and an array of three under `$.arr`. + fn tree() -> Value { + json!({ + "a": {"s": "text", "n": 1, "z": null, "o": {}, "e": [], "full": {"x": 1}}, + "arr": [10, 20, 30], + "b": {"s": "other"}, + }) + } + + /// 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]) + .iter() + .map(|(j, _, _)| row(doc, *j, Some(1))) + .collect() + } + + /// The row of the child at the concrete `path`, as `json_tree_children` + /// returns it. + async fn child_row(cipher: &Cipher, doc: &JsonDocument, path: &str) -> JsonNode { + row(doc, slot(cipher, doc, path).await, Some(1)) + } + + /// What a child opened to: an object's member by its key, or an + /// array's element by its index, with its value. + #[derive(Debug, PartialEq)] + enum Opened { + Member(String, Value), + Element(u64, Value), + } + + async fn open(cipher: &Cipher, child: JsonChild) -> Result { + JsonChildPlaintext::decrypt_from_with_context(child, cipher, aead()) + .await + .map(opened) + } + + /// The child a plaintext holds: exactly one of a key and an index. + fn opened(child: JsonChildPlaintext) -> Opened { + let value = child.value().clone(); + match (child.key(), child.index()) { + (Some(key), None) => Opened::Member(key.to_owned(), value), + (None, Some(index)) => Opened::Element(index, value), + other => panic!("a child has a key or an index, not {other:?}"), + } + } + + /// Each member opens with its own key, in whatever order the ordinals + /// put them, so no member is found by its value. + #[tokio::test] + async fn each_leaf_member_opens_to_its_key_and_value() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let a = key(&cipher, "$.a").await; + let mut members = serde_json::Map::new(); + let mut not_leaves = 0; + for node in children(&doc, &a) { + let child = a.open_child(node); + assert_eq!( + child.parent_path().to_string(), + "$.a", + "the parent asked about" + ); + match open(&cipher, child).await { + Ok(Opened::Member(key, value)) => { + assert!( + members.insert(key.clone(), value).is_none(), + "{key} opens once" + ); + } + Ok(element) => panic!("a member of $.a opened as {element:?}"), + Err(Error::JsonNotALeaf) => not_leaves += 1, + Err(error) => panic!("a child of $.a: {error:?}"), + } + } + assert_eq!( + Value::Object(members), + json!({"s": "text", "n": 1, "z": null, "o": {}, "e": []}), + "every leaf member opens to its key and its value" + ); + assert_eq!(not_leaves, 1, "the member with children is JsonNotALeaf"); + } + + #[tokio::test] + async fn each_element_opens_to_its_index_and_value_in_position_order() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let arr = key(&cipher, "$.arr").await; + let mut elements = Vec::new(); + for node in children(&doc, &arr) { + elements.push(open(&cipher, arr.open_child(node)).await.unwrap()); + } + assert_eq!( + elements, + vec![ + Opened::Element(0, json!(10)), + Opened::Element(1, json!(20)), + Opened::Element(2, json!(30)), + ], + "the elements in order, each with its index" + ); + } + + #[tokio::test] + async fn a_child_of_another_node_is_refused_by_its_selector() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let a = key(&cipher, "$.a").await; + // `$.b.s`, a genuine scalar child of `$.b`, offered as `$.a`'s. + let other = child_row(&cipher, &doc, "$.b.s").await; + assertions::wrong_entry(open(&cipher, a.open_child(other)).await, REACHED); + } + + /// The second element's row carrying the first's self tag: the same + /// selector, but its decrypted position derives another token. + #[tokio::test] + async fn an_element_read_as_another_position_is_refused() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let arr = key(&cipher, "$.arr").await; + let first = key(&cipher, "$.arr[0]").await; + let second = child_row(&cipher, &doc, "$.arr[1]").await; + let forged = with_x(vec![second], 0, x_of(&doc, &first)); + let forged = forged.into_iter().next().unwrap(); + assertions::wrong_entry(open(&cipher, arr.open_child(forged)).await, RULE); + } + + /// A member whose self tag is the one the element rule derives at the + /// ordinal its label stands for: its decrypted label is a key. + #[tokio::test] + async fn a_member_under_the_element_rule_is_refused_by_its_label() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let a = key(&cipher, "$.a").await; + let s = selector_bytes(&selector(&cipher, "$.a.s").await); + let as_element = chain::element_token(&a.token_bytes()[0], &s, 0); + let member = child_row(&cipher, &doc, "$.a.s").await; + let forged = with_x( + vec![member], + 0, + base64(&chain::self_tag(doc.header().iv(), &as_element)), + ); + let forged = forged.into_iter().next().unwrap(); + assertions::wrong_entry(open(&cipher, a.open_child(forged)).await, LABEL); + } + + #[tokio::test] + async fn a_row_at_another_depth_is_refused() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let a = key(&cipher, "$.a").await; + let at = slot(&cipher, &doc, "$.a.s").await; + assertions::wrong_entry( + open(&cipher, a.open_child(row(&doc, at, Some(2)))).await, + DEPTH, + ); + let undepthed = open(&cipher, a.open_child(row(&doc, at, None))).await; + assert_eq!( + undepthed.unwrap(), + Opened::Member("s".into(), json!("text")), + "a row with no depth is placed by the key" + ); + } + + /// Under the sealed root the top-level fields head the chain: they are + /// found by their own tokens and carry no parent tag, so none is a + /// child, and none is opened as one. + #[tokio::test] + async fn a_chain_head_is_refused_before_any_key_is_retrieved() { + let (cipher, retrieved) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let root = key(&cipher, "$").await; + let head = child_row(&cipher, &doc, "$.arr").await; + assert!( + head.entry().parent_tag().is_none(), + "a head has no parent tag" + ); + assertions::wrong_entry( + open(&cipher, root.open_child(head)).await, + "a child of the node the key names", + ); + assert_eq!( + retrieved.load(Ordering::SeqCst), + 0, + "the refusal retrieved no key" + ); + } + + #[tokio::test] + async fn a_key_with_a_wildcard_is_refused_before_any_key_is_retrieved() { + let (cipher, retrieved) = cipher().await; + let doc = seal(&cipher, &tree()).await; + // At the default bound a wildcard sends a token per element and a + // probe; at a bound of 0, the probe alone, which is one token too. + let probe_only = cipher + .default_keyset() + .json_subtree_key_with_bound( + &JsonPath::parse("$.arr[*]").unwrap(), + &JsonOptions::default(), + 0, + nonempty!("users").with("profile"), + ) + .await + .unwrap(); + assert_eq!(probe_only.tokens().len(), 1, "the probe alone"); + for elements in [key(&cipher, "$.arr[*]").await, probe_only] { + let element = child_row(&cipher, &doc, "$.arr[0]").await; + match open(&cipher, elements.open_child(element)).await { + Err(Error::Input(refusal)) => assert_eq!( + refusal.reason(), + Some(Reason::JsonPathWildcard), + "a wildcard names no one parent" + ), + other => panic!("expected an input refusal, got {other:?}"), + } + } + assert_eq!( + retrieved.load(Ordering::SeqCst), + 0, + "the refusal retrieved no key" + ); + } + + #[tokio::test] + async fn the_opening_shows_its_context() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let arr = key(&cipher, "$.arr").await; + let element = child_row(&cipher, &doc, "$.arr[2]").await; + let slot = element.slot(); + let child = arr.open_child(element); + assert_eq!(child.node().slot(), slot, "the row as returned"); + let opening = JsonChildPlaintext::decrypt_from_with_context(child, &cipher, aead()); + let shown = opening.context(); + assert!(!shown.has_failed(), "the opening has not failed: {shown}"); + assert_eq!( + shown.to_string(), + "context: users / profile\n", + "the column it opens under" + ); + assert_eq!( + opened(opening.await.unwrap()), + Opened::Element(2, json!(30)), + "the third element" + ); + } + + /// The same entries decrypted into a `JsonPlaintext`: the value alone, + /// after the same checks as a `JsonChildPlaintext`. + mod given_the_value_alone { + use super::*; + + async fn open_alone(cipher: &Cipher, child: JsonChild) -> Result { + JsonPlaintext::decrypt_from_with_context(child, cipher, aead()) + .await + .map(document) + } + + /// Entries that are not a leaf child of `$.a` or `$.arr`, each with + /// the key it is opened against: one per refusal. + async fn refused(cipher: &Cipher, doc: &JsonDocument) -> Vec<(&'static str, JsonChild)> { + let a = key(cipher, "$.a").await; + let arr = key(cipher, "$.arr").await; + let root = key(cipher, "$").await; + let first = key(cipher, "$.arr[0]").await; + let second = child_row(cipher, doc, "$.arr[1]").await; + let as_first = with_x(vec![second], 0, x_of(doc, &first)); + let at = slot(cipher, doc, "$.a.s").await; + vec![ + ( + "a child of another node", + a.open_child(child_row(cipher, doc, "$.b.s").await), + ), + ( + "an element read as another position", + arr.open_child(as_first.into_iter().next().unwrap()), + ), + ( + "a row at another depth", + a.open_child(row(doc, at, Some(2))), + ), + ( + "a chain head", + root.open_child(child_row(cipher, doc, "$.arr").await), + ), + ( + "a key with a wildcard", + key(cipher, "$.arr[*]") + .await + .open_child(child_row(cipher, doc, "$.arr[0]").await), + ), + ( + "a member with children", + a.open_child(child_row(cipher, doc, "$.a.full").await), + ), + ] + } + + #[tokio::test] + async fn each_element_opens_to_its_value() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let arr = key(&cipher, "$.arr").await; + let mut values = Vec::new(); + for node in children(&doc, &arr) { + values.push(open_alone(&cipher, arr.open_child(node)).await.unwrap()); + } + assert_eq!( + values, + vec![json!(10), json!(20), json!(30)], + "each element's value, in the order the database returned them" + ); + } + + #[tokio::test] + async fn each_leaf_member_opens_to_its_value() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let a = key(&cipher, "$.a").await; + let mut values = Vec::new(); + for node in children(&doc, &a) { + match open_alone(&cipher, a.open_child(node)).await { + Ok(value) => values.push(value.to_string()), + Err(Error::JsonNotALeaf) => {} + Err(error) => panic!("a child of $.a: {error:?}"), + } + } + values.sort(); + assert_eq!( + values, + ["\"text\"", "1", "[]", "null", "{}"], + "every leaf member's value, without its key" + ); + } + + #[tokio::test] + async fn a_wrong_entry_is_refused_as_for_a_child_plaintext() { + let (cipher, _) = cipher().await; + let doc = seal(&cipher, &tree()).await; + for (case, child) in refused(&cipher, &doc).await { + let alone = open_alone(&cipher, child.clone()).await; + let labelled = open(&cipher, child).await; + assertions::same_refusal(case, alone, labelled); + } + } + + #[tokio::test] + async fn a_chain_head_is_refused_before_any_key_is_retrieved() { + let (cipher, retrieved) = cipher().await; + let doc = seal(&cipher, &tree()).await; + let root = key(&cipher, "$").await; + let head = child_row(&cipher, &doc, "$.arr").await; + assertions::wrong_entry( + open_alone(&cipher, root.open_child(head)).await, + "a child of the node the key names", + ); + assert_eq!( + retrieved.load(Ordering::SeqCst), + 0, + "the refusal retrieved no key" + ); + } + } +} + /// What the read check allows by design, and says it allows: no bound field /// names an entry's row, or the element a node at a selector sits under, /// and nothing above the node at the top of a read is read. diff --git a/scripts/__tests__/stack-eql-conformance.test.mjs b/scripts/__tests__/stack-eql-conformance.test.mjs index 4b11afd3ed..85db5ca216 100644 --- a/scripts/__tests__/stack-eql-conformance.test.mjs +++ b/scripts/__tests__/stack-eql-conformance.test.mjs @@ -26,6 +26,7 @@ describe('required EQL/JSON conformance', () => { 'json-predicate-match-v1', 'json-extraction-v1', 'json-subtree-v1', + 'json-child-v1', 'json-tamper-v1', ]) const contract = read('conformance/stack-encrypt/eql-json-contract.md')