diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md new file mode 100644 index 0000000000..2b35a4e4c2 --- /dev/null +++ b/.changeset/eql-types-as-record-fields.md @@ -0,0 +1,14 @@ +--- +'@cipherstash/eql': minor +--- + +`eql-bindings`, the Rust crate released with this package: an EQL v4 type can now be a field of a Stack Encrypt record. + +- A `#[derive(EncryptTarget, DecryptSource)]` record with `struct = ..` can have fields such as `email: TextEq` or `profile: JsonTreeDocument`. The field's column is the record's scope and the field's name, so `scope = "members"` and the field `email` store `{"t": "members", "c": "email"}` in `i`. +- With no scope and no binding, a field writes the same terms as the type written on its own under that column, and as a data plan that names the type. A data plan is how the Go module writes the type. +- A record can list a scope or a binding, such as `scope(tenant: u64)` or `bind(row: u128)`. The terms of an EQL field then derive under the column and the scope. The ciphertext is sealed under the column, the scope and the binding. A field of any other type works the same way. `i` stores the column alone, so the reader supplies the scope and the binding again. The same is true of an EQL field of a record nested in another. +- A query from a field's marker takes the record's scope with `.scope(..)`. It gives the term of the values stored under that scope. +- A data plan that names an EQL type takes a scope and a binding in the same way. So a Go struct with an `encrypt_into` field now seals through `cipher.Scope(..).Bind(..)`, where it was refused. +- `JsonTreeDocument` now implements `EncryptTarget` and `DecryptSource` for `JsonPlaintext`. It encrypts under the default options, with the column as its context. + +The stored format, the SQL bundle, and the TypeScript types do not change. diff --git a/AGENTS.md b/AGENTS.md index 7bcaa561f4..9d886ec992 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,7 +85,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l - `languages/typescript/packages/utils`: Shared config (`utils/config`) and logger (`utils/logger`) - `languages/typescript/packages/bench`: Performance / index-engagement benchmarks (private, not published) - `languages/typescript/packages/protect-ffi`: Native FFI bindings to the CipherStash Client SDK (`@cipherstash/protect-ffi`) — the Rust core that `languages/typescript/packages/stack` encrypts and decrypts through, absorbed from `cipherstash/protectjs-ffi`. Contains a **nested Cargo workspace** (`crates/`) and six per-platform binary packages under `platforms/*`, each published as `@cipherstash/protect-ffi-` and linked here via `workspace:*`. Also holds the repo's live FFI integration suite at `integration-tests/` — a private workspace member (`@cipherstash/ffi-integration-tests`) enrolled by its own literal entry in `pnpm-workspace.yaml`, needing Docker and credentials, and deliberately carrying **no `test` script** so `pnpm test` cannot reach it. See the "Working on protect-ffi" notes below before touching it — its default `test` and `build` are deliberately Rust-free. -- `packages/eql`: The Encrypt Query Language subtree — the SQL bundle that stores and queries encrypted payloads — absorbed from `cipherstash/encrypt-query-language`. **The directory is the subtree root, not the package.** It was imported at a *verbatim prefix* so its repo-root-relative paths (mise tasks, `Doxyfile`, `sync-generated.mjs`) keep resolving, which puts the npm package `@cipherstash/eql` two levels down at `packages/eql/packages/eql` — the same shape as `languages/typescript/packages/protect-ffi/platforms/*`, and enrolled the same way, by an explicit `packages/eql/packages/*` glob in `pnpm-workspace.yaml`. The subtree root deliberately carries no `package.json`. Also contains a **nested Cargo workspace** at `packages/eql/crates/` (`eql-bindings`, published in lockstep with the npm package, plus `eql-domains` / `eql-codegen` / `eql-tests-macros`, which are not), a SQLx test crate at `packages/eql/tests/sqlx`, an unpublished encryption test crate at `packages/eql/tests/encryption` (real encryption with a fake key source, the executable Rustdoc example at `packages/eql/crates/eql-bindings/src/encryption/example.rs`, plus optional PostgreSQL coverage), an ~900-line `mise.toml` task surface, its own `AGENTS.md`, and `docs/`. See the "Working on EQL" notes below before touching it. +- `packages/eql`: The Encrypt Query Language subtree — the SQL bundle that stores and queries encrypted payloads — absorbed from `cipherstash/encrypt-query-language`. **The directory is the subtree root, not the package.** It was imported at a *verbatim prefix* so its repo-root-relative paths (mise tasks, `Doxyfile`, `sync-generated.mjs`) keep resolving, which puts the npm package `@cipherstash/eql` two levels down at `packages/eql/packages/eql` — the same shape as `languages/typescript/packages/protect-ffi/platforms/*`, and enrolled the same way, by an explicit `packages/eql/packages/*` glob in `pnpm-workspace.yaml`. The subtree root deliberately carries no `package.json`. Also contains a **nested Cargo workspace** at `packages/eql/crates/` (`eql-bindings`, published in lockstep with the npm package, plus `eql-domains` / `eql-codegen` / `eql-tests-macros`, which are not), a SQLx test crate at `packages/eql/tests/sqlx`, an unpublished encryption test crate at `packages/eql/tests/encryption` (real encryption with a fake key source, the executable Rustdoc example at `packages/eql/crates/eql-bindings/src/encryption/example.rs`, the Rust examples of `packages/eql/crates/eql-bindings/README.md` run as doctests, plus optional PostgreSQL coverage), an ~900-line `mise.toml` task surface, its own `AGENTS.md`, and `docs/`. See the "Working on EQL" notes below before touching it. **Repository ownership:** EQL now lives in `cipherstash/stack`. File and update EQL issues in this repository, never in the historical `cipherstash/encrypt-query-language` repository. Old upstream issue and PR diff --git a/conformance/stack-encrypt/declaration-grammar.md b/conformance/stack-encrypt/declaration-grammar.md index 86990816c9..12e59eacf8 100644 --- a/conformance/stack-encrypt/declaration-grammar.md +++ b/conformance/stack-encrypt/declaration-grammar.md @@ -149,7 +149,8 @@ With `bind`: part, a list inside the list, is refused (`bind`). - Every field's stored context is its label, extended, then the parts in order. No query context includes them, so a query on the plan is refused - (`bind_in_query`). No target field is admitted. + (`bind_in_query`). A target field is bound as any other field is: its + EQL value stores the label's column, and not the parts. - The key is reserved, like `context_field`: a field named `bind` is refused (`bind`). @@ -223,7 +224,9 @@ must never silently turn into a ciphertext-only field. For a resolver that supplies EQL types, additional existing rules apply: the target must be producible, its column label has exactly two segments, and the -plan has neither extensions nor a context field. An explicit kind matches the +plan has no context field. Extensions and `bind` parts come after a target +field's label, as they do for any other field; the EQL value stores the +label's column alone. An explicit kind matches the target's plaintext kind; otherwise that kind is inferred. Only a document target accepts JSON options. Sealed-null rules include the target's own indexes. Those resolver-dependent outcomes and normalization need an EQL profile; this 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 49341d216c..d8fceedd6c 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -253,7 +253,8 @@ The field is then stored as one EQL column, such as Go records already do this through the dynamic interface. A field there names its EQL type, such as `"target": "TextEq"`, and the engine runs that -type for the field. The Rust record derive does not support it yet. +type for the field. The Rust record derive does the same (#1658). The +field's column is the record's scope and the field's name. ```rust use eql_bindings::v4::{integer::IntegerOrd, text::TextEq}; @@ -265,8 +266,6 @@ struct Member { age: i32, } -// Not on `next` yet in Rust: EQL types as fields of a derived record. -// Go records do this today through the dynamic interface. #[derive(EncryptTarget, DecryptSource)] #[stash(struct = Member, scope = "members")] struct EncryptedMember { @@ -401,9 +400,8 @@ use stack_encrypt::json::JsonPlaintext; let column = Identifier::for_column("customers", "profile")?; -// Not on `next` yet: the new traits for EQL types, and the public -// `JsonPlaintext`. Today this needs `keyset.encrypt_as(&value, context)`, -// a `serde_json::Value`, and an owned context. +// Not on `next` yet: a context built with `Scope::new`. Today this +// passes the column itself: `.encrypt_into_with_context(&keyset, column.clone())`. let profile: JsonPlaintext = json!({ "name": "Ada", "age": 35 }).into(); let encrypted: JsonTreeDocument = profile .encrypt_into_with_context(&keyset, Scope::new(&column)) @@ -1483,31 +1481,51 @@ Base64. #### EQL types as fields - **What to build.** EQL types such as `TextEq` and `JsonTreeDocument` as - field types of the Rust record derive. In Rust today, an EQL type works - only on its own, through the older structural API, with a - `NonEmpty` context. The EQL types do derive the structural - `EncryptFrom` and `DecryptInto`. A record still cannot use them as - fields. - A record with a `TextEq` field, built against `next` on 7 November 2026, - fails with three errors. `NonEmpty` and - `ExpectedContext` do not implement `From`, and - the record derive gives each field a `CallerContext`. -- **The smallest fix.** Convert a `CallerContext` of two parts into an - `Identifier`, with the table first and the column second. `Identifier` - already gives the same context as that pair, so the stored bytes do not - change. + field types of the Rust record derive. +- **How it works.** The record derive gives each field a context of its + own: the record's scope, then the field's name. A field type that stores + its context stores that own context, as the type it stores. The stored + type implements `target::ContextFromField`. `Identifier` takes an own + context of two parts, the table first and the column second, and gives + the same context as that pair, so the stored bytes do not change. +- **What `i` stores.** The declared names only: the table and the column. + A record can also list a scope or a binding, supplied by the caller or + stored in the row. The terms of an EQL field derive under the query + context: the column, then the scope. The ciphertext is sealed under the + stored context: the column, then the scope, then the binding. A field + of any other type works the same way. `i` does not store the scope or + the binding, so the reader supplies them again, and a query supplies + the scope. An EQL field of a record nested in another stores its own + column in the same way. - **Why.** This gives the [EQL field example](#store-a-field-as-an-eql-type) and the [JSON example](#encrypt-a-json-document). -- **Done already.** The dynamic interface supports EQL fields, so Go - records use them today. A field there names its EQL type, and the engine - looks the type up by name through `eql-bindings` (the `TargetResolver` - in `dynamic/record.rs`). `Identifier` already gives the same context as - the `(table, column)` pair that a record derive builds. -- **Tracked in.** Issue #1486 is open, in part. No dedicated issue. Pull request #1504 defers the EQL owned implementations. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release must come first. +- **Done already.** In #1658: + - A Rust record with EQL fields encrypts and decrypts through the new + API, with or without a scope and a binding, and when it is nested in + another record. + - For a field of each kind (equality, storage only, order, and a JSON + document), a record with no scope writes the terms that a data plan + writes for the same declaration. A data plan is the path Go takes. + Each path opens the other's values + (`packages/eql/tests/encryption/tests/record_fields.rs`). + - `JsonTreeDocument` implements `EncryptTarget` and + `DecryptSource`. + - A query from a field's marker works for the equality and match + types, with the record's scope. A plan's query for an EQL type takes + a scope too, through the plan chain that #1488 removes. The order + types do not implement `Answers` yet, so a marker cannot query them. + - A data plan that names an EQL type takes a scope and a binding too. + `TargetResolver` receives them after the field's label, and + `TargetError::Extended` is removed. Under the same scope and binding, + a data plan and a derived record write the same terms, and each + opens the other's values. A Go struct with an `encrypt_into` field + seals through `cipher.Scope(..).Bind(..)`. +- **Tracked in.** Issue #1658. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `ContextFromField` must come before the `eql-bindings` release that uses it. - **Finished when** these are all true: - a Rust record with EQL fields encrypts, decrypts, and queries through - the new API; - - it writes the same bytes as a Go record with the same declaration. + the new API, including order queries; + - it writes the same terms as a Go record with the same declaration, + with and without a scope. #### A ready-made EQL resolver diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index bcfc2716fe..f32b0e4ec4 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -249,6 +249,32 @@ sends queries: the decoding of JSON paths and predicates, and the opening of a sealed JSON document. Stored values and query terms do not change. +### Changed + +- **An `encrypt_into` field takes a scope and a binding.** A cipher with a + scope or a binding refused a struct with a field that names an EQL type, + as `ErrEncoding`. It now seals the field as it seals any other. The scope + and the binding come after the column in the field's context: the search + terms derive under the column and the scope, and the value is sealed + under the binding too. The EQL value stores the table and the column + alone, in `i`. Open it through a cipher with the same scope and binding, + and query it through a cipher with the same scope. `Plan.Validate` takes + a plan with `Extension` or `Bind` and a target field. Values stored + through a cipher with no scope and no binding do not change. + - A `JsonSearch` document is found and read in the same way. A query, + and a read prepared with `Selector` or `Subtree`, derive under the + column and the scope. + - `Cipher.JSONOpen` opens a read's rows through a cipher with a binding, + where it refused one. Every row of one call opens under that binding. + - `Selector` and `Subtree` take a cipher with a binding, where they + refused one as `ErrEncoding`. The selector or the tokens derive under + the cipher's scopes alone, so they are the ones a cipher with the same + scopes and no binding derives. The entries open under the scopes and + the binding. So a read through a cipher with a binding reads that + binding's row. `Cipher.QueryTerm` takes a binding for the `selector` + and `subtree` operators for this. A query still refuses a binding, + and so do `Children` and `ChildCount`, whose tokens open nothing. + ## [0.1.0-rc.4] - 2026-11-13 ### Upgrading from rc.3 diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 710cee75a8..12c50c265b 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -443,7 +443,7 @@ Put the column on the left of `@@` (`WHERE name @@ $1::eql_v4.query_text_match`) Separate columns work today for four indexes: `equality`, `match`, `ore` and `ope`. A field with `encrypt_into` is stored under its table and column, which is what an EQL value records in its `i`. -A cipher extended with a tenant part (`cipher.Extend(...)`) has no column for the extended label, so it refuses a struct with an `encrypt_into` field; use `index=` columns for a tenant-extended struct until that rule is settled. +A cipher with a scope or a binding (`cipher.Scope(tenant).Bind(rowID)`) seals a struct with an `encrypt_into` field as it seals any other. The scope and the binding come after the column in the field's context, and `i` still holds the table and the column alone. Open the value through a cipher with the same scope and binding, and query it through a cipher with the same scope. ## When stashgen stops diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index d94dac78ac..dc9c7148f5 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -626,10 +626,21 @@ the column's `eql_v4.query_text_eq` operand takes; `TextEq` answers `eq` alone, and a `TextMatch` field's `Matches` returns an `encrypt.EQLMatchQuery`: the `eql.TextMatchQuery` operand with `Verify` and `TargetLimit`. `mise run -wasm:guest:build:eql` builds that guest beside the other. A cipher extended -with a tenant part refuses a struct with an `encrypt_into` field: an EQL -value is stored under a table and a column, and the extended label has no -column. +wasm:guest:build:eql` builds that guest beside the other. + +A cipher with a scope or a binding (`cipher.Scope(tenant).Bind(rowID)`) +seals a struct with an `encrypt_into` field as it seals any other struct. +The scope and the binding come after the column in the field's context. +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. ### Encrypted JSON documents diff --git a/languages/golang/encrypt/bindings_test.go b/languages/golang/encrypt/bindings_test.go index 6be958047d..95f436733a 100644 --- a/languages/golang/encrypt/bindings_test.go +++ b/languages/golang/encrypt/bindings_test.go @@ -130,16 +130,17 @@ func TestAFieldNamedBindIsRefused(t *testing.T) { } } -// An EQL type stores its column alone, so a binding has no column to sit -// under: the plan is refused, as an extended one is. -func TestABindingIsRefusedOnAnEQLType(t *testing.T) { +// An EQL type stores its column alone. A binding comes after the column in +// the field's context, so a plan with an EQL field takes one, as it takes a +// scope. The whole behaviour is in TestAnEQLFieldTakesAScopeAndABinding. +func TestABindingIsTakenOnAnEQLType(t *testing.T) { p := &record.Plan{ Context: []string{"users"}, Bind: []any{uint64(9)}, Fields: []record.Field{{Name: "email", Kind: record.String, Target: "TextEq"}}, } - if err := p.Validate(); err == nil { - t.Fatal("a bound EQL plan validated") + if err := p.Validate(); err != nil { + t.Fatalf("a bound EQL plan: %v", err) } } diff --git a/languages/golang/encrypt/cipher.go b/languages/golang/encrypt/cipher.go index d23a67ab45..abe20ce7ca 100644 --- a/languages/golang/encrypt/cipher.go +++ b/languages/golang/encrypt/cipher.go @@ -80,9 +80,11 @@ 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. 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 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. 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 5b23d85f60..ce7e0c946c 100644 --- a/languages/golang/encrypt/doc.go +++ b/languages/golang/encrypt/doc.go @@ -242,6 +242,15 @@ // A selection or a subtree read opens values as JSON text ([JSONValue], // [JSONRead.Open]). [DecodeJSON] reads one into a Go type. // +// 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 +// (Contains, EqAt, Match and the rest) opens nothing, so it takes no +// binding, and a query through a cipher with one is refused. +// // The SQL side of every JSON query, including extraction by selector, // ordered comparison at a path, subtree reads, and children, is documented // for SQL authors in the EQL v4 reference page, at diff --git a/languages/golang/encrypt/eql_test.go b/languages/golang/encrypt/eql_test.go index 30cb26635b..cbce008246 100644 --- a/languages/golang/encrypt/eql_test.go +++ b/languages/golang/encrypt/eql_test.go @@ -328,23 +328,90 @@ func TestTextEqIsRefusedByTheBuildWithoutEQLTypes(t *testing.T) { if err := eqlChecker.Check(ctx, notDocument); !errors.Is(err, encrypt.ErrEncoding) { t.Errorf("a string Json field: Check = %v, want ErrEncoding", err) } - // A declared type other than TextEq's plaintext, and an extended plan. + // A declared type other than TextEq's plaintext. wrongKind := &record.Plan{Context: []string{"users"}, Fields: []record.Field{{Name: "email", Kind: record.Uint64, Target: "TextEq"}}} if err := eqlChecker.Check(ctx, wrongKind); !errors.Is(err, encrypt.ErrEncoding) { t.Errorf("a uint64 TextEq field: Check = %v, want ErrEncoding", err) } - extended := &record.Plan{Context: []string{"users"}, Extension: []any{uint64(7)}, Fields: []record.Field{{Name: "email", Kind: record.String, Target: "TextEq"}}} - if err := eqlChecker.Check(ctx, extended); !errors.Is(err, encrypt.ErrEncoding) { - t.Errorf("an extended plan with a target field: Check = %v, want ErrEncoding", err) + // A plan with a scope and a binding: both come after a target field's + // column, so the engine takes the plan. + scoped := &record.Plan{Context: []string{"users"}, Extension: []any{uint64(7)}, Bind: []any{uint64(9)}, Fields: []record.Field{{Name: "email", Kind: record.String, Target: "TextEq"}}} + if err := eqlChecker.Check(ctx, scoped); err != nil { + t.Errorf("a plan with a scope, a binding and a target field: Check = %v", err) } } -func TestExtendedCipherRefusesATextEqField(t *testing.T) { +// A scope and a binding come after the column in an EQL field's context, as +// they do for a field with outputs. The EQL value stores the column alone. +// So a query supplies the scope, and whoever opens the value supplies the +// scope and the binding again. +func TestAnEQLFieldTakesAScopeAndABinding(t *testing.T) { c := deterministicEQLClient(t) ctx := context.Background() - tenant := c.DefaultKeyset().Extend(uint64(7)) - _, err := testusers.EncryptContact(ctx, tenant, contacts[:1]) - if !errors.Is(err, encrypt.ErrEncoding) { - t.Fatalf("an extended cipher sealed a TextEq field: %v", err) + plain := c.DefaultKeyset() + tenant := plain.Scope(uint64(7)) + bound := tenant.Bind(uint64(9)) + + encrypted, err := testusers.EncryptContact(ctx, bound, contacts[:1]) + if err != nil { + t.Fatalf("a cipher with a scope and a binding did not seal a TextEq field: %v", err) + } + env := decodeEnvelope(t, encrypted[0].Email) + if env.I.T != "users" || env.I.C != "email" { + t.Errorf("i = %+v, want users/email and nothing else", env.I) + } + + // The term is derived under the column, then the tenant. A query through + // the tenant's cipher gives the stored term, and names the column alone. + hmOf := func(cipher *encrypt.Cipher) string { + t.Helper() + query, err := testusers.ContactFields.Email.Eq(ctx, cipher, contacts[0].Email) + if err != nil { + t.Fatal(err) + } + var probe struct { + I struct{ T, C string } + HM string `json:"hm"` + } + if err := json.Unmarshal(query, &probe); err != nil { + t.Fatal(err) + } + if probe.I.T != "users" || probe.I.C != "email" { + t.Errorf("the query's i = %+v, want users/email", probe.I) + } + return probe.HM + } + if hm := hmOf(tenant); hm != env.HM { + t.Errorf("the tenant's query has hm %s, and the stored value %s", hm, env.HM) + } + if hmOf(plain) == env.HM || hmOf(plain.Scope(uint64(8))) == env.HM { + t.Error("a query with no tenant, or with another, gave the tenant's term") + } + // A binding is in no query context: another row has the same term. + other, err := testusers.EncryptContact(ctx, tenant.Bind(uint64(10)), contacts[:1]) + if err != nil { + t.Fatal(err) + } + if decodeEnvelope(t, other[0].Email).HM != env.HM { + t.Error("another row of the tenant has another term") + } + + // The value opens under the same scope and binding, and under no other. + decrypted, err := testusers.DecryptContact(ctx, bound, encrypted) + if err != nil { + t.Fatal(err) + } + if decrypted[0] != contacts[0] { + t.Errorf("opened %+v, want %+v", decrypted[0], contacts[0]) + } + for name, cipher := range map[string]*encrypt.Cipher{ + "another tenant": plain.Scope(uint64(8)).Bind(uint64(9)), + "another row": tenant.Bind(uint64(10)), + "no binding": tenant, + "no scope": plain, + } { + if _, err := testusers.DecryptContact(ctx, cipher, encrypted); err == nil { + t.Errorf("%s: the value opened", name) + } } } diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 7cfbdabd07..d7a829ae08 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -192,9 +192,10 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::Predicate { .. } => STATUS_ENCODING, Error::Cipher(e) => status_for_error(e), // A target refusal is a statement about the plan, the label or the - // value (an unknown or unproducible type, an extended plan, a value - // of another kind, stored bytes that are not the type) — malformed - // input, like the rest — save the resolver's own failure. + // value (an unknown or unproducible type, a label that is not a + // column, a value of another kind, stored bytes that are not the + // type) — malformed input, like the rest — save the resolver's own + // failure. Error::Target(stack_encrypt::dynamic::TargetError::Other(_)) => STATUS_INTERNAL, Error::Target(_) => STATUS_ENCODING, Error::Internal => STATUS_INTERNAL, @@ -471,10 +472,6 @@ mod tests { name: "DateOrdOre".into(), reason: "no kind for this family".into(), }, - TargetError::Extended { - name: "email".into(), - label: "users/email".into(), - }, TargetError::ContextField { name: "email".into(), context_field: "tenant".into(), diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index 2e9b15d801..64d6deea94 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -36,11 +36,21 @@ import ( // text of each value the read reached, in document order: plaintext, which // the caller owns. One ZeroKMS request for every group. For generated code. // +// The rows open under the contexts their document was sealed under. So a +// document sealed through a cipher with a scope opens through a cipher with +// the same scope. A document sealed through a cipher with a binding too +// opens through a cipher with the same scope and binding, and every group +// 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. +// // 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) { - p, err := cph.queryPlan(plan, field) + p, err := cph.readPlan(plan, field) if err != nil { return nil, err } @@ -233,6 +243,12 @@ type JSONRange[Q ~[]byte] struct { // the cipher's keyset), so the entries open only as answers to it: the // engine derives the selector again and refuses an entry that does not // carry it. E is the column's entry type, eql.JSONEntry. +// +// It keeps the cipher it was prepared through, and opens through it. A +// cipher with a binding prepares one: the selector derives under the +// cipher's scopes alone, so it is the selector a cipher with the same +// scopes and no binding derives, and the entries open under the scopes and +// the binding. type JSONSelection[E ~[]byte] struct { cipher *Cipher plan *record.Plan @@ -281,6 +297,12 @@ func (s JSONSelection[E]) LogValue() slog.Value { // whole document; a nil opens to no value. A container's entry is refused: // read a container with a subtree read. An entry that is not the selector's // is [ErrEncoding]. +// +// Every entry of one call opens under the binding of the cipher the +// selection was prepared through. So through a cipher with a binding, pass +// only the entry of the row that binding names. An entry sealed under +// another binding, or under none where the cipher has one, does not open: +// ZeroKMS refuses its data key. func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, error) { if s.cipher == nil { return nil, fmt.Errorf("%w: a zero JSONSelection has no request to open against", ErrEncoding) @@ -320,6 +342,11 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err // the path, the bound and the cipher's keyset); the engine derives the read // again from it, and checks every row against it. E is the column's entry // type, eql.JSONEntry. +// +// It keeps the cipher it was prepared through, and opens through it, as a +// [JSONSelection] does: through a cipher with a binding the tokens are +// those of the cipher's scopes alone, and the rows open under the scopes +// and the binding. type JSONRead[E ~[]byte] struct { cipher *Cipher plan *record.Plan @@ -375,6 +402,12 @@ func (r JSONRead[E]) LogValue() slog.Value { // the read asked for, or a wildcard read of an array longer than the bound, // is [ErrEncoding]. // +// Every group 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 +// group of the row that binding names. An entry sealed under another +// binding, or under none where the cipher has one, does not open: ZeroKMS +// refuses its data key. +// // Opening checks each row against the read, not that the database // returned every row it should have, nor that the rows came from the row // the caller meant. diff --git a/languages/golang/encrypt/json_fields_test.go b/languages/golang/encrypt/json_fields_test.go index 6384c92d7f..8ea000cd7d 100644 --- a/languages/golang/encrypt/json_fields_test.go +++ b/languages/golang/encrypt/json_fields_test.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "reflect" + "slices" "strings" "testing" @@ -222,3 +223,197 @@ func TestJSONReadTypesPrintAndLogRedacted(t *testing.T) { t.Errorf("slog records no field or token count: %s", logged.String()) } } + +// 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. +func subtreeLeafRow(t *testing.T, entry []byte) eql.JSONEntry { + t.Helper() + var fields map[string]json.RawMessage + if err := json.Unmarshal(entry, &fields); err != nil { + t.Fatal(err) + } + fields["d"] = json.RawMessage(`0`) + row, err := json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + return eql.JSONEntry(row) +} + +// 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. +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}`)}} + const path = "$.name" + + // selectorRead opens the entry `col -> selector` returns through + // cipher. + selectorRead := func(cipher *encrypt.Cipher, document []byte) (encrypt.JSONSelector, error) { + t.Helper() + sel, err := f.Selector(ctx, cipher, path) + if err != nil { + return "", err + } + entry := jsonEntry(t, document, string(sel.Selector())) + if entry == nil { + t.Fatal("the selector names no entry of the document") + } + row := eql.JSONEntry(entry) + values, err := sel.Open(ctx, []*eql.JSONEntry{&row}) + if err != nil { + return sel.Selector(), err + } + if len(values) != 1 || !values[0].Found || string(values[0].JSON) != `"Alice"` { + t.Fatalf("the selection opened %+v", values) + } + return sel.Selector(), nil + } + // subtreeRead opens the row json_tree_subtree returns through cipher. + subtreeRead := func(cipher *encrypt.Cipher, document []byte) (encrypt.JSONTokens, error) { + t.Helper() + read, err := f.Subtree(ctx, cipher, path, encrypt.JSONReadOptions{}) + if err != nil { + return nil, err + } + // The entry the selector at the same path names is the scalar's + // node: the row json_tree_subtree returns for it. + sel, err := f.Selector(ctx, cipher, path) + if err != nil { + return nil, err + } + entry := jsonEntry(t, document, string(sel.Selector())) + if entry == nil { + t.Fatal("the selector names no entry of the document") + } + value, err := read.OpenOne(ctx, []eql.JSONEntry{subtreeLeafRow(t, entry)}) + if err != nil { + return read.Tokens(), err + } + if !value.Found || string(value.JSON) != `"Alice"` { + t.Fatalf("the subtree read opened %+v", value) + } + return read.Tokens(), nil + } + + plain := c.DefaultKeyset() + for _, scoped := range []struct { + name string + cipher *encrypt.Cipher + }{ + {"no scope", plain}, + {"a scope", plain.Scope(uint64(7))}, + } { + t.Run(scoped.name, func(t *testing.T) { + bound := scoped.cipher.Bind(uint64(9)) + encrypted, err := testusers.EncryptCustomer(ctx, bound, in) + if err != nil { + t.Fatal(err) + } + document := []byte(encrypted[0].Profile) + + selector, err := selectorRead(bound, document) + if err != nil { + t.Fatalf("Selector through the cipher that sealed the document: %v", err) + } + tokens, err := subtreeRead(bound, document) + if err != nil { + t.Fatalf("Subtree 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 { + t.Errorf("the bound cipher's selector is not its scopes' own: %v", err) + } + unboundRead, err := f.Subtree(ctx, scoped.cipher, path, encrypt.JSONReadOptions{}) + if err != nil || !slices.Equal(unboundRead.Tokens(), tokens) { + t.Errorf("the bound cipher's tokens are not its scopes' own: %v", err) + } + // A binding part Bind refuses is reported when the read is + // prepared, not when it opens. + if _, err := f.Selector(ctx, scoped.cipher.Bind(""), path); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("Selector through a cipher with an empty binding: %v, want ErrEncoding", err) + } + 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) + } + + // An ordered path's accessor prepares its selection the same way. + atAge, err := f.At.Age.Selector(ctx, bound) + if err != nil { + t.Fatalf("At.Age.Selector through a cipher with a binding: %v", err) + } + if want, err := f.Selector(ctx, scoped.cipher, "$.age"); err != nil || atAge.Selector() != want.Selector() { + t.Errorf("At.Age's selector is not its scopes' own: %v", err) + } + + // A cipher with the same scopes and another binding, or none, + // finds the entry and does not open it: the entry was sealed + // under the binding, so ZeroKMS refuses its data key + // (ErrForbidden), as it refuses a record's. + for whose, other := range map[string]*encrypt.Cipher{ + "no binding": scoped.cipher, + "another row": scoped.cipher.Bind(uint64(10)), + } { + if _, err := selectorRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("%s: Selector opened the entry, or not as ErrForbidden: %v", whose, err) + } + if _, err := subtreeRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("%s: Subtree opened the row, 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. + 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 }(), + "EqAt": func() error { _, err := f.EqAt(ctx, bound, path, "Alice"); return err }(), + "At.Age.Lt": func() error { _, err := f.At.Age.Lt(ctx, bound, 40); return err }(), + "Match": func() error { + _, err := f.Match(ctx, bound, `$.age < 40`, map[string]any{}, encrypt.JSONReadOptions{}) + return err + }(), + "Elements.Visits.Match": func() error { + _, 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) { + t.Errorf("%s through a cipher with a binding: %v, want ErrEncoding", name, err) + } + } + + // A document sealed with no binding reads through a cipher with + // no binding, and not through one with a binding. + plainEncrypted, err := testusers.EncryptCustomer(ctx, scoped.cipher, in) + if err != nil { + t.Fatal(err) + } + plainDocument := []byte(plainEncrypted[0].Profile) + if _, err := selectorRead(scoped.cipher, plainDocument); err != nil { + t.Errorf("Selector of a document sealed with no binding: %v", err) + } + if _, err := subtreeRead(scoped.cipher, plainDocument); err != nil { + t.Errorf("Subtree of 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) + } + if _, err := subtreeRead(bound, plainDocument); !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("a bound cipher's Subtree opened a document sealed with no binding: %v", err) + } + }) + } +} diff --git a/languages/golang/encrypt/json_tree_test.go b/languages/golang/encrypt/json_tree_test.go index 9fd49a5037..253cc4506b 100644 --- a/languages/golang/encrypt/json_tree_test.go +++ b/languages/golang/encrypt/json_tree_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "reflect" + "slices" "strings" "testing" @@ -262,6 +263,152 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { } } +// 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. +func jsonEntry(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) + } + 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) + out, _ := json.Marshal(entry) + return out + } + } + return nil +} + +// A JSON document sealed through a cipher with a scope, or with a scope and +// a binding, is found and read under them. +// +// Its selectors derive under the column, then the scope, so a cipher with +// the scope finds its entries, and a cipher with another scope, or none, +// does not. A binding is in no query, and a read derives its selector +// under the scope alone. The entries open under the scope and the binding, +// so a cipher with another binding, or none, finds an entry and does not +// open it. +func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { + c := deterministicEQLClient(t) + ctx := context.Background() + plain := c.DefaultKeyset() + tenant := plain.Scope(uint64(7)) + bound := tenant.Bind(uint64(9)) + source := []record.Source{{"profile": []byte(`{"name":"Alice","age":34}`)}} + request := vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}} + selector := func(cipher *encrypt.Cipher) string { + t.Helper() + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "selector", vcvalue.Object{{Key: "path", Value: "$.name"}}) + if err != nil { + t.Fatal(err) + } + return term.Text[0] + } + opens := func(cipher *encrypt.Cipher, entry []byte) error { + t.Helper() + opened, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", request, [][][]byte{{entry}}) + if err != nil { + return err + } + if len(opened) != 1 || len(opened[0]) != 1 || string(opened[0][0]) != `"Alice"` { + t.Fatalf("opened %q", opened) + } + return nil + } + + for _, sealedBy := range []struct { + name string + cipher *encrypt.Cipher + // The ciphers that find the entry and do not open it. + closed map[string]*encrypt.Cipher + }{ + {"a scope", tenant, map[string]*encrypt.Cipher{ + "a binding the document was not sealed under": bound, + }}, + {"a scope and a binding", bound, map[string]*encrypt.Cipher{ + "another row": tenant.Bind(uint64(10)), + "no row": tenant, + }}, + } { + t.Run(sealedBy.name, func(t *testing.T) { + sealed, err := sealedBy.cipher.Seal(ctx, jsonPlan(), source) + if err != nil { + t.Fatalf("the cipher did not seal a JSON document: %v", err) + } + document := sealed[0]["profile"].EQL + var stored struct{ I struct{ T, C string } } + if err := json.Unmarshal(document, &stored); err != nil { + t.Fatal(err) + } + if stored.I.T != "users" || stored.I.C != "profile" { + t.Errorf("i = %+v, want users/profile and nothing else", stored.I) + } + + // A read prepared with the scope and no binding opens through the + // cipher the document was sealed through. + name := jsonEntry(t, document, selector(tenant)) + if name == nil { + t.Fatal("the tenant's selector names no entry of the tenant's document") + } + if err := opens(sealedBy.cipher, name); err != nil { + t.Fatalf("the cipher that sealed the document did not open its entry: %v", err) + } + for whose, other := range sealedBy.closed { + if err := opens(other, name); err == nil { + t.Errorf("%s: the entry opened", whose) + } + } + for whose, other := range map[string]*encrypt.Cipher{ + "another tenant": plain.Scope(uint64(8)), + "no tenant": plain, + } { + if jsonEntry(t, document, selector(other)) != nil { + t.Errorf("%s: the selector names an entry of the tenant's document", whose) + } + if err := opens(other, name); err == nil { + t.Errorf("%s: the entry opened", whose) + } + } + }) + } + + // 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. + if got := selector(bound); got != selector(tenant) { + t.Errorf("a selector through a cipher with a binding is not the tenant's") + } + subtree := func(cipher *encrypt.Cipher) ([]string, error) { + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "subtree", vcvalue.Object{{Key: "path", Value: "$.name"}}) + return term.Text, err + } + boundTokens, err := subtree(bound) + if err != nil { + t.Fatalf("a subtree read through a cipher with a binding: %v", err) + } + 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"} { + input := vcvalue.Object{{Key: "path", Value: "$.name"}} + if operator == "eq_at" { + input = append(input, vcvalue.Field{Key: "json", Value: []byte(`"Alice"`)}) + } + if _, err := bound.QueryTerm(ctx, jsonPlan(), "profile", operator, input); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("%s through a cipher with a binding: %v, want ErrEncoding", operator, err) + } + } +} + // decodeNumbers decodes JSON text with each number kept as its text. func decodeNumbers(text []byte) (any, error) { dec := json.NewDecoder(bytes.NewReader(text)) diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index f2c0182229..ff6cefaaa3 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -128,9 +128,15 @@ func (l Limit) FetchOr(page uint64) uint64 { // know, is [ErrEncoding] naming the field, as a mistyped value is; match // text that cuts no token is [ErrTerm]. A range the wrong way round is not // 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]). // 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.queryPlan(plan, field) + p, err := cph.operandPlan(plan, field, operator) if err != nil { return QueryTerm{}, err } diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index bb19e369c7..730598110d 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -185,6 +185,45 @@ func (cph *Cipher) queryPlan(plan *record.Plan, field string) (*record.Plan, err if len(p.Bind) != 0 { return nil, fmt.Errorf("%w: field %q: a query takes no binding; a binding is in the stored context only, so a query by the scopes alone finds the row", ErrEncoding, field) } + 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. +func (cph *Cipher) operandPlan(plan *record.Plan, field, operator string) (*record.Plan, error) { + if operator == "selector" || operator == "subtree" { + // The copy keeps the cipher's error, so a binding part Bind refused + // is reported here, before the read is prepared. + scopes := cph.copy() + scopes.bindings = nil + return scopes.queryPlan(plan, field) + } + return cph.queryPlan(plan, field) +} + +// readPlan is the plan a read of field's document opens under: as +// [Cipher.queryPlan], and with this cipher's bindings. The engine derives +// the read's selector or key under the scopes, as it derives a query's +// term. It opens each entry under the bindings too, because the document +// was sealed under them. +func (cph *Cipher) readPlan(plan *record.Plan, field string) (*record.Plan, error) { + p, err := cph.plan(plan) + if err != nil { + return nil, err + } + return cph.underNamedContext(p, field) +} + +// underNamedContext is p for a query or a read on field: p itself, or for +// a plan that takes its context from a field, p under the context named +// with [Cipher.Context]. +func (cph *Cipher) underNamedContext(p *record.Plan, field string) (*record.Plan, error) { if p.ContextField == "" { return p, nil } diff --git a/languages/golang/internal/record/record.go b/languages/golang/internal/record/record.go index 17f0cc5389..7fc5e51a12 100644 --- a/languages/golang/internal/record/record.go +++ b/languages/golang/internal/record/record.go @@ -436,19 +436,18 @@ func (p *Plan) Validate() error { if len(f.Outputs) != 0 { return fmt.Errorf("record: field %q names the EQL type %s and outputs; a field has one or the other", f.Name, f.Target) } - // An EQL value is stored under a table and a column: the - // context is the table, the identity the column. The engine - // refuses anything else when the plan is built; saying it here - // names the field before the guest is asked. + // An EQL value stores a table and a column: the context is the + // table, the identity the column. The engine refuses any other + // context when the plan is built; saying it here names the + // field before the guest is asked. + // + // The plan's scopes (Extension) and bindings (Bind) come after + // the column, as they do for a field with outputs. The EQL + // value does not store them, so whoever reads it supplies them + // again. if len(p.Context) != 1 { return fmt.Errorf("record: field %q names the EQL type %s, and an EQL column is a table and a column: the context %q has %d segments, not one", f.Name, f.Target, strings.Join(p.Context, "/"), len(p.Context)) } - if len(p.Extension) != 0 { - return fmt.Errorf("record: field %q names the EQL type %s, and an EQL column is a table and a column: an extended context has no column", f.Name, f.Target) - } - if len(p.Bind) != 0 { - return fmt.Errorf("record: field %q names the EQL type %s, and an EQL column is a table and a column: a bound context has no column", f.Name, f.Target) - } continue } if len(f.Outputs) == 0 { diff --git a/languages/golang/internal/record/record_test.go b/languages/golang/internal/record/record_test.go index af71701935..113db00e2f 100644 --- a/languages/golang/internal/record/record_test.go +++ b/languages/golang/internal/record/record_test.go @@ -105,16 +105,18 @@ func TestTargetFieldWiresItsTypeInsteadOfOutputs(t *testing.T) { if err := both.Validate(); err == nil { t.Fatal("a field with a target and outputs was accepted") } - // An EQL column is a table and a column: a two-segment context, or an - // extension, leaves the target field no column, and the refusal names - // the field — before the guest is asked. + // An EQL column is a table and a column: a two-segment context leaves + // the target field no column, and the refusal names the field — before + // the guest is asked. deep := &Plan{Context: []string{"app", "users"}, Fields: []Field{{Name: "email", Kind: String, Target: "TextEq"}}} if err := deep.Validate(); err == nil || !strings.Contains(err.Error(), `field "email"`) || !strings.Contains(err.Error(), `"app/users" has 2 segments`) { t.Fatalf("a target under app/users: %v", err) } - extended := &Plan{Context: []string{"users"}, Extension: []any{uint64(7)}, Fields: []Field{{Name: "email", Kind: String, Target: "TextEq"}}} - if err := extended.Validate(); err == nil || !strings.Contains(err.Error(), "extended context has no column") { - t.Fatalf("an extended target: %v", err) + // A scope and a binding come after the column, so a target field takes + // both. The EQL value stores the column alone. + scoped := &Plan{Context: []string{"users"}, Extension: []any{uint64(7)}, Bind: []any{uint64(9)}, Fields: []Field{{Name: "email", Kind: String, Target: "TextEq"}}} + if err := scoped.Validate(); err != nil { + t.Fatalf("a target under a scope and a binding: %v", err) } // The same context seals a plain field as before. plain := &Plan{Context: []string{"app", "users"}, Fields: []Field{{Name: "email", Kind: String, Outputs: []Output{Ciphertext}}}} diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 55ddde4b0e..03db2eaf9e 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -1224,6 +1224,7 @@ dependencies = [ "tokio", "uuid", "vitaminc-aead 0.10.0", + "zeroize", ] [[package]] diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index a21c71541e..3ac5b71242 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -9,6 +9,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **EQL types as record fields** (#1658). An EQL v4 type can be a field + of a Stack Encrypt `#[derive(EncryptTarget, DecryptSource)]` record + with `struct = ..`. The field's column is the record's scope and the + field's name: `scope = "members"` and the field `email` store + `{"t": "members", "c": "email"}` in `i`. The field writes the terms the + type writes on its own under `Identifier::for_column("members", + "email")`, and the terms a data plan that names the type writes. + - `Identifier` implements `stack_encrypt::target::ContextFromField`. + - A record can list a scope or a binding, such as `scope(tenant: u64)` + or `bind(row: u128)`, supplied by the caller or stored in the row. The + terms of an EQL field then derive under the column and the scope. The + ciphertext is sealed under the column, the scope and the binding. A + field of any other type works the same way. `i` stores the column + alone, and nothing a caller supplies. The reader supplies the scope + and the binding again. + - An EQL field of a record nested in another stores its own column too. + The outer record's names come after it in the field's context. + - A query from the field's marker, such as `EncryptedMember::EMAIL.eq(..)`, + gives the term stored in the row, for the types that answer it. For a + record with a scope, pass the scope: `.scope(Scope::new(tenant))`. + - A plan's query for an EQL type can carry a scope too. It gives the + term of the values stored under that scope, so `QueryLabelError` has + no `Extended` variant. + - A data plan that names an EQL type takes a scope and a binding too + (`targets` feature). `EqlTargets` runs the type under the field's + label, then the plan's scopes and bindings, and the value stores the + column alone. Under the same scope and binding, a data plan and a + derived record write the same terms, and each opens the other's + values. This is the path the Go module takes. + - The encrypt input of an EQL type is the hidden + `stack_encrypt::target::StoredContext`. A caller passes a + `NonEmpty`. Generic code names the input as + `ContextInput: AcceptsContext>`. + +- **`JsonTreeDocument` implements `EncryptTarget` and + `DecryptSource`** (#1658). It encrypts from a + `JsonPlaintext` under the default options, with the column as its + context, and writes the search terms that `JsonTree::default()` writes + for the same document. It can be a record field too. It also + implements `DecryptInto`, the form a record field opens + through, as every other EQL type does. + - **`Target::leaf_query_sql_domain`** (`targets` feature, #1350): the domain a document type's ordering at a path binds as, `eql_v4.query_json_leaf` for `JsonSearch` and `None` for every @@ -138,9 +180,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 does not answer, or another index named with `.via(..)`, does not compile. Each answering type is an `op::LabelledTarget`. The label must name the column, table then column, - and the query must not be extended, or the awaited query is refused - before any keyset is resolved, with a `QueryLabelError` in - `Error::Other`. `eql_bindings::encryption::query` holds `TwinIndex` + or the awaited query is refused before any keyset is resolved, with a + `QueryLabelError` in `Error::Other`. `eql_bindings::encryption::query` holds `TwinIndex` (Stack Encrypt's index, its query sent as the twin, for the twin's own plaintext only), `MatchTwin`, `QueryTwin` and `QueryLabelError`. `Hmac256` and `BloomFilter` now declare their indexes (`EncryptFrom::indexes`), diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index af167efb2a..850d23e8cf 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -119,6 +119,20 @@ Plans, the dynamic layer, and `encrypt_as` still use them, until Stack Encrypt removes them. Stack Encrypt writes EQL v4 only, so no `v3` type implements these traits. `eql-codegen` emits the derives. +Each Rust example in this file is a complete program, and the encryption +test crate runs it as a doctest: + +```bash +# From packages/eql: +cargo test -p eql-encryption-tests --doc +``` + +The examples build their cipher over `FakeDataKeySource`, from the +`test-support` feature of `stack-kms`. It holds its keys in memory, so an +example needs no credentials. A real program passes its own key source to +`.kms(..)`, or leaves `.kms(..)` out to use ZeroKMS. That needs Stack +Encrypt's `http` feature, which is on by default. + The other v4 types Stack Encrypt produces take a Rust primitive as their plaintext, or, for a date, a timestamp or a decimal, one of `eql_bindings::v4::plaintext`'s types: @@ -219,19 +233,33 @@ repeated member, valid Unicode), and a `c` that opens but does not hold a document is `Error::OpenedType`. Nothing inside a `Json` value can be queried: use `JsonSearch` for a document that is searched. -```rust,ignore +```rust use eql_bindings::v4::{json::Json, plaintext::JsonPlaintext}; use eql_bindings::Identifier; use serde_json::json; -use stack_encrypt::{DecryptFrom, EncryptInto}; - -let column = Identifier::for_column("users", "profile")?; -let profile = JsonPlaintext::from(json!({"name": "Ada", "tags": ["maths"]})); -let stored: Json = profile.encrypt_into_with_context(&keyset, column.clone()).await?; -// INSERT ... VALUES ($1::public.eql_v4_json), binding sqlx::types::Json(&stored) - -let opened = JsonPlaintext::decrypt_from_with_context(stored, &keyset, column).await?; -assert_eq!(opened.value()["tags"][0], "maths"); +use stack_encrypt::{DecryptFrom, EncryptInto, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + + let column = Identifier::for_column("users", "profile")?; + let profile = JsonPlaintext::from(json!({"name": "Ada", "tags": ["maths"]})); + let stored: Json = profile + .encrypt_into_with_context(&keyset, column.clone()) + .await?; + // INSERT ... VALUES ($1::public.eql_v4_json), binding sqlx::types::Json(&stored) + + let opened = JsonPlaintext::decrypt_from_with_context(stored, &keyset, column).await?; + assert_eq!(opened.value()["tags"][0], "maths"); + Ok(()) +} ``` Each ordered v4 family also has two range query types, one per order term: @@ -247,32 +275,45 @@ resolve an untyped `$1`. Nothing produces a range yet, since the ordered types are not producible, and Stack Encrypt will need to build the envelope when they are. EQL v3 has no range types or `between`. -The generated API docs include a complete, executable example in the -`eql_bindings::encryption` module, from cipher setup through decryption. Its -[source](src/encryption/example.rs) is also run by the encryption test crate: +A text column with an equality term, from cipher setup through decryption: -```bash -# From packages/eql: -cargo test -p eql-encryption-tests --test text_eq_example +```rust +use eql_bindings::v4::text::{TextEq, TextEqQuery}; +use eql_bindings::Identifier; +use stack_encrypt::{DecryptFrom, EncryptInto, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + + let column = Identifier::for_column("users", "email")?; + let stored: TextEq = "alice@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column.clone()) + .await?; + // The query for the same text carries the stored equality term. + let query: TextEqQuery = "alice@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column.clone()) + .await?; + assert_eq!(query.hm, stored.hm); + + let opened = String::decrypt_from_with_context(stored, &keyset, column).await?; + assert_eq!(opened, "alice@example.com"); + Ok(()) +} ``` -With an initialized cipher, the essential calls are: - -```rust,ignore -use eql_bindings::{Identifier, v4::text::{TextEq, TextEqQuery}}; - -use stack_encrypt::{DecryptFrom, EncryptInto}; - -let column = Identifier::for_column("users", "email")?; -let keyset = cipher.default_keyset(); -let stored: TextEq = "alice@example.com".to_owned() - .encrypt_into_with_context(&keyset, column.clone()) - .await?; -let query: TextEqQuery = "alice@example.com".to_owned() - .encrypt_into_with_context(&keyset, column.clone()) - .await?; -let opened = String::decrypt_from_with_context(stored, &keyset, column).await?; -``` +The generated API docs of the `eql_bindings::encryption` module show the same +steps. That example is a program of its own +([source](src/encryption/example.rs)), which the encryption test crate runs +too: `cargo test -p eql-encryption-tests --test text_eq_example`. Both identifier components must be nonempty. Encryption stores the identifier in `i`; its table and column supply the ciphertext AAD, term context, and ZeroKMS @@ -318,22 +359,52 @@ A query names an operator, and a plan for the column's EQL type finds the index that answers it (Stack Encrypt's ADR-0009). The term that comes back is the type's query twin, the value the `eql_v4.query_*` domain takes: -```rust,ignore +```rust use eql_bindings::v4::text::{TextEq, TextMatch}; use stack_encrypt::op::{self, Probabilistic, Stats}; -use stack_encrypt::Plan; - -// A plan for the column's type, under the label that names the column: -// "users/email" is Identifier::for_column("users", "email"). -let email_plan = Plan::value::().context("users/email").encrypt_into::().build()?; -let query = cipher.query(op::Eq, "alice@example.com").on(&email_plan).await?; // a TextEqQuery -// WHERE email = $1::eql_v4.query_text_eq, binding sqlx::types::Json(&query) - -let name_plan = Plan::value::().context("users/name").encrypt_into::().build()?; -let query = cipher.query(op::Matches, "ali").on(&name_plan).await?; // a MatchTwin -let fetch = query.target_limit(10, &Stats::declared(1_000_000)).fetch_or(50); -// WHERE name @@ $1::eql_v4.query_text_match LIMIT $2, then keep the -// decrypted rows for which query.verify(&name) is true. +use stack_encrypt::{Plan, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + + // A plan for the column's type, under the label that names the column: + // "users/email" is Identifier::for_column("users", "email"). + let email_plan = Plan::value::() + .context("users/email") + .encrypt_into::() + .build()?; + // A `TextEqQuery`. + let query = cipher + .query(op::Eq, "alice@example.com") + .on(&email_plan) + .await?; + // WHERE email = $1::eql_v4.query_text_eq, binding sqlx::types::Json(&query) + assert_eq!(query.i.t, "users"); + assert_eq!(query.i.c, "email"); + + let name_plan = Plan::value::() + .context("users/name") + .encrypt_into::() + .build()?; + // A `MatchTwin`. + let query = cipher.query(op::Matches, "ali").on(&name_plan).await?; + // How many rows to fetch to expect 10 real matches in a million. + let fetch = query + .target_limit(10, &Stats::declared(1_000_000)) + .fetch_or(50); + assert!(fetch >= 10); + // WHERE name @@ $1::eql_v4.query_text_match LIMIT $2, binding `fetch`. + // Then keep the decrypted rows that verify. + assert!(query.verify("Alice Nguyen")); + assert!(!query.verify("Bob Li")); + Ok(()) +} ``` | v4 type | Operator | Query term | @@ -355,11 +426,9 @@ once, and the chain sends one index's term. Query them through the data path (`stack_encrypt::dynamic::query_term`) for now. The label must name the column the value was written under, as two -segments, table then column. A label of any other length, and a query -extended with `.extend(..)` (whose terms would be derived under more than -the column the twin stores), are refused when the query is awaited, before -any keyset is resolved, with an `encryption::query::QueryLabelError` in -`Error::Other`. A label's segments are plain, so a table or column name +segments, table then column. A label of any other length is refused when +the query is awaited, before any keyset is resolved, with an +`encryption::query::QueryLabelError` in `Error::Other`. A label's segments are plain, so a table or column name that is not a plain label segment cannot be named on a plan, and such a column, which `Identifier::for_column` accepts, cannot be queried this way: for instance a name that starts with a digit, `-` or `b64:`, or one holding @@ -398,6 +467,151 @@ the domain check on insert. A plain `=` between a v3 column and a v4 query term still returns zero rows with no error, so keep each column to one version. +### EQL types as record fields + +An EQL type can be a field of a Stack Encrypt record. The record derive gives +each field the record's scope and the field's name, and the EQL type stores +that pair as its column in `i`: + +```rust +use eql_bindings::v4::{integer::IntegerOrd, json_tree::JsonTreeDocument, text::TextEq}; +use serde_json::json; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[derive(zeroize::Zeroize)] +struct Member { + id: u64, + email: String, + age: i32, + profile: JsonPlaintext, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Member, scope = "members")] +struct EncryptedMember { + #[stash(passthrough)] + id: u64, + email: TextEq, // i = {"t": "members", "c": "email"} + age: IntegerOrd, // i = {"t": "members", "c": "age"} + profile: JsonTreeDocument, // i = {"t": "members", "c": "profile"} +} + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + + let member = Member { + id: 7, + email: "alice@example.com".into(), + age: 36, + profile: JsonPlaintext::from(json!({"name": "Alice"})), + }; + let stored: EncryptedMember = member.encrypt_into(&keyset).await?; + assert_eq!(stored.email.i.t, "members"); + assert_eq!(stored.email.i.c, "email"); + + // A query from the field's marker carries the stored equality term. + let query = EncryptedMember::EMAIL + .eq("alice@example.com") + .encrypt(&keyset) + .await?; + assert_eq!(query.hm, stored.email.hm); + + let opened = Member::decrypt_from(stored, &keyset).await?; + assert_eq!(opened.email, "alice@example.com"); + Ok(()) +} +``` + +Each field writes the terms its type writes on its own under +`Identifier::for_column("members", )`, and the terms a data plan that +names the type writes. On decrypt, each field's stored `i` must be its own +column, checked before any key is requested. So a renamed field does not +read the rows written under its old name. Keep the old name with +`#[stash(identity = "email")]`, as for a field of any other type. + +A record can also list a scope or a binding, such as a tenant or a row ID. +The caller passes them as `Scope::new(tenant).bind(row)`. This record has +one EQL field, to keep the example short: + +```rust +use eql_bindings::v4::text::TextEq; +use stack_encrypt::target::Scope; +use stack_encrypt::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[derive(zeroize::Zeroize)] +struct Member { + id: u64, + email: String, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Member, scope = "members", scope(tenant: u64), bind(row: u128))] +struct EncryptedMember { + #[stash(passthrough)] + id: u64, + email: TextEq, // i = {"t": "members", "c": "email"} +} + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + let tenant = 42u64; + let row = 9u128; + + let member = Member { + id: 7, + email: "alice@example.com".into(), + }; + let stored: EncryptedMember = member + .encrypt_into_with_context(&keyset, Scope::new(tenant).bind(row)) + .await?; + // `i` stores the table and the column, and not the tenant or the row. + assert_eq!(stored.email.i.t, "members"); + assert_eq!(stored.email.i.c, "email"); + + // A query supplies the scope, and no binding. + let query = EncryptedMember::EMAIL + .eq("alice@example.com") + .scope(Scope::new(tenant)) + .encrypt(&keyset) + .await?; + assert_eq!(query.hm, stored.email.hm); + + // The reader supplies the scope and the binding again. + let opened = + Member::decrypt_from_with_context(stored, &keyset, Scope::new(tenant).bind(row)).await?; + assert_eq!(opened.email, "alice@example.com"); + Ok(()) +} +``` + +`i` stores the table and the column, and nothing a caller supplies. A field +of any other type uses the scope and the binding in the same way: + +- the terms of the field derive under the column, then the scope. So a + query supplies the scope, and finds only the values stored under it; +- a binding is in no query, so it does not change the terms; +- the ciphertext is sealed under the column, then the scope, then the + binding. So the reader supplies the scope and the binding again, and a + value does not open without them. + +An EQL field of a record nested in another stores its own column in the same +way. The outer record's names come after the column in the field's context. + ### EQL types as plan field targets A binding has no Rust type to name: its plan arrives as data, and a field of @@ -410,7 +624,7 @@ indexes it carries (`eq` / `match` / `ore` / `ope` / `json`), its query twin, and whether the engine can produce it today, with the reason when not. A guest serializes it for its `se_targets` export; the module docs are the wire format. `encrypt`, `decrypt` and `query` dispatch on the name and run the type's own -Rust plan — the same `EncryptFrom` the typed `encrypt_as::` runs, so +Rust declaration — the same one the typed `encrypt_into::` runs, so the two paths produce the same identifier and equality term and open each other's values. An unproducible name is refused with the table's reason; an unknown one with "no such EQL type". Every type in the table is producible @@ -418,16 +632,42 @@ today. A type that stores a JSON document (`Json`, `JsonSearch`) takes the plaintext kind `json`: the document's UTF-8 JSON text, in a text or bytes value, and it opens back to its text. -```rust,ignore +```rust +// Needs the `targets` feature. use eql_bindings::encryption::targets; -use stack_encrypt::Label; +use eql_bindings::v4::text::{TextEq, TextEqQuery}; use stack_encrypt::dynamic::ValueFrame; - -let column = Label::new(["users", "email"])?; // the field's context: table/column -let email = ValueFrame::of("alice@example.com")?; // the plaintext as its transport frame -let stored: Vec = targets::encrypt("TextEq", &keyset, &column, email.clone())?.await?; -let probe: Vec = targets::query("TextEq", &keyset, &column, email)?.await?; -let opened: ValueFrame = targets::decrypt("TextEq", &cipher, &column, &stored)?.await?; +use stack_encrypt::target::IndexSpec; +use stack_encrypt::{Label, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + + // The field's context: the table, then the column. + let column = Label::new(["users", "email"])?; + // The plaintext, as its transport frame. + let email = ValueFrame::of("alice@example.com")?; + + // Each call names the type, and returns the EQL value as JSON bytes. + let stored: Vec = targets::encrypt("TextEq", &keyset, &column, email.clone())?.await?; + // A query also names the index that answers its operator. + let index = IndexSpec::Equality; + let probe: Vec = targets::query("TextEq", &index, &keyset, &column, email.clone())?.await?; + let stored_value: TextEq = serde_json::from_slice(&stored)?; + let query: TextEqQuery = serde_json::from_slice(&probe)?; + assert_eq!(query.hm, stored_value.hm); + + let opened: ValueFrame = targets::decrypt("TextEq", &cipher, &column, &stored)?.await?; + assert_eq!(opened, email); + Ok(()) +} ``` The table and the dispatch are generated into `src/v4/targets.rs` beside @@ -438,7 +678,10 @@ the Go package `languages/golang/encrypt/eql` from the same rows engine's `TargetResolver` (stack-encrypt's `dynamic` module) is implemented over this module by `encryption::EqlTargets`. A program that runs data plans with EQL types passes `&EqlTargets` wherever the dynamic interface takes a -resolver, as the Go guest's `eql` build does. A type is producible exactly +resolver, as the Go guest's `eql` build does. A data plan's scopes and +bindings reach the type through `EqlTargets`: the type runs under the +field's label, then those parts, and the EQL value stores the column alone, +as it does for a [record field](#eql-types-as-record-fields). A type is producible exactly when its generated struct carries the `stack-encrypt` derives (`ENCRYPTION_DOMAINS` in `eql-codegen`), because the dispatch runs the derived plan; `targets::targets()` lists them, each with `producible` and, when it is diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 98452b07bd..9e98f1f95b 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -113,7 +113,8 @@ use stack_encrypt::sem::{ }; use stack_encrypt::target::transcode::{Reader, Transcode, Visitor}; use stack_encrypt::target::{ - self, AeadContext, CallerContext, DecryptSource, EncryptTarget, IndexSpec, RequiredContext, + self, AeadContext, CallerContext, ContextFromField, DecryptSource, EncryptTarget, IndexSpec, + RequiredContext, }; use stack_encrypt::{ CipherText, ContextPiece, Decrypt, DecryptField, DecryptInto, Decryptable, Decryption, @@ -200,6 +201,34 @@ impl<'a> IntoContext<'a> for &'a Identifier { } } +/// An EQL type can be a field of a derived `struct = ..` record. The record +/// gives the field a context of its own: the record's scope, then the +/// field's name, such as `("members", "email")`. The EQL type stores that +/// pair in `i` as its column: table `members`, column `email`. +/// +/// `i` holds those two declared names, and nothing a caller supplies. A +/// record can also list a scope or a binding, such as a tenant or a row ID. +/// They come after the column, as they do for a field of any other type. +/// The field's terms derive under the column and the scope. Its +/// ciphertext is sealed under the column, the scope and the binding. None +/// of that is stored in `i`, so the reader supplies the scope and the +/// binding again. The names of a record that holds this one as a field +/// come after the column as a scope does. +/// +/// With no scope and no binding, the field writes the terms that the type +/// writes on its own under `Identifier::for_column("members", "email")`. +impl ContextFromField for Identifier { + fn from_field(own: &ContextPiece<'_>) -> Option> { + let ContextPiece::List(parts) = own else { + return None; + }; + let [ContextPiece::Text(table), ContextPiece::Text(column)] = parts.as_slice() else { + return None; + }; + Self::for_column(table.as_ref(), column.as_ref()).ok() + } +} + /// Builds the final EQL ciphertext string from a native sealed leaf. #[doc(hidden)] pub struct CiphertextVisitor; diff --git a/packages/eql/crates/eql-bindings/src/encryption/json_example.rs b/packages/eql/crates/eql-bindings/src/encryption/json_example.rs new file mode 100644 index 0000000000..6785107685 --- /dev/null +++ b/packages/eql/crates/eql-bindings/src/encryption/json_example.rs @@ -0,0 +1,30 @@ +use eql_bindings::{v4::json_tree::JsonTreeDocument, Identifier}; +use serde_json::json; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::{DecryptFrom, EncryptInto, StackCipher}; +use stack_kms::FakeDataKeySource; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + // Local example only: these keys are held in memory, not in ZeroKMS. + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await?; + let keyset = cipher.default_keyset(); + let column = Identifier::for_column("customers", "profile")?; + + // Encryption takes the document by value and wipes it. The stored + // document records its column in `i`. + let profile = JsonPlaintext::from(json!({"name": "Ada", "age": 36})); + let document: JsonTreeDocument = profile + .encrypt_into_with_context(&keyset, column.clone()) + .await?; + assert_eq!(document.i.t, "customers"); + assert_eq!(document.i.c, "profile"); + + // Decrypt to the document, also checking the expected table and column. + let opened = JsonPlaintext::decrypt_from_with_context(document, &keyset, column).await?; + assert_eq!(opened.value(), &json!({"name": "Ada", "age": 36})); + Ok(()) +} diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 38ac1bdadf..0f31e62ae0 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -36,9 +36,14 @@ //! instance, though `Identifier::for_column` takes such a name. A column //! whose table or column name is not a plain segment can be written but //! not named on a plan, so it cannot be queried this way. A label of any other length -//! names no column, and a query extended with `.extend(..)` is derived under -//! more than the column the twin stores, so the awaited query refuses both, -//! before any keyset is resolved or term derived. +//! names no column, so the awaited query refuses it, before any keyset is +//! resolved or term derived. +//! +//! A query can carry a scope: `.scope(..)` on a query from a record +//! field's marker, or the chain's `.extend(..)` on a plan's query. Its term +//! is then derived under the column and the scope, and matches the values +//! a record stored under the same scope. The twin stores the column alone, +//! as the stored value does: a scope is never stored in `i`. //! //! The plan is for queries. Stack Encrypt runs a plan's encryption under //! the label, and an EQL type is sealed under its column instead, so write @@ -182,10 +187,10 @@ pub trait QueryTwin: Sized { /// The index an EQL v4 type answers an operator through: Stack Encrypt's /// index `I`, whose query term is sent as the type's query twin `Q`. /// -/// It derives exactly what `I` derives, under the plan's label, and checks -/// and refuses what `I` refuses, as well as a label that names no column -/// and any extension; it then writes the term into the twin, with the -/// column the label names. It answers for the twin's own plaintext +/// It derives exactly what `I` derives, under the plan's label and any +/// scope the query carries, and checks and refuses what `I` refuses, as +/// well as a label that names no column; it then writes the term into the +/// twin, with the column the label names. It answers for the twin's own plaintext /// ([`QueryTwin::Plaintext`]) only. `TextEq` answers [`op::Eq`](struct@op::Eq) through /// `TwinIndex`, and `TextMatch` answers /// [`op::Matches`](struct@op::Matches) through @@ -239,20 +244,19 @@ impl, Q> Index for TwinIndex { } } -/// Refuse a query context no EQL query value can record: a label that -/// names no column (it must be two segments, table then column), or any -/// extension (`.extend(..)`), since the terms would be derived under the -/// column and the extension while the twin stores the column alone, and -/// would match nothing. Before any keyset is resolved or term derived. -fn check_column(label: &Label, extended: bool) -> Result<(), Error> { +/// Refuse a label no EQL query value can record: one that names no column +/// (it must be two segments, table then column). Before any keyset is +/// resolved or term derived. +/// +/// A scope the query carries is not refused. The twin stores the column +/// alone, and so does a value a record stored under that scope: the scope +/// is in the term, and in neither `i`. +fn check_column(label: &Label) -> Result<(), Error> { if Identifier::column_of(label).is_none() { return Err(Error::Other(Box::new(QueryLabelError::NotAColumn { label: label.to_string(), }))); } - if extended { - return Err(Error::Other(Box::new(QueryLabelError::Extended))); - } Ok(()) } @@ -269,10 +273,6 @@ pub enum QueryLabelError { /// The label, rendered. label: String, }, - /// The query was extended with `.extend(..)`, so its terms would be - /// derived under more than the column the twin stores, and would match - /// nothing. - Extended, } impl fmt::Display for QueryLabelError { @@ -282,10 +282,6 @@ impl fmt::Display for QueryLabelError { f, "{label:?} is not an EQL column identifier: expected two segments, table and column" ), - Self::Extended => f.write_str( - "an EQL query value stores the column it queries and nothing else, so its query \ - cannot be extended", - ), } } } @@ -317,8 +313,8 @@ where fn prepare(&self, value: &Q::Plaintext) -> Result<(), Error> { Supports::::prepare(&self.index, value) } - fn check_label(&self, label: &Label, extended: bool) -> Result<(), Error> { - check_column(label, extended) + fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { + check_column(label) } fn query((): (), term: EqualityTerm, token: QueryToken) -> Q { Q::assemble(column(&token), hmac256(&term)) @@ -341,8 +337,8 @@ where fn prepare(&self, value: &Q::Plaintext) -> Result { Supports::::prepare(&self.index, value) } - fn check_label(&self, label: &Label, extended: bool) -> Result<(), Error> { - check_column(label, extended) + fn check_label(&self, label: &Label, _extended: bool) -> Result<(), Error> { + check_column(label) } fn query(tokens: QueryTokens, terms: MatchTerms, token: QueryToken) -> MatchTwin { let column = column(&token); diff --git a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs index 53fd3e15c9..6e8c8a082a 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs @@ -5,10 +5,10 @@ //! documentation on `EqlTargets`. use stack_encrypt::dynamic::{self, TargetDescriptor, TargetOptions, TargetResolver, ValueFrame}; -use stack_encrypt::target::IndexSpec; +use stack_encrypt::target::{DeclaredContext, IndexSpec}; use stack_encrypt::{KeysetCipher, Label, Pending, StackCipher}; -use super::targets::{self, decrypt, encrypt_with, query, Target, TargetError}; +use super::targets::{self, decrypt_under, encrypt_under, query_under, Target, TargetError}; /// Gives Stack Encrypt every EQL type that this crate defines. /// @@ -19,8 +19,12 @@ use super::targets::{self, decrypt, encrypt_with, query, Target, TargetError}; /// is that resolver. /// /// `EqlTargets` lists every type in [`targets`](super::targets::targets). -/// For a type that a plan names, `EqlTargets` calls [`encrypt_with`], -/// [`decrypt`], or [`query`]. +/// For a type that a plan names, `EqlTargets` runs the type as +/// [`encrypt_with`](super::targets::encrypt_with), +/// [`decrypt`](super::targets::decrypt) and +/// [`query`](super::targets::query) do, under the field's label and then +/// the scopes and the bindings of the plan. The EQL value stores the +/// label's column alone. /// /// Pass `&EqlTargets` wherever the dynamic interface accepts a resolver, /// such as `stack_encrypt::dynamic::record::plan_with`. @@ -55,9 +59,12 @@ impl TargetResolver for EqlTargets { options: Option<&TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, dynamic::TargetError> { - Ok(encrypt_with(name, options, keyset, label, plaintext)?) + Ok(encrypt_under( + name, options, keyset, label, parts, plaintext, + )?) } fn decrypt<'a, K: 'static>( @@ -65,9 +72,10 @@ impl TargetResolver for EqlTargets { name: &str, cipher: &'a StackCipher, label: &Label, + parts: &DeclaredContext, stored: &[u8], ) -> Result, dynamic::TargetError> { - Ok(decrypt(name, cipher, label, stored)?) + Ok(decrypt_under(name, cipher, label, parts, stored)?) } fn query<'a, K: 'static>( @@ -76,9 +84,10 @@ impl TargetResolver for EqlTargets { index: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, label: &Label, + scopes: &DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, dynamic::TargetError> { - Ok(query(name, index, keyset, label, plaintext)?) + Ok(query_under(name, index, keyset, label, scopes, plaintext)?) } } diff --git a/packages/eql/crates/eql-bindings/src/encryption/targets.rs b/packages/eql/crates/eql-bindings/src/encryption/targets.rs index 6e66020c39..54cb2d952c 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/targets.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/targets.rs @@ -81,9 +81,16 @@ //! label has two segments ([`Identifier::from_label`]): `users/email` is //! `{"t": "users", "c": "email"}`, sealed under the same AAD, bound to the //! same ZeroKMS descriptor and deriving the same equality term as the typed -//! `encrypt_as::` call with `Identifier::for_column("users", +//! `encrypt_into::` call with `Identifier::for_column("users", //! "email")`. A label of any other length is refused: there is no column to //! store it in. +//! +//! A data plan can also carry scopes and bindings, such as a tenant or a +//! row ID. Stack Encrypt hands them to [`EqlTargets`](super::EqlTargets) +//! beside the label, and the type runs under the label, then those parts, +//! as a field of a derived record does. The EQL value stores the column +//! alone, so whoever reads it supplies the parts again. The functions here +//! take the label alone: they run a type with no scope and no binding. use std::fmt; @@ -91,10 +98,11 @@ use serde::{de::DeserializeOwned, Serialize}; use stack_encrypt::dynamic::{TargetOptions, ValueFrame, ValueKind}; use stack_encrypt::json::JsonOptions; use stack_encrypt::kms::MaybeSend; -use stack_encrypt::target::{ExpectedContext, IndexSpec}; +use stack_encrypt::target::{ + CallerContext, DeclaredContext, EncryptTarget, ExpectedContext, IndexSpec, StoredContext, +}; use stack_encrypt::{ - Decrypt, DecryptInto, Encrypt, EncryptFrom, Error, KeysetCipher, Label, NonEmpty, Pending, - StackCipher, + Decrypt, DecryptInto, Encrypt, Error, KeysetCipher, Label, NonEmpty, Pending, StackCipher, }; use crate::v4::targets::{decrypt_named, encrypt_named, query_named, TARGETS}; @@ -397,9 +405,46 @@ pub fn encrypt_with<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, context: &Label, plaintext: ValueFrame, +) -> Result, K>, TargetError> { + encrypt_under( + name, + options, + keyset, + context, + &DeclaredContext::default(), + plaintext, + ) +} + +/// The context of a plan field that names an EQL type: the field's label, +/// which must name a column, then `parts`, the scopes and the bindings of +/// the plan and of the call. +/// +/// The EQL value stores the column alone. The terms derive under the +/// column and the scopes, and the value is sealed under the bindings too, +/// as a field of a derived record is. +/// +/// # Errors +/// +/// [`TargetError::Context`] for a label that is not a column. +fn field_context(label: &Label, parts: &DeclaredContext) -> Result { + let _ = Identifier::from_label(label)?; + Ok(parts.clone().under(NonEmpty::from(label.clone()))) +} + +/// [`encrypt_with`], with the scopes and the bindings that come after the +/// field's label: what [`EqlTargets`](super::EqlTargets) runs for Stack +/// Encrypt's data plan. +pub(crate) fn encrypt_under<'a, K: 'static>( + name: &str, + options: Option<&TargetOptions>, + keyset: &'a KeysetCipher<'_, K>, + label: &Label, + parts: &DeclaredContext, + plaintext: ValueFrame, ) -> Result, K>, TargetError> { producible(name)?; - let column = Identifier::from_label(context)?; + let context = field_context(label, parts)?; if let Some(document) = document(name) { let options = match options { None => JsonOptions::default(), @@ -407,12 +452,12 @@ pub fn encrypt_with<'a, K: 'static>( name: document.name, })?, }; - return encrypt_document(document.name, &options, keyset, column, &plaintext); + return encrypt_document(document.name, &options, keyset, context, &plaintext); } if let Some(target) = options.and(target(name)) { return Err(TargetError::Options { name: target.name }); } - encrypt_named(name, keyset, column, plaintext) + encrypt_named(name, keyset, context, plaintext) } /// Open a stored value of the named type back to its plaintext, checking @@ -430,13 +475,26 @@ pub fn decrypt<'a, K: 'static>( opener: impl Into>, context: &Label, stored: &[u8], +) -> Result, TargetError> { + decrypt_under(name, opener, context, &DeclaredContext::default(), stored) +} + +/// [`decrypt`], with the scopes and the bindings that come after the +/// field's label. The stored column must be the label's, and the value +/// opens under the label, then `parts`. +pub(crate) fn decrypt_under<'a, K: 'static>( + name: &str, + opener: impl Into>, + label: &Label, + parts: &DeclaredContext, + stored: &[u8], ) -> Result, TargetError> { producible(name)?; - let column = Identifier::from_label(context)?; + let context = field_context(label, parts)?; if let Some(document) = document(name) { - return decrypt_document(document.name, opener.into(), column, stored); + return decrypt_document(document.name, opener.into(), context, stored); } - decrypt_named(name, opener.into(), column, stored) + decrypt_named(name, opener.into(), context, stored) } /// The stored domain of a document family (`eql-domains`' @@ -448,13 +506,14 @@ fn document(name: &str) -> Option<&'static Target> { /// Seal one `JsonSearch` value: the document the field's text holds, /// parsed by the engine's rules, laid out by the JSON index under -/// `options`, under the column. The parsed document is wiped when this -/// returns; the pending has taken what it seals. +/// `options`, under the field's context. The document stores the column +/// alone. The parsed document is wiped when this returns; the pending has +/// taken what it seals. fn encrypt_document<'a, K: 'static>( name: &'static str, options: &JsonOptions, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: &ValueFrame, ) -> Result, K>, TargetError> { let document = @@ -464,21 +523,19 @@ fn encrypt_document<'a, K: 'static>( })?; Ok(keyset .run( - stack_encrypt::target::Layout::::encryption::( - &crate::v4::json_tree::JsonTree::new(options.clone()), - ), + crate::v4::json_tree::JsonTree::new(options.clone()).sealing(), document.value(), - column, + StoredContext::from(context), ) .try_map(|value| serde_json::to_vec(&value).map_err(|error| Error::Other(Box::new(error))))) } /// Open one stored `JsonSearch` value to the document's text, checking -/// it was stored under the column. +/// it was stored under the field's column. fn decrypt_document<'a, K: 'static>( name: &'static str, opener: Opener<'a, K>, - column: NonEmpty, + context: CallerContext, stored: &[u8], ) -> Result, TargetError> { use crate::v4::json_tree::JsonTreeDocument; @@ -487,7 +544,7 @@ fn decrypt_document<'a, K: 'static>( target: name, source, })?; - let expected: ExpectedContext = column.into(); + let expected: ExpectedContext = context.into(); Ok(match opener { Opener::Client(cipher) => { cipher.decrypt_as::(value, expected) @@ -524,6 +581,27 @@ pub fn query<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, context: &Label, plaintext: ValueFrame, +) -> Result, K>, TargetError> { + query_under( + name, + index, + keyset, + context, + &DeclaredContext::default(), + plaintext, + ) +} + +/// [`query`], with the scopes that come after the field's label. The term +/// is derived under the label, then `scopes`, and the query value stores +/// the column alone. +pub(crate) fn query_under<'a, K: 'static>( + name: &str, + index: &IndexSpec, + keyset: &'a KeysetCipher<'_, K>, + label: &Label, + scopes: &DeclaredContext, + plaintext: ValueFrame, ) -> Result, K>, TargetError> { producible(name)?; let Some(target) = target(name) else { @@ -536,8 +614,8 @@ pub fn query<'a, K: 'static>( if document(name).is_some() { return Err(TargetError::DocumentQuery { name: target.name }); } - let column = Identifier::from_label(context)?; - query_named(name, index, keyset, column, plaintext) + let context = field_context(label, scopes)?; + query_named(name, index, keyset, context, plaintext) } /// Refuse a query through an index the type does not carry. @@ -792,25 +870,29 @@ impl Plaintext for Option { /// Run a target's own plan over one runtime value and resolve to the EQL /// value's JSON bytes. The generated dispatch calls this with the type and -/// its plaintext; it is the one place the typed `encrypt_as` is reached from -/// a name. +/// its plaintext; it is the one place the type's own declaration is reached +/// from a name. +/// +/// `context` is the field's context: its column, then the scopes and the +/// bindings. The type stores the column, as it does as a field of a derived +/// record ([`StoredContext`]). pub(crate) fn run_target<'a, T, S, K>( name: &'static str, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> where - T: EncryptFrom> + Serialize, - S: Plaintext, + T: EncryptTarget> + Serialize, + S: Plaintext + zeroize::Zeroize, K: 'static, { - // The copy lives only until `encrypt_as` has cloned what it seals, and - // is wiped when this returns: the frame kept its bytes in `Protected`, + // The copy lives only until the run has cloned what it seals, and is + // wiped when this returns: the frame kept its bytes in `Protected`, // and the copy is held to the same rule. let plaintext = zeroize::Zeroizing::new(S::from_frame(name, &plaintext)?); Ok(keyset - .encrypt_as::(&plaintext, column) + .run(T::encryption(), &*plaintext, StoredContext::from(context)) .try_map(|value| serde_json::to_vec(&value).map_err(|error| Error::Other(Box::new(error))))) } @@ -821,19 +903,19 @@ where pub(crate) fn run_projected<'a, P, Q, S, K>( name: &'static str, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> where - P: EncryptFrom> + Into, + P: EncryptTarget> + Into, Q: Serialize, - S: Plaintext, + S: Plaintext + zeroize::Zeroize, K: 'static, { // Wiped when this returns, as in `run_target`. let plaintext = zeroize::Zeroizing::new(S::from_frame(name, &plaintext)?); Ok(keyset - .encrypt_as::(&plaintext, column) + .run(P::encryption(), &*plaintext, StoredContext::from(context)) .try_map(|value| { let query: Q = value.into(); serde_json::to_vec(&query).map_err(|error| Error::Other(Box::new(error))) @@ -841,11 +923,13 @@ where } /// Parse a stored EQL value as the target and describe opening it through -/// the target's own `DecryptInto`, under the column the caller expects. +/// the target's own `DecryptInto`. The stored column must be the field's, +/// and the value opens under the field's context: its column, then the +/// scopes and the bindings. pub(crate) fn open_target<'a, T, S, K>( name: &'static str, opener: Opener<'a, K>, - column: NonEmpty, + context: CallerContext, stored: &[u8], ) -> Result, TargetError> where @@ -857,10 +941,7 @@ where target: name, source, })?; - // `decrypt_as`, not `run_decryption`: this crate compiles against the - // crates.io stack-encrypt its manifest names (0.2.0), which has the - // typed call and not the by-value runner. Same plan, same pending. - let expected: ExpectedContext = column.into(); + let expected: ExpectedContext = context.into(); Ok(match opener { Opener::Client(cipher) => cipher.decrypt_as::(value, expected), Opener::Keyset(keyset) => keyset.decrypt_as::(value, expected), 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 e7f4ab1a44..5e40b6a10e 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -23,10 +23,13 @@ use schemars::{schema_for, JsonSchema, Schema}; use serde::{Deserialize, Serialize}; use serde_json::Value; use stack_encrypt::json::{ - JsonDocument, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonQuery, JsonSelector, - JsonSubtree, JsonSubtreeKey, + JsonDocument, JsonLeafQuery, JsonNode, JsonOptions, JsonPath, JsonPlaintext, JsonQuery, + JsonSelector, JsonSubtree, JsonSubtreeKey, +}; +use stack_encrypt::target::{ + AeadContext, DecryptSource, EncryptTarget, ExpectedContext, IndexSpec, Json, Layout, + StoredContext, }; -use stack_encrypt::target::{AeadContext, ExpectedContext, IndexSpec, Json, Layout}; use stack_encrypt::{ DecryptField, DecryptInto, Decryptable, Decryption, EncryptFrom, Encryption, Error, NonEmpty, }; @@ -482,6 +485,21 @@ impl JsonTree { } } +impl JsonTree { + /// Seal a document under these options, and write its column to `i`. + /// + /// On its own, the document stores the column the caller passes, and + /// seals under it. As a field of a record, it stores the field's own + /// column, and seals under the scopes and bindings of the record too. + pub(crate) fn sealing<'s, K: 'static>( + &self, + ) -> Encryption<'s, Value, JsonTreeDocument, K, StoredContext> { + Layout::::encryption::(&self.index) + .storing(|document, column: Identifier| (column, document)) + .try_map(|(column, document)| JsonTreeDocument::envelope(column, &document)) + } +} + /// A document seals as the JSON index lays it out under the layout's /// options, under the column it is stored in: the [`Identifier`] is the /// context the data key is minted under and every selector derives @@ -492,10 +510,7 @@ impl Layout for JsonTree { fn encryption<'s, K: 'static>( &self, ) -> Encryption<'s, Value, JsonTreeDocument, K, NonEmpty> { - Layout::::encryption::(&self.index) - .accepting::>() - .map_with_context(|document, i: NonEmpty| (i, document)) - .try_map(|(i, document)| JsonTreeDocument::envelope(i.into_inner(), &document)) + self.sealing().accepting() } fn index(&self) -> &Json { &self.index @@ -524,17 +539,79 @@ impl EncryptFrom for JsonTreeDocument { impl DecryptInto for JsonTreeDocument { type Context = ExpectedContext; fn decryption(self, context: Self::Context) -> Decryption { - let column = match context.validate(self.i.clone()) { - Ok(column) => column, + self.open(context) + } +} + +impl JsonTreeDocument { + /// Open the document, once its stored column has passed the caller's + /// check. The check runs before any key is requested. + /// + /// On its own, the document opens under the stored column. As a field + /// of a record, it opens under the scopes and bindings of the record + /// too. + fn open(self, context: ExpectedContext) -> Decryption { + let context = match context.decryption_context(self.i.clone()) { + Ok(context) => context, Err(error) => return Decryption::failed(error), }; match self.document() { - Ok(document) => document.decryption(AeadContext::from(column)), + Ok(document) => document.decryption(AeadContext::from(context)), Err(error) => Decryption::failed(error), } } } +/// A [`JsonPlaintext`] seals into a document as a `serde_json::Value` does, +/// under the default options ([`JsonTree::default`]), with the column as +/// its context. +/// +/// The code below is executed by `cargo test -p eql-encryption-tests --test +/// json_example`. It is not one of this crate's doctests, for the reason +/// the [encryption example](crate::encryption#example) gives: the test key +/// source and the runtime it needs stay in the encryption test crate. +#[doc = concat!("```rust,ignore\n", include_str!("../encryption/json_example.rs"), "\n```")] +/// +/// It can be a field of a derived `struct = ..` record. The field's column +/// is then the record's scope and the field's name. A scope or a binding +/// that the record lists is not stored in the document: the reader supplies +/// it again. +impl EncryptTarget for JsonTreeDocument { + type ContextInput = StoredContext; + fn encryption<'s, K: 'static>() -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> + where + JsonPlaintext: 's, + { + JsonTree::default().sealing().project(JsonPlaintext::value) + } + fn indexes() -> Vec { + JsonTree::default().specs() + } +} + +/// Decrypts to the plaintext document, under the stored column. +/// +/// - `decrypt_from_with_context(document, &keyset, column)` checks that the +/// stored column is `column`. The check runs before any key is +/// requested. +/// - `decrypt_from(document, &keyset)` opens the document under the column +/// it stores, without that check. +impl DecryptSource for JsonTreeDocument { + type ContextInput = ExpectedContext; + fn decryption(self, context: Self::ContextInput) -> Decryption { + self.open(context).map(JsonPlaintext::from) + } +} + +/// The same as [`DecryptSource`]. A field of a derived +/// record opens through this trait, as every other EQL type does. +impl DecryptInto for JsonTreeDocument { + type Context = ExpectedContext; + fn decryption(self, context: Self::Context) -> Decryption { + self.open(context).map(JsonPlaintext::from) + } +} + impl Decryptable for JsonTreeDocument { const DECRYPTABLE: bool = true; } @@ -544,7 +621,7 @@ where Ctx: Into<>::Context>, { fn decryption_field(self, context: Ctx) -> Option> { - Some(self.decryption(context.into())) + Some(>::decryption(self, context.into())) } } diff --git a/packages/eql/crates/eql-bindings/src/v4/targets.rs b/packages/eql/crates/eql-bindings/src/v4/targets.rs index 65ec8111a5..33df630928 100644 --- a/packages/eql/crates/eql-bindings/src/v4/targets.rs +++ b/packages/eql/crates/eql-bindings/src/v4/targets.rs @@ -8,10 +8,9 @@ use crate::v4::plaintext::Date; use crate::v4::plaintext::Decimal; use crate::v4::plaintext::JsonPlaintext; use crate::v4::plaintext::Timestamp; -use crate::Identifier; use stack_encrypt::dynamic::ValueFrame; -use stack_encrypt::target::IndexSpec; -use stack_encrypt::{KeysetCipher, NonEmpty, Pending}; +use stack_encrypt::target::{CallerContext, IndexSpec}; +use stack_encrypt::{KeysetCipher, Pending}; /// Every EQL type a plan may name as a target, in /// `eql-domains::CATALOG` order: one per stored scalar domain, then /// one per document family's stored type @@ -638,238 +637,239 @@ pub const TARGETS: &[Target] = &[ pub(crate) const DOCUMENT_FAMILIES: &[&str] = &["json_tree"]; /// Run the named type's own encryption plan for one field, or refuse /// the name: the type is not producible (`TargetError::Unproducible`) -/// or does not exist (`TargetError::Unknown`). +/// or does not exist (`TargetError::Unknown`). `context` is the +/// field's context: its column, then the scopes and the bindings. pub(crate) fn encrypt_named<'a, K: 'static>( name: &str, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { match name { "Integer" => run_target::, K>( - "Integer", keyset, column, plaintext, + "Integer", keyset, context, plaintext, ), "IntegerEq" => run_target::, K>( "IntegerEq", keyset, - column, + context, plaintext, ), "IntegerOrdOre" => run_target::( "IntegerOrdOre", keyset, - column, + context, plaintext, ), "IntegerOrd" => run_target::( "IntegerOrd", keyset, - column, + context, plaintext, ), "IntegerOrdOpe" => run_target::( "IntegerOrdOpe", keyset, - column, + context, plaintext, ), "Smallint" => run_target::, K>( - "Smallint", keyset, column, plaintext, + "Smallint", keyset, context, plaintext, ), "SmallintEq" => run_target::, K>( "SmallintEq", keyset, - column, + context, plaintext, ), "SmallintOrdOre" => run_target::( "SmallintOrdOre", keyset, - column, + context, plaintext, ), "SmallintOrd" => run_target::( "SmallintOrd", keyset, - column, + context, plaintext, ), "SmallintOrdOpe" => run_target::( "SmallintOrdOpe", keyset, - column, + context, plaintext, ), - "Bigint" => { - run_target::, K>("Bigint", keyset, column, plaintext) - } + "Bigint" => run_target::, K>( + "Bigint", keyset, context, plaintext, + ), "BigintEq" => run_target::, K>( - "BigintEq", keyset, column, plaintext, + "BigintEq", keyset, context, plaintext, ), "BigintOrdOre" => run_target::( "BigintOrdOre", keyset, - column, + context, plaintext, ), "BigintOrd" => { - run_target::("BigintOrd", keyset, column, plaintext) + run_target::("BigintOrd", keyset, context, plaintext) } "BigintOrdOpe" => run_target::( "BigintOrdOpe", keyset, - column, + context, plaintext, ), "Date" => { - run_target::, K>("Date", keyset, column, plaintext) + run_target::, K>("Date", keyset, context, plaintext) } "DateEq" => { - run_target::, K>("DateEq", keyset, column, plaintext) + run_target::, K>("DateEq", keyset, context, plaintext) } "DateOrdOre" => { - run_target::("DateOrdOre", keyset, column, plaintext) + run_target::("DateOrdOre", keyset, context, plaintext) } "DateOrd" => { - run_target::("DateOrd", keyset, column, plaintext) + run_target::("DateOrd", keyset, context, plaintext) } "DateOrdOpe" => { - run_target::("DateOrdOpe", keyset, column, plaintext) + run_target::("DateOrdOpe", keyset, context, plaintext) } "Timestamp" => run_target::, K>( "Timestamp", keyset, - column, + context, plaintext, ), "TimestampEq" => run_target::, K>( "TimestampEq", keyset, - column, + context, plaintext, ), "TimestampOrdOre" => run_target::( "TimestampOrdOre", keyset, - column, + context, plaintext, ), "TimestampOrd" => run_target::( "TimestampOrd", keyset, - column, + context, plaintext, ), "TimestampOrdOpe" => run_target::( "TimestampOrdOpe", keyset, - column, + context, plaintext, ), "Numeric" => run_target::, K>( - "Numeric", keyset, column, plaintext, + "Numeric", keyset, context, plaintext, ), "NumericEq" => run_target::, K>( "NumericEq", keyset, - column, + context, plaintext, ), "NumericOrdOre" => run_target::( "NumericOrdOre", keyset, - column, + context, plaintext, ), "NumericOrd" => run_target::( "NumericOrd", keyset, - column, + context, plaintext, ), "NumericOrdOpe" => run_target::( "NumericOrdOpe", keyset, - column, + context, plaintext, ), "Text" => { - run_target::, K>("Text", keyset, column, plaintext) + run_target::, K>("Text", keyset, context, plaintext) } "TextEq" => run_target::, K>( - "TextEq", keyset, column, plaintext, + "TextEq", keyset, context, plaintext, ), "TextMatch" => { - run_target::("TextMatch", keyset, column, plaintext) + run_target::("TextMatch", keyset, context, plaintext) } "TextOrdOre" => run_target::( "TextOrdOre", keyset, - column, + context, plaintext, ), "TextOrd" => { - run_target::("TextOrd", keyset, column, plaintext) + run_target::("TextOrd", keyset, context, plaintext) } "TextOrdOpe" => run_target::( "TextOrdOpe", keyset, - column, + context, plaintext, ), "TextSearchOre" => run_target::( "TextSearchOre", keyset, - column, + context, plaintext, ), "TextSearch" => run_target::( "TextSearch", keyset, - column, + context, plaintext, ), "Boolean" => run_target::, K>( - "Boolean", keyset, column, plaintext, + "Boolean", keyset, context, plaintext, ), "Real" => { - run_target::, K>("Real", keyset, column, plaintext) + run_target::, K>("Real", keyset, context, plaintext) } "RealEq" => { - run_target::, K>("RealEq", keyset, column, plaintext) + run_target::, K>("RealEq", keyset, context, plaintext) } "RealOrdOre" => { - run_target::("RealOrdOre", keyset, column, plaintext) + run_target::("RealOrdOre", keyset, context, plaintext) } "RealOrd" => { - run_target::("RealOrd", keyset, column, plaintext) + run_target::("RealOrd", keyset, context, plaintext) } "RealOrdOpe" => { - run_target::("RealOrdOpe", keyset, column, plaintext) - } - "Double" => { - run_target::, K>("Double", keyset, column, plaintext) + run_target::("RealOrdOpe", keyset, context, plaintext) } + "Double" => run_target::, K>( + "Double", keyset, context, plaintext, + ), "DoubleEq" => run_target::, K>( - "DoubleEq", keyset, column, plaintext, + "DoubleEq", keyset, context, plaintext, ), "DoubleOrdOre" => run_target::( "DoubleOrdOre", keyset, - column, + context, plaintext, ), "DoubleOrd" => { - run_target::("DoubleOrd", keyset, column, plaintext) + run_target::("DoubleOrd", keyset, context, plaintext) } "DoubleOrdOpe" => run_target::( "DoubleOrdOpe", keyset, - column, + context, plaintext, ), "Json" => run_target::, K>( - "Json", keyset, column, plaintext, + "Json", keyset, context, plaintext, ), _ => Err(refuse(name)), } @@ -879,216 +879,220 @@ pub(crate) fn encrypt_named<'a, K: 'static>( pub(crate) fn decrypt_named<'a, K: 'static>( name: &str, opener: Opener<'a, K>, - column: NonEmpty, + context: CallerContext, stored: &[u8], ) -> Result, TargetError> { match name { "Integer" => open_target::, K>( - "Integer", opener, column, stored, + "Integer", opener, context, stored, ), "IntegerEq" => open_target::, K>( "IntegerEq", opener, - column, + context, stored, ), "IntegerOrdOre" => open_target::( "IntegerOrdOre", opener, - column, + context, stored, ), "IntegerOrd" => { - open_target::("IntegerOrd", opener, column, stored) + open_target::("IntegerOrd", opener, context, stored) } "IntegerOrdOpe" => open_target::( "IntegerOrdOpe", opener, - column, + context, stored, ), "Smallint" => open_target::, K>( - "Smallint", opener, column, stored, + "Smallint", opener, context, stored, ), "SmallintEq" => open_target::, K>( "SmallintEq", opener, - column, + context, stored, ), "SmallintOrdOre" => open_target::( "SmallintOrdOre", opener, - column, + context, stored, ), "SmallintOrd" => open_target::( "SmallintOrd", opener, - column, + context, stored, ), "SmallintOrdOpe" => open_target::( "SmallintOrdOpe", opener, - column, + context, stored, ), "Bigint" => { - open_target::, K>("Bigint", opener, column, stored) + open_target::, K>("Bigint", opener, context, stored) } "BigintEq" => open_target::, K>( - "BigintEq", opener, column, stored, + "BigintEq", opener, context, stored, ), "BigintOrdOre" => open_target::( "BigintOrdOre", opener, - column, + context, stored, ), "BigintOrd" => { - open_target::("BigintOrd", opener, column, stored) + open_target::("BigintOrd", opener, context, stored) } "BigintOrdOpe" => open_target::( "BigintOrdOpe", opener, - column, + context, stored, ), - "Date" => open_target::, K>("Date", opener, column, stored), + "Date" => { + open_target::, K>("Date", opener, context, stored) + } "DateEq" => { - open_target::, K>("DateEq", opener, column, stored) + open_target::, K>("DateEq", opener, context, stored) } "DateOrdOre" => { - open_target::("DateOrdOre", opener, column, stored) + open_target::("DateOrdOre", opener, context, stored) } "DateOrd" => { - open_target::("DateOrd", opener, column, stored) + open_target::("DateOrd", opener, context, stored) } "DateOrdOpe" => { - open_target::("DateOrdOpe", opener, column, stored) + open_target::("DateOrdOpe", opener, context, stored) } "Timestamp" => open_target::, K>( "Timestamp", opener, - column, + context, stored, ), "TimestampEq" => open_target::, K>( "TimestampEq", opener, - column, + context, stored, ), "TimestampOrdOre" => open_target::( "TimestampOrdOre", opener, - column, + context, stored, ), "TimestampOrd" => open_target::( "TimestampOrd", opener, - column, + context, stored, ), "TimestampOrdOpe" => open_target::( "TimestampOrdOpe", opener, - column, + context, stored, ), "Numeric" => open_target::, K>( - "Numeric", opener, column, stored, + "Numeric", opener, context, stored, ), "NumericEq" => open_target::, K>( "NumericEq", opener, - column, + context, stored, ), "NumericOrdOre" => open_target::( "NumericOrdOre", opener, - column, + context, stored, ), "NumericOrd" => open_target::( "NumericOrd", opener, - column, + context, stored, ), "NumericOrdOpe" => open_target::( "NumericOrdOpe", opener, - column, + context, stored, ), "Text" => { - open_target::, K>("Text", opener, column, stored) + open_target::, K>("Text", opener, context, stored) } "TextEq" => { - open_target::, K>("TextEq", opener, column, stored) + open_target::, K>("TextEq", opener, context, stored) } "TextMatch" => { - open_target::("TextMatch", opener, column, stored) + open_target::("TextMatch", opener, context, stored) } "TextOrdOre" => { - open_target::("TextOrdOre", opener, column, stored) + open_target::("TextOrdOre", opener, context, stored) } "TextOrd" => { - open_target::("TextOrd", opener, column, stored) + open_target::("TextOrd", opener, context, stored) } "TextOrdOpe" => { - open_target::("TextOrdOpe", opener, column, stored) + open_target::("TextOrdOpe", opener, context, stored) } "TextSearchOre" => open_target::( "TextSearchOre", opener, - column, + context, stored, ), "TextSearch" => { - open_target::("TextSearch", opener, column, stored) + open_target::("TextSearch", opener, context, stored) } "Boolean" => open_target::, K>( - "Boolean", opener, column, stored, + "Boolean", opener, context, stored, ), - "Real" => open_target::, K>("Real", opener, column, stored), + "Real" => open_target::, K>("Real", opener, context, stored), "RealEq" => { - open_target::, K>("RealEq", opener, column, stored) + open_target::, K>("RealEq", opener, context, stored) } "RealOrdOre" => { - open_target::("RealOrdOre", opener, column, stored) + open_target::("RealOrdOre", opener, context, stored) + } + "RealOrd" => { + open_target::("RealOrd", opener, context, stored) } - "RealOrd" => open_target::("RealOrd", opener, column, stored), "RealOrdOpe" => { - open_target::("RealOrdOpe", opener, column, stored) + open_target::("RealOrdOpe", opener, context, stored) } "Double" => { - open_target::, K>("Double", opener, column, stored) + open_target::, K>("Double", opener, context, stored) } "DoubleEq" => open_target::, K>( - "DoubleEq", opener, column, stored, + "DoubleEq", opener, context, stored, ), "DoubleOrdOre" => open_target::( "DoubleOrdOre", opener, - column, + context, stored, ), "DoubleOrd" => { - open_target::("DoubleOrd", opener, column, stored) + open_target::("DoubleOrd", opener, context, stored) } "DoubleOrdOpe" => open_target::( "DoubleOrdOpe", opener, - column, + context, stored, ), "Json" => open_target::, K>( - "Json", opener, column, stored, + "Json", opener, context, stored, ), _ => Err(refuse(name)), } @@ -1102,167 +1106,167 @@ pub(crate) fn query_named<'a, K: 'static>( name: &str, index: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { match name { "IntegerEq" => run_target::, K>( "IntegerEq", keyset, - column, + context, plaintext, ), "IntegerOrdOre" => run_target::( "IntegerOrdOre", keyset, - column, + context, plaintext, ), "IntegerOrd" => run_target::( "IntegerOrd", keyset, - column, + context, plaintext, ), "IntegerOrdOpe" => run_target::( "IntegerOrdOpe", keyset, - column, + context, plaintext, ), "SmallintEq" => run_target::, K>( "SmallintEq", keyset, - column, + context, plaintext, ), "SmallintOrdOre" => run_target::( "SmallintOrdOre", keyset, - column, + context, plaintext, ), "SmallintOrd" => run_target::( "SmallintOrd", keyset, - column, + context, plaintext, ), "SmallintOrdOpe" => run_target::( "SmallintOrdOpe", keyset, - column, + context, plaintext, ), "BigintEq" => run_target::, K>( - "BigintEq", keyset, column, plaintext, + "BigintEq", keyset, context, plaintext, ), "BigintOrdOre" => run_target::( "BigintOrdOre", keyset, - column, + context, plaintext, ), "BigintOrd" => run_target::( "BigintOrd", keyset, - column, + context, plaintext, ), "BigintOrdOpe" => run_target::( "BigintOrdOpe", keyset, - column, + context, plaintext, ), "DateEq" => run_target::, K>( - "DateEq", keyset, column, plaintext, + "DateEq", keyset, context, plaintext, ), "DateOrdOre" => run_target::( "DateOrdOre", keyset, - column, + context, plaintext, ), "DateOrd" => { - run_target::("DateOrd", keyset, column, plaintext) + run_target::("DateOrd", keyset, context, plaintext) } "DateOrdOpe" => run_target::( "DateOrdOpe", keyset, - column, + context, plaintext, ), "TimestampEq" => run_target::, K>( "TimestampEq", keyset, - column, + context, plaintext, ), "TimestampOrdOre" => run_target::( "TimestampOrdOre", keyset, - column, + context, plaintext, ), "TimestampOrd" => run_target::( "TimestampOrd", keyset, - column, + context, plaintext, ), "TimestampOrdOpe" => run_target::( "TimestampOrdOpe", keyset, - column, + context, plaintext, ), "NumericEq" => run_target::, K>( "NumericEq", keyset, - column, + context, plaintext, ), "NumericOrdOre" => run_target::( "NumericOrdOre", keyset, - column, + context, plaintext, ), "NumericOrd" => run_target::( "NumericOrd", keyset, - column, + context, plaintext, ), "NumericOrdOpe" => run_target::( "NumericOrdOpe", keyset, - column, + context, plaintext, ), "TextEq" => run_target::, K>( - "TextEq", keyset, column, plaintext, + "TextEq", keyset, context, plaintext, ), "TextMatch" => run_target::( "TextMatch", keyset, - column, + context, plaintext, ), "TextOrdOre" => run_target::( "TextOrdOre", keyset, - column, + context, plaintext, ), - "TextOrd" => { - run_target::("TextOrd", keyset, column, plaintext) - } + "TextOrd" => run_target::( + "TextOrd", keyset, context, plaintext, + ), "TextOrdOpe" => run_target::( "TextOrdOpe", keyset, - column, + context, plaintext, ), "TextSearchOre" => match index.key() { @@ -1271,19 +1275,19 @@ pub(crate) fn query_named<'a, K: 'static>( super::text::TextSearchOreQuery, String, K, - >("TextSearchOre", keyset, column, plaintext), + >("TextSearchOre", keyset, context, plaintext), "ore_block" => run_projected::< super::text::TextSearchOreOrderQuery, super::text::TextSearchOreQuery, String, K, - >("TextSearchOre", keyset, column, plaintext), + >("TextSearchOre", keyset, context, plaintext), "match" => run_projected::< super::text::TextSearchOreMatchQuery, super::text::TextSearchOreQuery, String, K, - >("TextSearchOre", keyset, column, plaintext), + >("TextSearchOre", keyset, context, plaintext), _ => Err(no_index("TextSearchOre", index)), }, "TextSearch" => match index.key() { @@ -1292,58 +1296,58 @@ pub(crate) fn query_named<'a, K: 'static>( super::text::TextSearchQuery, String, K, - >("TextSearch", keyset, column, plaintext), + >("TextSearch", keyset, context, plaintext), "ope" => run_projected::< super::text::TextSearchOrderQuery, super::text::TextSearchQuery, String, K, - >("TextSearch", keyset, column, plaintext), + >("TextSearch", keyset, context, plaintext), "match" => run_projected::< super::text::TextSearchMatchQuery, super::text::TextSearchQuery, String, K, - >("TextSearch", keyset, column, plaintext), + >("TextSearch", keyset, context, plaintext), _ => Err(no_index("TextSearch", index)), }, "RealEq" => run_target::, K>( - "RealEq", keyset, column, plaintext, + "RealEq", keyset, context, plaintext, ), "RealOrdOre" => run_target::( "RealOrdOre", keyset, - column, + context, plaintext, ), "RealOrd" => { - run_target::("RealOrd", keyset, column, plaintext) + run_target::("RealOrd", keyset, context, plaintext) } "RealOrdOpe" => run_target::( "RealOrdOpe", keyset, - column, + context, plaintext, ), "DoubleEq" => run_target::, K>( - "DoubleEq", keyset, column, plaintext, + "DoubleEq", keyset, context, plaintext, ), "DoubleOrdOre" => run_target::( "DoubleOrdOre", keyset, - column, + context, plaintext, ), "DoubleOrd" => run_target::( "DoubleOrd", keyset, - column, + context, plaintext, ), "DoubleOrdOpe" => run_target::( "DoubleOrdOpe", keyset, - column, + context, plaintext, ), _ => Err(refuse_query(name)), diff --git a/packages/eql/crates/eql-codegen/src/targets.rs b/packages/eql/crates/eql-codegen/src/targets.rs index 56928b6d71..7d87083c52 100644 --- a/packages/eql/crates/eql-codegen/src/targets.rs +++ b/packages/eql/crates/eql-codegen/src/targets.rs @@ -463,7 +463,7 @@ fn render_targets_from(rows: &[Row]) -> String { .map(|r| { let (name, ty, source) = arm(r, &r.name); let source = stored_source(r, source); - quote! { #name => run_target::<#ty, #source, K>(#name, keyset, column, plaintext), } + quote! { #name => run_target::<#ty, #source, K>(#name, keyset, context, plaintext), } }) .collect(); let decrypt_arms: TokenStream = producible @@ -471,7 +471,7 @@ fn render_targets_from(rows: &[Row]) -> String { .map(|r| { let (name, ty, source) = arm(r, &r.name); let source = stored_source(r, source); - quote! { #name => open_target::<#ty, #source, K>(#name, opener, column, stored), } + quote! { #name => open_target::<#ty, #source, K>(#name, opener, context, stored), } }) .collect(); // A producible type with no query twin (a storage-only domain) gets no @@ -489,7 +489,7 @@ fn render_targets_from(rows: &[Row]) -> String { let source = stored_source(r, source); if r.projections.is_empty() { return Some( - quote! { #name => run_target::<#ty, #source, K>(#name, keyset, column, plaintext), }, + quote! { #name => run_target::<#ty, #source, K>(#name, keyset, context, plaintext), }, ); } let by_index: TokenStream = r @@ -498,7 +498,7 @@ fn render_targets_from(rows: &[Row]) -> String { .map(|(key, projection)| { let (_, projection, _) = arm(r, projection); quote! { - #key => run_projected::<#projection, #ty, #source, K>(#name, keyset, column, plaintext), + #key => run_projected::<#projection, #ty, #source, K>(#name, keyset, context, plaintext), } }) .collect(); @@ -550,12 +550,11 @@ fn render_targets_from(rows: &[Row]) -> String { #![doc = #mod_doc] use stack_encrypt::dynamic::ValueFrame; - use stack_encrypt::target::IndexSpec; + use stack_encrypt::target::{CallerContext, IndexSpec}; #imports use crate::encryption::targets::{#helpers refuse, refuse_query, Opener, Target, TargetError}; - use crate::Identifier; - use stack_encrypt::{KeysetCipher, NonEmpty, Pending}; + use stack_encrypt::{KeysetCipher, Pending}; /// Every EQL type a plan may name as a target, in /// `eql-domains::CATALOG` order: one per stored scalar domain, then @@ -574,11 +573,12 @@ fn render_targets_from(rows: &[Row]) -> String { /// Run the named type's own encryption plan for one field, or refuse /// the name: the type is not producible (`TargetError::Unproducible`) - /// or does not exist (`TargetError::Unknown`). + /// or does not exist (`TargetError::Unknown`). `context` is the + /// field's context: its column, then the scopes and the bindings. pub(crate) fn encrypt_named<'a, K: 'static>( name: &str, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { match name { @@ -592,7 +592,7 @@ fn render_targets_from(rows: &[Row]) -> String { pub(crate) fn decrypt_named<'a, K: 'static>( name: &str, opener: Opener<'a, K>, - column: NonEmpty, + context: CallerContext, stored: &[u8], ) -> Result, TargetError> { match name { @@ -610,7 +610,7 @@ fn render_targets_from(rows: &[Row]) -> String { name: &str, #index_param: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, - column: NonEmpty, + context: CallerContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { match name { diff --git a/packages/eql/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index d477df2edc..fd3161bd37 100644 --- a/packages/eql/tests/encryption/Cargo.toml +++ b/packages/eql/tests/encryption/Cargo.toml @@ -4,6 +4,16 @@ version = "0.1.0" edition = "2021" publish = false +# Run the Rust examples in the eql-bindings README as doctests +# (`cargo test -p eql-encryption-tests --doc`). `src/lib.rs` holds no code: +# it includes the README as documentation when doctests are built. The +# examples are complete programs, and use this crate's test key source and +# async runtime, which stay out of eql-bindings' default test build. +[lib] +path = "src/lib.rs" +# The library has no unit tests, only the README's doctests. +test = false + # Execute the exact source included in the public Rustdoc example. Keep its # test key source and async runtime out of eql-bindings' default test build. [[test]] @@ -17,6 +27,12 @@ name = "query_example" path = "../../crates/eql-bindings/src/encryption/query_example.rs" harness = false +# The same, for the JSON document example on `JsonTreeDocument`. +[[test]] +name = "json_example" +path = "../../crates/eql-bindings/src/encryption/json_example.rs" +harness = false + # Keep crypto/Postgres test dependencies out of eql-bindings' default test build. [dev-dependencies] # `jiff` and `rust_decimal`: the date, timestamp and decimal plaintexts @@ -38,6 +54,7 @@ rust_decimal = { version = "1", default-features = false, features = ["std"] } stack-kms = { path = "../../../stack-kms", default-features = false, features = ["test-support"] } serde = "1" serde_json = "1" +zeroize = { version = "1", features = ["derive"] } uuid = "1" tokio = { version = "1", features = ["rt", "macros"] } postgres = "0.19" diff --git a/packages/eql/tests/encryption/src/lib.rs b/packages/eql/tests/encryption/src/lib.rs new file mode 100644 index 0000000000..bd7125b350 --- /dev/null +++ b/packages/eql/tests/encryption/src/lib.rs @@ -0,0 +1,14 @@ +#![cfg_attr(doctest, doc = include_str!("../../../crates/eql-bindings/README.md"))] +// Keep the attribute above on the first line of this file. A doctest is then +// reported at its line in the README: `src/lib.rs - (line 233)` is the code +// block that starts at line 233 of `crates/eql-bindings/README.md`. +// +// This library holds no code of its own. The tests of `eql-bindings`' +// `stack-encrypt` feature are under `tests/`. +// +// It runs the Rust examples in the `eql-bindings` README as doctests. Each +// example is a complete program, and needs a key source and an async +// runtime. This crate has both, and `eql-bindings` keeps them out of its own +// test build. From `packages/eql`: +// +// cargo test -p eql-encryption-tests --doc diff --git a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs index 5890bb1bf2..7bb373e986 100644 --- a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs +++ b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs @@ -14,7 +14,9 @@ //! (selectors, ordering terms, the containment selector set) for the same //! document under the same column, and each opens what the other sealed; //! - text that is not a document is refused before any key is requested, -//! naming the field and a code, never a byte of the text. +//! naming the field and a code, never a byte of the text; +//! - a document sealed under a scope and a binding is found by a query +//! under the scope, and read under the scope and the binding. mod common; @@ -1050,6 +1052,116 @@ fn stored_of(row: &stack_encrypt::StackCipherText) -> JsonTreeDocument { stored(row) } +/// [`plan`], as a binding sends it for a caller that added a tenant as a +/// scope and, for a seal or a read, a row ID as a binding. The scope +/// extends the field's context, and `"bind"` carries the binding. A query +/// takes no binding. +fn scoped_plan(tenant: u64, row: Option) -> record::Plan { + let mut wire = json!({ + "profile": { + "context": [["users", "profile"], tenant], + "type": "json", + "null": "sql", + "target": { + "name": "JsonSearch", + "options": {"ordered": ["$.age", "$.visits[*].at"]} + } + } + }); + if let Some(row) = row { + wire["bind"] = json!([row]); + } + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &EqlTargets, + ) + .unwrap() +} + +/// A document sealed under a tenant and a row, through the resolver a +/// language SDK installs. Its `i` is the column alone. A query under the +/// tenant finds it, and a query under another tenant, or none, does not. A +/// read finds its entry under the tenant, and opens it under the tenant and +/// the row. +#[tokio::test] +async fn a_scoped_document_is_found_and_read_under_its_scope() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let sealing = scoped_plan(7, Some(9)); + let text = json!({"name": "Alice", "age": 34, "visits": [{"at": 3}, {"at": 1}]}).to_string(); + let sealed = record::encrypt_with( + &keyset, + frame(BTreeMap::from([("profile", text.as_str())])), + &sealing, + &EqlTargets, + ) + .unwrap() + .await + .unwrap(); + let stored = stored_of(&sealed); + assert_eq!(stored.i, *column().get(), "`i` is the column alone"); + let document = engine_document(&stored); + + // A containment query. + let alice = json!(json!({"name": "Alice"}).to_string()); + let contains = |plan: record::Plan| { + let (keyset, alice) = (&keyset, alice.clone()); + async move { + containment(one(&data_term( + keyset, + &plan, + "contains", + &[("json", alice)], + ) + .await)) + } + }; + assert!( + contains(scoped_plan(7, None)) + .await + .matches(document.selector_set()), + "the tenant's query finds the tenant's document" + ); + for (other, whose) in [ + (scoped_plan(8, None), "another tenant"), + (plan(), "no tenant"), + ] { + assert!( + !contains(other).await.matches(document.selector_set()), + "{whose}" + ); + } + + // A read: `->` by selector, then the entry opened. + let name = data_term( + &keyset, + &scoped_plan(7, None), + "selector", + &[("path", json!("$.name"))], + ) + .await; + let dynamic::Operand::Text(name) = name.operand() else { + panic!("a selector is text") + }; + let entry = extracted_row(&document, name).expect("the tenant's selector names an entry"); + let request = || json!({"operation": "selector", "path": "$.name"}); + let names = open(&keyset, &sealing, request(), vec![vec![entry.clone()]]) + .await + .unwrap(); + assert_eq!(names, [vec![json!("Alice")]]); + for (other, whose) in [ + (scoped_plan(7, Some(10)), "another row"), + (scoped_plan(7, None), "no row"), + (scoped_plan(8, Some(9)), "another tenant"), + (plan(), "no tenant"), + ] { + let refused = open(&keyset, &other, request(), vec![vec![entry.clone()]]).await; + assert!(refused.is_err(), "{whose}"); + } +} + /// A document is queried by a JSON operator, which the engine derives /// from named inputs; eql-bindings' one-plaintext query refuses it by /// name rather than falling through its generated dispatch. diff --git a/packages/eql/tests/encryption/tests/migration_shim.rs b/packages/eql/tests/encryption/tests/migration_shim.rs index ecc013b744..85c66614ea 100644 --- a/packages/eql/tests/encryption/tests/migration_shim.rs +++ b/packages/eql/tests/encryption/tests/migration_shim.rs @@ -18,7 +18,7 @@ use std::cmp::Ordering; use eql_bindings::v4::integer::{IntegerOrdOre, IntegerOrdOreQuery}; use eql_bindings::v4::text::{TextEq, TextEqQuery}; use eql_bindings::Identifier; -use stack_encrypt::target::{EncryptTarget, Encryption, NoCallerContext, RequiredContext, Zeroize}; +use stack_encrypt::target::{AcceptsContext, EncryptTarget, Encryption, NoCallerContext, Zeroize}; use stack_encrypt::{DecryptFrom, EncryptInto, Error, NonEmpty}; /// A value decrypted from EQL v3, with the column it was stored in. @@ -39,7 +39,8 @@ struct Shim(T); impl EncryptTarget> for Shim where P: Zeroize, - T: EncryptTarget>>, + T: EncryptTarget

, + T::ContextInput: AcceptsContext>, { type ContextInput = NoCallerContext; fn encryption<'s, K: 'static>() -> Encryption<'s, V3Plaintext

, Self, K, NoCallerContext> diff --git a/packages/eql/tests/encryption/tests/readme_examples.rs b/packages/eql/tests/encryption/tests/readme_examples.rs new file mode 100644 index 0000000000..70b9283856 --- /dev/null +++ b/packages/eql/tests/encryption/tests/readme_examples.rs @@ -0,0 +1,92 @@ +//! Every Rust code block in the `eql-bindings` README is run. +//! +//! `src/lib.rs` includes the README as documentation, so `cargo test` runs +//! each Rust block as a doctest of this crate. rustdoc skips a block marked +//! `ignore`, and only compiles one marked `no_run`. It reports both as +//! passing. So no Rust block may carry a marker. +//! +//! rustdoc also reads a block as Rust when its info string holds only +//! rustdoc's own words, such as `ignore` or `should_panic`, or is empty. So +//! this test does not try to tell which blocks rustdoc compiles. It allows +//! two kinds of block, and refuses every other: +//! +//! - `rust`, alone: rustdoc compiles it and runs it; +//! - one of [`OTHER_LANGUAGES`]: a word rustdoc does not know, so the +//! block is not a doctest. + +const README: &str = include_str!("../../../crates/eql-bindings/README.md"); + +/// The languages a block may name that are not Rust. rustdoc knows none of +/// these words, so it does not compile a block that names one. +const OTHER_LANGUAGES: [&str; 6] = ["bash", "json", "sh", "sql", "text", "toml"]; + +/// The info string of each fenced code block, with the line it opens on. +fn code_blocks(markdown: &str) -> Vec<(usize, &str)> { + let mut blocks = Vec::new(); + let mut open = false; + for (index, line) in markdown.lines().enumerate() { + let Some(info) = line.strip_prefix("```") else { + continue; + }; + if !open { + blocks.push((index + 1, info.trim())); + } + open = !open; + } + assert!(!open, "the last code block is not closed"); + blocks +} + +/// Whether a block with this info string is allowed: a Rust block that is +/// run, or a block in another language. +fn allowed(info: &str) -> bool { + info == "rust" || OTHER_LANGUAGES.contains(&info) +} + +#[test] +fn every_rust_block_in_the_readme_is_run() { + let blocks = code_blocks(README); + assert!( + blocks.iter().any(|(_, info)| *info == "rust"), + "the README has no Rust code block" + ); + for (line, info) in blocks { + assert!( + allowed(info), + "README line {line}: a code block marked `{info}`. Mark a Rust example `rust` \ + alone, so that it is run. Mark any other block with its language, one of \ + {OTHER_LANGUAGES:?}" + ); + } +} + +#[test] +fn the_scan_reads_each_blocks_info_string() { + let blocks = code_blocks("```rust,ignore\nlet x = 1;\n```\n\n```sh\nls\n```\n\n```\nx\n```\n"); + assert_eq!(blocks, [(1, "rust,ignore"), (5, "sh"), (9, "")]); +} + +#[test] +fn a_block_rustdoc_would_skip_is_refused() { + for info in ["rust", "sh", "bash", "text"] { + assert!(allowed(info), "`{info}` is allowed"); + } + // Every one of these is Rust to rustdoc, and none is run as written: + // skipped, compiled only, expected to fail, or run with no language + // named. + for info in [ + "", + "ignore", + "no_run", + "rust,ignore", + "rust,no_run", + "rust ignore", + "should_panic", + "compile_fail", + "rust,should_panic", + "edition2021", + "sh,ignore", + ] { + assert!(!allowed(info), "`{info}` is refused"); + } +} diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs new file mode 100644 index 0000000000..022e7950f4 --- /dev/null +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -0,0 +1,1046 @@ +//! EQL types as fields of a derived `struct = ..` record. +//! +//! A record gives each field its scope and the field's name, such as +//! `("members", "email")`. An EQL field stores that pair as its column, `i`. +//! So the field must write what the same type writes on its own under +//! `Identifier::for_column("members", "email")`, and what a data plan writes +//! for a field that names the type. A data plan is the path the Go module +//! takes. Here: +//! +//! - a record with EQL fields encrypts and decrypts through the new API; +//! - each field writes the terms the type writes on its own, and each value +//! opens through the other path; +//! - a query from the field's marker gives the stored term; +//! - the derive and a data plan write the same terms for a field of each +//! kind (equality, storage only, order, JSON document), and each opens +//! the other's value; +//! - a scope or a binding that the record lists, supplied by the caller or +//! stored in the row, comes after the column in the field's context. The +//! terms derive under the column and the scope. The ciphertext is sealed +//! under the binding too. `i` stores neither. The reader supplies both +//! again, and a query supplies the scope; +//! - under a scope and a binding, the derive and a data plan still write +//! the same terms, and each opens the other's values; +//! - an EQL field of a record nested in another stores its own column too; +//! - a field that stores another column is refused before any key is +//! requested; +//! - a renamed field keeps its column with `identity`, and reads the rows +//! written under its old name. With no `identity` they are refused; +//! - a JSON document, `JsonTreeDocument`, encrypts from a `JsonPlaintext` +//! through the new API, writes the search terms the old path writes, and +//! is a record field too. + +mod common; + +use eql_bindings::encryption::{EqlTargets, NativeCiphertextVisitor as NativeLeaf}; +use eql_bindings::v4::integer::IntegerOrd; +use eql_bindings::v4::json_tree::{JsonTree, JsonTreeDocument}; +use eql_bindings::v4::text::{Text, TextEq, TextEqQuery}; +use eql_bindings::Identifier; +use serde::Serialize; +use serde_json::{json, Value}; +use stack_encrypt::dynamic::{self, record, Op, Operand, Planned, QueryTerm, ValueFrame}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::target::transcode::Reader as _; +use stack_encrypt::target::{AeadContext, Bind, Layout, Parts, Scope}; +use stack_encrypt::testing::{bind, scope, Expect}; +use stack_encrypt::{ + assert_context, nonempty, AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, + DecryptSource, EncryptInto, EncryptTarget, Error, NonEmpty, StackCipherText, +}; +use zeroize::Zeroize; + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct Member { + id: u64, + email: String, + age: i32, +} + +/// The plan's example "Store a field as an EQL type". +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Member, scope = "members")] +struct EncryptedMember { + #[stash(passthrough)] + id: u64, + email: TextEq, + age: IntegerOrd, +} + +fn ada() -> Member { + Member { + id: 7, + email: "ada@example.com".into(), + age: 36, + } +} + +fn column(name: &str) -> NonEmpty { + Identifier::for_column("members", name).unwrap() +} + +/// A stored payload without its ciphertext: the envelope and every term. +/// `c` is sealed under a new nonce each time, so its bytes differ. +fn terms_of(stored: &T) -> serde_json::Value { + let mut json = serde_json::to_value(stored).unwrap(); + let object = json.as_object_mut().unwrap(); + assert!(object.remove("c").is_some(), "a stored value carries `c`"); + json +} + +#[tokio::test] +async fn a_record_with_eql_fields_round_trips() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedMember = ada().encrypt_into(&keyset).await.unwrap(); + assert_eq!(stored.id, 7, "the passthrough field is carried as it is"); + assert_eq!(stored.email.i, *column("email").get()); + assert_eq!(stored.age.i, *column("age").get()); + assert_eq!( + calls.lock().unwrap().generate.len(), + 1, + "both fields' keys in one request" + ); + + let opened = Member::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened, ada()); +} + +#[tokio::test] +async fn an_eql_field_writes_what_the_type_writes_on_its_own() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let member = ada(); + let stored: EncryptedMember = member.clone().encrypt_into(&keyset).await.unwrap(); + let email: TextEq = member + .email + .clone() + .encrypt_into_with_context(&keyset, column("email")) + .await + .unwrap(); + let age: IntegerOrd = member + .age + .encrypt_into_with_context(&keyset, column("age")) + .await + .unwrap(); + assert_eq!( + terms_of(&stored.email), + terms_of(&email), + "the same email terms" + ); + assert_eq!(terms_of(&stored.age), terms_of(&age), "the same age terms"); + + // The record's fields open on their own, under the column. + let opened = String::decrypt_from_with_context(stored.email, &keyset, column("email")) + .await + .unwrap(); + assert_eq!(opened, member.email); + let opened = i32::decrypt_from_with_context(stored.age, &keyset, column("age")) + .await + .unwrap(); + assert_eq!(opened, member.age); + + // And the values written on their own open as the record's fields. + let record = EncryptedMember { + id: member.id, + email, + age, + }; + assert_eq!(Member::decrypt_from(record, &keyset).await.unwrap(), member); +} + +#[tokio::test] +async fn a_query_from_the_field_marker_gives_the_stored_term() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedMember = ada().encrypt_into(&keyset).await.unwrap(); + + let query = EncryptedMember::EMAIL + .eq("ada@example.com") + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!( + query.i, stored.email.i, + "the query names the field's column" + ); + assert_eq!(query.hm, stored.email.hm, "and carries the stored term"); + + let other = EncryptedMember::EMAIL + .eq("bob@example.com") + .encrypt(&keyset) + .await + .unwrap(); + assert_ne!(other.hm, stored.email.hm); +} + +#[derive(Clone, Zeroize)] +struct Contact { + email: String, + name: String, + age: i32, + profile: JsonPlaintext, +} + +fn contact() -> Contact { + Contact { + email: "ada@example.com".into(), + name: "Ada".into(), + age: 36, + profile: profile().into(), + } +} + +/// A field of each kind: equality, storage only, order, and a JSON +/// document. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Contact, scope = "contacts")] +struct EncryptedContact { + email: TextEq, + name: Text, + age: IntegerOrd, + profile: JsonTreeDocument, +} + +/// The data plan that declares the record's fields with EQL targets, as a +/// binding writes it. +fn contact_plan() -> record::Plan { + let wire = serde_json::json!({ + "email": {"context": ["contacts", "email"], "target": "TextEq"}, + "name": {"context": ["contacts", "name"], "target": "Text"}, + "age": {"context": ["contacts", "age"], "target": "IntegerOrd"}, + "profile": {"context": ["contacts", "profile"], "target": "JsonSearch"}, + }); + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &EqlTargets, + ) + .unwrap() +} + +/// A contact as a binding sends it to a data plan: the JSON document as +/// its text. +#[derive(Serialize)] +struct ContactRow { + email: String, + name: String, + age: i32, + profile: String, +} + +/// A contact as a data plan opens it: the JSON document as the bytes of +/// its text. +#[derive(serde::Deserialize)] +struct OpenedContact { + email: String, + name: String, + age: i32, + profile: Bytes, +} + +/// The EQL value of `field`, in a row a data plan sealed. +fn eql_payload<'a>(row: &'a mut StackCipherText, field: &str) -> &'a mut Vec { + let CipherText::Map(fields) = row else { + panic!("a row is a map") + }; + let Some((_, CipherText::Map(outputs))) = fields.iter_mut().find(|(name, _)| name == field) + else { + panic!("{field} is a map of outputs"); + }; + let Some((_, CipherText::Passthrough(payload))) = + outputs.iter_mut().find(|(key, _)| key == "eql") + else { + panic!("{field}'s EQL value is a passthrough"); + }; + &mut payload.0 +} + +/// An EQL value in a row: its JSON text, framed as bytes. +struct Bytes(Vec); +impl Serialize for Bytes { + fn serialize(&self, s: S) -> Result { + s.serialize_bytes(&self.0) + } +} +impl<'de> serde::Deserialize<'de> for Bytes { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = Bytes; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("bytes") + } + fn visit_bytes(self, v: &[u8]) -> Result { + Ok(Bytes(v.to_vec())) + } + fn visit_byte_buf(self, v: Vec) -> Result { + Ok(Bytes(v)) + } + } + d.deserialize_bytes(V) + } +} + +fn read_eql(row: &mut StackCipherText, field: &str) -> T { + let bytes: Bytes = dynamic::frame::serde::from_slice(eql_payload(row, field)).unwrap(); + serde_json::from_slice(&bytes.0).unwrap() +} + +fn write_eql(row: &mut StackCipherText, field: &str, value: &T) { + let json = serde_json::to_vec(value).unwrap(); + *eql_payload(row, field) = dynamic::frame::serde::to_vec(&Bytes(json)) + .unwrap() + .risky_unwrap(); +} + +#[tokio::test] +async fn the_derive_and_a_data_plan_write_the_same_row() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let plan = contact_plan(); + let derived: EncryptedContact = contact().encrypt_into(&keyset).await.unwrap(); + let source = ContactRow { + email: "ada@example.com".into(), + name: "Ada".into(), + age: 36, + profile: profile().to_string(), + }; + let source = ValueFrame::from_bytes( + dynamic::frame::serde::to_vec(&source) + .unwrap() + .as_protected_ref(), + ) + .unwrap(); + let mut row = record::encrypt_with(&keyset, source, &plan, &EqlTargets) + .unwrap() + .await + .unwrap(); + + let planned_email: TextEq = read_eql(&mut row, "email"); + let planned_name: Text = read_eql(&mut row, "name"); + let planned_age: IntegerOrd = read_eql(&mut row, "age"); + let planned_profile: JsonTreeDocument = read_eql(&mut row, "profile"); + assert_eq!(terms_of(&derived.email), terms_of(&planned_email)); + assert_eq!(terms_of(&derived.name), terms_of(&planned_name)); + assert_eq!(terms_of(&derived.age), terms_of(&planned_age)); + assert_eq!( + document_terms(&derived.profile), + document_terms(&planned_profile) + ); + + // The data plan's values open as the record's fields. + let record = EncryptedContact { + email: planned_email, + name: planned_name, + age: planned_age, + profile: planned_profile, + }; + let opened = Contact::decrypt_from(record, &keyset).await.unwrap(); + assert_eq!(opened.email, "ada@example.com"); + assert_eq!(opened.name, "Ada"); + assert_eq!(opened.age, 36); + assert_eq!(opened.profile.value(), &profile()); + + // The record's values, in the data plan's row, open through the plan. + write_eql(&mut row, "email", &derived.email); + write_eql(&mut row, "name", &derived.name); + write_eql(&mut row, "age", &derived.age); + write_eql(&mut row, "profile", &derived.profile); + let opened = record::decrypt_with(&cipher, row, &plan, None, &EqlTargets) + .unwrap() + .await + .unwrap(); + let opened: OpenedContact = dynamic::frame::serde::from_slice(opened.risky_ref()).unwrap(); + assert_eq!(opened.email, "ada@example.com"); + assert_eq!(opened.name, "Ada"); + assert_eq!(opened.age, 36); + assert_eq!( + serde_json::from_slice::(&opened.profile.0).unwrap(), + profile() + ); +} + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct Tenanted { + email: String, +} + +fn tenanted() -> Tenanted { + Tenanted { + email: "ada@example.com".into(), + } +} + +/// A record whose caller supplies a tenant scope and a row binding. An EQL +/// field stores its column in `i`, and neither the tenant nor the row. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Tenanted, scope = "members", scope(tenant: u64), bind(row: u128))] +struct EncryptedTenanted { + email: TextEq, +} + +/// The tenant and the row the tests seal under. +fn tenant_and_row() -> Parts, Bind> { + Scope::new(42u64).bind(9u128) +} + +/// The record shows the contexts of an EQL field's ciphertext and term +/// before any key is requested: the column, the tenant, then the row. +#[test] +fn a_record_shows_the_scope_and_the_binding_of_an_eql_field() { + assert_context!( + EncryptedTenanted::contexts(), + "email.c" = { + query = [["members", "email"], scope::("tenant")], + stored = [ + [ + Expect::from(["members", "email"]), + Expect::from(scope::("tenant")), + ], + bind::("row"), + ], + }, + "email.hm" = { + query = [["members", "email"], scope::("tenant")], + stored = [ + [ + Expect::from(["members", "email"]), + Expect::from(scope::("tenant")), + ], + bind::("row"), + ], + }, + ); +} + +#[tokio::test] +async fn an_eql_field_stores_its_column_and_not_the_scope_or_the_binding() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedTenanted = tenanted() + .encrypt_into_with_context(&keyset, tenant_and_row()) + .await + .unwrap(); + assert_eq!( + stored.email.i, + *column("email").get(), + "`i` holds the declared names alone" + ); + + // The ciphertext is sealed under the column, then the tenant, then the + // row: it opens as a Stack Encrypt leaf under exactly that context. + let leaf = stored.email.c.clone().read(NativeLeaf).unwrap(); + let context = AeadContext::from(tenant_and_row()).extend(nonempty!("members").with("email")); + let opened: String = cipher.decrypt_as(leaf, context).await.unwrap(); + assert_eq!(opened, "ada@example.com"); + + // The term is derived under the column, then the tenant. A query from + // the field's marker under the same tenant gives the stored term, and + // names the column alone. + let query = EncryptedTenanted::EMAIL + .eq("ada@example.com") + .scope(Scope::new(42u64)) + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(query.i, stored.email.i); + assert_eq!(query.hm, stored.email.hm); + let other_tenant = EncryptedTenanted::EMAIL + .eq("ada@example.com") + .scope(Scope::new(43u64)) + .encrypt(&keyset) + .await + .unwrap(); + assert_ne!(other_tenant.hm, stored.email.hm); + + // So it is not the term of the column alone. + let alone: TextEq = "ada@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column("email")) + .await + .unwrap(); + assert_ne!(alone.hm, stored.email.hm); + + // A binding is in no query context: another row has the same term. + let other_row: EncryptedTenanted = tenanted() + .encrypt_into_with_context(&keyset, Scope::new(42u64).bind(10u128)) + .await + .unwrap(); + assert_eq!(other_row.email.hm, stored.email.hm); + + // The reader supplies the tenant and the row again. + let opened = Tenanted::decrypt_from_with_context(stored, &keyset, tenant_and_row()) + .await + .unwrap(); + assert_eq!(opened, tenanted()); +} + +#[tokio::test] +async fn an_eql_field_opens_only_under_the_scope_and_the_binding_it_was_sealed_under() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedTenanted = tenanted() + .encrypt_into_with_context(&keyset, tenant_and_row()) + .await + .unwrap(); + let again = || EncryptedTenanted { + email: stored.email.clone(), + }; + + let other_tenant = + Tenanted::decrypt_from_with_context(again(), &keyset, Scope::new(43u64).bind(9u128)); + assert!(other_tenant.await.is_err(), "another tenant"); + let other_row = + Tenanted::decrypt_from_with_context(again(), &keyset, Scope::new(42u64).bind(10u128)); + assert!(other_row.await.is_err(), "another row"); + + // On its own, the field's value stores the same column. It was sealed + // under the tenant and the row too, so the column alone does not open + // it. + let alone = + String::decrypt_from_with_context(stored.email.clone(), &keyset, column("email")).await; + assert!(alone.is_err(), "the column alone"); + + // And a value sealed under the column alone does not open as the + // record's field. + let email: TextEq = "ada@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column("email")) + .await + .unwrap(); + let record = EncryptedTenanted { email }; + let opened = Tenanted::decrypt_from_with_context(record, &keyset, tenant_and_row()).await; + assert!(opened.is_err(), "sealed without the tenant and the row"); + + // The stored column is checked first, before any key is requested. + let email: TextEq = "ada@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column("other")) + .await + .unwrap(); + let record = EncryptedTenanted { email }; + let before = calls.lock().unwrap().retrieve.len(); + match Tenanted::decrypt_from_with_context(record, &keyset, tenant_and_row()).await { + Err(Error::ContextMismatch { .. }) => {} + Err(other) => panic!("expected ContextMismatch, got {other:?}"), + Ok(_) => panic!("expected ContextMismatch, got a value"), + } + assert_eq!(calls.lock().unwrap().retrieve.len(), before); +} + +#[derive(Clone, Zeroize)] +struct Lead { + email: String, + profile: JsonPlaintext, +} + +/// A record with a scalar field and a document field, under a tenant scope +/// and a row binding that the caller supplies. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Lead, scope = "leads", scope(tenant: u64), bind(row: u128))] +struct EncryptedLead { + email: TextEq, + profile: JsonTreeDocument, +} + +/// The data plan that declares the same two fields with EQL targets. It +/// lists no scope and no binding: the call supplies them, as it does for +/// the record. +fn lead_plan() -> record::Plan { + let wire = serde_json::json!({ + "email": {"context": ["leads", "email"], "target": "TextEq"}, + "profile": {"context": ["leads", "profile"], "target": "JsonSearch"}, + }); + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &EqlTargets, + ) + .unwrap() +} + +/// A lead as a binding sends it to a data plan. +fn lead_row() -> ValueFrame { + #[derive(Serialize)] + struct Row { + email: String, + profile: String, + } + let row = Row { + email: "ada@example.com".into(), + profile: profile().to_string(), + }; + ValueFrame::from_bytes( + dynamic::frame::serde::to_vec(&row) + .unwrap() + .as_protected_ref(), + ) + .unwrap() +} + +/// A scope and a binding reach an EQL type through a data plan as they +/// reach it through the derive. So the two paths write the same terms +/// under the same tenant and row, each stores the column alone, and each +/// opens what the other sealed. A data plan is the path Go takes. +#[tokio::test] +async fn the_derive_and_a_data_plan_write_the_same_row_under_a_scope_and_a_binding() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let plan = lead_plan(); + let derived: EncryptedLead = Lead { + email: "ada@example.com".into(), + profile: profile().into(), + } + .encrypt_into_with_context(&keyset, tenant_and_row()) + .await + .unwrap(); + let seal = || async { + let row: StackCipherText = Planned::with_resolver(&plan, lead_row(), EqlTargets) + .encrypt_into_with_context(&keyset, tenant_and_row()) + .await + .unwrap(); + row + }; + + let mut row = seal().await; + let planned_email: TextEq = read_eql(&mut row, "email"); + let planned_profile: JsonTreeDocument = read_eql(&mut row, "profile"); + let leads = |name: &str| Identifier::for_column("leads", name).unwrap().into_inner(); + assert_eq!(planned_email.i, leads("email"), "the column alone"); + assert_eq!(planned_profile.i, leads("profile"), "the column alone"); + assert_eq!(terms_of(&planned_email), terms_of(&derived.email)); + assert_eq!( + document_terms(&planned_profile), + document_terms(&derived.profile) + ); + // The terms are the tenant's, and not the column's alone. + let alone: TextEq = "ada@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, Identifier::for_column("leads", "email").unwrap()) + .await + .unwrap(); + assert_ne!(alone.hm, planned_email.hm); + + // The data plan's values open as the record's fields. + let record = EncryptedLead { + email: planned_email, + profile: planned_profile, + }; + let opened = Lead::decrypt_from_with_context(record, &keyset, tenant_and_row()) + .await + .unwrap(); + assert_eq!(opened.email, "ada@example.com"); + assert_eq!(opened.profile.value(), &profile()); + + // The record's values, in the data plan's row, open through the plan. + write_eql(&mut row, "email", &derived.email); + write_eql(&mut row, "profile", &derived.profile); + let opened = ValueFrame::decrypt_from_with_context( + Planned::with_resolver(&plan, row, EqlTargets), + &keyset, + tenant_and_row(), + ) + .await + .unwrap(); + #[derive(serde::Deserialize)] + struct Opened { + email: String, + profile: Bytes, + } + let opened: Opened = dynamic::frame::serde::from_slice(opened.risky_ref()).unwrap(); + assert_eq!(opened.email, "ada@example.com"); + assert_eq!( + serde_json::from_slice::(&opened.profile.0).unwrap(), + profile() + ); + + // The plan opens its row only under the same tenant and row. + for parts in [ + Scope::new(43u64).bind(9u128), + Scope::new(42u64).bind(10u128), + ] { + let refused = ValueFrame::decrypt_from_with_context( + Planned::with_resolver(&plan, seal().await, EqlTargets), + &keyset, + parts, + ) + .await; + assert!(refused.is_err()); + } + let refused = ValueFrame::decrypt_from( + Planned::with_resolver(&plan, seal().await, EqlTargets), + &keyset, + ) + .await; + assert!(refused.is_err(), "with no tenant and no row"); + + // A query through the plan, under the tenant, is the stored term. It + // names the column alone. + let by_email = plan.query_with("email", Op::Eq, &EqlTargets).unwrap(); + let term = |tenant: u64| { + let (by_email, keyset) = (&by_email, &keyset); + async move { + let value = ValueFrame::of("ada@example.com").unwrap(); + let term: QueryTerm = Planned::with_resolver(by_email, value, EqlTargets) + .encrypt_into_with_context(keyset, Scope::new(tenant)) + .await + .unwrap(); + let Operand::One(json) = term.operand() else { + panic!("an equality query has one operand"); + }; + serde_json::from_slice::(json).unwrap() + } + }; + let query = term(42).await; + assert_eq!(query.i, derived.email.i); + assert_eq!(query.hm, derived.email.hm); + assert_ne!(term(43).await.hm, derived.email.hm); +} + +#[derive(Clone, Zeroize)] +struct Note { + id: u128, + tenant: u64, + title: String, + body: JsonPlaintext, +} + +/// A record that stores its scope and its binding in the row, in fields of +/// its own. Its EQL fields still store their columns alone. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Note, scope = "notes", scope(field = "tenant"), bind(field = "id"))] +struct EncryptedNote { + #[stash(passthrough)] + id: u128, + #[stash(passthrough)] + tenant: u64, + title: TextEq, + body: JsonTreeDocument, +} + +#[tokio::test] +async fn an_eql_field_of_a_record_that_stores_its_scope_and_binding() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let note = Note { + id: 9, + tenant: 42, + title: "Renewal".into(), + body: profile().into(), + }; + let stored: EncryptedNote = note.encrypt_into(&keyset).await.unwrap(); + let notes = |name: &str| Identifier::for_column("notes", name).unwrap().into_inner(); + assert_eq!(stored.title.i, notes("title")); + assert_eq!(stored.body.i, notes("body")); + + // A query supplies the tenant, since it cannot read a row. + let query = EncryptedNote::TITLE + .eq("Renewal") + .scope(Scope::new(42u64)) + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(query.i, stored.title.i); + assert_eq!(query.hm, stored.title.hm); + + // The fields of this row do not open in another row. + let moved = EncryptedNote { + id: 10, + tenant: stored.tenant, + title: stored.title.clone(), + body: stored.body.clone(), + }; + assert!(Note::decrypt_from(moved, &keyset).await.is_err()); + + // The row supplies its tenant and its ID, so the reader passes none. + let opened = Note::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened.id, 9); + assert_eq!(opened.tenant, 42); + assert_eq!(opened.title, "Renewal"); + assert_eq!(opened.body.value(), &profile()); +} + +/// A record with an EQL field and nothing the caller supplies. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Tenanted, scope = "members")] +struct EncryptedPlain { + email: TextEq, +} + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct Holder { + member: Tenanted, +} + +/// That record as a field of another. Its EQL field's context is then its +/// own pair, followed by the outer field's pair. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Holder, scope = "holders")] +struct EncryptedHolder { + member: EncryptedPlain, +} + +#[tokio::test] +async fn an_eql_field_of_a_nested_record_stores_its_own_column() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let holder = Holder { member: tenanted() }; + let stored: EncryptedHolder = holder.clone().encrypt_into(&keyset).await.unwrap(); + + // The inner record's scope and the field's name. The outer record's + // names come after them in the context, and are not stored. + assert_eq!(stored.member.email.i, *column("email").get()); + + // A query from the nested field's marker gives the stored term. + let query = EncryptedHolder::MEMBER + .field(EncryptedPlain::EMAIL) + .eq("ada@example.com") + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(query.i, stored.member.email.i); + assert_eq!(query.hm, stored.member.email.hm); + + // The inner record on its own writes another term: its field has no + // outer names in its context. + let plain: EncryptedPlain = tenanted().encrypt_into(&keyset).await.unwrap(); + assert_eq!(plain.email.i, stored.member.email.i); + assert_ne!(plain.email.hm, stored.member.email.hm); + + assert_eq!(Holder::decrypt_from(stored, &keyset).await.unwrap(), holder); +} + +#[tokio::test] +async fn a_field_that_stores_another_column_is_refused() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let mut stored: EncryptedMember = ada().encrypt_into(&keyset).await.unwrap(); + stored.email = "ada@example.com" + .to_owned() + .encrypt_into_with_context(&keyset, column("other")) + .await + .unwrap(); + + match Member::decrypt_from(stored, &keyset).await { + Err(Error::ContextMismatch { .. }) => {} + Err(other) => panic!("expected ContextMismatch, got {other:?}"), + Ok(_) => panic!("expected ContextMismatch, got a value"), + } + assert!( + calls.lock().unwrap().retrieve.is_empty(), + "refused before any key is requested" + ); +} + +/// `Member`, after its `email` field was renamed to `email_address`. +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct RenamedMember { + id: u64, + email_address: String, + age: i32, +} + +/// The renamed field keeps its old name as its column, with `identity`. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = RenamedMember, scope = "members")] +struct EncryptedRenamedMember { + #[stash(passthrough)] + id: u64, + #[stash(identity = "email")] + email_address: TextEq, + age: IntegerOrd, +} + +/// The renamed field with no `identity`: its column is its new name. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = RenamedMember, scope = "members")] +struct EncryptedUnpinnedMember { + #[stash(passthrough)] + id: u64, + email_address: TextEq, + age: IntegerOrd, +} + +/// A field's name is part of its context, so a renamed field does not open +/// the rows written under its old name. `identity` keeps the old name: the +/// field then stores, and expects, the column the rows already hold. +#[tokio::test] +async fn a_renamed_eql_field_keeps_its_column_with_identity() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + // A row written before the rename. + let before: EncryptedMember = ada().encrypt_into(&keyset).await.unwrap(); + assert_eq!(before.email.i, *column("email").get()); + + // The renamed record reads it, with the old name kept. + let row = EncryptedRenamedMember { + id: before.id, + email_address: before.email.clone(), + age: before.age.clone(), + }; + let opened = RenamedMember::decrypt_from(row, &keyset).await.unwrap(); + assert_eq!(opened.email_address, "ada@example.com"); + + // It writes the column and the terms the record wrote before. + let after: EncryptedRenamedMember = opened.encrypt_into(&keyset).await.unwrap(); + assert_eq!(after.email_address.i, *column("email").get()); + assert_eq!(terms_of(&after.email_address), terms_of(&before.email)); + + // With no `identity`, the field's column is `email_address`. The row + // stores `email`, so it is refused before any key is requested. + let retrieved = calls.lock().unwrap().retrieve.len(); + let row = EncryptedUnpinnedMember { + id: before.id, + email_address: before.email, + age: before.age, + }; + match RenamedMember::decrypt_from(row, &keyset).await { + Err(Error::ContextMismatch { .. }) => {} + Err(other) => panic!("expected ContextMismatch, got {other:?}"), + Ok(_) => panic!("expected ContextMismatch, got a value"), + } + assert_eq!( + calls.lock().unwrap().retrieve.len(), + retrieved, + "refused before any key is requested" + ); +} + +fn profile() -> Value { + json!({"name": "Ada", "age": 36, "tags": ["maths", "engines"]}) +} + +/// What each stored entry shows a query, as a sorted list: its selector, +/// its ordering term and whether it carries a parent tag. Entries are +/// stored in a random order, so two seals of one document compare as +/// multisets. +fn search_terms(document: &JsonTreeDocument) -> Vec<(String, String, bool)> { + let mut terms: Vec<_> = document + .sv + .iter() + .map(|entry| { + ( + serde_json::to_string(&entry.s).unwrap(), + serde_json::to_string(&entry.op).unwrap(), + entry.p.is_some(), + ) + }) + .collect(); + terms.sort(); + terms +} + +/// A stored document without what differs between two seals of it: the +/// key header `h`, sealed under a new key each time, and the entries' own +/// ciphertexts. The search terms of every entry and the query group are +/// kept, sorted, since both are stored in a random order. +fn document_terms(document: &JsonTreeDocument) -> (Value, Vec<(String, String, bool)>) { + let mut json = serde_json::to_value(document).unwrap(); + let object = json.as_object_mut().unwrap(); + assert!(object.remove("h").is_some(), "a document carries `h`"); + assert!(object.remove("sv").is_some(), "a document carries `sv`"); + let group = object["q"].as_object_mut().unwrap(); + for list in group.values_mut() { + list.as_array_mut() + .unwrap() + .sort_by_key(|entry| entry.to_string()); + } + (json, search_terms(document)) +} + +#[tokio::test] +async fn a_json_document_encrypts_from_a_json_plaintext() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let column = || Identifier::for_column("customers", "profile").unwrap(); + + let stored: JsonTreeDocument = JsonPlaintext::from(profile()) + .encrypt_into_with_context(&keyset, column()) + .await + .unwrap(); + let old: JsonTreeDocument = keyset + .run(JsonTree::default().encryption(), &profile(), column()) + .await + .unwrap(); + assert_eq!( + document_terms(&stored), + document_terms(&old), + "the same envelope and search terms" + ); + + // Each path opens what the other sealed. + let opened = JsonPlaintext::decrypt_from_with_context(old, &keyset, column()) + .await + .unwrap(); + assert_eq!(opened.value(), &profile()); + let opened: Value = cipher + .decrypt_as(stored.clone(), column().into()) + .await + .unwrap(); + assert_eq!(opened, profile()); + + // Without a column, the document opens under the one it stores. + let opened = JsonPlaintext::decrypt_from(stored.clone(), &keyset) + .await + .unwrap(); + assert_eq!(opened.value(), &profile()); + + // Under another column, it is refused before any key is requested. + let before = calls.lock().unwrap().retrieve.len(); + let other = Identifier::for_column("customers", "bio").unwrap(); + match JsonPlaintext::decrypt_from_with_context(stored, &keyset, other).await { + Err(Error::ContextMismatch { .. }) => {} + Err(other) => panic!("expected ContextMismatch, got {other:?}"), + Ok(_) => panic!("expected ContextMismatch, got a value"), + } + assert_eq!(calls.lock().unwrap().retrieve.len(), before); +} + +#[derive(Clone, Zeroize)] +struct Customer { + id: u64, + profile: JsonPlaintext, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Customer, scope = "customers")] +struct EncryptedCustomer { + #[stash(passthrough)] + id: u64, + profile: JsonTreeDocument, +} + +#[tokio::test] +async fn a_json_document_is_a_record_field() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let customer = Customer { + id: 3, + profile: profile().into(), + }; + let stored: EncryptedCustomer = customer.encrypt_into(&keyset).await.unwrap(); + assert_eq!( + stored.profile.i, + Identifier { + t: "customers".into(), + c: "profile".into() + }, + "the field's column is the record's scope and the field's name" + ); + let old: JsonTreeDocument = keyset + .run( + JsonTree::default().encryption(), + &profile(), + Identifier::for_column("customers", "profile").unwrap(), + ) + .await + .unwrap(); + assert_eq!(document_terms(&stored.profile), document_terms(&old)); + + let opened = Customer::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened.id, 3); + assert_eq!(opened.profile.value(), &profile()); +} diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index 3ea0a1c4ff..767c435c86 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -23,7 +23,10 @@ use eql_bindings::Identifier; use serde::Serialize; use stack_encrypt::dynamic::{self, record, FieldPlan, Op, Operand, TargetDescriptor, ValueFrame}; use stack_encrypt::op::{self, Probabilistic, Stats}; +use stack_encrypt::target::Scope; use stack_encrypt::{ContextPiece, Encrypt, Error, NonEmpty, Plan, StackCipher}; +use stack_encrypt::{DecryptSource, EncryptInto, EncryptTarget}; +use zeroize::Zeroize; type Cipher = StackCipher; @@ -441,59 +444,105 @@ async fn a_typed_query_refuses_what_the_data_path_refuses() { assert_eq!(calls.lock().unwrap().loads, 0, "refused before any keyset"); } -/// A query extended with `.extend(..)` derives its terms under the column -/// and the extension, while the twin stores the column alone, so it could -/// match nothing: it is refused, before the named keyset is loaded, for an +#[derive(Clone, Zeroize)] +struct Person { + email: String, + name: String, +} + +/// A record whose caller supplies a tenant scope, with an exact field and a +/// match field. Each field stores its column, and not the tenant. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Person, scope = "users", scope(tenant: i64))] +struct EncryptedPerson { + email: TextEq, + name: TextMatch, +} + +/// A query extended with `.extend(..)` derives its term under the column +/// and the extension. A record stores its fields the same way under a +/// scope. So the extended query is the term of the row stored under that +/// scope, and the twin stores the column alone, as the row does. For an /// exact type and for `TextMatch`. #[tokio::test] -async fn an_extended_typed_query_is_refused_before_any_keyset() { - let (cipher, calls) = common::cipher().await; +async fn an_extended_typed_query_finds_a_value_stored_under_the_same_scope() { + let (cipher, _) = common::cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedPerson = Person { + email: "bob@example.com".into(), + name: "Bob Jones".into(), + } + .encrypt_into_with_context(&keyset, Scope::new(7i64)) + .await + .unwrap(); + let email = Plan::value::() .context("users/email") .encrypt_into::() .build() .unwrap(); + let query = cipher + .query(op::Eq, "bob@example.com") + .extend(7i64) + .on(&email) + .await + .unwrap(); + assert_eq!(query.i, stored.email.i, "the twin stores the column alone"); + assert_eq!(query.hm, stored.email.hm, "the term of the stored row"); + + // Another scope, or none, gives another term. + let other = cipher + .query(op::Eq, "bob@example.com") + .extend(8i64) + .on(&email) + .await + .unwrap(); + assert_ne!(other.hm, stored.email.hm); + let unscoped = cipher + .query(op::Eq, "bob@example.com") + .on(&email) + .await + .unwrap(); + assert_eq!(unscoped.i, stored.email.i); + assert_ne!(unscoped.hm, stored.email.hm); + let name = Plan::value::() .context("users/name") .encrypt_into::() .build() .unwrap(); - let refusals = [ - cipher - .query(op::Eq, "bob") - .extend(7i64) - .keyset("tenant") - .on(&email) - .await - .map(drop), - cipher - .query(op::Matches, "alice") - .extend(7i64) - .keyset("tenant") - .on(&name) - .await - .map(drop), - ]; - for refused in refusals { - let Err(Error::Other(reason)) = &refused else { - panic!("{refused:?}"); - }; - assert_eq!( - reason.downcast_ref::(), - Some(&QueryLabelError::Extended), - "{reason}" - ); - } - assert_eq!(calls.lock().unwrap().loads, 0, "refused before any keyset"); - - // Unextended, the same query loads the keyset and runs. - cipher - .query(op::Eq, "bob") - .keyset("tenant") - .on(&email) + let query = cipher + .query(op::Matches, "jones") + .extend(7i64) + .on(&name) + .await + .unwrap(); + assert_eq!(query.twin().i, stored.name.i); + // Every position the query sets is set in the stored filter. + assert!( + query + .twin() + .bf + .0 + .iter() + .all(|position| stored.name.bf.0.contains(position)), + "the stored filter contains the query's" + ); + let other = cipher + .query(op::Matches, "jones") + .extend(8i64) + .on(&name) .await .unwrap(); - assert_eq!(calls.lock().unwrap().loads, 1); + assert!( + !other + .twin() + .bf + .0 + .iter() + .all(|position| stored.name.bf.0.contains(position)), + "under another scope the filter differs" + ); } /// A record field naming a storage-only EQL type may store a null as the diff --git a/packages/eql/tests/encryption/tests/v4_owned.rs b/packages/eql/tests/encryption/tests/v4_owned.rs index da042dd1be..f9d7f933c6 100644 --- a/packages/eql/tests/encryption/tests/v4_owned.rs +++ b/packages/eql/tests/encryption/tests/v4_owned.rs @@ -653,9 +653,15 @@ async fn a_value_is_refused_under_another_column_before_any_key_is_requested() { #[test] fn the_traits_the_compile_fail_examples_refuse_exist_for_the_right_shapes() { use eql_bindings::Identifier; - use stack_encrypt::target::{DecryptSource, EncryptTarget, RequiredContext}; + use stack_encrypt::target::{AcceptsContext, DecryptSource, EncryptTarget}; fn decrypts>() {} - fn encrypts>>>() {} + // The context a caller passes is the column identifier. + fn encrypts() + where + T: EncryptTarget, + T::ContextInput: AcceptsContext>, + { + } decrypts::(); encrypts::(); encrypts::(); diff --git a/packages/stack-encrypt-derive/docs/attributes.md b/packages/stack-encrypt-derive/docs/attributes.md index d238460265..7e3f0ba70f 100644 --- a/packages/stack-encrypt-derive/docs/attributes.md +++ b/packages/stack-encrypt-derive/docs/attributes.md @@ -108,7 +108,7 @@ pass one, or must not pass one. This table shows which: |---|---|---|---| | `struct = User, scope = "users"` | `DeclaredScopes`, which takes no context from the caller | The same as for encryption | `user.encrypt_into(&keyset)` | | `plaintext = T` | `RequiredContext`, or `RequiredContext` with `context_type = AeadContext` | The same as for encryption | `value.encrypt_into_with_context(&keyset, nonempty!("users/email"))` | -| With a `context_field` of type `C` | `RequiredContext>` | Nothing, or the `NonEmpty` the caller expects | `T::decrypt_from_with_context(record, &cipher, nonempty!(..))`, which checks the stored context before it decrypts | +| With a `context_field` of type `C` | The `NonEmpty` that the record stores, which the caller must pass | Nothing, or the `NonEmpty` the caller expects | `T::decrypt_from_with_context(record, &cipher, nonempty!(..))`, which checks the stored context before it decrypts | #### Check where a record with a `context_field` came from @@ -163,6 +163,10 @@ context from the record. These targets accept one: `RequiredContext`. - `StackCipherText`, whose input is `RequiredContext`. - A `plaintext` record. +- A record with a `context_field`, when the stored type implements + `ContextFromField`. An EQL type is one. It stores the field's own + context, `("users", "")`, and not the record's scopes or + bindings. The reader supplies those again. - Another `struct` record. The outer field's context then extends the inner record's own contexts. diff --git a/packages/stack-encrypt-derive/src/owned_decrypt.rs b/packages/stack-encrypt-derive/src/owned_decrypt.rs index ca08c18a00..11a7882c29 100644 --- a/packages/stack-encrypt-derive/src/owned_decrypt.rs +++ b/packages/stack-encrypt-derive/src/owned_decrypt.rs @@ -227,8 +227,10 @@ fn struct_body( } /// A `plaintext = T` record. Its one recoverable field opens under the -/// required context. A `context_field` record first builds that context from -/// the context it stores, and checks it against the caller's expectation. +/// required context. A `context_field` record first checks the context it +/// stores against the caller's expectation, and builds that context from it. +/// A record that is a field of a `struct = ..` record also opens under the +/// scopes and bindings of that record (`ExpectedContext::decryption_context`). fn value_body( record: &Record, plaintext: &Type, @@ -242,7 +244,7 @@ fn value_body( let stored = record.context_field().map(|field| { let member = &field.member; quote! { - let __context = match __context.validate(self.#member) { + let __context = match __context.decryption_context(self.#member) { ::core::result::Result::Ok(context) => <#threaded as #krate::target::AcceptsContext>::supplied(::core::convert::Into::into(context)), ::core::result::Result::Err(error) => return #krate::target::Decryption::failed(error), }; diff --git a/packages/stack-encrypt-derive/src/owned_encrypt.rs b/packages/stack-encrypt-derive/src/owned_encrypt.rs index d62cbdbe09..b91efdc264 100644 --- a/packages/stack-encrypt-derive/src/owned_encrypt.rs +++ b/packages/stack-encrypt-derive/src/owned_encrypt.rs @@ -102,9 +102,10 @@ fn markers(input: &DeriveInput, record: &Record) -> TokenStream { } /// The caller's input on the encrypt side. A record whose fields have their -/// own contexts takes an extension. A record that stores its context requires -/// the `NonEmpty` it stores. Any other record requires the caller context, -/// or the type `context_type` names. +/// own contexts takes an extension. A record that stores its context takes a +/// `StoredContext`: the caller passes the `NonEmpty` it stores. Any +/// other record requires the caller context, or the type `context_type` +/// names. pub(crate) fn encrypt_input(record: &Record) -> Type { let krate = &record.krate; if record.parts.caller_any() { @@ -113,7 +114,7 @@ pub(crate) fn encrypt_input(record: &Record) -> Type { } if let Some(field) = record.context_field() { let ty = &field.ty; - parse_quote!(#krate::target::RequiredContext<#krate::NonEmpty<#ty>>) + parse_quote!(#krate::target::StoredContext<#ty>) } else if record.by_field { parse_quote!(#krate::target::DeclaredScopes) } else { @@ -335,8 +336,8 @@ fn struct_derive(input: &DeriveInput, record: &Record) -> TokenStream { quote_spanned! {ty.span()=> #check let #local = <#ty as #krate::target::EncryptTarget<_>>::encryption::<__K>() + .under_field(#own) .project(|__source: &#source| &__source.#from) - .under(#own) .named(#name); } } @@ -369,9 +370,11 @@ fn struct_derive(input: &DeriveInput, record: &Record) -> TokenStream { } => { let own = own_expr(krate, context); let name = field_name(field); + // `under_field` wipes the field's plaintext when the + // context is refused before the field's target runs. quote_spanned! {ty.span()=> let #local = <#ty as #krate::target::EncryptTarget<_>>::owned_encryption::<__K>() - .under(#own) + .under_field(#own) .named(#name); } } @@ -511,8 +514,9 @@ fn own_expr(krate: &syn::Path, context: &OwnContext) -> TokenStream { /// `#[stash(plaintext = T)]`, or no record attribute. Every field's target /// runs over the whole value, under the one required context, and the results -/// are zipped. A record with a `context_field` requires the `NonEmpty` it -/// stores, and returns it beside the outputs. +/// are zipped. A record with a `context_field` stores its context +/// (`Encryption::storing`): the `NonEmpty` the caller passes, or the +/// field's own context when the record is a field of a `struct = ..` record. fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> TokenStream { let krate = &record.krate; let input_type = encrypt_input(record); @@ -570,17 +574,10 @@ fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> Toke let value = literal(record, None); quote!(#zipped.map(move |#zip_pattern| #value).accepting::()) } - Some(_) => { - let value = literal( - record, - Some( - quote!(#krate::target::RequiredContext::into_inner(__stored).into_inner()), - ), - ); + Some(stored) => { + let value = literal(record, Some(quote!(__stored))); quote! { - #zipped - .accepting::() - .map_with_context(move |#zip_pattern, __stored: Self::ContextInput| #value) + #zipped.storing(move |#zip_pattern, __stored: #stored| #value) } } }; diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index dd6e68978a..b10400a4e3 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -53,6 +53,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The builder state is `WithAuthStrategy`, behind the `http` feature. - Needs stack-auth 0.44.0 and stack-kms 0.2.0. + +- **A field type that stores its context can be a record field** (#1658). + A derived `struct = ..` record gives each field a context of its own: + the record's scope, then the field's name. A type that stores its + context in the row (`#[stash(context_field)]`), such as an EQL type that + stores a table and a column, stores that own context. The stored type + implements the new trait `target::ContextFromField`. + - `ContextFromField::from_field` builds the stored context from the + field's own context, or returns `None` when the type cannot store it. + - The scopes and the bindings that the record lists, and the names of a + record that holds this one, come after the own context, as they do + for a field of any other type. The search terms derive under the own + context and the scopes. The data key and the AAD derive under the + bindings too. The field does not store them, so the reader supplies + them again. + - On decrypt, the stored context must equal the field's own, as a + standalone decrypt with an expected context checks it. + - An own context that the type cannot store is refused before any key + is requested, on encrypt and on decrypt, with the new + `PlanError::ContextNotStorable` + (`stack_encrypt::plan_context_not_storable`), which names that + context (`members/email`). + - The encrypt input of a `context_field` record is the hidden type + `target::StoredContext`, in place of + `RequiredContext>`. A caller passes a `NonEmpty`. + Generic code names the input as + `ContextInput: AcceptsContext>`. + - **`json::JsonPlaintext`, a JSON document as one ciphertext** (#1636). `JsonPlaintext` holds a `serde_json::Value` and wipes it when it is dropped. Build one with `JsonPlaintext::from(value)` or @@ -214,6 +242,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 jiff has no leap seconds, so the error now says only what is wrong: `Timestamp::new` was given nanoseconds of one second or more. +- **A data plan field that names an EQL type takes a scope and a + binding** (#1658). `dynamic::TargetResolver` now receives them: + `encrypt` and `decrypt` take `parts: &DeclaredContext` after the label, + and `query` takes `scopes: &DeclaredContext`. A resolver runs the type + under the label, then those parts (`parts.clone().under(label)`), as + the lowering runs a field with outputs. + - Such a plan was refused with `TargetError::Extended`, at build time + for an extended plan and at `with_bindings` and a scoped call. That + variant and its code `stack_encrypt::target_extended` are removed. + - The EQL value stores the label's column alone. Whoever reads it + supplies the scopes and the bindings again. + - `Plan::contexts()` and `Planned::contexts()` show a target field + under the same parts as a field with outputs. + - A document field's JSON operators and reads run under the same + parts. `dynamic::query_term` derives a JSON operand under the label, + then the plan's scopes, so a query finds the documents sealed under + the same scopes. `dynamic::json_open` derives its selector or read + key under them too, and opens each entry under the plan's bindings + as well. + - `dynamic::json_open` and `check_json_open` take a plan with a + binding, where they refused one (`Reason::BindInQuery`): the entries + were sealed under it. A query still refuses a binding. + - **`target::legacy` is removed** (#1488). It held two traits, implemented for every type, that gave the structural API a second call syntax: `value.encrypt_into(&keyset)`, @@ -768,6 +819,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A derived record wipes an owned plaintext when a caller's part is + empty.** An empty scope or binding is refused where a field is given + its context, before the field's own target runs. The plaintext of that + field was then dropped without being wiped. The derive now emits the + hidden `Encryption::under_field`, which wipes it. `Encryption::under` + is unchanged: its plaintext need not be `Zeroize`. + - The docs of `dynamic::read` said the engine never calls it. `dynamic::query_term` does: it reads a query's input as the field's kind. - **A refused context no longer drops a copy of the plaintext unwiped** diff --git a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md index 4fafcc0a08..19c4eef5cf 100644 --- a/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md +++ b/packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md @@ -499,6 +499,9 @@ keeps every ciphertext openable and orphans every stored term. Moving a row ID from a scope to a binding, or a tenant the other way, is a search-index migration. -An EQL type refuses a binding, as it refuses an extension: its stored -context is its table and column, and nothing else. +An EQL type takes a scope and a binding, as any other field type does. +Its `i` stores its table and column, and nothing a caller supplies: the +scope and the binding come after the column in its context, and are not +stored. An earlier version of this record said that an EQL type refuses +both. That refusal was removed on 15 November 2026. diff --git a/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs b/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs index 19eff4853d..7ab1d5fc71 100644 --- a/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs +++ b/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs @@ -89,6 +89,7 @@ impl TargetResolver for Fixed { _: Option<&TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("check_record runs no cipher") @@ -98,6 +99,7 @@ impl TargetResolver for Fixed { _: &str, _: &'a StackCipher, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("check_record runs no cipher") @@ -108,6 +110,7 @@ impl TargetResolver for Fixed { _: &stack_encrypt::target::IndexSpec, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("check_record runs no cipher") diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 4fa0b408d6..3e5a43fdb6 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -175,6 +175,9 @@ mod tests { }, PlanError::EmptyIndexes => PlanError::EmptyIndexes, PlanError::EmptyPart => PlanError::EmptyPart, + PlanError::ContextNotStorable { .. } => PlanError::ContextNotStorable { + field: "users/email".into(), + }, PlanError::NotInPlan { .. } => PlanError::NotInPlan { field: field() }, PlanError::NotInValue { .. } => PlanError::NotInValue { field: field() }, PlanError::FieldType { .. } => PlanError::FieldType { @@ -248,10 +251,6 @@ mod tests { reason: "block ORE".into(), }, TargetError::NoQuery { .. } => TargetError::NoQuery { name: target() }, - TargetError::Extended { .. } => TargetError::Extended { - name: name(), - label: "users/email".into(), - }, TargetError::ContextField { .. } => TargetError::ContextField { name: name(), context_field: "tenant".into(), @@ -650,19 +649,19 @@ mod tests { json!({ "target": "TextEq", "reason": "block ORE" }), ), ( - Box::new(TargetError::Extended { + Box::new(TargetError::ContextField { name: name(), - label: "users/email".into(), + context_field: "tenant".into(), }), - json!({ "field": "email", "label": "users/email" }), + json!({ "field": "email", "context_field": "tenant" }), ), // Before the lowering names the field, there is none to give. ( - Box::new(TargetError::Extended { + Box::new(TargetError::ContextField { name: String::new(), - label: "users/email".into(), + context_field: "tenant".into(), }), - json!({ "label": "users/email" }), + json!({ "context_field": "tenant" }), ), ( Box::new(TargetError::Kind { diff --git a/packages/stack-encrypt/src/contexts.rs b/packages/stack-encrypt/src/contexts.rs index 301681b291..a1f0ebf3c3 100644 --- a/packages/stack-encrypt/src/contexts.rs +++ b/packages/stack-encrypt/src/contexts.rs @@ -754,9 +754,10 @@ pub trait SuppliedContext: sealed::Sealed { mod sealed { use crate::target::{ AeadContext, CallerContext, DeclaredContext, DeclaredScopes, NoCallerContext, - OptionalContext, RequiredContext, + OptionalContext, RequiredContext, StoredContext, }; pub trait Sealed {} + impl Sealed for StoredContext {} impl Sealed for NoCallerContext {} impl Sealed for DeclaredScopes {} impl Sealed for DeclaredContext {} @@ -786,6 +787,12 @@ impl SuppliedContext for RequiredContext { C::parts_shape() } } +/// A record that stores its context takes it as a `NonEmpty`. +impl SuppliedContext for crate::target::StoredContext { + fn supplies() -> CallerShape { + NonEmpty::::parts_shape() + } +} impl SuppliedContext for OptionalContext { fn supplies() -> CallerShape { let shape = C::parts_shape(); @@ -1154,13 +1161,13 @@ impl LeafShape { } /// One named leaf under a context known when the declaration is written, -/// and extended by nothing: a data plan's EQL field, sealed under its label -/// by the resolver. +/// then the context it is handed: a data plan's EQL field, which the +/// resolver runs under its label and the plan's parts. #[cfg_attr(not(feature = "dynamic"), allow(dead_code))] -pub(crate) fn known_leaf(name: &str, piece: ContextPiece<'static>) -> LeafShape { +pub(crate) fn leaf_under(name: &str, piece: ContextPiece<'static>) -> LeafShape { LeafShape { name: Some(Arc::from(name)), - shape: Shape::Known(piece), + shape: Shape::under(piece), } } diff --git a/packages/stack-encrypt/src/dynamic/json_predicate.rs b/packages/stack-encrypt/src/dynamic/json_predicate.rs index 29c90ef39e..d7f85aa9d0 100644 --- a/packages/stack-encrypt/src/dynamic/json_predicate.rs +++ b/packages/stack-encrypt/src/dynamic/json_predicate.rs @@ -37,12 +37,12 @@ use zeroize::Zeroizing; use super::json_query::{ derive_input, eql, json_reason, leaf, member_of, ordered_path_of, Bounds, Compare, Input, - Parsed, Predicate, + Parsed, Predicate, Under, }; use super::query::{Op, Operand}; use super::{Error, Reason}; use crate::json::{parse_text, string_end, string_text, JsonOptions, JsonPath, Segment, MAX_DEPTH}; -use crate::{KeysetCipher, Label, Pending}; +use crate::{KeysetCipher, Pending}; /// How deeply a predicate may nest parentheses, `!` and `exists`. The /// parser descends once per level, so the bound keeps a hostile predicate @@ -1234,7 +1234,7 @@ fn operand_value(operand: Operand) -> Result { /// tree. pub(super) fn derive<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, - label: &Label, + under: &Under<'_>, options: &JsonOptions, node: Node, ) -> Result, Error> { @@ -1243,7 +1243,7 @@ pub(super) fn derive<'a, K: 'static>( let operands = leaves .into_iter() .map(|(op, input)| { - derive_input(keyset, label, options, op, input).map(|p| p.try_map(operand_value)) + derive_input(keyset, under, options, op, input).map(|p| p.try_map(operand_value)) }) .collect::, _>>()?; Ok(Pending::all(keyset, operands) diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index e19f4d4f2d..4672501d24 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -209,8 +209,8 @@ use crate::json::{ JsonQuery, JsonSubtree, JsonSubtreeKey, }; use crate::sem::TermError; -use crate::target::{AeadContext, DeclaredContext, Index, Json, Owned}; -use crate::{KeysetCipher, Label, NonEmpty, Pending}; +use crate::target::{AeadContext, CallerContext, DeclaredContext, Index, Json, Owned}; +use crate::{ContextPiece, KeysetCipher, Label, NonEmpty, Pending}; /// The SQL type a JSON operand binds as. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -722,19 +722,65 @@ pub(super) fn check(op: Op, options: &JsonOptions, input: &ValueFrame) -> Result read_input(op, options, input).map(drop) } -/// The JSON index's terms of `value` under the column, as the stored -/// document's were derived. +/// Where a document field's queries and reads run: under the field's +/// label, then the scopes and the bindings of its plan, as the document +/// was sealed. +/// +/// For example, take the field `profile` of the table `users`, in a plan +/// whose caller added the tenant 7 as a scope and the row 9 as a binding. +/// A selector, a read key and every other term derive under +/// `users/profile`, then 7: the query context. An entry that a read +/// returns opens under `users/profile`, then 7, then 9: the stored +/// context. +#[derive(Clone)] +pub(super) struct Under<'p> { + label: &'p Label, + /// The plan's scopes, then its bindings. + parts: DeclaredContext, +} + +impl<'p> Under<'p> { + /// The field with the label `label`, in a plan whose scopes and + /// bindings are `parts`. + pub(super) fn new(label: &'p Label, parts: DeclaredContext) -> Self { + Self { label, parts } + } + + fn column(&self) -> NonEmpty