From fdf30b8642789cecec8640235a9b8eaa26bec525 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 14 Nov 2026 23:16:23 +1100 Subject: [PATCH 01/13] feat(stack-encrypt): a field type that stores its context can be a record field A derived struct record gives each field its scope and the field's name, as a CallerContext. A field type that stores its context in the row, such as an EQL type that stores a table and a column, could not take it: the derive converts with From, and the conversion can fail. A record that lists a caller scope or a binding gives the field more than a table and a column, and an EQL payload has nowhere to store it. - target::FromFieldContext: a type that stores its context rebuilds it from the field's CallerContext, or returns None. - Encryption::under converts the field's context through the hidden trait target::FromCaller. Every From type implements it, so callers compile unchanged. RequiredContext> implements it for T: FromFieldContext, and refuses a context T cannot store. - ExpectedContext converts from a CallerContext the same way. On decrypt the stored context must equal the field's. - PlanError::ContextNotStorable, refused before any key is requested. - FromCaller carries an on_unimplemented message, so a field whose type cannot take the record's context says so, not that a hidden trait is missing. Part of #1658. --- packages/stack-encrypt/CHANGELOG.md | 21 ++ packages/stack-encrypt/src/codes.rs | 1 + packages/stack-encrypt/src/dynamic/record.rs | 8 +- packages/stack-encrypt/src/plan/error.rs | 14 +- packages/stack-encrypt/src/target/context.rs | 61 +++++- packages/stack-encrypt/src/target/input.rs | 44 +++- packages/stack-encrypt/src/target/mod.rs | 6 +- .../stack-encrypt/src/target/operations.rs | 8 +- packages/stack-encrypt/tests/field_context.rs | 198 ++++++++++++++++++ .../ui/owned_record_field_context.stderr | 21 +- 10 files changed, 356 insertions(+), 26 deletions(-) create mode 100644 packages/stack-encrypt/tests/field_context.rs diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index dd6e68978a..b25f547bfc 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -53,6 +53,27 @@ 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 its scope and the + field's name. A type that stores its context in the row, such as an EQL + type that stores a table and a column, implements the new trait + `target::FromFieldContext` to take that context as the one it stores. + - `FromFieldContext::from_field_context` rebuilds the stored context + from the field's `CallerContext`, or returns `None` when the type + cannot store it. + - A context 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`). A record that lists a + caller scope or a binding gives its fields such a context. + - On decrypt, the stored context must equal the field's, as a + standalone decrypt with an expected context checks it. + - `Encryption::under` now converts the field's context through the + hidden trait `target::FromCaller`, which every + `From` type implements. A caller of `under` compiles + unchanged. + - **`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 diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 4fa0b408d6..30bb912597 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -175,6 +175,7 @@ mod tests { }, PlanError::EmptyIndexes => PlanError::EmptyIndexes, PlanError::EmptyPart => PlanError::EmptyPart, + PlanError::ContextNotStorable => PlanError::ContextNotStorable, PlanError::NotInPlan { .. } => PlanError::NotInPlan { field: field() }, PlanError::NotInValue { .. } => PlanError::NotInValue { field: field() }, PlanError::FieldType { .. } => PlanError::FieldType { diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 5b0dcc3304..a2e9eaa728 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -672,9 +672,11 @@ fn refusal(error: crate::Error) -> (Option, Reason) { } P::BindInQuery => (None, Reason::BindInQuery), P::EmptyPart => (None, Reason::EmptyBinding), - P::IdentityWithoutField | P::MixedCiphers | P::TwoContextSources { .. } | P::NoContext => { - (None, Reason::Refused) - } + P::IdentityWithoutField + | P::MixedCiphers + | P::TwoContextSources { .. } + | P::NoContext + | P::ContextNotStorable => (None, Reason::Refused), } } diff --git a/packages/stack-encrypt/src/plan/error.rs b/packages/stack-encrypt/src/plan/error.rs index d660dfc39b..5f95ea0c80 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -251,6 +251,17 @@ pub enum PlanError { help("Give the scope or binding a value. An empty part would put every row under one context.") )] EmptyPart, + /// A record field's type stores its context in the row, and the record + /// gives the field a context it cannot store. An EQL type stores a + /// table and a column, so it takes the record's scope and the field's + /// name, and nothing more: no caller scope and no binding. Refused + /// before any key is requested. + #[error("the field's type cannot store the context the record gives it")] + #[diagnostic( + code(stack_encrypt::plan_context_not_storable), + help("A field whose type stores its context, such as an EQL type, takes the record's scope and the field's name alone. Remove the record's caller scope and binding, or give the field a type that does not store its context.") + )] + ContextNotStorable, /// A field was declared both as a typed target (`encrypt_into`) and with /// a data verb. A field is one or the other: the target's type decides /// its layout and its queries. @@ -326,7 +337,8 @@ impl crate::ErrorPayload for PlanError { | Self::MixedCiphers | Self::NoContext | Self::BindInQuery - | Self::EmptyPart => serde_json::Map::new(), + | Self::EmptyPart + | Self::ContextNotStorable => serde_json::Map::new(), } } } diff --git a/packages/stack-encrypt/src/target/context.rs b/packages/stack-encrypt/src/target/context.rs index feec30f47b..57e4c35edd 100644 --- a/packages/stack-encrypt/src/target/context.rs +++ b/packages/stack-encrypt/src/target/context.rs @@ -921,10 +921,22 @@ impl DeclaredContext { // both still showed the type. #[doc(hidden)] #[derive(Clone, Debug)] -pub struct ExpectedContext(Option>); +pub struct ExpectedContext(Expected); + +/// What [`ExpectedContext`] checks the stored context against. +#[derive(Clone, Debug)] +enum Expected { + /// Any nonempty stored context. + Any, + /// A stored context equal to this one. + Exactly(NonEmpty), + /// Nothing: a record gave the field a context its type cannot store, so + /// no stored context can be the one expected. + NotStorable, +} impl Default for ExpectedContext { fn default() -> Self { - Self(None) + Self(Expected::Any) } } impl From<()> for ExpectedContext { @@ -934,9 +946,40 @@ impl From<()> for ExpectedContext { } impl From> for ExpectedContext { fn from(value: NonEmpty) -> Self { - Self(Some(value)) + Self(Expected::Exactly(value)) + } +} +/// A record field whose type stores its context expects the context the +/// record gives the field. A context the type cannot store is refused when +/// the field is opened, before any key is requested. +impl From for ExpectedContext { + fn from(context: CallerContext) -> Self { + Self(match T::from_field_context(&context) { + Some(expected) => Expected::Exactly(expected), + None => Expected::NotStorable, + }) } } + +/// A context type that a record field's type stores in the row, and can +/// rebuild from the context the record gives the field. +/// +/// A derived `struct = ..` record gives each field the record's scope and +/// the field's name, extended by the caller's scopes and bindings, as a +/// [`CallerContext`]. A field type that stores its context takes that +/// context as the type it stores, so it can be a field of a record. +/// `eql_bindings::Identifier` implements this: an EQL type stores a table +/// and a column, so it takes `("members", "email")` and refuses a context +/// with a caller scope or a binding. +/// +/// The rebuilt context must give the same context as the one the record +/// gave. Then the field writes the bytes it writes on its own under that +/// context. +pub trait FromFieldContext: Sized { + /// The context the field's type stores, rebuilt from the context the + /// record gives the field, or `None` when the type cannot store it. + fn from_field_context(context: &CallerContext) -> Option>; +} impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { /// Check the stored context against this expectation and prove it /// nonempty, yielding the context the record is opened under. @@ -949,11 +992,15 @@ impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { /// context is data the record was handed, not something the cipher has /// authenticated yet: both checks happen before any key is requested. pub fn validate(self, stored: T) -> Result, Error> { - if let Some(expected) = self.0 { - if expected.into_inner() != stored { - let stored = Descriptor::from_piece(&stored.into_context()); - return Err(Error::ContextMismatch { stored }); + match self.0 { + Expected::Any => {} + Expected::Exactly(expected) => { + if expected.into_inner() != stored { + let stored = Descriptor::from_piece(&stored.into_context()); + return Err(Error::ContextMismatch { stored }); + } } + Expected::NotStorable => return Err(crate::plan::PlanError::ContextNotStorable.into()), } nonempty(stored) } diff --git a/packages/stack-encrypt/src/target/input.rs b/packages/stack-encrypt/src/target/input.rs index 9b42236f69..28560fd9e5 100644 --- a/packages/stack-encrypt/src/target/input.rs +++ b/packages/stack-encrypt/src/target/input.rs @@ -13,8 +13,8 @@ //! example, `RequiredContext` stays required, although `u64` has a //! default of zero. -use super::context::{CallerContext, DeclaredContext, ExpectedContext}; -use crate::{ContextPiece, IntoContext, NonEmpty}; +use super::context::{CallerContext, DeclaredContext, ExpectedContext, FromFieldContext}; +use crate::{ContextPiece, Error, IntoContext, NonEmpty}; mod sealed { pub trait Sealed {} @@ -144,6 +144,46 @@ impl> From for RequiredContext { Self::supplied(C::from(context)) } } + +/// The context a record field's declaration takes, built from the context +/// the record gives the field. [`Encryption::under`](super::Encryption::under) +/// converts through it. +/// +/// A context that converts from a [`CallerContext`] cannot fail. A field +/// type that stores its context ([`FromFieldContext`]) can refuse the one +/// the record gives it, before any key is requested. +/// +/// **This trait is for generated code.** A field type implements +/// [`FromFieldContext`], not this. +#[doc(hidden)] +#[diagnostic::on_unimplemented( + message = "a field whose type takes `{Self}` cannot be a field of a `struct = ..` record", + label = "this field's type cannot take the context the record gives it", + note = "the record gives each field its scope and the field's name as a `CallerContext`; a field's type takes it if its context input converts from `CallerContext`, or is `RequiredContext>` where `T` implements `FromFieldContext`" +)] +pub trait FromCaller: Sized { + /// Convert the field's context, or refuse it. + /// + /// # Errors + /// + /// [`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable) + /// when the field's type cannot store the context. + fn from_caller(context: CallerContext) -> Result; +} +impl> FromCaller for C { + fn from_caller(context: CallerContext) -> Result { + Ok(C::from(context)) + } +} +// A field whose type stores its context takes the record's context for the +// field as that type, or refuses it. +impl FromCaller for RequiredContext> { + fn from_caller(context: CallerContext) -> Result { + T::from_field_context(&context) + .map(Self::supplied) + .ok_or_else(|| crate::plan::PlanError::ContextNotStorable.into()) + } +} // A record that derives terms gives its ciphertext fields the AEAD part of the // context it requires. impl From> for RequiredContext { diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index 6ebfd35709..0e526f9f14 100644 --- a/packages/stack-encrypt/src/target/mod.rs +++ b/packages/stack-encrypt/src/target/mod.rs @@ -192,8 +192,8 @@ pub(crate) use self::core::{bind_pending, seal_pending}; #[doc(hidden)] pub use context::ExpectedContext; pub use context::{ - AeadContext, Bind, BindPart, CallerContext, CheckedInput, DeclaredContext, Extends, NoBind, - NoScope, Parts, Scope, ScopePart, Scopes, StoredParts, + AeadContext, Bind, BindPart, CallerContext, CheckedInput, DeclaredContext, Extends, + FromFieldContext, NoBind, NoScope, Parts, Scope, ScopePart, Scopes, StoredParts, }; pub use conversion::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget}; pub use index::{ @@ -201,7 +201,7 @@ pub use index::{ Select, TermSet, Whole, }; pub use input::{ - AcceptsContext, AllowsNoContext, ContextInput, DeclaredScopes, NoCallerContext, + AcceptsContext, AllowsNoContext, ContextInput, DeclaredScopes, FromCaller, NoCallerContext, OptionalContext, RequiredContext, ScalarContext, }; #[cfg(feature = "dynamic")] diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 66f6815ea3..a9ea28e95b 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -18,7 +18,7 @@ use super::context::{AeadContext, CallerContext, DeclaredContext, Extends, Store use super::conversion::{DecryptSource, EncryptTarget}; use super::core::{encrypt_native, open_native, Term}; use super::index::{Index, IndexSpec, Json}; -use super::input::{AcceptsContext, NoCallerContext, RequiredContext}; +use super::input::{AcceptsContext, FromCaller, NoCallerContext, RequiredContext}; use super::source::{Borrowed, ConsumeSource, Owned, ShareSource, SourceMode}; use super::{CipherRef, Pending}; use crate::contexts::{self, Contexts, Placeholder, Shape, Shapes, SuppliedContext}; @@ -363,15 +363,15 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> own: NonEmpty + MaybeSend + 's>, ) -> Encryption<'s, S, T, K, DeclaredContext, M> where - Ctx: From, + Ctx: FromCaller, { let own = contexts::piece_of(own); self.shapes = contexts::substitute(self.shapes, &Shape::under(own.get().clone())); let Self { build, shapes } = self; Encryption { build: Box::new(move |source, cipher, cx: DeclaredContext| { - match cx.checked_under(own) { - Ok(context) => build(source, cipher, context.into()), + match cx.checked_under(own).and_then(Ctx::from_caller) { + Ok(context) => build(source, cipher, context), Err(error) => Pending::failed(cipher, error), } }), diff --git a/packages/stack-encrypt/tests/field_context.rs b/packages/stack-encrypt/tests/field_context.rs new file mode 100644 index 0000000000..d73a61d579 --- /dev/null +++ b/packages/stack-encrypt/tests/field_context.rs @@ -0,0 +1,198 @@ +//! A field type that stores its context, as a field of a derived `struct = +//! ..` record (`FromFieldContext`). +//! +//! The record gives each field its scope and the field's name. A field type +//! that stores a table and a column takes that pair as the context it +//! stores, as an EQL type in `eql-bindings` does. Here `Column` stands in +//! for EQL's `Identifier`: +//! +//! - the field stores the pair, and writes the term it writes on its own +//! under that column; +//! - on decrypt, the stored column must be the field's; +//! - a record that lists a caller scope or a binding gives the field a +//! context it cannot store, and every call is refused before any key is +//! requested. +use std::sync::atomic::Ordering; + +use stack_encrypt::sem::EqualityTerm; +use stack_encrypt::target::{ + Bind, CallerContext, DecryptSource, EncryptTarget, FromFieldContext, Scope, +}; +use stack_encrypt::{ + Ciphertext, ContextPiece, DecryptFrom, EncryptInto, Error, IntoContext, MaybeEmpty, NonEmpty, + PlanError, +}; +use zeroize::Zeroize; +mod common; + +/// A table and a column, as EQL's `Identifier` stores them. +#[derive(Clone, Debug, PartialEq)] +struct Column { + table: String, + column: String, +} + +impl Column { + fn of(table: &str, column: &str) -> NonEmpty { + NonEmpty::new(Self { + table: table.into(), + column: column.into(), + }) + .unwrap() + } +} + +impl MaybeEmpty for Column { + fn is_empty(&self) -> bool { + self.table.is_empty() || self.column.is_empty() + } +} + +/// The same two parts a record gives a field: the scope, then the name. +impl<'a> IntoContext<'a> for Column { + fn into_context(self) -> ContextPiece<'a> { + ContextPiece::List(vec![ + ContextPiece::Text(self.table.into()), + ContextPiece::Text(self.column.into()), + ]) + } +} + +impl FromFieldContext for Column { + fn from_field_context(context: &CallerContext) -> Option> { + if context.has_bindings() { + return None; + } + let ContextPiece::List(parts) = context.query() else { + return None; + }; + let [ContextPiece::Text(table), ContextPiece::Text(column)] = parts.as_slice() else { + return None; + }; + NonEmpty::new(Self { + table: table.to_string(), + column: column.to_string(), + }) + .ok() + } +} + +/// A value that stores its column, as an EQL `TextEq` does. +#[derive(Clone, EncryptTarget, DecryptSource)] +#[stash(plaintext = String)] +struct Stored { + #[stash(context_field)] + column: Column, + c: Ciphertext, + hm: EqualityTerm, +} + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct User { + email: String, +} + +fn ada() -> User { + User { + email: "ada@example.com".into(), + } +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users")] +struct EncryptedUser { + email: Stored, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(tenant: u64))] +struct TenantUser { + email: Stored, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", bind(row: u128))] +struct BoundUser { + email: Stored, +} + +fn assert_not_storable(result: Result) { + match result { + Err(Error::Plan(PlanError::ContextNotStorable)) => {} + Err(other) => panic!("expected ContextNotStorable, got {other:?}"), + Ok(_) => panic!("expected ContextNotStorable, got a value"), + } +} + +#[tokio::test] +async fn a_field_stores_the_record_scope_and_its_name() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let stored: EncryptedUser = ada().encrypt_into(&keyset).await.unwrap(); + assert_eq!(stored.email.column, *Column::of("users", "email").get()); + + // The term the field writes on its own under the column. + let alone: Stored = ada() + .email + .encrypt_into_with_context(&keyset, Column::of("users", "email")) + .await + .unwrap(); + assert_eq!(stored.email.hm, alone.hm); + + let opened = User::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened, ada()); + + // The value written on its own opens as the record's field. + let record = EncryptedUser { email: alone }; + assert_eq!(User::decrypt_from(record, &keyset).await.unwrap(), ada()); +} + +#[tokio::test] +async fn a_field_that_stores_another_column_is_refused() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let elsewhere: Stored = ada() + .email + .encrypt_into_with_context(&keyset, Column::of("users", "name")) + .await + .unwrap(); + let record = EncryptedUser { email: elsewhere }; + let before = retrieves.load(Ordering::SeqCst); + assert!(matches!( + User::decrypt_from(record, &keyset).await, + Err(Error::ContextMismatch { .. }) + )); + assert_eq!(retrieves.load(Ordering::SeqCst), before, "no key requested"); +} + +#[tokio::test] +async fn a_caller_scope_or_binding_is_refused_before_any_key() { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + + let scoped: Result = ada() + .encrypt_into_with_context(&keyset, Scope::new(42u64)) + .await; + assert_not_storable(scoped); + let bound: Result = ada() + .encrypt_into_with_context(&keyset, Bind::new(9u128)) + .await; + assert_not_storable(bound); + assert_eq!(generates.load(Ordering::SeqCst), 0, "no key requested"); + + // A value stored under the field's own column does not open in such a + // record either: the record's context is not the one it stores. + let alone: Stored = ada() + .email + .encrypt_into_with_context(&keyset, Column::of("users", "email")) + .await + .unwrap(); + let before = retrieves.load(Ordering::SeqCst); + let scoped = TenantUser { + email: alone.clone(), + }; + assert_not_storable(User::decrypt_from_with_context(scoped, &keyset, Scope::new(42u64)).await); + let bound = BoundUser { email: alone }; + assert_not_storable(User::decrypt_from_with_context(bound, &keyset, Bind::new(9u128)).await); + assert_eq!(retrieves.load(Ordering::SeqCst), before, "no key requested"); +} diff --git a/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr b/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr index 82fca205a9..9c21f46407 100644 --- a/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr +++ b/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr @@ -1,17 +1,25 @@ -error[E0277]: the trait bound `NoCallerContext: From` is not satisfied +error[E0277]: a field whose type takes `NoCallerContext` cannot be a field of a `struct = ..` record --> tests/ui/owned_record_field_context.rs:54:12 | 54 | fixed: Fixed, - | ^^^^^ the trait `From` is not implemented for `NoCallerContext` + | ^^^^^ this field's type cannot take the context the record gives it | + = help: the trait `From` is not implemented for `NoCallerContext` + = note: the record gives each field its scope and the field's name as a `CallerContext`; a field's type takes it if its context input converts from `CallerContext`, or is `RequiredContext>` where `T` implements `FromFieldContext` +help: the trait `FromCaller` is implemented for `RequiredContext>` + --> src/target/input.rs + | + | impl FromCaller for RequiredContext> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `NoCallerContext` to implement `FromCaller` note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under` --> src/target/operations.rs | | pub fn under( | ----- required by a bound in this associated function ... - | Ctx: From, - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` + | Ctx: FromCaller, + | ^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` error[E0277]: the trait bound `u64: From` is not satisfied --> tests/ui/owned_record_field_context.rs:55:12 @@ -30,11 +38,12 @@ error[E0277]: the trait bound `u64: From` is not satisfied `u64` implements `From` and $N others = note: required for `RequiredContext` to implement `From` + = note: required for `RequiredContext` to implement `FromCaller` note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under` --> src/target/operations.rs | | pub fn under( | ----- required by a bound in this associated function ... - | Ctx: From, - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` + | Ctx: FromCaller, + | ^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` From c17b725518408431e3460187b83e908cfeb47982 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 14 Nov 2026 23:16:24 +1100 Subject: [PATCH 02/13] feat(eql-bindings): EQL types as record fields An EQL v4 type can now be a field of a derived struct record. The field's column is the record's scope and the field's name, and the field writes the bytes the type writes on its own under that column. - Identifier implements FromFieldContext. It takes a context of two text parts with no binding, and only when it gives back the same context, so the stored bytes cannot differ. - JsonTreeDocument implements EncryptTarget and DecryptSource under the default options, and DecryptInto, the form a record field opens through. - tests/record_fields.rs: a record with EQL fields round-trips; each field writes the terms the type writes on its own and each opens the other's value; a marker query gives the stored term; the derive and a data plan, the path Go takes, write the same terms and open each other's values; a caller scope or binding is refused before any key is requested; so is a field that stores another column; and the JSON document works on its own and as a field. - The API plan, the eql-bindings README and CHANGELOG, and a @cipherstash/eql changeset. Closes #1658. --- .changeset/eql-types-as-record-fields.md | 12 + .../2026-10-24-stack-encrypt-api-plan.md | 47 +- packages/eql/Cargo.lock | 1 + packages/eql/crates/eql-bindings/CHANGELOG.md | 23 + packages/eql/crates/eql-bindings/README.md | 44 ++ .../eql/crates/eql-bindings/src/encryption.rs | 31 +- .../crates/eql-bindings/src/v4/json_tree.rs | 71 ++- packages/eql/tests/encryption/Cargo.toml | 1 + .../tests/encryption/tests/record_fields.rs | 504 ++++++++++++++++++ 9 files changed, 704 insertions(+), 30 deletions(-) create mode 100644 .changeset/eql-types-as-record-fields.md create mode 100644 packages/eql/tests/encryption/tests/record_fields.rs diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md new file mode 100644 index 0000000000..108b733619 --- /dev/null +++ b/.changeset/eql-types-as-record-fields.md @@ -0,0 +1,12 @@ +--- +'@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`. +- 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 that lists a caller scope or a binding cannot have an EQL field, because an EQL value stores only a table and a column. Every call is refused with `PlanError::ContextNotStorable`, before any key is requested. +- `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/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 49341d216c..69f83fd021 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,27 +1481,26 @@ 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 `CallerContext`. + A field type that stores its context implements + `target::FromFieldContext`, and takes that context as the one it + stores. `Identifier` takes a 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. It refuses a caller scope or a binding, + which an EQL payload cannot store, with + `PlanError::ContextNotStorable`, before any key is requested. - **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.** All of it, in #1658. A Rust record with EQL fields + encrypts, decrypts and queries through the new API, and writes the + terms a data plan writes for the same declaration, which is the path + Go takes (`packages/eql/tests/encryption/tests/record_fields.rs`). + `JsonTreeDocument` implements `EncryptTarget` and + `DecryptSource`. Order queries from a marker are not + answered by the EQL types: only the equality and match types implement + `Answers`. +- **Tracked in.** Issue #1658. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `FromFieldContext` 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; 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..837a7ef3f7 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -9,6 +9,29 @@ 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 bytes the + type writes on its own under `Identifier::for_column("members", + "email")`, and what a data plan that names the type writes. + - `Identifier` implements `stack_encrypt::target::FromFieldContext`. + - A record that lists a caller scope or a binding cannot have an EQL + field: an EQL payload stores a table and a column, and nothing more. + Every call is refused with `PlanError::ContextNotStorable`, before + any key is requested. + - 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. + +- **`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 diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index af167efb2a..7762d9fc0f 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -398,6 +398,50 @@ 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,ignore +use eql_bindings::v4::{integer::IntegerOrd, json_tree::JsonTreeDocument, text::TextEq}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget}; + +#[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"} +} + +let stored: EncryptedMember = member.encrypt_into(&keyset).await?; +let query = EncryptedMember::EMAIL.eq("alice@example.com").encrypt(&keyset).await?; +let opened = Member::decrypt_from(stored, &keyset).await?; +``` + +Each field writes what its type writes on its own under +`Identifier::for_column("members", )`, and what 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. + +An EQL value stores a table and a column, and nothing more. So a record that +lists a caller scope (`scope(tenant: u64)`) or a binding (`bind(row: u128)`) +cannot have an EQL field. Every call to it is refused with +`PlanError::ContextNotStorable`, before any key is requested. + ### EQL types as plan field targets A binding has no Rust type to name: its plan arrives as data, and a field of diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 98452b07bd..210ef70a11 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, DecryptSource, EncryptTarget, FromFieldContext, 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 its scope and the field's name, `("members", "email")`, +/// and the EQL type stores that pair as its column: table `members`, column +/// `email`. It is the context the record gave, so the field writes what the +/// type writes on its own under `Identifier::for_column("members", "email")`. +/// +/// An EQL payload stores a table and a column, and nothing more. So a +/// record that lists a caller scope or a binding cannot have an EQL field: +/// the field refuses the context, before any key is requested. +impl FromFieldContext for Identifier { + fn from_field_context(context: &CallerContext) -> Option> { + if context.has_bindings() { + return None; + } + let query = context.query(); + let ContextPiece::List(parts) = &query else { + return None; + }; + let [ContextPiece::Text(table), ContextPiece::Text(column)] = parts.as_slice() else { + return None; + }; + let identifier = Self::for_column(table.as_ref(), column.as_ref()).ok()?; + // Only the context the record gave: a pair that reads as a column + // but encodes differently would seal under another context. + (identifier.get().to_context() == query).then_some(identifier) + } +} + /// 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/v4/json_tree.rs b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs index e7f4ab1a44..19d1ca5cd3 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, + RequiredContext, }; -use stack_encrypt::target::{AeadContext, ExpectedContext, IndexSpec, Json, Layout}; use stack_encrypt::{ DecryptField, DecryptInto, Decryptable, Decryption, EncryptFrom, Encryption, Error, NonEmpty, }; @@ -524,6 +527,14 @@ impl EncryptFrom for JsonTreeDocument { impl DecryptInto for JsonTreeDocument { type Context = ExpectedContext; fn decryption(self, context: Self::Context) -> Decryption { + self.open(context) + } +} + +impl JsonTreeDocument { + /// Open the document under the stored column, once it has passed the + /// caller's check. The check runs before any key is requested. + fn open(self, context: ExpectedContext) -> Decryption { let column = match context.validate(self.i.clone()) { Ok(column) => column, Err(error) => return Decryption::failed(error), @@ -535,6 +546,58 @@ impl DecryptInto for JsonTreeDocument { } } +/// A [`JsonPlaintext`] seals into a document as a `serde_json::Value` does, +/// under the default options ([`JsonTree::default`]), with the column as +/// its context: +/// +/// ```ignore +/// let document: JsonTreeDocument = profile +/// .encrypt_into_with_context(&keyset, Identifier::for_column("customers", "profile")?) +/// .await?; +/// ``` +/// +/// 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. +impl EncryptTarget for JsonTreeDocument { + type ContextInput = RequiredContext>; + fn encryption<'s, K: 'static>() -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> + where + JsonPlaintext: 's, + { + Layout::::encryption::(JsonTree::default().index()) + .project(JsonPlaintext::value) + .accepting::() + .map_with_context(|document, column: Self::ContextInput| (column, document)) + .try_map(|(column, document)| { + JsonTreeDocument::envelope(column.into_inner().into_inner(), &document) + }) + } + fn indexes() -> Vec { + JsonTree::default().specs() + } +} + +/// Decrypts to the plaintext document, under the stored column. Pass the +/// column you expect, `column.into()`, and the stored column must equal +/// it. Pass `().into()`, or decrypt with `decrypt_from`, and the document +/// opens under the stored column without that check. Either way the check +/// runs before any key is requested. +impl DecryptSource for JsonTreeDocument { + type ContextInput = ExpectedContext; + fn decryption(self, context: Self::ContextInput) -> Decryption { + self.open(context).map(JsonPlaintext::from) + } +} + +/// The structural form of [`DecryptSource`], which a record +/// field opens through, as it is for every other EQL type. +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 +607,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/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index d477df2edc..d40e902f5f 100644 --- a/packages/eql/tests/encryption/Cargo.toml +++ b/packages/eql/tests/encryption/Cargo.toml @@ -38,6 +38,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/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs new file mode 100644 index 0000000000..3dd0b28c53 --- /dev/null +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -0,0 +1,504 @@ +//! 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, and each opens the +//! other's value; +//! - a record that lists a caller scope or a binding cannot store an EQL +//! field, and is refused before any key is requested; +//! - a field that stores another column is refused before any key is +//! requested; +//! - 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 std::collections::BTreeMap; + +use eql_bindings::encryption::EqlTargets; +use eql_bindings::v4::integer::IntegerOrd; +use eql_bindings::v4::json_tree::{JsonTree, JsonTreeDocument}; +use eql_bindings::v4::text::{Text, TextEq}; +use eql_bindings::Identifier; +use serde::Serialize; +use serde_json::{json, Value}; +use stack_encrypt::dynamic::{self, record, ValueFrame}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::target::{Bind, Layout, Scope}; +use stack_encrypt::{ + AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, DecryptSource, Encrypt, + EncryptInto, EncryptTarget, Error, NonEmpty, PlanError, 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, Debug, PartialEq, Zeroize)] +struct Contact { + email: String, + name: String, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Contact, scope = "contacts")] +struct EncryptedContact { + email: TextEq, + name: Text, +} + +/// 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"}, + }); + record::plan_with( + dynamic::frame::serde::to_vec(&wire) + .unwrap() + .as_protected_ref(), + &EqlTargets, + ) + .unwrap() +} + +fn frame(value: T) -> ValueFrame { + ValueFrame::of(value).unwrap() +} + +/// 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 contact = Contact { + email: "ada@example.com".into(), + name: "Ada".into(), + }; + let derived: EncryptedContact = contact.clone().encrypt_into(&keyset).await.unwrap(); + let source = BTreeMap::from([("email", "ada@example.com"), ("name", "Ada")]); + let mut row = record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) + .unwrap() + .await + .unwrap(); + + let planned_email: TextEq = read_eql(&mut row, "email"); + let planned_name: Text = read_eql(&mut row, "name"); + assert_eq!(terms_of(&derived.email), terms_of(&planned_email)); + assert_eq!(terms_of(&derived.name), terms_of(&planned_name)); + + // The data plan's values open as the record's fields. + let record = EncryptedContact { + email: planned_email, + name: planned_name, + }; + assert_eq!( + Contact::decrypt_from(record, &keyset).await.unwrap(), + contact + ); + + // 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); + let opened = record::decrypt_with(&cipher, row, &plan, None, &EqlTargets) + .unwrap() + .await + .unwrap(); + let opened: BTreeMap = + dynamic::frame::serde::from_slice(opened.risky_ref()).unwrap(); + assert_eq!(opened["email"], contact.email); + assert_eq!(opened["name"], contact.name); +} + +#[derive(Clone, Zeroize)] +struct Tenanted { + email: String, +} + +/// A record whose caller supplies a tenant scope. An EQL payload has +/// nowhere to store the tenant. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Tenanted, scope = "members", scope(tenant: u64))] +struct EncryptedTenanted { + email: TextEq, +} + +/// A record whose caller supplies a row binding. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Tenanted, scope = "members", bind(row: u128))] +struct EncryptedBound { + email: TextEq, +} + +fn assert_not_storable(result: Result) { + match result { + Err(Error::Plan(PlanError::ContextNotStorable)) => {} + Err(other) => panic!("expected ContextNotStorable, got {other:?}"), + Ok(_) => panic!("expected ContextNotStorable, got a value"), + } +} + +#[tokio::test] +async fn a_record_with_a_caller_scope_or_binding_cannot_store_an_eql_field() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let tenanted = || Tenanted { + email: "ada@example.com".into(), + }; + + let scoped: Result = tenanted() + .encrypt_into_with_context(&keyset, Scope::new(42u64)) + .await; + assert_not_storable(scoped); + let bound: Result = tenanted() + .encrypt_into_with_context(&keyset, Bind::new(9u128)) + .await; + assert_not_storable(bound); + assert!( + calls.lock().unwrap().generate.is_empty(), + "refused before any key is requested" + ); + + // A value written on its own under the column does not open in such a + // record either. + 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, Scope::new(42u64)).await; + assert_not_storable(opened); + assert!( + calls.lock().unwrap().retrieve.is_empty(), + "refused before any key is requested" + ); +} + +#[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" + ); +} + +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 +} + +#[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!(stored.i, old.i); + assert_eq!( + search_terms(&stored), + search_terms(&old), + "the same 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!(search_terms(&stored.profile), search_terms(&old)); + + let opened = Customer::decrypt_from(stored, &keyset).await.unwrap(); + assert_eq!(opened.id, 3); + assert_eq!(opened.profile.value(), &profile()); +} From c53d39d7f0d74f1ea5f51efa80b7c2f5900b67f5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 09:20:02 +1100 Subject: [PATCH 03/13] fix(stack-encrypt,eql-bindings): address the review of EQL types as fields The refusal of a context a field cannot store now names the field, as issue #1658 asks. A record's context carries the field's own context, which comes from the declaration and never from the caller, so `PlanError::ContextNotStorable { field }` reads `members/email` and its payload holds no caller data. The tests now compare the derive with a data plan for a field of each kind (equality, storage only, order and a JSON document). They compare a JSON document's whole envelope except its key header, and they show the refusal on decrypt for a binding and for an EQL field of a nested record. `JsonTree::sealing` holds the one encryption chain both JSON paths use. The docs say "terms" where they said "bytes", and no longer point callers at the hidden `ExpectedContext`. Refs #1658 --- .changeset/eql-types-as-record-fields.md | 2 +- .../2026-10-24-stack-encrypt-api-plan.md | 24 ++- packages/eql/crates/eql-bindings/CHANGELOG.md | 8 +- packages/eql/crates/eql-bindings/README.md | 8 +- .../eql/crates/eql-bindings/src/encryption.rs | 2 + .../crates/eql-bindings/src/v4/json_tree.rs | 52 ++++-- .../tests/encryption/tests/record_fields.rs | 176 +++++++++++++++--- packages/stack-encrypt/CHANGELOG.md | 3 +- packages/stack-encrypt/src/codes.rs | 4 +- packages/stack-encrypt/src/dynamic/record.rs | 2 +- packages/stack-encrypt/src/plan/error.rs | 15 +- packages/stack-encrypt/src/target/context.rs | 49 +++-- packages/stack-encrypt/src/target/input.rs | 8 +- packages/stack-encrypt/tests/field_context.rs | 5 +- 14 files changed, 271 insertions(+), 87 deletions(-) diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md index 108b733619..01fe9d7a26 100644 --- a/.changeset/eql-types-as-record-fields.md +++ b/.changeset/eql-types-as-record-fields.md @@ -6,7 +6,7 @@ - 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`. - 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 that lists a caller scope or a binding cannot have an EQL field, because an EQL value stores only a table and a column. Every call is refused with `PlanError::ContextNotStorable`, before any key is requested. +- A record that lists a caller scope or a binding cannot have an EQL field, because an EQL value stores only a table and a column. Every call is refused with `PlanError::ContextNotStorable`, which names the field, before any key is requested. - `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/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 69f83fd021..08b6e6ce6f 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1492,19 +1492,23 @@ Base64. `PlanError::ContextNotStorable`, before any key is requested. - **Why.** This gives the [EQL field example](#store-a-field-as-an-eql-type) and the [JSON example](#encrypt-a-json-document). -- **Done already.** All of it, in #1658. A Rust record with EQL fields - encrypts, decrypts and queries through the new API, and writes the - terms a data plan writes for the same declaration, which is the path - Go takes (`packages/eql/tests/encryption/tests/record_fields.rs`). - `JsonTreeDocument` implements `EncryptTarget` and - `DecryptSource`. Order queries from a marker are not - answered by the EQL types: only the equality and match types implement - `Answers`. +- **Done already.** In #1658: + - A Rust record with EQL fields encrypts and decrypts through the new + API. + - For a field of each kind (equality, storage only, order, and a JSON + document), it 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. The order types do not implement `Answers` yet, so a marker + cannot query them. - **Tracked in.** Issue #1658. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `FromFieldContext` 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. #### A ready-made EQL resolver diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 837a7ef3f7..53d9b90ea6 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -13,14 +13,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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 bytes the + `{"t": "members", "c": "email"}` in `i`. The field writes the terms the type writes on its own under `Identifier::for_column("members", - "email")`, and what a data plan that names the type writes. + "email")`, and the terms a data plan that names the type writes. - `Identifier` implements `stack_encrypt::target::FromFieldContext`. - A record that lists a caller scope or a binding cannot have an EQL field: an EQL payload stores a table and a column, and nothing more. - Every call is refused with `PlanError::ContextNotStorable`, before - any key is requested. + Every call is refused with `PlanError::ContextNotStorable`, which + names the field (`members/email`), before any key is requested. - 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. diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 7762d9fc0f..7831da8f7e 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -432,15 +432,17 @@ let query = EncryptedMember::EMAIL.eq("alice@example.com").encrypt(&keyset).awai let opened = Member::decrypt_from(stored, &keyset).await?; ``` -Each field writes what its type writes on its own under -`Identifier::for_column("members", )`, and what a data plan that +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. An EQL value stores a table and a column, and nothing more. So a record that lists a caller scope (`scope(tenant: u64)`) or a binding (`bind(row: u128)`) cannot have an EQL field. Every call to it is refused with -`PlanError::ContextNotStorable`, before any key is requested. +`PlanError::ContextNotStorable`, which names the field, before any key is +requested. The same goes for an EQL field of a record nested in another: its +context has more parts than a table and a column. ### EQL types as plan field targets diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 210ef70a11..395fb2be17 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -215,6 +215,8 @@ impl FromFieldContext for Identifier { if context.has_bindings() { return None; } + // A caller scope nests the field's pair inside a longer list, so a + // context with one is not two text parts and is refused below. let query = context.query(); let ContextPiece::List(parts) = &query else { return None; 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 19d1ca5cd3..94c4123f8c 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -27,8 +27,8 @@ use stack_encrypt::json::{ JsonSelector, JsonSubtree, JsonSubtreeKey, }; use stack_encrypt::target::{ - AeadContext, DecryptSource, EncryptTarget, ExpectedContext, IndexSpec, Json, Layout, - RequiredContext, + AeadContext, CallerContext, DecryptSource, EncryptTarget, ExpectedContext, IndexSpec, Json, + Layout, RequiredContext, }; use stack_encrypt::{ DecryptField, DecryptInto, Decryptable, Decryption, EncryptFrom, Encryption, Error, NonEmpty, @@ -485,6 +485,25 @@ impl JsonTree { } } +impl JsonTree { + /// Seal a document under these options, under the column that the + /// caller's context `C` holds. `column` takes the column out of it. + fn sealing<'s, K: 'static, C>( + &self, + column: fn(C) -> Identifier, + ) -> Encryption<'s, Value, JsonTreeDocument, K, C> + where + C: Into + Clone + Send + 'static, + { + Layout::::encryption::(&self.index) + .accepting::() + .map_with_context(|document, context: C| (context, document)) + .try_map(move |(context, document)| { + JsonTreeDocument::envelope(column(context), &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 @@ -495,10 +514,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(NonEmpty::into_inner) } fn index(&self) -> &Json { &self.index @@ -564,24 +580,22 @@ impl EncryptTarget for JsonTreeDocument { where JsonPlaintext: 's, { - Layout::::encryption::(JsonTree::default().index()) + JsonTree::default() + .sealing(|column: Self::ContextInput| column.into_inner().into_inner()) .project(JsonPlaintext::value) - .accepting::() - .map_with_context(|document, column: Self::ContextInput| (column, document)) - .try_map(|(column, document)| { - JsonTreeDocument::envelope(column.into_inner().into_inner(), &document) - }) } fn indexes() -> Vec { JsonTree::default().specs() } } -/// Decrypts to the plaintext document, under the stored column. Pass the -/// column you expect, `column.into()`, and the stored column must equal -/// it. Pass `().into()`, or decrypt with `decrypt_from`, and the document -/// opens under the stored column without that check. Either way the check -/// runs before any key is requested. +/// 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 { @@ -589,8 +603,8 @@ impl DecryptSource for JsonTreeDocument { } } -/// The structural form of [`DecryptSource`], which a record -/// field opens through, as it is for every other EQL type. +/// 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 { diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index 3dd0b28c53..5bb3bc9b1e 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -11,10 +11,12 @@ //! - 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, and each opens the -//! other's value; +//! - 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 record that lists a caller scope or a binding cannot store an EQL -//! field, and is refused before any key is requested; +//! field, nor can a record nested in another, and each is refused before +//! any key is requested; //! - a field that stores another column is refused before any key is //! requested; //! - a JSON document, `JsonTreeDocument`, encrypts from a `JsonPlaintext` @@ -23,8 +25,6 @@ mod common; -use std::collections::BTreeMap; - use eql_bindings::encryption::EqlTargets; use eql_bindings::v4::integer::IntegerOrd; use eql_bindings::v4::json_tree::{JsonTree, JsonTreeDocument}; @@ -36,8 +36,8 @@ use stack_encrypt::dynamic::{self, record, ValueFrame}; use stack_encrypt::json::JsonPlaintext; use stack_encrypt::target::{Bind, Layout, Scope}; use stack_encrypt::{ - AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, DecryptSource, Encrypt, - EncryptInto, EncryptTarget, Error, NonEmpty, PlanError, StackCipherText, + AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, DecryptSource, EncryptInto, + EncryptTarget, Error, NonEmpty, PlanError, StackCipherText, }; use zeroize::Zeroize; @@ -165,17 +165,32 @@ async fn a_query_from_the_field_marker_gives_the_stored_term() { assert_ne!(other.hm, stored.email.hm); } -#[derive(Clone, Debug, PartialEq, Zeroize)] +#[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 @@ -184,6 +199,8 @@ 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) @@ -194,8 +211,24 @@ fn contact_plan() -> record::Plan { .unwrap() } -fn frame(value: T) -> ValueFrame { - ValueFrame::of(value).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. @@ -258,43 +291,66 @@ 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 contact = Contact { + 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 derived: EncryptedContact = contact.clone().encrypt_into(&keyset).await.unwrap(); - let source = BTreeMap::from([("email", "ada@example.com"), ("name", "Ada")]); - let mut row = record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) + 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, }; - assert_eq!( - Contact::decrypt_from(record, &keyset).await.unwrap(), - contact - ); + 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: BTreeMap = - dynamic::frame::serde::from_slice(opened.risky_ref()).unwrap(); - assert_eq!(opened["email"], contact.email); - assert_eq!(opened["name"], contact.name); + 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, Zeroize)] @@ -317,9 +373,12 @@ struct EncryptedBound { email: TextEq, } +/// The refusal names the field by the record's scope and its name. fn assert_not_storable(result: Result) { match result { - Err(Error::Plan(PlanError::ContextNotStorable)) => {} + Err(Error::Plan(PlanError::ContextNotStorable { field })) => { + assert_eq!(field, "members/email"); + } Err(other) => panic!("expected ContextNotStorable, got {other:?}"), Ok(_) => panic!("expected ContextNotStorable, got a value"), } @@ -353,15 +412,57 @@ async fn a_record_with_a_caller_scope_or_binding_cannot_store_an_eql_field() { .encrypt_into_with_context(&keyset, column("email")) .await .unwrap(); - let record = EncryptedTenanted { email }; + let record = EncryptedTenanted { + email: email.clone(), + }; let opened = Tenanted::decrypt_from_with_context(record, &keyset, Scope::new(42u64)).await; assert_not_storable(opened); + let record = EncryptedBound { email }; + let opened = Tenanted::decrypt_from_with_context(record, &keyset, Bind::new(9u128)).await; + assert_not_storable(opened); assert!( calls.lock().unwrap().retrieve.is_empty(), "refused before any key is requested" ); } +/// 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, Zeroize)] +struct Holder { + member: Tenanted, +} + +/// That record as a field of another. Its EQL field's context is then its +/// own pair, extended by the outer record's. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Holder, scope = "holders")] +struct EncryptedHolder { + member: EncryptedPlain, +} + +#[tokio::test] +async fn an_eql_field_of_a_nested_record_is_refused() { + let (cipher, calls) = common::cipher().await; + let keyset = cipher.default_keyset(); + let holder = Holder { + member: Tenanted { + email: "ada@example.com".into(), + }, + }; + let nested: Result = holder.encrypt_into(&keyset).await; + assert_not_storable(nested); + assert!( + calls.lock().unwrap().generate.is_empty(), + "refused before any key is requested" + ); +} + #[tokio::test] async fn a_field_that_stores_another_column_is_refused() { let (cipher, calls) = common::cipher().await; @@ -408,6 +509,24 @@ fn search_terms(document: &JsonTreeDocument) -> Vec<(String, String, bool)> { 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; @@ -422,11 +541,10 @@ async fn a_json_document_encrypts_from_a_json_plaintext() { .run(JsonTree::default().encryption(), &profile(), column()) .await .unwrap(); - assert_eq!(stored.i, old.i); assert_eq!( - search_terms(&stored), - search_terms(&old), - "the same search terms" + document_terms(&stored), + document_terms(&old), + "the same envelope and search terms" ); // Each path opens what the other sealed. @@ -496,7 +614,7 @@ async fn a_json_document_is_a_record_field() { ) .await .unwrap(); - assert_eq!(search_terms(&stored.profile), search_terms(&old)); + assert_eq!(document_terms(&stored.profile), document_terms(&old)); let opened = Customer::decrypt_from(stored, &keyset).await.unwrap(); assert_eq!(opened.id, 3); diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index b25f547bfc..eeb856bcce 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -65,7 +65,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A context 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`). A record that lists a + (`stack_encrypt::plan_context_not_storable`), which names the field + by the record's scope and its name (`members/email`). A record that lists a caller scope or a binding gives its fields such a context. - On decrypt, the stored context must equal the field's, as a standalone decrypt with an expected context checks it. diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 30bb912597..71a077e934 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -175,7 +175,9 @@ mod tests { }, PlanError::EmptyIndexes => PlanError::EmptyIndexes, PlanError::EmptyPart => PlanError::EmptyPart, - PlanError::ContextNotStorable => PlanError::ContextNotStorable, + PlanError::ContextNotStorable { .. } => PlanError::ContextNotStorable { + field: "users/email".into(), + }, PlanError::NotInPlan { .. } => PlanError::NotInPlan { field: field() }, PlanError::NotInValue { .. } => PlanError::NotInValue { field: field() }, PlanError::FieldType { .. } => PlanError::FieldType { diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index a2e9eaa728..7f25855c49 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -676,7 +676,7 @@ fn refusal(error: crate::Error) -> (Option, Reason) { | P::MixedCiphers | P::TwoContextSources { .. } | P::NoContext - | P::ContextNotStorable => (None, Reason::Refused), + | P::ContextNotStorable { .. } => (None, Reason::Refused), } } diff --git a/packages/stack-encrypt/src/plan/error.rs b/packages/stack-encrypt/src/plan/error.rs index 5f95ea0c80..4a21034b0a 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -256,12 +256,17 @@ pub enum PlanError { /// table and a column, so it takes the record's scope and the field's /// name, and nothing more: no caller scope and no binding. Refused /// before any key is requested. - #[error("the field's type cannot store the context the record gives it")] + #[error("field {field:?}: its type cannot store the context the record gives it")] #[diagnostic( code(stack_encrypt::plan_context_not_storable), help("A field whose type stores its context, such as an EQL type, takes the record's scope and the field's name alone. Remove the record's caller scope and binding, or give the field a type that does not store its context.") )] - ContextNotStorable, + ContextNotStorable { + /// The field, as its own context renders: the record's scope and + /// the field's name, `members/email`. Empty when the context was + /// not built for a record field. + field: String, + }, /// A field was declared both as a typed target (`encrypt_into`) and with /// a data verb. A field is one or the other: the target's type decides /// its layout and its queries. @@ -288,7 +293,8 @@ impl crate::ErrorPayload for PlanError { | Self::NotInPlan { field } | Self::NotInValue { field } | Self::NoSuchField { field } - | Self::TargetWithVerbs { field } => payload([("field", field.as_str().into())]), + | Self::TargetWithVerbs { field } + | Self::ContextNotStorable { field } => payload([("field", field.as_str().into())]), Self::SharedIdentity { identity, first, @@ -337,8 +343,7 @@ impl crate::ErrorPayload for PlanError { | Self::MixedCiphers | Self::NoContext | Self::BindInQuery - | Self::EmptyPart - | Self::ContextNotStorable => serde_json::Map::new(), + | Self::EmptyPart => serde_json::Map::new(), } } } diff --git a/packages/stack-encrypt/src/target/context.rs b/packages/stack-encrypt/src/target/context.rs index 57e4c35edd..e530606b05 100644 --- a/packages/stack-encrypt/src/target/context.rs +++ b/packages/stack-encrypt/src/target/context.rs @@ -69,6 +69,11 @@ pub struct CallerContext { /// binding spelled as data ([`from_piece`](Self::from_piece)) is not /// checked here: the dynamic grammar allows an empty extension part. empty_part: bool, + /// The record field this context was built for: the field's own + /// context, as [`DeclaredContext::under`] and [`extend`](Self::extend) + /// were given it. It comes from the declaration, never from the + /// caller, so an error can name the field with it. + field: Option, } impl<'c, T> From> for CallerContext where @@ -97,6 +102,7 @@ impl From> for CallerContext { scopes, bindings: binding.into_iter().collect(), empty_part: empty_scope || empty_bind, + field: None, } } } @@ -132,6 +138,7 @@ impl CallerContext { scopes: Some(piece), bindings: Vec::new(), empty_part: false, + field: None, } } /// Refuse an empty part. A context with no scope passes: a record @@ -212,6 +219,7 @@ impl CallerContext { scopes: None, bindings: vec![piece], empty_part: false, + field: None, } } /// The parts a record stores in its row, as the caller context the @@ -223,6 +231,7 @@ impl CallerContext { scopes: stored.scope, bindings: stored.bind.into_iter().collect(), empty_part: stored.empty_part, + field: None, } } /// The own context `own`, extended by this caller context: the field's @@ -234,6 +243,7 @@ impl CallerContext { pub fn extend<'c, O: IntoContext<'c>>(self, own: NonEmpty) -> Self { let own = own.into_context().into_owned(); Self { + field: Some(Descriptor::from_piece(&own)), scopes: Some(match self.scopes { Some(scopes) => nest(own, scopes), None => own, @@ -254,8 +264,21 @@ impl CallerContext { } self.bindings.extend(part.bindings); self.empty_part |= part.empty_part; + self.field = self.field.or(part.field); self } + /// The refusal of a record field whose type cannot store this context, + /// naming the field by its own context. + pub(crate) fn not_storable(&self) -> Error { + crate::plan::PlanError::ContextNotStorable { + field: self + .field + .as_ref() + .map(|field| field.as_str().to_owned()) + .unwrap_or_default(), + } + .into() + } /// The scopes and the bindings, for [`Contexts`](crate::Contexts). #[cfg_attr(not(feature = "dynamic"), allow(dead_code))] pub(crate) fn pieces(&self) -> (Option>, Vec>) { @@ -725,6 +748,7 @@ impl StoredParts { scopes: None, bindings: Vec::new(), empty_part: empty_scope || empty_bind, + field: None, }; match (&self.scope, scope) { (Some(stored), Some(passed)) if *stored != passed => { @@ -868,9 +892,11 @@ impl DeclaredContext { /// `((("users", "age"), id), region)` under `id` then `region`. The /// bindings of every part follow the scopes, in order. pub fn under<'c, O: IntoContext<'c>>(self, own: NonEmpty) -> CallerContext { - self.0 - .into_iter() - .fold(CallerContext::from(own), CallerContext::then) + let own = own.into_context().into_owned(); + let field = Descriptor::from_piece(&own); + let mut context = CallerContext::scopes(own); + context.field = Some(field); + self.0.into_iter().fold(context, CallerContext::then) } /// [`under`](Self::under), refusing a part the caller passed empty. @@ -931,8 +957,9 @@ enum Expected { /// A stored context equal to this one. Exactly(NonEmpty), /// Nothing: a record gave the field a context its type cannot store, so - /// no stored context can be the one expected. - NotStorable, + /// no stored context can be the one expected. The context names the + /// field in the refusal. + NotStorable(CallerContext), } impl Default for ExpectedContext { fn default() -> Self { @@ -956,7 +983,7 @@ impl From for ExpectedContext { fn from(context: CallerContext) -> Self { Self(match T::from_field_context(&context) { Some(expected) => Expected::Exactly(expected), - None => Expected::NotStorable, + None => Expected::NotStorable(context), }) } } @@ -968,12 +995,12 @@ impl From for ExpectedContext { /// the field's name, extended by the caller's scopes and bindings, as a /// [`CallerContext`]. A field type that stores its context takes that /// context as the type it stores, so it can be a field of a record. -/// `eql_bindings::Identifier` implements this: an EQL type stores a table -/// and a column, so it takes `("members", "email")` and refuses a context -/// with a caller scope or a binding. +/// For example, a type that stores a table and a column takes +/// `("members", "email")`, and refuses a context with a caller scope or a +/// binding, since it has nowhere to store them. /// /// The rebuilt context must give the same context as the one the record -/// gave. Then the field writes the bytes it writes on its own under that +/// gave. Then the field writes the terms it writes on its own under that /// context. pub trait FromFieldContext: Sized { /// The context the field's type stores, rebuilt from the context the @@ -1000,7 +1027,7 @@ impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { return Err(Error::ContextMismatch { stored }); } } - Expected::NotStorable => return Err(crate::plan::PlanError::ContextNotStorable.into()), + Expected::NotStorable(context) => return Err(context.not_storable()), } nonempty(stored) } diff --git a/packages/stack-encrypt/src/target/input.rs b/packages/stack-encrypt/src/target/input.rs index 28560fd9e5..5bbf6e18fa 100644 --- a/packages/stack-encrypt/src/target/input.rs +++ b/packages/stack-encrypt/src/target/input.rs @@ -177,11 +177,17 @@ impl> FromCaller for C { } // A field whose type stores its context takes the record's context for the // field as that type, or refuses it. +// +// This impl and the blanket one above do not overlap only because +// `RequiredContext>` does not implement `From`. +// The `From` impl for `RequiredContext` needs +// `C: From`, and `NonEmpty` has no such impl. Adding one +// would stop this from compiling. impl FromCaller for RequiredContext> { fn from_caller(context: CallerContext) -> Result { T::from_field_context(&context) .map(Self::supplied) - .ok_or_else(|| crate::plan::PlanError::ContextNotStorable.into()) + .ok_or_else(|| context.not_storable()) } } // A record that derives terms gives its ciphertext fields the AEAD part of the diff --git a/packages/stack-encrypt/tests/field_context.rs b/packages/stack-encrypt/tests/field_context.rs index d73a61d579..4e8f112d0c 100644 --- a/packages/stack-encrypt/tests/field_context.rs +++ b/packages/stack-encrypt/tests/field_context.rs @@ -116,9 +116,12 @@ struct BoundUser { email: Stored, } +/// The refusal names the field by the record's scope and its name. fn assert_not_storable(result: Result) { match result { - Err(Error::Plan(PlanError::ContextNotStorable)) => {} + Err(Error::Plan(PlanError::ContextNotStorable { field })) => { + assert_eq!(field, "users/email"); + } Err(other) => panic!("expected ContextNotStorable, got {other:?}"), Ok(_) => panic!("expected ContextNotStorable, got a value"), } From ad5ffdb734a6dca62a9f269ba8576e317d70bcfe Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 13:45:45 +1100 Subject: [PATCH 04/13] fix(stack-encrypt,eql-bindings): an EQL field takes a scope and a binding Second round of review on EQL types as record fields. An EQL field refused every record that lists a scope or a binding, and every record nested in another, because `i` stores only a table and a column. The extra context does not need to be stored. A field type that stores its context now stores the field's own context alone: the record's scope and the field's name. The scopes and bindings of the record come after it. The ciphertext and the terms derive under all of it, as they do for a field of any other type, and the reader supplies the scopes and bindings again. stack-encrypt: - `ContextFromField` replaces `FromFieldContext`. It builds the stored context from the field's own context. The hidden `FromCaller` is gone: `Encryption::under` takes `From` again. - `CallerContext` keeps the field's own context apart, in place of the `Descriptor` that only named the field in an error. - The encrypt input of a `context_field` record is the hidden `StoredContext`: the context to store, and the context to run under. `ExpectedContext::opening` gives the same on decrypt. - `PlanError::ContextNotStorable` now means that the type cannot store the field's own context. It names that context, and is never empty. - The derive emits `Encryption::under_field`, which wipes an owned plaintext when a caller's part is empty. `under` dropped it unwiped. eql-bindings: - `Identifier` implements `ContextFromField`. - `JsonTreeDocument` takes the same input, so a document field takes a scope and a binding too. Its doc example is now compiled. - A query for an EQL type takes a scope. `QueryLabelError::Extended` is removed. --- .changeset/eql-types-as-record-fields.md | 5 +- .../2026-10-24-stack-encrypt-api-plan.md | 44 +- packages/eql/crates/eql-bindings/CHANGELOG.md | 29 +- packages/eql/crates/eql-bindings/README.md | 38 +- .../eql/crates/eql-bindings/src/encryption.rs | 38 +- .../eql-bindings/src/encryption/query.rs | 52 +- .../crates/eql-bindings/src/v4/json_tree.rs | 78 ++- .../tests/encryption/tests/migration_shim.rs | 5 +- .../tests/encryption/tests/record_fields.rs | 313 +++++++++--- .../tests/encryption/tests/typed_queries.rs | 127 +++-- .../eql/tests/encryption/tests/v4_owned.rs | 10 +- .../stack-encrypt-derive/docs/attributes.md | 6 +- .../stack-encrypt-derive/src/owned_decrypt.rs | 8 +- .../stack-encrypt-derive/src/owned_encrypt.rs | 33 +- packages/stack-encrypt/CHANGELOG.md | 47 +- packages/stack-encrypt/src/contexts.rs | 9 +- packages/stack-encrypt/src/op/mod.rs | 4 +- packages/stack-encrypt/src/plan/error.rs | 23 +- packages/stack-encrypt/src/target/context.rs | 483 +++++++++++++++--- packages/stack-encrypt/src/target/input.rs | 91 +--- packages/stack-encrypt/src/target/mod.rs | 23 +- .../stack-encrypt/src/target/operations.rs | 96 +++- packages/stack-encrypt/tests/field_context.rs | 353 ++++++++++--- packages/stack-encrypt/tests/owned_records.rs | 51 +- .../ui/owned_aead_record_with_term.stderr | 19 +- .../ui/owned_record_field_context.stderr | 33 +- .../ui/owned_record_field_stores_context.rs | 30 ++ .../owned_record_field_stores_context.stderr | 52 ++ 28 files changed, 1577 insertions(+), 523 deletions(-) create mode 100644 packages/stack-encrypt/tests/ui/owned_record_field_stores_context.rs create mode 100644 packages/stack-encrypt/tests/ui/owned_record_field_stores_context.stderr diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md index 01fe9d7a26..1bc407caeb 100644 --- a/.changeset/eql-types-as-record-fields.md +++ b/.changeset/eql-types-as-record-fields.md @@ -5,8 +5,9 @@ `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`. -- 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 that lists a caller scope or a binding cannot have an EQL field, because an EQL value stores only a table and a column. Every call is refused with `PlanError::ContextNotStorable`, which names the field, before any key is requested. +- 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 ciphertext and the terms of an EQL field then derive under the column, the scope and the binding, as they do for a field of any other type. `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 can carry a scope: `.scope(..)` on a query from a field's marker, or `.extend(..)` on a plan's query. It gives the term of the values stored under that scope. - `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/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 08b6e6ce6f..d392c99299 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1482,33 +1482,45 @@ Base64. - **What to build.** EQL types such as `TextEq` and `JsonTreeDocument` as field types of the Rust record derive. -- **How it works.** The record derive gives each field a `CallerContext`. - A field type that stores its context implements - `target::FromFieldContext`, and takes that context as the one it - stores. `Identifier` takes a 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. It refuses a caller scope or a binding, - which an EQL payload cannot store, with - `PlanError::ContextNotStorable`, before any key is requested. +- **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 ciphertext and the terms of an EQL field derive + under the column, then the scope, then the binding, as they do for a + field of any other type. `i` does not store them, 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.** In #1658: - A Rust record with EQL fields encrypts and decrypts through the new - API. + 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), it 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`). + 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. The order types do not implement `Answers` yet, so a marker - cannot query them. -- **Tracked in.** Issue #1658. `eql-bindings` builds against the crates.io `stack-encrypt`, so a `stack-encrypt` release with `FromFieldContext` must come before the `eql-bindings` release that uses it. + types, with the record's scope. A plan's query for an EQL type takes + `.extend(..)`. The order types do not implement `Answers` yet, so a + marker cannot query them. +- **Not done.** A data plan still refuses a scope or a binding on a field + that names an EQL type (`TargetError::Extended`). So a Go record cannot + yet write an EQL field under a scope. +- **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, including order queries; - - it writes the same terms as a Go record with the same declaration. + - 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/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 53d9b90ea6..c162ff8955 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -16,13 +16,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `{"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::FromFieldContext`. - - A record that lists a caller scope or a binding cannot have an EQL - field: an EQL payload stores a table and a column, and nothing more. - Every call is refused with `PlanError::ContextNotStorable`, which - names the field (`members/email`), before any key is requested. + - `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 + ciphertext and the terms of an EQL field then derive under the column, + the scope and the binding, as they do for a field of any other type. + `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. + 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, with + `.extend(..)`. It gives the term of the values stored under that + scope. `QueryLabelError` has no `Extended` variant. + - 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 @@ -161,9 +173,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 7831da8f7e..0cc2c626ac 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -437,12 +437,38 @@ Each field writes the terms its type writes on its own under names the type writes. On decrypt, each field's stored `i` must be its own column, checked before any key is requested. -An EQL value stores a table and a column, and nothing more. So a record that -lists a caller scope (`scope(tenant: u64)`) or a binding (`bind(row: u128)`) -cannot have an EQL field. Every call to it is refused with -`PlanError::ContextNotStorable`, which names the field, before any key is -requested. The same goes for an EQL field of a record nested in another: its -context has more parts than a table and a column. +A record can also list a scope or a binding, such as a tenant or a row ID: + +```rust,ignore +#[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"} +} + +let parts = || Scope::new(tenant).bind(row); +let stored: EncryptedMember = member.encrypt_into_with_context(&keyset, parts()).await?; +let query = EncryptedMember::EMAIL + .eq("alice@example.com") + .scope(Scope::new(tenant)) + .encrypt(&keyset) + .await?; +let opened = Member::decrypt_from_with_context(stored, &keyset, parts()).await?; +``` + +`i` stores the table and the column, and nothing a caller supplies. The +ciphertext and the terms of the field derive under the column, then the +scope, then the binding, as they do for a field of any other type. So: + +- the reader supplies the scope and the binding again, and a value does not + open without them; +- 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. + +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 diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 395fb2be17..bca643dea9 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -113,7 +113,7 @@ use stack_encrypt::sem::{ }; use stack_encrypt::target::transcode::{Reader, Transcode, Visitor}; use stack_encrypt::target::{ - self, AeadContext, CallerContext, DecryptSource, EncryptTarget, FromFieldContext, IndexSpec, + self, AeadContext, CallerContext, ContextFromField, DecryptSource, EncryptTarget, IndexSpec, RequiredContext, }; use stack_encrypt::{ @@ -202,32 +202,28 @@ impl<'a> IntoContext<'a> for &'a Identifier { } /// An EQL type can be a field of a derived `struct = ..` record. The record -/// gives the field its scope and the field's name, `("members", "email")`, -/// and the EQL type stores that pair as its column: table `members`, column -/// `email`. It is the context the record gave, so the field writes what the -/// type writes on its own under `Identifier::for_column("members", "email")`. +/// 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`. /// -/// An EQL payload stores a table and a column, and nothing more. So a -/// record that lists a caller scope or a binding cannot have an EQL field: -/// the field refuses the context, before any key is requested. -impl FromFieldContext for Identifier { - fn from_field_context(context: &CallerContext) -> Option> { - if context.has_bindings() { - return None; - } - // A caller scope nests the field's pair inside a longer list, so a - // context with one is not two text parts and is refused below. - let query = context.query(); - let ContextPiece::List(parts) = &query else { +/// `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. +/// The field's ciphertext and terms derive under them, after the column, +/// as a field of any other type does. They are not stored in `i`, so the +/// reader supplies them again. The names of a record that holds this one +/// as a field come after the column in the same way. +/// +/// 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; }; - let identifier = Self::for_column(table.as_ref(), column.as_ref()).ok()?; - // Only the context the record gave: a pair that reads as a column - // but encodes differently would seal under another context. - (identifier.get().to_context() == query).then_some(identifier) + Self::for_column(table.as_ref(), column.as_ref()).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..0d67f4f978 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: `.extend(..)` on a plan's query, or +//! `.scope(..)` on a query from a record field's marker. 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/v4/json_tree.rs b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs index 94c4123f8c..9d620aac94 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -27,8 +27,8 @@ use stack_encrypt::json::{ JsonSelector, JsonSubtree, JsonSubtreeKey, }; use stack_encrypt::target::{ - AeadContext, CallerContext, DecryptSource, EncryptTarget, ExpectedContext, IndexSpec, Json, - Layout, RequiredContext, + AeadContext, DecryptSource, EncryptTarget, ExpectedContext, IndexSpec, Json, Layout, + StoredContext, }; use stack_encrypt::{ DecryptField, DecryptInto, Decryptable, Decryption, EncryptFrom, Encryption, Error, NonEmpty, @@ -486,21 +486,17 @@ impl JsonTree { } impl JsonTree { - /// Seal a document under these options, under the column that the - /// caller's context `C` holds. `column` takes the column out of it. - fn sealing<'s, K: 'static, C>( + /// 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. + fn sealing<'s, K: 'static>( &self, - column: fn(C) -> Identifier, - ) -> Encryption<'s, Value, JsonTreeDocument, K, C> - where - C: Into + Clone + Send + 'static, - { + ) -> Encryption<'s, Value, JsonTreeDocument, K, StoredContext> { Layout::::encryption::(&self.index) - .accepting::() - .map_with_context(|document, context: C| (context, document)) - .try_map(move |(context, document)| { - JsonTreeDocument::envelope(column(context), &document) - }) + .storing(|document, column: Identifier| (column, document)) + .try_map(|(column, document)| JsonTreeDocument::envelope(column, &document)) } } @@ -514,7 +510,7 @@ impl Layout for JsonTree { fn encryption<'s, K: 'static>( &self, ) -> Encryption<'s, Value, JsonTreeDocument, K, NonEmpty> { - self.sealing(NonEmpty::into_inner) + self.sealing().accepting() } fn index(&self) -> &Json { &self.index @@ -548,15 +544,19 @@ impl DecryptInto for JsonTreeDocument { } impl JsonTreeDocument { - /// Open the document under the stored column, once it has passed the - /// caller's check. The check runs before any key is requested. + /// 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 column = match context.validate(self.i.clone()) { - Ok(column) => column, + let context = match context.opening(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), } } @@ -566,23 +566,45 @@ impl JsonTreeDocument { /// under the default options ([`JsonTree::default`]), with the column as /// its context: /// -/// ```ignore +/// ```no_run +/// use eql_bindings::{v4::json_tree::JsonTreeDocument, Identifier}; +/// use stack_encrypt::json::JsonPlaintext; +/// use stack_encrypt::kms::{DataKeySource, IndexKeySource}; +/// use stack_encrypt::{DecryptFrom, EncryptInto, KeysetCipher}; +/// +/// # async fn example(keyset: &KeysetCipher<'_, K>) -> Result<(), Box> +/// # where +/// # K: DataKeySource + IndexKeySource + Sync + 'static, +/// # { +/// let column = Identifier::for_column("customers", "profile")?; +/// let profile = JsonPlaintext::from(serde_json::json!({"name": "Ada", "age": 36})); /// let document: JsonTreeDocument = profile -/// .encrypt_into_with_context(&keyset, Identifier::for_column("customers", "profile")?) +/// .encrypt_into_with_context(keyset, column.clone()) /// .await?; +/// assert_eq!(document.i, *column.get()); +/// +/// // The column is checked against the one the document stores. +/// let opened = JsonPlaintext::decrypt_from_with_context(document, keyset, column).await?; +/// assert_eq!(opened.value()["name"], "Ada"); +/// # Ok(()) +/// # } /// ``` /// +/// The example is compiled, and not run: this crate's doctests have no key +/// source. `record_fields.rs` in the encryption test crate runs the same +/// calls. +/// /// 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. +/// 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 = RequiredContext>; + type ContextInput = StoredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> where JsonPlaintext: 's, { - JsonTree::default() - .sealing(|column: Self::ContextInput| column.into_inner().into_inner()) - .project(JsonPlaintext::value) + JsonTree::default().sealing().project(JsonPlaintext::value) } fn indexes() -> Vec { JsonTree::default().specs() 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/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index 5bb3bc9b1e..f56eefb369 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -14,9 +14,11 @@ //! - 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 record that lists a caller scope or a binding cannot store an EQL -//! field, nor can a record nested in another, and each is refused before -//! any key is requested; +//! - 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 +//! ciphertext and the terms derive under it, and `i` does not store it. +//! The reader supplies it again, and a query supplies the scope; +//! - 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 JSON document, `JsonTreeDocument`, encrypts from a `JsonPlaintext` @@ -25,7 +27,7 @@ mod common; -use eql_bindings::encryption::EqlTargets; +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}; @@ -34,10 +36,12 @@ use serde::Serialize; use serde_json::{json, Value}; use stack_encrypt::dynamic::{self, record, ValueFrame}; use stack_encrypt::json::JsonPlaintext; -use stack_encrypt::target::{Bind, Layout, Scope}; +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::{ - AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, DecryptSource, EncryptInto, - EncryptTarget, Error, NonEmpty, PlanError, StackCipherText, + assert_context, nonempty, AsProtectedRef as _, CipherText, Controlled as _, DecryptFrom, + DecryptSource, EncryptInto, EncryptTarget, Error, NonEmpty, StackCipherText, }; use zeroize::Zeroize; @@ -353,77 +357,235 @@ async fn the_derive_and_a_data_plan_write_the_same_row() { ); } -#[derive(Clone, Zeroize)] +#[derive(Clone, Debug, PartialEq, Zeroize)] struct Tenanted { email: String, } -/// A record whose caller supplies a tenant scope. An EQL payload has -/// nowhere to store the tenant. +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))] +#[stash(struct = Tenanted, scope = "members", scope(tenant: u64), bind(row: u128))] struct EncryptedTenanted { email: TextEq, } -/// A record whose caller supplies a row binding. -#[derive(EncryptTarget, DecryptSource)] -#[stash(struct = Tenanted, scope = "members", bind(row: u128))] -struct EncryptedBound { - 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"), + ], + }, + ); } -/// The refusal names the field by the record's scope and its name. -fn assert_not_storable(result: Result) { - match result { - Err(Error::Plan(PlanError::ContextNotStorable { field })) => { - assert_eq!(field, "members/email"); - } - Err(other) => panic!("expected ContextNotStorable, got {other:?}"), - Ok(_) => panic!("expected ContextNotStorable, got a value"), - } +#[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 a_record_with_a_caller_scope_or_binding_cannot_store_an_eql_field() { +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 tenanted = || Tenanted { - email: "ada@example.com".into(), + let stored: EncryptedTenanted = tenanted() + .encrypt_into_with_context(&keyset, tenant_and_row()) + .await + .unwrap(); + let again = || EncryptedTenanted { + email: stored.email.clone(), }; - let scoped: Result = tenanted() - .encrypt_into_with_context(&keyset, Scope::new(42u64)) - .await; - assert_not_storable(scoped); - let bound: Result = tenanted() - .encrypt_into_with_context(&keyset, Bind::new(9u128)) - .await; - assert_not_storable(bound); - assert!( - calls.lock().unwrap().generate.is_empty(), - "refused before any key is requested" - ); - - // A value written on its own under the column does not open in such a - // record either. + 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: email.clone(), + 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 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 opened = Tenanted::decrypt_from_with_context(record, &keyset, Scope::new(42u64)).await; - assert_not_storable(opened); - let record = EncryptedBound { email }; - let opened = Tenanted::decrypt_from_with_context(record, &keyset, Bind::new(9u128)).await; - assert_not_storable(opened); - assert!( - calls.lock().unwrap().retrieve.is_empty(), - "refused before any key is requested" - ); + 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. @@ -433,13 +595,13 @@ struct EncryptedPlain { email: TextEq, } -#[derive(Clone, Zeroize)] +#[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, extended by the outer record's. +/// own pair, followed by the outer field's pair. #[derive(EncryptTarget, DecryptSource)] #[stash(struct = Holder, scope = "holders")] struct EncryptedHolder { @@ -447,20 +609,33 @@ struct EncryptedHolder { } #[tokio::test] -async fn an_eql_field_of_a_nested_record_is_refused() { - let (cipher, calls) = common::cipher().await; +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 { - email: "ada@example.com".into(), - }, - }; - let nested: Result = holder.encrypt_into(&keyset).await; - assert_not_storable(nested); - assert!( - calls.lock().unwrap().generate.is_empty(), - "refused before any key is requested" - ); + 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] 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..cf35737c54 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::opening`). 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.opening(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 eeb856bcce..09b95dfeb5 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -55,25 +55,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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 its scope and the - field's name. A type that stores its context in the row, such as an EQL - type that stores a table and a column, implements the new trait - `target::FromFieldContext` to take that context as the one it stores. - - `FromFieldContext::from_field_context` rebuilds the stored context - from the field's `CallerContext`, or returns `None` when the type - cannot store it. - - A context 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 the field - by the record's scope and its name (`members/email`). A record that lists a - caller scope or a binding gives its fields such a context. - - On decrypt, the stored context must equal the field's, as a + 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. The field + runs under all of it, as a field of any other type does, and does not + store them. 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. - - `Encryption::under` now converts the field's context through the - hidden trait `target::FromCaller`, which every - `From` type implements. A caller of `under` compiles - unchanged. + - 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 @@ -790,6 +794,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/src/contexts.rs b/packages/stack-encrypt/src/contexts.rs index 301681b291..f61f7efa79 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(); diff --git a/packages/stack-encrypt/src/op/mod.rs b/packages/stack-encrypt/src/op/mod.rs index b33b1a2cae..76079c0c90 100644 --- a/packages/stack-encrypt/src/op/mod.rs +++ b/packages/stack-encrypt/src/op/mod.rs @@ -772,8 +772,8 @@ pub trait Supports>: Index { /// (`.extend(..)`) when `extended` is true: for an index whose query term /// records the context it was derived under, a context it cannot record. /// An EQL query value stores the column it queries, so its index refuses - /// a label that names no column, and any extension, which the column - /// cannot hold. Run when the query is awaited, before [`prepare`](Self::prepare) + /// a label that names no column. It takes a scope: the stored value does + /// not store one either. Run when the query is awaited, before [`prepare`](Self::prepare) /// and before any keyset is resolved; every index in this crate takes /// any context and returns `Ok(())`. fn check_label(&self, _label: &Label, _extended: bool) -> Result<(), Error> { diff --git a/packages/stack-encrypt/src/plan/error.rs b/packages/stack-encrypt/src/plan/error.rs index 4a21034b0a..173c6d6f54 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -251,20 +251,23 @@ pub enum PlanError { help("Give the scope or binding a value. An empty part would put every row under one context.") )] EmptyPart, - /// A record field's type stores its context in the row, and the record - /// gives the field a context it cannot store. An EQL type stores a - /// table and a column, so it takes the record's scope and the field's - /// name, and nothing more: no caller scope and no binding. Refused - /// before any key is requested. - #[error("field {field:?}: its type cannot store the context the record gives it")] + /// A field's type stores the field's own context in the row, and + /// cannot store this one. The own context is the declared part: the + /// record's scope and the field's name. An EQL type stores it as a + /// table and a column, so the own context must be two text parts. + /// + /// The scopes and bindings of the record are not stored, so they never + /// cause this error. Refused before any key is requested. + #[error("field {field:?}: its type cannot store the field's own context")] #[diagnostic( code(stack_encrypt::plan_context_not_storable), - help("A field whose type stores its context, such as an EQL type, takes the record's scope and the field's name alone. Remove the record's caller scope and binding, or give the field a type that does not store its context.") + help("A field type that stores its context, such as an EQL type, stores the field's own context: the record's scope and the field's name. Declare the field in a `struct = ..` record with a `scope = \"..\"`, which gives it an own context of two text parts, or give the field a type that does not store its context.") )] ContextNotStorable { - /// The field, as its own context renders: the record's scope and - /// the field's name, `members/email`. Empty when the context was - /// not built for a record field. + /// The field's own context, as it renders: the record's scope and + /// the field's name, `members/email`. A context that no record + /// built for a field has no own part. This is then the whole query + /// context that the type was given. field: String, }, /// A field was declared both as a typed target (`encrypt_into`) and with diff --git a/packages/stack-encrypt/src/target/context.rs b/packages/stack-encrypt/src/target/context.rs index e530606b05..7fdd510418 100644 --- a/packages/stack-encrypt/src/target/context.rs +++ b/packages/stack-encrypt/src/target/context.rs @@ -69,11 +69,13 @@ pub struct CallerContext { /// binding spelled as data ([`from_piece`](Self::from_piece)) is not /// checked here: the dynamic grammar allows an empty extension part. empty_part: bool, - /// The record field this context was built for: the field's own - /// context, as [`DeclaredContext::under`] and [`extend`](Self::extend) - /// were given it. It comes from the declaration, never from the - /// caller, so an error can name the field with it. - field: Option, + /// The field's own context, when a record built this context for one + /// of its fields: the record's scope and the field's name, as + /// [`DeclaredContext::under`] and [`extend`](Self::extend) were given + /// them, before any scope or binding. It is the part that a field type + /// which stores its context stores ([`ContextFromField`]). `None` for a + /// context the caller built. + own: Option>, } impl<'c, T> From> for CallerContext where @@ -102,7 +104,7 @@ impl From> for CallerContext { scopes, bindings: binding.into_iter().collect(), empty_part: empty_scope || empty_bind, - field: None, + own: None, } } } @@ -138,7 +140,7 @@ impl CallerContext { scopes: Some(piece), bindings: Vec::new(), empty_part: false, - field: None, + own: None, } } /// Refuse an empty part. A context with no scope passes: a record @@ -219,7 +221,7 @@ impl CallerContext { scopes: None, bindings: vec![piece], empty_part: false, - field: None, + own: None, } } /// The parts a record stores in its row, as the caller context the @@ -231,7 +233,7 @@ impl CallerContext { scopes: stored.scope, bindings: stored.bind.into_iter().collect(), empty_part: stored.empty_part, - field: None, + own: None, } } /// The own context `own`, extended by this caller context: the field's @@ -243,7 +245,7 @@ impl CallerContext { pub fn extend<'c, O: IntoContext<'c>>(self, own: NonEmpty) -> Self { let own = own.into_context().into_owned(); Self { - field: Some(Descriptor::from_piece(&own)), + own: Some(own.clone()), scopes: Some(match self.scopes { Some(scopes) => nest(own, scopes), None => own, @@ -264,18 +266,32 @@ impl CallerContext { } self.bindings.extend(part.bindings); self.empty_part |= part.empty_part; - self.field = self.field.or(part.field); self } - /// The refusal of a record field whose type cannot store this context, - /// naming the field by its own context. - pub(crate) fn not_storable(&self) -> Error { + /// The context a field type that stores its context stores for this + /// field: the field's own context, as `T`. + /// + /// `None` when `T` cannot store the own context, when `T` stores a + /// context that encodes differently from it, or when no record built + /// this context for a field. A stored context that encoded differently + /// would name one context in the row while the field ran under + /// another. + fn stored_as<'c, T>(&self) -> Option> + where + T: ContextFromField + Clone + IntoContext<'c>, + { + let own = self.own.as_ref()?; + let stored = T::from_field(own)?; + (stored.get().clone().into_context() == *own).then_some(stored) + } + /// The refusal of a field whose type cannot store this context's own + /// part. It names the field by its own context, `members/email`. A + /// context that no record built for a field has no own part, so the + /// refusal names the whole query context. + fn not_storable(&self) -> Error { + let named = self.own.clone().unwrap_or_else(|| self.query()); crate::plan::PlanError::ContextNotStorable { - field: self - .field - .as_ref() - .map(|field| field.as_str().to_owned()) - .unwrap_or_default(), + field: Descriptor::from_piece(&named).as_str().to_owned(), } .into() } @@ -748,7 +764,7 @@ impl StoredParts { scopes: None, bindings: Vec::new(), empty_part: empty_scope || empty_bind, - field: None, + own: None, }; match (&self.scope, scope) { (Some(stored), Some(passed)) if *stored != passed => { @@ -893,9 +909,8 @@ impl DeclaredContext { /// bindings of every part follow the scopes, in order. pub fn under<'c, O: IntoContext<'c>>(self, own: NonEmpty) -> CallerContext { let own = own.into_context().into_owned(); - let field = Descriptor::from_piece(&own); - let mut context = CallerContext::scopes(own); - context.field = Some(field); + let mut context = CallerContext::scopes(own.clone()); + context.own = Some(own); self.0.into_iter().fold(context, CallerContext::then) } @@ -956,10 +971,15 @@ enum Expected { Any, /// A stored context equal to this one. Exactly(NonEmpty), - /// Nothing: a record gave the field a context its type cannot store, so - /// no stored context can be the one expected. The context names the - /// field in the refusal. - NotStorable(CallerContext), + /// The context of a record field. The stored context must be the + /// field's own context, `own`. The field then opens under `context`: + /// its own context, then the scopes and bindings of the record, which + /// the field does not store. `own` is `None` when the field's type + /// cannot store the own context. Nothing opens then. + Field { + own: Option>, + context: CallerContext, + }, } impl Default for ExpectedContext { fn default() -> Self { @@ -976,61 +996,229 @@ impl From> for ExpectedContext { Self(Expected::Exactly(value)) } } -/// A record field whose type stores its context expects the context the -/// record gives the field. A context the type cannot store is refused when -/// the field is opened, before any key is requested. -impl From for ExpectedContext { +/// A record field whose type stores its context expects the field's own +/// context in the row: the record's scope and the field's name. The field +/// opens under that context, then the scopes and bindings of the record. +/// The field does not store those, so the reader supplies them again. +impl<'c, T> From for ExpectedContext +where + T: ContextFromField + Clone + IntoContext<'c>, +{ fn from(context: CallerContext) -> Self { - Self(match T::from_field_context(&context) { - Some(expected) => Expected::Exactly(expected), - None => Expected::NotStorable(context), + Self(Expected::Field { + own: context.stored_as(), + context, }) } } - -/// A context type that a record field's type stores in the row, and can -/// rebuild from the context the record gives the field. -/// -/// A derived `struct = ..` record gives each field the record's scope and -/// the field's name, extended by the caller's scopes and bindings, as a -/// [`CallerContext`]. A field type that stores its context takes that -/// context as the type it stores, so it can be a field of a record. -/// For example, a type that stores a table and a column takes -/// `("members", "email")`, and refuses a context with a caller scope or a -/// binding, since it has nowhere to store them. -/// -/// The rebuilt context must give the same context as the one the record -/// gave. Then the field writes the terms it writes on its own under that -/// context. -pub trait FromFieldContext: Sized { - /// The context the field's type stores, rebuilt from the context the - /// record gives the field, or `None` when the type cannot store it. - fn from_field_context(context: &CallerContext) -> Option>; -} impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { /// Check the stored context against this expectation and prove it - /// nonempty, yielding the context the record is opened under. + /// nonempty. It returns the stored context alone. A record opens under + /// the context [`opening`](Self::opening) returns: a record field also + /// opens under the scopes and bindings of its record. /// /// # Errors /// /// [`Error::ContextMismatch`] if an expected context was given and the /// stored one differs from it; the error carries the stored context's - /// descriptor. Otherwise fails if the stored context is empty. A stored + /// descriptor. [`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable) + /// if the record is a field whose type cannot store the field's own + /// context. Otherwise fails if the stored context is empty. A stored /// context is data the record was handed, not something the cipher has - /// authenticated yet: both checks happen before any key is requested. + /// authenticated yet: every check happens before any key is requested. pub fn validate(self, stored: T) -> Result, Error> { - match self.0 { - Expected::Any => {} - Expected::Exactly(expected) => { - if expected.into_inner() != stored { - let stored = Descriptor::from_piece(&stored.into_context()); - return Err(Error::ContextMismatch { stored }); - } + let expected = match self.0 { + Expected::Any => None, + Expected::Exactly(expected) => Some(expected), + Expected::Field { own: Some(own), .. } => Some(own), + Expected::Field { own: None, context } => return Err(context.not_storable()), + }; + if let Some(expected) = expected { + if expected.into_inner() != stored { + let stored = Descriptor::from_piece(&stored.into_context()); + return Err(Error::ContextMismatch { stored }); } - Expected::NotStorable(context) => return Err(context.not_storable()), } nonempty(stored) } + + /// Check the stored context as [`validate`](Self::validate) does, and + /// return the context the record opens under. + /// + /// On its own, a record opens under the context it stores. As a field + /// of another record, it opens under that context, then the scopes and + /// bindings of the record, which the field does not store. + /// + /// # Errors + /// + /// As [`validate`](Self::validate), before any key is requested. + pub fn opening(self, stored: T) -> Result { + let context = match &self.0 { + Expected::Field { context, .. } => Some(context.clone()), + Expected::Any | Expected::Exactly(_) => None, + }; + let stored = self.validate(stored)?; + Ok(context.unwrap_or_else(|| CallerContext::from(stored))) + } +} + +/// What a record that stores its context is given when it encrypts: the +/// context it stores, and the context its fields run under. +/// +/// A `#[stash(context_field)]` record, such as an EQL type, writes its +/// context into the row. +/// +/// - On its own, the caller passes that context as a `NonEmpty`. It is +/// the whole context. +/// - As a field of a `struct = ..` record, it stores the field's own +/// context: the record's scope and the field's name +/// ([`ContextFromField`]). The scopes and bindings of the record come +/// after it. They are not stored in the field. The reader supplies them +/// again, as for a field of any other type. +// `#[doc(hidden)]` is on the definition for the reason given on +// `ExpectedContext`. +#[doc(hidden)] +#[derive(Clone, Debug)] +pub struct StoredContext { + /// The context the record stores. `None` when the record is a field + /// whose type cannot store the field's own context. + stored: Option>, + /// The context the record's fields run under: the stored context, then + /// the scopes and bindings that are not stored. + context: CallerContext, +} +impl<'c, T: Clone + IntoContext<'c>> From> for StoredContext { + fn from(stored: NonEmpty) -> Self { + Self { + context: CallerContext::from(stored.clone()), + stored: Some(stored), + } + } +} +/// A record field whose type stores its context stores the field's own +/// context, and runs under the whole context the record gives the field. +impl<'c, T> From for StoredContext +where + T: ContextFromField + Clone + IntoContext<'c>, +{ + fn from(context: CallerContext) -> Self { + Self { + stored: context.stored_as(), + context, + } + } +} +impl StoredContext { + /// The context to store, and the context the record's fields run + /// under. + /// + /// # Errors + /// + /// [`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable) + /// when the record is a field whose type cannot store the field's own + /// context. + pub(super) fn into_parts(self) -> Result<(T, CallerContext), Error> { + match self.stored { + Some(stored) => Ok((stored.into_inner(), self.context)), + None => Err(self.context.not_storable()), + } + } +} + +/// A context type that a field's type stores in the row, built from the +/// field's own context. +/// +/// A `struct = ..` record gives each field a context of its own: the +/// record's scope, then the field's name, such as `("members", "email")`. +/// A field type that stores its context writes that own context into the +/// row, as the type it stores. For example, a type that stores a table and +/// a column stores the table `members` and the column `email`. Implement +/// this trait for the stored type. A type that stores it can then be a +/// field of a record. +/// +/// Only the own context is stored. A record can also list scopes and +/// bindings, such as a tenant or a row ID. They come after the own +/// context, and the data key, the AAD and the search terms derive under +/// all of it. They are not stored in the field, so whoever reads the field +/// supplies them again. The same is true of the names of a record that +/// holds this record as a field. +/// +/// The context that `from_field` returns must encode as `own` does +/// ([`IntoContext`]). The field then writes the terms that its type writes +/// on its own under that context. A context that encodes differently is +/// refused, as `None` is, with +/// [`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable), +/// before any key is requested. +/// +/// # Example +/// +/// A type that stores a table and a column, as an EQL type does: +/// +/// ``` +/// use stack_encrypt::target::ContextFromField; +/// use stack_encrypt::{nonempty, ContextPiece, IntoContext, MaybeEmpty, NonEmpty}; +/// +/// #[derive(Clone, Debug, PartialEq)] +/// struct Column { +/// table: String, +/// column: String, +/// } +/// +/// impl MaybeEmpty for Column { +/// fn is_empty(&self) -> bool { +/// self.table.is_empty() || self.column.is_empty() +/// } +/// } +/// +/// // The context of a column: its table, then its column. +/// impl<'a> IntoContext<'a> for Column { +/// fn into_context(self) -> ContextPiece<'a> { +/// ContextPiece::List(vec![ +/// ContextPiece::Text(self.table.into()), +/// ContextPiece::Text(self.column.into()), +/// ]) +/// } +/// } +/// +/// // A field's own context is the record's scope, then the field's name. +/// // A column stores the scope as its table and the name as its column. +/// impl ContextFromField for Column { +/// 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; +/// }; +/// NonEmpty::new(Self { +/// table: table.to_string(), +/// column: column.to_string(), +/// }) +/// .ok() +/// } +/// } +/// +/// // The field `email` of a record whose scope is `members`. +/// let own = nonempty!("members").with("email").into_context(); +/// let stored = Column::from_field(&own).expect("a table and a column"); +/// assert_eq!(stored.get().table, "members"); +/// assert_eq!(stored.get().column, "email"); +/// // The stored column encodes as the field's own context does. +/// assert_eq!(stored.into_inner().into_context(), own); +/// +/// // A column cannot store a context of three parts. +/// let longer = nonempty!("members").with("email").with("work").into_context(); +/// assert!(Column::from_field(&longer).is_none()); +/// ``` +#[diagnostic::on_unimplemented( + message = "a field whose type stores a `{Self}` as its context cannot be a field of a `struct = ..` record", + label = "a `{Self}` cannot be built from the field's own context", + note = "the record gives each field a context of its own: the record's scope, then the field's name. Implement `ContextFromField` for `{Self}` to store that context" +)] +pub trait ContextFromField: Sized { + /// The context this type stores for a field whose own context is + /// `own`, or `None` when this type cannot store `own`. + fn from_field(own: &ContextPiece<'_>) -> Option>; } macro_rules! integer_contexts { @@ -1085,6 +1273,171 @@ mod tests { ); } + /// A stored context of two text parts, for the tests of a field type + /// that stores its context. + #[derive(Clone, Debug, PartialEq)] + struct Pair(String, String); + impl MaybeEmpty for Pair { + fn is_empty(&self) -> bool { + self.0.is_empty() || self.1.is_empty() + } + } + impl<'a> IntoContext<'a> for Pair { + fn into_context(self) -> ContextPiece<'a> { + ContextPiece::List(vec![text(&self.0), text(&self.1)]) + } + } + fn pair_of(own: &ContextPiece<'_>) -> Option<(String, String)> { + let ContextPiece::List(parts) = own else { + return None; + }; + let [ContextPiece::Text(first), ContextPiece::Text(second)] = parts.as_slice() else { + return None; + }; + Some((first.to_string(), second.to_string())) + } + impl ContextFromField for Pair { + fn from_field(own: &ContextPiece<'_>) -> Option> { + let (first, second) = pair_of(own)?; + NonEmpty::new(Self(first, second)).ok() + } + } + + /// A stored context that does not encode as the field's own context + /// does: it swaps the two parts. + #[derive(Clone, Debug, PartialEq)] + struct Swapped(Pair); + impl MaybeEmpty for Swapped { + fn is_empty(&self) -> bool { + self.0.is_empty() + } + } + impl<'a> IntoContext<'a> for Swapped { + fn into_context(self) -> ContextPiece<'a> { + self.0.into_context() + } + } + impl ContextFromField for Swapped { + fn from_field(own: &ContextPiece<'_>) -> Option> { + let (first, second) = pair_of(own)?; + NonEmpty::new(Self(Pair(second, first))).ok() + } + } + + fn not_storable(error: Error) -> String { + match error { + Error::Plan(crate::plan::PlanError::ContextNotStorable { field }) => field, + other => panic!("expected ContextNotStorable, got {other:?}"), + } + } + + /// A field stores its own context, and runs under the whole context + /// the record gives it: the scopes and the bindings come after the own + /// context, and are not stored. + #[test] + fn a_field_stores_its_own_context_and_runs_under_the_whole_one() { + let own = || nonempty!("users").with("email"); + let field = DeclaredContext::default() + .with(CallerContext::from(Scope::new(7u64).bind(9u128))) + .under(own()); + let (stored, context) = StoredContext::::from(field.clone()) + .into_parts() + .unwrap(); + assert_eq!(stored, Pair("users".into(), "email".into())); + assert_eq!(context.query(), field.query()); + assert_eq!(context.stored(), field.stored()); + assert_ne!(context.stored(), stored.clone().into_context()); + + // On decrypt the stored context must be the field's own, and the + // field opens under the same whole context. + let opening = ExpectedContext::::from(field.clone()) + .opening(stored) + .unwrap(); + assert_eq!(opening.stored(), field.stored()); + let elsewhere = ExpectedContext::::from(field) + .opening(Pair("users".into(), "name".into())) + .unwrap_err(); + assert!(matches!(elsewhere, Error::ContextMismatch { .. })); + } + + /// On its own, a record stores the context the caller passes, and runs + /// under it. + #[test] + fn a_context_passed_on_its_own_is_stored_and_is_the_whole_context() { + let passed = NonEmpty::new(Pair("users".into(), "email".into())).unwrap(); + let (stored, context) = StoredContext::from(passed.clone()).into_parts().unwrap(); + assert_eq!(stored, *passed.get()); + assert_eq!(context.stored(), passed.clone().into_context()); + + let opening = ExpectedContext::from(passed.clone()) + .opening(stored) + .unwrap(); + assert_eq!(opening.stored(), passed.into_context()); + } + + /// A type that cannot store the field's own context is refused, and the + /// refusal names that context. So is a type whose stored context + /// encodes differently from it: the row would name one context while + /// the field ran under another. + #[test] + fn an_own_context_the_type_cannot_store_is_refused() { + let three = DeclaredContext::default().under(nonempty!("users").with("email").with("x")); + let refused = StoredContext::::from(three.clone()) + .into_parts() + .unwrap_err(); + assert_eq!(not_storable(refused), "(users/email)/x"); + let stored = Pair("users".into(), "email".into()); + let refused = ExpectedContext::::from(three) + .opening(stored.clone()) + .unwrap_err(); + assert_eq!(not_storable(refused), "(users/email)/x"); + + let field = DeclaredContext::default().under(nonempty!("users").with("email")); + let refused = StoredContext::::from(field.clone()) + .into_parts() + .unwrap_err(); + assert_eq!(not_storable(refused), "users/email"); + let refused = ExpectedContext::::from(field) + .opening(Swapped(stored)) + .unwrap_err(); + assert_eq!(not_storable(refused), "users/email"); + } + + /// A context that no record built for a field has no own part to store. + /// The refusal names the context the type was given. + #[test] + fn a_context_not_built_for_a_field_has_nothing_to_store() { + let caller = CallerContext::from(Scope::new(7u64)); + let refused = StoredContext::::from(caller) + .into_parts() + .unwrap_err(); + assert_eq!(not_storable(refused), "7u64"); + } + + /// The own context is the field's, whatever the parts that follow it + /// were built for: a record nested in another passes its fields the + /// outer field's context, which has an own part too. + #[test] + fn the_own_context_of_a_nested_field_is_the_inner_one() { + let outer = DeclaredContext::default().under(nonempty!("teams").with("lead")); + let inner = DeclaredContext::from(outer).under(nonempty!("users").with("email")); + let (stored, context) = StoredContext::::from(inner).into_parts().unwrap(); + assert_eq!(stored, Pair("users".into(), "email".into())); + assert_eq!( + context.query(), + nest( + nonempty!("users").with("email").into_context().into_owned(), + nonempty!("teams").with("lead").into_context().into_owned(), + ) + ); + + // `extend` puts its own context first too. + let extended = + CallerContext::from(Scope::new(7u64)).extend(nonempty!("users").with("email")); + let (stored, _) = StoredContext::::from(extended).into_parts().unwrap(); + assert_eq!(stored, Pair("users".into(), "email".into())); + } + #[test] fn a_declared_context_knows_whether_it_carries_a_binding() { assert!(!DeclaredContext::from(Scope::new(7u64)).has_bindings()); diff --git a/packages/stack-encrypt/src/target/input.rs b/packages/stack-encrypt/src/target/input.rs index 5bbf6e18fa..991ad6e659 100644 --- a/packages/stack-encrypt/src/target/input.rs +++ b/packages/stack-encrypt/src/target/input.rs @@ -6,6 +6,7 @@ //! | [`RequiredContext`] | Refused | `C` | The caller supplies the context, or the part of it that the declaration selects. | //! | [`OptionalContext`] | Allowed | `C` | For an opaque scalar. A context left out is the empty context. | //! | [`DeclaredScopes`] | Allowed | Refused | A derived `struct = ..` record. Each field has its own context. A record that contains it, or a plan, passes that field's context. | +//! | The encrypt input of a `#[stash(context_field)]` record | Refused | `NonEmpty` | The record stores the context passed. | //! | The decrypt input of a `#[stash(context_field)]` record | Allowed | `NonEmpty` | A context left out opens under the stored context, unchecked. A context passed is checked against the stored one. | //! //! A trait bound decides whether a method is available ([`AllowsNoContext`] @@ -13,8 +14,8 @@ //! example, `RequiredContext` stays required, although `u64` has a //! default of zero. -use super::context::{CallerContext, DeclaredContext, ExpectedContext, FromFieldContext}; -use crate::{ContextPiece, Error, IntoContext, NonEmpty}; +use super::context::{CallerContext, DeclaredContext, ExpectedContext, StoredContext}; +use crate::{ContextPiece, IntoContext, NonEmpty}; mod sealed { pub trait Sealed {} @@ -145,51 +146,6 @@ impl> From for RequiredContext { } } -/// The context a record field's declaration takes, built from the context -/// the record gives the field. [`Encryption::under`](super::Encryption::under) -/// converts through it. -/// -/// A context that converts from a [`CallerContext`] cannot fail. A field -/// type that stores its context ([`FromFieldContext`]) can refuse the one -/// the record gives it, before any key is requested. -/// -/// **This trait is for generated code.** A field type implements -/// [`FromFieldContext`], not this. -#[doc(hidden)] -#[diagnostic::on_unimplemented( - message = "a field whose type takes `{Self}` cannot be a field of a `struct = ..` record", - label = "this field's type cannot take the context the record gives it", - note = "the record gives each field its scope and the field's name as a `CallerContext`; a field's type takes it if its context input converts from `CallerContext`, or is `RequiredContext>` where `T` implements `FromFieldContext`" -)] -pub trait FromCaller: Sized { - /// Convert the field's context, or refuse it. - /// - /// # Errors - /// - /// [`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable) - /// when the field's type cannot store the context. - fn from_caller(context: CallerContext) -> Result; -} -impl> FromCaller for C { - fn from_caller(context: CallerContext) -> Result { - Ok(C::from(context)) - } -} -// A field whose type stores its context takes the record's context for the -// field as that type, or refuses it. -// -// This impl and the blanket one above do not overlap only because -// `RequiredContext>` does not implement `From`. -// The `From` impl for `RequiredContext` needs -// `C: From`, and `NonEmpty` has no such impl. Adding one -// would stop this from compiling. -impl FromCaller for RequiredContext> { - fn from_caller(context: CallerContext) -> Result { - T::from_field_context(&context) - .map(Self::supplied) - .ok_or_else(|| context.not_storable()) - } -} // A record that derives terms gives its ciphertext fields the AEAD part of the // context it requires. impl From> for RequiredContext { @@ -197,28 +153,6 @@ impl From> for RequiredContext` it stores. It runs its fields under the caller context built -// from that value. -impl<'c, T: IntoContext<'c>> From>> for RequiredContext { - fn from(context: RequiredContext>) -> Self { - Self::supplied(context.into_inner().into()) - } -} -impl<'c, T: IntoContext<'c>> From>> - for RequiredContext -{ - fn from(context: RequiredContext>) -> Self { - Self::supplied(context.into_inner().into()) - } -} -// A record that stores its context takes the `NonEmpty` it stores from its -// structural trait as the required input. -impl From> for RequiredContext> { - fn from(context: NonEmpty) -> Self { - Self::supplied(context) - } -} // The contexts of the structural declarations, wrapped as the required input // of the owned leaf that replaces each one. A plan or a structural record // gives an owned field its context this way. @@ -242,8 +176,23 @@ impl> From> for CallerContext { } } -/// The input of a record that stores its context: the context the caller -/// expects, or none. +/// The encrypt input of a record that stores its context: the context the +/// caller passes, which the record stores. The context is required. +/// +/// As a field of a `struct = ..` record, the record stores the field's own +/// context instead, and runs under the scopes and bindings of the record +/// too ([`ContextFromField`](super::ContextFromField)). +impl sealed::Sealed for StoredContext {} +impl ContextInput for StoredContext {} +impl<'c, T: Clone + IntoContext<'c>> AcceptsContext for StoredContext { + type Value = NonEmpty; + fn supplied(value: NonEmpty) -> Self { + Self::from(value) + } +} + +/// The decrypt input of a record that stores its context: the context the +/// caller expects, or none. /// /// - If the caller passes a `NonEmpty`, the stored context must equal it. A /// different stored context is refused before any key is retrieved. diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index 0e526f9f14..c54307b6dd 100644 --- a/packages/stack-encrypt/src/target/mod.rs +++ b/packages/stack-encrypt/src/target/mod.rs @@ -183,25 +183,26 @@ pub mod transcode; mod tuples; pub(crate) use self::core::{bind_pending, seal_pending}; -/// The check that a `#[stash(context_field)]` record runs on decrypt. -/// -/// `ExpectedContext` is not part of the API. Only the derives and the EQL -/// types name it, and a caller passes a `NonEmpty` or nothing. The type -/// is public only because the derives emit code in other crates that -/// names it. The definition is hidden too. -#[doc(hidden)] -pub use context::ExpectedContext; pub use context::{ - AeadContext, Bind, BindPart, CallerContext, CheckedInput, DeclaredContext, Extends, - FromFieldContext, NoBind, NoScope, Parts, Scope, ScopePart, Scopes, StoredParts, + AeadContext, Bind, BindPart, CallerContext, CheckedInput, ContextFromField, DeclaredContext, + Extends, NoBind, NoScope, Parts, Scope, ScopePart, Scopes, StoredParts, }; +/// The inputs of a `#[stash(context_field)]` record: the context it stores +/// on encrypt, and the check it runs on decrypt. +/// +/// `StoredContext` and `ExpectedContext` are not part of the API. Only the +/// derives and the EQL types name them, and a caller passes a `NonEmpty` +/// or nothing. They are public only because the derives emit code in other +/// crates that names them. The definitions are hidden too. +#[doc(hidden)] +pub use context::{ExpectedContext, StoredContext}; pub use conversion::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget}; pub use index::{ indexed, At, Encrypted, Equality, Index, IndexSpec, Indexes, Json, Match, Ope, Ore, OreBlock, Select, TermSet, Whole, }; pub use input::{ - AcceptsContext, AllowsNoContext, ContextInput, DeclaredScopes, FromCaller, NoCallerContext, + AcceptsContext, AllowsNoContext, ContextInput, DeclaredScopes, NoCallerContext, OptionalContext, RequiredContext, ScalarContext, }; #[cfg(feature = "dynamic")] diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index a9ea28e95b..077d746e72 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -14,11 +14,13 @@ // One context per target, threaded through the declaration tree: // packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md. -use super::context::{AeadContext, CallerContext, DeclaredContext, Extends, StoredParts}; +use super::context::{ + AeadContext, CallerContext, DeclaredContext, Extends, StoredContext, StoredParts, +}; use super::conversion::{DecryptSource, EncryptTarget}; use super::core::{encrypt_native, open_native, Term}; use super::index::{Index, IndexSpec, Json}; -use super::input::{AcceptsContext, FromCaller, NoCallerContext, RequiredContext}; +use super::input::{AcceptsContext, NoCallerContext, RequiredContext}; use super::source::{Borrowed, ConsumeSource, Owned, ShareSource, SourceMode}; use super::{CipherRef, Pending}; use crate::contexts::{self, Contexts, Placeholder, Shape, Shapes, SuppliedContext}; @@ -358,21 +360,64 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> /// its own cannot be run under `()`. Available wherever a /// [`CallerContext`] can become what the subtree needs: a leaf of either /// kind, or a record whose own contexts a caller's extends. + /// + /// A part the caller passed empty is refused here, before the subtree + /// runs. In [`Owned`] mode that refusal drops the plaintext without + /// wiping it, because `S` need not be `Zeroize`. A derived record wipes + /// it instead. pub fn under( + self, + own: NonEmpty + MaybeSend + 's>, + ) -> Encryption<'s, S, T, K, DeclaredContext, M> + where + Ctx: From, + { + self.under_refusing(own, drop) + } + /// [`under`](Self::under), for a field of a derived `struct = ..` + /// record. A context that is refused here wipes a plaintext that was + /// passed by value. `under` drops it as it is. + /// + /// **This method is for generated code.** The derive emits it for each + /// sealed field, in the borrowed form and in the owned form. The + /// plaintext is `Zeroize`, as the source of every + /// [`EncryptTarget`] is. + #[doc(hidden)] + pub fn under_field( + self, + own: NonEmpty + MaybeSend + 's>, + ) -> Encryption<'s, S, T, K, DeclaredContext, M> + where + Ctx: From, + S: zeroize::Zeroize, + { + self.under_refusing(own, |source| { + M::release(source, |value| { + drop(vitaminc_protected::Protected::new(value)) + }) + }) + } + /// The body of [`under`](Self::under). `refused` is given the source + /// when the context is refused, before the subtree has seen it. + fn under_refusing( mut self, own: NonEmpty + MaybeSend + 's>, + refused: fn(M::Source), ) -> Encryption<'s, S, T, K, DeclaredContext, M> where - Ctx: FromCaller, + Ctx: From, { let own = contexts::piece_of(own); self.shapes = contexts::substitute(self.shapes, &Shape::under(own.get().clone())); let Self { build, shapes } = self; Encryption { build: Box::new(move |source, cipher, cx: DeclaredContext| { - match cx.checked_under(own).and_then(Ctx::from_caller) { - Ok(context) => build(source, cipher, context), - Err(error) => Pending::failed(cipher, error), + match cx.checked_under(own) { + Ok(context) => build(source, cipher, context.into()), + Err(error) => { + refused(source); + Pending::failed(cipher, error) + } } }), shapes, @@ -468,6 +513,45 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { shapes, } } + /// Store the context this description runs under, for a record that + /// writes its context into the row (`#[stash(context_field)]`). + /// + /// The result takes a [`StoredContext`]: the context to store, and the + /// context to run under. `store` builds the output from this + /// description's output and the context to store. + /// + /// - On its own, the record stores the context the caller passes, and + /// runs under it. + /// - As a field of a `struct = ..` record, it stores the field's own + /// context, and runs under the scopes and bindings of the record too. + /// + /// A field whose type cannot store the field's own context fails here, + /// before any key is requested + /// ([`PlanError::ContextNotStorable`](crate::PlanError::ContextNotStorable)). + /// The plaintext is borrowed, so the refusal drops no plaintext. + /// + /// **This method is for generated code.** The derive emits it at the + /// root of a `#[stash(context_field)]` record. + #[doc(hidden)] + pub fn storing(self, store: F) -> Encryption<'s, S, U, K, StoredContext> + where + Ctx: From, + C: MaybeSend + 'static, + F: FnOnce(T, C) -> U + MaybeSend + 'static, + { + let Self { build, shapes } = self; + Encryption { + build: Box::new( + move |source, cipher, cx: StoredContext| match cx.into_parts() { + Ok((stored, context)) => { + build(source, cipher, context.into()).map(move |value| store(value, stored)) + } + Err(error) => Pending::failed(cipher, error), + }, + ), + shapes, + } + } /// Takes the context from a field of the plaintext. The caller then /// supplies no context. /// diff --git a/packages/stack-encrypt/tests/field_context.rs b/packages/stack-encrypt/tests/field_context.rs index 4e8f112d0c..14efc035a7 100644 --- a/packages/stack-encrypt/tests/field_context.rs +++ b/packages/stack-encrypt/tests/field_context.rs @@ -1,26 +1,30 @@ //! A field type that stores its context, as a field of a derived `struct = -//! ..` record (`FromFieldContext`). +//! ..` record (`ContextFromField`). //! -//! The record gives each field its scope and the field's name. A field type -//! that stores a table and a column takes that pair as the context it -//! stores, as an EQL type in `eql-bindings` does. Here `Column` stands in -//! for EQL's `Identifier`: +//! The record gives each field a context of its own: the record's scope, +//! then the field's name. A field type that stores a table and a column +//! stores that pair, as an EQL type in `eql-bindings` does. Here `Column` +//! stands in for EQL's `Identifier`: //! -//! - the field stores the pair, and writes the term it writes on its own -//! under that column; +//! - the field stores its own context, and writes the term it writes on its +//! own under that column; //! - on decrypt, the stored column must be the field's; -//! - a record that lists a caller scope or a binding gives the field a -//! context it cannot store, and every call is refused before any key is -//! requested. +//! - a scope or a binding that the record lists comes after the own +//! context. The field runs under it, as a field of any other type does, +//! and does not store it. The reader supplies it again; +//! - a field of a record nested in another stores its own context too; +//! - a type that cannot store the field's own context is refused before any +//! key is requested. use std::sync::atomic::Ordering; use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::{ - Bind, CallerContext, DecryptSource, EncryptTarget, FromFieldContext, Scope, + Bind, CallerContext, ContextFromField, DecryptField, DecryptSource, EncryptTarget, Encryption, + NoCallerContext, Scope, }; use stack_encrypt::{ - Ciphertext, ContextPiece, DecryptFrom, EncryptInto, Error, IntoContext, MaybeEmpty, NonEmpty, - PlanError, + nonempty, Ciphertext, ContextPiece, DecryptFrom, Descriptor, EncryptInto, Encrypted, Error, + IntoContext, MaybeEmpty, NonEmpty, PlanError, }; use zeroize::Zeroize; mod common; @@ -58,12 +62,9 @@ impl<'a> IntoContext<'a> for Column { } } -impl FromFieldContext for Column { - fn from_field_context(context: &CallerContext) -> Option> { - if context.has_bindings() { - return None; - } - let ContextPiece::List(parts) = context.query() else { +impl ContextFromField for Column { + 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 { @@ -98,35 +99,25 @@ fn ada() -> User { } } -#[derive(EncryptTarget, DecryptSource)] -#[stash(struct = User, scope = "users")] -struct EncryptedUser { - email: Stored, -} - -#[derive(EncryptTarget, DecryptSource)] -#[stash(struct = User, scope = "users", scope(tenant: u64))] -struct TenantUser { - email: Stored, +/// A user's email on its own under the `users/email` column, with no record +/// around it. +async fn alone(keyset: &stack_encrypt::KeysetCipher<'_, K>) -> Stored +where + K: stack_encrypt::kms::DataKeySource + stack_encrypt::kms::IndexKeySource + Sync + 'static, +{ + ada() + .email + .encrypt_into_with_context(keyset, Column::of("users", "email")) + .await + .unwrap() } #[derive(EncryptTarget, DecryptSource)] -#[stash(struct = User, scope = "users", bind(row: u128))] -struct BoundUser { +#[stash(struct = User, scope = "users")] +struct EncryptedUser { email: Stored, } -/// The refusal names the field by the record's scope and its name. -fn assert_not_storable(result: Result) { - match result { - Err(Error::Plan(PlanError::ContextNotStorable { field })) => { - assert_eq!(field, "users/email"); - } - Err(other) => panic!("expected ContextNotStorable, got {other:?}"), - Ok(_) => panic!("expected ContextNotStorable, got a value"), - } -} - #[tokio::test] async fn a_field_stores_the_record_scope_and_its_name() { let cipher = common::stack_cipher().await; @@ -135,11 +126,7 @@ async fn a_field_stores_the_record_scope_and_its_name() { assert_eq!(stored.email.column, *Column::of("users", "email").get()); // The term the field writes on its own under the column. - let alone: Stored = ada() - .email - .encrypt_into_with_context(&keyset, Column::of("users", "email")) - .await - .unwrap(); + let alone = alone(&keyset).await; assert_eq!(stored.email.hm, alone.hm); let opened = User::decrypt_from(stored, &keyset).await.unwrap(); @@ -168,34 +155,266 @@ async fn a_field_that_stores_another_column_is_refused() { assert_eq!(retrieves.load(Ordering::SeqCst), before, "no key requested"); } +// --- A scope and a binding come after the own context, and are not stored --- + +/// The caller supplies a tenant scope and a row binding. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(tenant: u64), bind(row: u128))] +struct TenantUser { + email: Stored, +} + +/// The same record with a field type that stores nothing: the term and the +/// ciphertext, under the context the record gives the field. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users", scope(tenant: u64), bind(row: u128))] +struct NativeTenantUser { + email: Encrypted, +} + #[tokio::test] -async fn a_caller_scope_or_binding_is_refused_before_any_key() { - let (cipher, generates, retrieves) = common::counting_cipher().await; +async fn a_scope_and_a_binding_are_used_and_not_stored() { + let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); + let parts = || Scope::new(42u64).bind(9u128); + let stored: TenantUser = ada() + .encrypt_into_with_context(&keyset, parts()) + .await + .unwrap(); - let scoped: Result = ada() - .encrypt_into_with_context(&keyset, Scope::new(42u64)) - .await; - assert_not_storable(scoped); - let bound: Result = ada() - .encrypt_into_with_context(&keyset, Bind::new(9u128)) - .await; - assert_not_storable(bound); - assert_eq!(generates.load(Ordering::SeqCst), 0, "no key requested"); + // Only the field's own context is stored. + assert_eq!(stored.email.column, *Column::of("users", "email").get()); - // A value stored under the field's own column does not open in such a - // record either: the record's context is not the one it stores. - let alone: Stored = ada() + // The term derives under the tenant too, as a field of any other type + // does. So it is not the term of the column alone. + let native: NativeTenantUser = ada() + .encrypt_into_with_context(&keyset, parts()) + .await + .unwrap(); + assert_eq!(stored.email.hm, native.email.terms); + assert_ne!(stored.email.hm, alone(&keyset).await.hm); + + // The binding is in no query context: another row has the same term. + let other_row: TenantUser = ada() + .encrypt_into_with_context(&keyset, Scope::new(42u64).bind(10u128)) + .await + .unwrap(); + assert_eq!(stored.email.hm, other_row.email.hm); + // Another tenant has another term. + let other_tenant: TenantUser = ada() + .encrypt_into_with_context(&keyset, Scope::new(43u64).bind(9u128)) + .await + .unwrap(); + assert_ne!(stored.email.hm, other_tenant.email.hm); + + // The reader supplies the scope and the binding again. + let opened = User::decrypt_from_with_context(stored, &keyset, parts()) + .await + .unwrap(); + assert_eq!(opened, ada()); +} + +#[tokio::test] +async fn a_field_opens_only_under_the_scope_and_binding_it_was_sealed_under() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = || async { + let stored: TenantUser = ada() + .encrypt_into_with_context(&keyset, Scope::new(42u64).bind(9u128)) + .await + .unwrap(); + stored + }; + + let other_tenant = + User::decrypt_from_with_context(sealed().await, &keyset, Scope::new(43u64).bind(9u128)); + assert!(other_tenant.await.is_err(), "another tenant"); + let other_row = + User::decrypt_from_with_context(sealed().await, &keyset, Scope::new(42u64).bind(10u128)); + assert!(other_row.await.is_err(), "another row"); + + // A value written on its own stores the same column. It was sealed + // under the column alone, so it does not open as the record's field. + let record = TenantUser { + email: alone(&keyset).await, + }; + let opened = User::decrypt_from_with_context(record, &keyset, Scope::new(42u64).bind(9u128)); + assert!(opened.await.is_err(), "sealed without the scope"); + + // The stored column is still checked first, before any key. + let elsewhere: Stored = ada() .email - .encrypt_into_with_context(&keyset, Column::of("users", "email")) + .encrypt_into_with_context(&keyset, Column::of("users", "name")) .await .unwrap(); + let record = TenantUser { email: elsewhere }; let before = retrieves.load(Ordering::SeqCst); - let scoped = TenantUser { - email: alone.clone(), + assert!(matches!( + User::decrypt_from_with_context(record, &keyset, Scope::new(42u64).bind(9u128)).await, + Err(Error::ContextMismatch { .. }) + )); + assert_eq!(retrieves.load(Ordering::SeqCst), before, "no key requested"); +} + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct Account { + id: u128, + tenant: u64, + email: String, +} + +/// The scope and the binding are stored in the row, in fields of the +/// record. The field that stores its context still stores its own alone. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Account, scope = "accounts", scope(field = "tenant"), bind(field = "id"))] +struct EncryptedAccount { + #[stash(passthrough)] + id: u128, + #[stash(passthrough)] + tenant: u64, + email: Stored, +} + +#[tokio::test] +async fn a_scope_and_a_binding_stored_in_the_row_are_not_stored_in_the_field() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let account = Account { + id: 9, + tenant: 42, + email: "ada@example.com".into(), + }; + let stored: EncryptedAccount = account.clone().encrypt_into(&keyset).await.unwrap(); + assert_eq!(stored.email.column, *Column::of("accounts", "email").get()); + + // The row supplies its scope and its binding, so the reader passes none. + let moved = EncryptedAccount { + id: 10, + tenant: stored.tenant, + email: stored.email.clone(), }; - assert_not_storable(User::decrypt_from_with_context(scoped, &keyset, Scope::new(42u64)).await); - let bound = BoundUser { email: alone }; - assert_not_storable(User::decrypt_from_with_context(bound, &keyset, Bind::new(9u128)).await); + assert_eq!( + Account::decrypt_from(stored, &keyset).await.unwrap(), + account + ); + // The same field in another row does not open. + assert!(Account::decrypt_from(moved, &keyset).await.is_err()); +} + +#[derive(Clone, Debug, PartialEq, Zeroize)] +struct Team { + lead: User, +} + +/// A record that holds another. The inner field's context is its own pair, +/// then the outer field's. +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = Team, scope = "teams")] +struct EncryptedTeam { + lead: EncryptedUser, +} + +#[tokio::test] +async fn a_field_of_a_nested_record_stores_its_own_context() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let team = Team { lead: ada() }; + let stored: EncryptedTeam = team.clone().encrypt_into(&keyset).await.unwrap(); + + // The inner record's scope and the field's name. The outer record's + // names come after them, and are not stored. + assert_eq!( + stored.lead.email.column, + *Column::of("users", "email").get() + ); + assert_ne!(stored.lead.email.hm, alone(&keyset).await.hm); + + assert_eq!(Team::decrypt_from(stored, &keyset).await.unwrap(), team); +} + +// --- A context the type cannot store ---------------------------------------- + +/// `Stored`, under an own context of three parts. A `Column` stores two. +struct Misplaced(#[allow(dead_code)] Stored); +impl EncryptTarget for Misplaced { + type ContextInput = NoCallerContext; + fn encryption<'s, K: 'static>() -> Encryption<'s, String, Self, K, Self::ContextInput> { + >::encryption() + .under(nonempty!("users").with("email").with("work")) + .map(Self) + .accepting() + } +} + +/// The refusal names the context the type could not store. +fn assert_not_storable(result: Result, named: &str) { + match result { + Err(Error::Plan(PlanError::ContextNotStorable { field })) => assert_eq!(field, named), + Err(other) => panic!("expected ContextNotStorable, got {other:?}"), + Ok(_) => panic!("expected ContextNotStorable, got a value"), + } +} + +#[tokio::test] +async fn an_own_context_the_type_cannot_store_is_refused_before_any_key() { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let own = Descriptor::of(nonempty!("users").with("email").with("work")); + + let sealed: Result = ada().email.encrypt_into(&keyset).await; + assert_not_storable(sealed, own.as_str()); + assert_eq!(generates.load(Ordering::SeqCst), 0, "no key requested"); + + // The same on decrypt: no stored column can be the field's own. + let stored = alone(&keyset).await; + let before = retrieves.load(Ordering::SeqCst); + let context = + CallerContext::from(Scope::new(7u64)).extend(nonempty!("users").with("email").with("work")); + let opening = + >::decryption_field(stored.clone(), context).unwrap(); + assert_not_storable(cipher.run_decryption(opening).await, own.as_str()); + + // A context that no record built for a field has no own part. The + // refusal names the context the type was given. + let opening = >::decryption_field( + stored, + CallerContext::from(Scope::new(7u64)), + ) + .unwrap(); + assert_not_storable(cipher.run_decryption(opening).await, "7u64"); assert_eq!(retrieves.load(Ordering::SeqCst), before, "no key requested"); } + +/// A scope or a binding alone, with no field that stores its context, is +/// unchanged by all this: the record still requires it. +#[tokio::test] +async fn a_binding_alone_still_binds_the_field() { + #[derive(EncryptTarget, DecryptSource)] + #[stash(struct = User, scope = "users", bind(row: u128))] + struct BoundUser { + email: Stored, + } + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let stored: BoundUser = ada() + .encrypt_into_with_context(&keyset, Bind::new(9u128)) + .await + .unwrap(); + assert_eq!(stored.email.column, *Column::of("users", "email").get()); + // A binding is in no query context, so the term is the column's. + assert_eq!(stored.email.hm, alone(&keyset).await.hm); + + let moved = BoundUser { + email: stored.email.clone(), + }; + assert!( + User::decrypt_from_with_context(moved, &keyset, Bind::new(10u128)) + .await + .is_err(), + "another row" + ); + let opened = User::decrypt_from_with_context(stored, &keyset, Bind::new(9u128)) + .await + .unwrap(); + assert_eq!(opened, ada()); +} diff --git a/packages/stack-encrypt/tests/owned_records.rs b/packages/stack-encrypt/tests/owned_records.rs index 0076f9c43c..1cf16006b3 100644 --- a/packages/stack-encrypt/tests/owned_records.rs +++ b/packages/stack-encrypt/tests/owned_records.rs @@ -14,9 +14,9 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use stack_encrypt::sem::{EqualityTerm, MatchTerms, OreTerm}; use stack_encrypt::target::{ - AcceptsContext, AeadContext, DecryptField, DecryptSource, Decryptable, Decryption, + AcceptsContext, AeadContext, Bind, DecryptField, DecryptSource, Decryptable, Decryption, EncryptTarget, Encryption, NoCallerContext, OptionalContext, Owned, RequiredContext, - ScalarContext, + ScalarContext, Scope, }; use stack_encrypt::{ nonempty, Ciphertext, Controlled, DecryptFrom, EncryptInto, Encrypted, Error, NonEmpty, @@ -441,6 +441,53 @@ async fn a_sealed_field_is_not_leaked_when_the_scope_is_refused() { .await; } +/// A record whose caller supplies a scope. An empty scope is refused where +/// the field is given its context, before the field's own target runs. +#[allow(dead_code)] // These tests only encrypt. +#[derive(EncryptTarget)] +#[stash(struct = ProbeRow, scope = "rows", scope(tenant: String))] +struct TenantProbeRow { + secret: StackCipherText, +} + +#[tokio::test] +async fn a_sealed_field_is_not_leaked_when_a_caller_part_is_empty() { + assert_refused_without_a_leak(|leaked, keyset| { + ProbeRow { + secret: probe(leaked), + } + .encrypt_into_with_context::(keyset, Scope::new(String::new())) + }) + .await; +} + +#[derive(Zeroize)] +struct ProbePair { + first: Probe, + second: Probe, +} +/// Two sealed fields: the record divides the plaintext between them, and +/// each is refused in turn. +#[allow(dead_code)] // These tests only encrypt. +#[derive(EncryptTarget)] +#[stash(struct = ProbePair, scope = "pairs", bind(row: String))] +struct BoundProbePair { + first: StackCipherText, + second: StackCipherText, +} + +#[tokio::test] +async fn no_sealed_field_is_leaked_when_a_caller_part_is_empty() { + assert_refused_without_a_leak(|leaked, keyset| { + ProbePair { + first: probe(leaked), + second: probe(leaked), + } + .encrypt_into_with_context::(keyset, Bind::new(String::new())) + }) + .await; +} + #[tokio::test] async fn a_nested_sealed_field_is_not_leaked_when_the_outer_scope_is_refused() { assert_refused_without_a_leak(|leaked, keyset| { diff --git a/packages/stack-encrypt/tests/ui/owned_aead_record_with_term.stderr b/packages/stack-encrypt/tests/ui/owned_aead_record_with_term.stderr index 5e130aaf90..d73640a1be 100644 --- a/packages/stack-encrypt/tests/ui/owned_aead_record_with_term.stderr +++ b/packages/stack-encrypt/tests/ui/owned_aead_record_with_term.stderr @@ -7,13 +7,22 @@ error[E0277]: the trait bound `RequiredContext: From>` is not implemented for `RequiredContext` - but trait `From>>` is implemented for it +help: the following other types implement trait `From` --> src/target/input.rs | - | impl<'c, T: IntoContext<'c>> From>> for RequiredContext { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = help: for that trait implementation, expected `NonEmpty<_>`, found `AeadContext` + | impl> From for RequiredContext { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RequiredContext` implements `From` +... + | impl From> for RequiredContext { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RequiredContext` implements `From>` +... + | impl From for RequiredContext { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RequiredContext` implements `From` + | + ::: src/target/context.rs + | + | impl From> for super::input::RequiredContext> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RequiredContext>` implements `From>` = note: required for `RequiredContext` to implement `Into>` note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::accepting` --> src/target/operations.rs diff --git a/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr b/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr index 9c21f46407..fef2ec6183 100644 --- a/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr +++ b/packages/stack-encrypt/tests/ui/owned_record_field_context.stderr @@ -1,25 +1,17 @@ -error[E0277]: a field whose type takes `NoCallerContext` cannot be a field of a `struct = ..` record +error[E0277]: the trait bound `NoCallerContext: From` is not satisfied --> tests/ui/owned_record_field_context.rs:54:12 | 54 | fixed: Fixed, - | ^^^^^ this field's type cannot take the context the record gives it + | ^^^^^ the trait `From` is not implemented for `NoCallerContext` | - = help: the trait `From` is not implemented for `NoCallerContext` - = note: the record gives each field its scope and the field's name as a `CallerContext`; a field's type takes it if its context input converts from `CallerContext`, or is `RequiredContext>` where `T` implements `FromFieldContext` -help: the trait `FromCaller` is implemented for `RequiredContext>` - --> src/target/input.rs - | - | impl FromCaller for RequiredContext> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: required for `NoCallerContext` to implement `FromCaller` -note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under` +note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` --> src/target/operations.rs | - | pub fn under( - | ----- required by a bound in this associated function + | pub fn under_field( + | ----------- required by a bound in this associated function ... - | Ctx: FromCaller, - | ^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` + | Ctx: From, + | ^^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` error[E0277]: the trait bound `u64: From` is not satisfied --> tests/ui/owned_record_field_context.rs:55:12 @@ -38,12 +30,11 @@ error[E0277]: the trait bound `u64: From` is not satisfied `u64` implements `From` and $N others = note: required for `RequiredContext` to implement `From` - = note: required for `RequiredContext` to implement `FromCaller` -note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under` +note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` --> src/target/operations.rs | - | pub fn under( - | ----- required by a bound in this associated function + | pub fn under_field( + | ----------- required by a bound in this associated function ... - | Ctx: FromCaller, - | ^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under` + | Ctx: From, + | ^^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` diff --git a/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.rs b/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.rs new file mode 100644 index 0000000000..c090c73f27 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.rs @@ -0,0 +1,30 @@ +//! A field type that stores its context (`#[stash(context_field)]`) can be a +//! field of a `struct = ..` record only when the stored type can be built +//! from the field's own context (`ContextFromField`). A `String` cannot, so +//! the field is a compile error. +use stack_encrypt::sem::EqualityTerm; +use stack_encrypt::target::{DecryptSource, EncryptTarget}; +use stack_encrypt::Ciphertext; + +/// A value that stores its context as text. +#[derive(EncryptTarget, DecryptSource)] +#[stash(plaintext = String)] +struct Stored { + #[stash(context_field)] + column: String, + c: Ciphertext, + hm: EqualityTerm, +} + +#[derive(zeroize::Zeroize)] +struct User { + email: String, +} + +#[derive(EncryptTarget, DecryptSource)] +#[stash(struct = User, scope = "users")] +struct EncryptedUser { + email: Stored, +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.stderr b/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.stderr new file mode 100644 index 0000000000..a7cab809a6 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/owned_record_field_stores_context.stderr @@ -0,0 +1,52 @@ +error[E0277]: a field whose type stores a `std::string::String` as its context cannot be a field of a `struct = ..` record + --> tests/ui/owned_record_field_stores_context.rs:27:12 + | +27 | email: Stored, + | ^^^^^^ a `std::string::String` cannot be built from the field's own context + | + = help: the trait `ContextFromField` is not implemented for `std::string::String` + = note: the record gives each field a context of its own: the record's scope, then the field's name. Implement `ContextFromField` for `std::string::String` to store that context +help: the following other types implement trait `From` + --> src/target/context.rs + | + | impl<'c, T: Clone + IntoContext<'c>> From> for StoredContext { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `StoredContext` implements `From>` +... + | / impl<'c, T> From for StoredContext + | | where + | | T: ContextFromField + Clone + IntoContext<'c>, + | |__________________________________________________^ `StoredContext` implements `From` + = note: required for `StoredContext` to implement `From` +note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` + --> src/target/operations.rs + | + | pub fn under_field( + | ----------- required by a bound in this associated function +... + | Ctx: From, + | ^^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::under_field` + +error[E0277]: a field whose type stores a `std::string::String` as its context cannot be a field of a `struct = ..` record + --> tests/ui/owned_record_field_stores_context.rs:27:12 + | +27 | email: Stored, + | ^^^^^^ a `std::string::String` cannot be built from the field's own context + | + = help: the trait `ContextFromField` is not implemented for `std::string::String` + = note: the record gives each field a context of its own: the record's scope, then the field's name. Implement `ContextFromField` for `std::string::String` to store that context +help: the trait `DecryptField<__P, __Ctx>` is implemented for `Stored` + --> tests/ui/owned_record_field_stores_context.rs:10:25 + | +10 | #[derive(EncryptTarget, DecryptSource)] + | ^^^^^^^^^^^^^ + = note: required for `ExpectedContext` to implement `From` + = note: required for `CallerContext` to implement `Into>` +note: required for `Stored` to implement `DecryptField` + --> tests/ui/owned_record_field_stores_context.rs:10:25 + | +10 | #[derive(EncryptTarget, DecryptSource)] + | ^^^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro +11 | #[stash(plaintext = String)] +12 | struct Stored { + | ^^^^^^ + = note: this error originates in the derive macro `DecryptSource` (in Nightly builds, run with -Z macro-backtrace for more info) From 6dbb1cfdbc8e99273ed6e27b2a1f1841c37d2120 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 14:13:49 +1100 Subject: [PATCH 05/13] docs(stack-encrypt,eql-bindings): a binding is in the ciphertext, not the terms The docs of EQL types as record fields said that the terms of a field derive under the binding. They do not. Search terms derive under the query context: the field's own context, then the scopes. The data key and the AAD derive under the stored context, which adds the bindings. The tests already held that: two rows under one scope have one term. Say so in the trait doc, the `Identifier` impl, both CHANGELOGs, the README, the changeset and the API plan. The README's record with a scope and a binding left out two fields of `Member`, so it would not compile. It now names them all. --- .changeset/eql-types-as-record-fields.md | 2 +- .../2026-10-24-stack-encrypt-api-plan.md | 12 +++++++----- packages/eql/crates/eql-bindings/CHANGELOG.md | 9 +++++---- packages/eql/crates/eql-bindings/README.md | 19 +++++++++++-------- .../eql/crates/eql-bindings/src/encryption.rs | 10 ++++++---- .../tests/encryption/tests/record_fields.rs | 5 +++-- packages/stack-encrypt/CHANGELOG.md | 8 +++++--- packages/stack-encrypt/src/target/context.rs | 15 +++++++++++---- 8 files changed, 49 insertions(+), 31 deletions(-) diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md index 1bc407caeb..ba2e8dd7de 100644 --- a/.changeset/eql-types-as-record-fields.md +++ b/.changeset/eql-types-as-record-fields.md @@ -6,7 +6,7 @@ - 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 ciphertext and the terms of an EQL field then derive under the column, the scope and the binding, as they do for a field of any other type. `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 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 can carry a scope: `.scope(..)` on a query from a field's marker, or `.extend(..)` on a plan's query. It gives the term of the values stored under that scope. - `JsonTreeDocument` now implements `EncryptTarget` and `DecryptSource` for `JsonPlaintext`. It encrypts under the default options, with the column as its context. 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 d392c99299..dea9a260a1 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1490,11 +1490,13 @@ Base64. 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 ciphertext and the terms of an EQL field derive - under the column, then the scope, then the binding, as they do for a - field of any other type. `i` does not store them, 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. + 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.** In #1658: diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index c162ff8955..d276252e25 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -19,10 +19,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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 - ciphertext and the terms of an EQL field then derive under the column, - the scope and the binding, as they do for a field of any other type. - `i` stores the column alone, and nothing a caller supplies. The reader - supplies the scope and the binding again. + 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(..)`, diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 0cc2c626ac..26ff6462c0 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -445,7 +445,9 @@ A record can also list a scope or a binding, such as a tenant or a row ID: struct EncryptedMember { #[stash(passthrough)] id: u64, - email: TextEq, // i = {"t": "members", "c": "email"} + email: TextEq, // i = {"t": "members", "c": "email"} + age: IntegerOrd, // i = {"t": "members", "c": "age"} + profile: JsonTreeDocument, // i = {"t": "members", "c": "profile"} } let parts = || Scope::new(tenant).bind(row); @@ -458,14 +460,15 @@ let query = EncryptedMember::EMAIL let opened = Member::decrypt_from_with_context(stored, &keyset, parts()).await?; ``` -`i` stores the table and the column, and nothing a caller supplies. The -ciphertext and the terms of the field derive under the column, then the -scope, then the binding, as they do for a field of any other type. So: +`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 reader supplies the scope and the binding again, and a value does not - open without them; -- 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 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. diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index bca643dea9..9e98f1f95b 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -208,10 +208,12 @@ impl<'a> IntoContext<'a> for &'a Identifier { /// /// `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. -/// The field's ciphertext and terms derive under them, after the column, -/// as a field of any other type does. They are not stored in `i`, so the -/// reader supplies them again. The names of a record that holds this one -/// as a field come after the column in the same way. +/// 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")`. diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index f56eefb369..68d73bac1f 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -16,8 +16,9 @@ //! 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 -//! ciphertext and the terms derive under it, and `i` does not store it. -//! The reader supplies it again, and a query supplies the scope; +//! 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; //! - 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; diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 09b95dfeb5..6782e88697 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -63,9 +63,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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. The field - runs under all of it, as a field of any other type does, and does not - store them. The reader supplies them again. + 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 diff --git a/packages/stack-encrypt/src/target/context.rs b/packages/stack-encrypt/src/target/context.rs index 7fdd510418..cb440cafba 100644 --- a/packages/stack-encrypt/src/target/context.rs +++ b/packages/stack-encrypt/src/target/context.rs @@ -1138,10 +1138,17 @@ impl StoredContext { /// /// Only the own context is stored. A record can also list scopes and /// bindings, such as a tenant or a row ID. They come after the own -/// context, and the data key, the AAD and the search terms derive under -/// all of it. They are not stored in the field, so whoever reads the field -/// supplies them again. The same is true of the names of a record that -/// holds this record as a field. +/// context, as they do for a field of any other type: +/// +/// - the search terms derive under the query context: the own context, +/// then the scopes. A binding is not in it, so a binding does not +/// separate search terms; +/// - the data key and the AAD derive under the stored context: the query +/// context, then the bindings. +/// +/// The scopes and the bindings are not stored in the field, so whoever +/// reads the field supplies them again. The names of a record that holds +/// this record as a field come after the own context as scopes do. /// /// The context that `from_field` returns must encode as `own` does /// ([`IntoContext`]). The field then writes the terms that its type writes From 2b811b8f152ce52df660b27b79e5e7f0da4eb353 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 14:32:53 +1100 Subject: [PATCH 06/13] docs(eql-bindings): do not teach `.extend(..)` in the release notes The plan chain's `.extend(..)` is to be removed with the chain. The changeset, the eql-bindings CHANGELOG and the API plan named it as a way to scope a query. They now name the marker's `.scope(..)` alone, and say that a plan's query takes a scope without naming the chain's method. The module doc of `encryption::query` still names it, after the marker form: that module documents the chain as it is today. --- .changeset/eql-types-as-record-fields.md | 2 +- docs/plans/2026-10-24-stack-encrypt-api-plan.md | 4 ++-- packages/eql/crates/eql-bindings/CHANGELOG.md | 6 +++--- .../eql/crates/eql-bindings/src/encryption/query.rs | 10 +++++----- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md index ba2e8dd7de..899cf065cb 100644 --- a/.changeset/eql-types-as-record-fields.md +++ b/.changeset/eql-types-as-record-fields.md @@ -7,7 +7,7 @@ - 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 can carry a scope: `.scope(..)` on a query from a field's marker, or `.extend(..)` on a plan's query. It gives the term of the values stored under that scope. +- 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. - `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/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index dea9a260a1..459b0c3f2e 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1512,8 +1512,8 @@ Base64. `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 - `.extend(..)`. The order types do not implement `Answers` yet, so a - marker cannot query them. + a scope too, through the plan chain that #1488 removes. The order + types do not implement `Answers` yet, so a marker cannot query them. - **Not done.** A data plan still refuses a scope or a binding on a field that names an EQL type (`TargetError::Extended`). So a Go record cannot yet write an EQL field under a scope. diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index d276252e25..452cd019fe 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -29,9 +29,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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, with - `.extend(..)`. It gives the term of the values stored under that - scope. `QueryLabelError` has no `Extended` variant. + - 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. - 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 diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index 0d67f4f978..0f31e62ae0 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -39,11 +39,11 @@ //! names no column, so the awaited query refuses it, before any keyset is //! resolved or term derived. //! -//! A query can carry a scope: `.extend(..)` on a plan's query, or -//! `.scope(..)` on a query from a record field's marker. 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`. +//! 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 From a424544a4529dc2ea2453eebac2fbca4e72b7f5a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 15:09:38 +1100 Subject: [PATCH 07/13] feat(stack-encrypt,golang)!: an EQL field in a data plan takes a scope A data plan refused a scope or a binding on a field that names an EQL type (`TargetError::Extended`). So a Go struct with an `encrypt_into` field could not be sealed through `cipher.Scope(..).Bind(..)`. The derive path lost the same refusal earlier in this pull request. The resolver now receives the scopes and the bindings after the field's label, and runs the type under all of them. The EQL value stores the column alone, as a field of a derived record does. Whoever reads it supplies the scopes and the bindings again. stack-encrypt: - `dynamic::TargetResolver::encrypt` and `decrypt` take `parts: &DeclaredContext`, and `query` takes `scopes`. - `Plan::new_with`, `with_bindings` and a scoped call no longer refuse a target field. `TargetError::Extended` is removed. - `contexts()` shows a target field under the same parts as a field with outputs. eql-bindings: - `EqlTargets` runs a type through its own `EncryptTarget` declaration, under the label and then the parts. The generated dispatch threads the field's context in place of its column. Go: - `Plan.Validate` takes a plan with `Extension` or `Bind` and a target field. The Go tests seal, query and open an `encrypt_into` field through a cipher with a scope and a binding. Under the same scope and binding, a derived record and a data plan write the same terms, and each opens the other's values. BREAKING CHANGE: `dynamic::TargetResolver::encrypt`, `decrypt` and `query` take one more parameter, and `TargetError::Extended` is removed. Neither is in a published release of stack-encrypt. --- .changeset/eql-types-as-record-fields.md | 1 + .../stack-encrypt/declaration-grammar.md | 7 +- .../2026-10-24-stack-encrypt-api-plan.md | 9 +- languages/golang/CHANGELOG.md | 13 + languages/golang/cmd/stashgen/README.md | 2 +- languages/golang/encrypt/README.md | 13 +- languages/golang/encrypt/bindings_test.go | 11 +- languages/golang/encrypt/eql_test.go | 85 ++++- languages/golang/encrypt/guest/src/status.rs | 11 +- languages/golang/internal/record/record.go | 19 +- .../golang/internal/record/record_test.go | 14 +- packages/eql/crates/eql-bindings/CHANGELOG.md | 6 + packages/eql/crates/eql-bindings/README.md | 7 +- .../eql-bindings/src/encryption/resolver.rs | 23 +- .../eql-bindings/src/encryption/targets.rs | 161 ++++++-- .../crates/eql-bindings/src/v4/json_tree.rs | 2 +- .../eql/crates/eql-bindings/src/v4/targets.rs | 316 ++++++++-------- .../eql/crates/eql-codegen/src/targets.rs | 22 +- .../tests/encryption/tests/record_fields.rs | 176 ++++++++- packages/stack-encrypt/CHANGELOG.md | 14 + ...t-threaded-through-the-declaration-tree.md | 7 +- .../fuzz/fuzz_targets/check_record.rs | 3 + packages/stack-encrypt/src/codes.rs | 16 +- packages/stack-encrypt/src/contexts.rs | 8 +- packages/stack-encrypt/src/dynamic/mod.rs | 2 +- packages/stack-encrypt/src/dynamic/query.rs | 15 +- packages/stack-encrypt/src/dynamic/record.rs | 344 ++++++++++++------ packages/stack-encrypt/src/dynamic/target.rs | 64 ++-- packages/stack-encrypt/tests/heap_hygiene.rs | 3 + .../stack-encrypt/tests/json_operators.rs | 25 +- packages/stack-encrypt/tests/planned.rs | 73 ++-- 31 files changed, 997 insertions(+), 475 deletions(-) diff --git a/.changeset/eql-types-as-record-fields.md b/.changeset/eql-types-as-record-fields.md index 899cf065cb..2b35a4e4c2 100644 --- a/.changeset/eql-types-as-record-fields.md +++ b/.changeset/eql-types-as-record-fields.md @@ -8,6 +8,7 @@ - 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/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 459b0c3f2e..d8fceedd6c 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -1514,9 +1514,12 @@ Base64. 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. -- **Not done.** A data plan still refuses a scope or a binding on a field - that names an EQL type (`TargetError::Extended`). So a Go record cannot - yet write an EQL field under a scope. + - 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 diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index bcfc2716fe..fa0c49b760 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -249,6 +249,19 @@ 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. + ## [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..66a1763c57 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -626,10 +626,15 @@ 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. ### 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/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/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/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 452cd019fe..3ac5b71242 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -32,6 +32,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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 diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 26ff6462c0..89c0aa1a88 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -485,7 +485,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 @@ -513,7 +513,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/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 9d620aac94..ad35402874 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -491,7 +491,7 @@ impl JsonTree { /// On its own, the document stores the column the caller passes, and /// seals under it. As a field of a record, it stores the field's own /// column, and seals under the scopes and bindings of the record too. - fn sealing<'s, K: 'static>( + pub(crate) fn sealing<'s, K: 'static>( &self, ) -> Encryption<'s, Value, JsonTreeDocument, K, StoredContext> { Layout::::encryption::(&self.index) 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/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index 68d73bac1f..49b0773e04 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -19,6 +19,8 @@ //! 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; @@ -31,11 +33,11 @@ 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}; +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, ValueFrame}; +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}; @@ -526,6 +528,176 @@ async fn an_eql_field_opens_only_under_the_scope_and_the_binding_it_was_sealed_u 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, diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 6782e88697..8565f501b5 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -242,6 +242,20 @@ 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. + - **`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)`, 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 71a077e934..3e5a43fdb6 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -251,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(), @@ -653,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 f61f7efa79..a1f0ebf3c3 100644 --- a/packages/stack-encrypt/src/contexts.rs +++ b/packages/stack-encrypt/src/contexts.rs @@ -1161,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/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index bcd58beca8..26d6e15c18 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -321,7 +321,7 @@ pub enum Error { /// A plan field names an EQL type as its target and the name, the /// field's label or type, or the value does not fit: the build holds no /// EQL types, no type has the name, the engine cannot produce it yet, - /// the plan is extended, or the value is of another kind. Decided when + /// the label is not a column, or the value is of another kind. Decided when /// the plan is built or the value is read, before any key is touched /// — save [`TargetError::Other`], which is the resolver's own failure. #[error(transparent)] diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index c7ebabcf7a..28bafa044a 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -784,7 +784,7 @@ fn query_tokens(value: &ValueFrame, options: &MatchOptions) -> Result Result(&self, _: &str, _: Option<&TargetOptions>, -/// # _: &'a KeysetCipher<'_, K>, _: &Label, _: ValueFrame, +/// # _: &'a KeysetCipher<'_, K>, _: &Label, _: &DeclaredContext, _: ValueFrame, /// # ) -> Result, K>, TargetError> { unreachable!() } -/// # fn decrypt<'a, K: 'static>(&self, _: &str, _: &'a StackCipher, _: &Label, _: &[u8], +/// # fn decrypt<'a, K: 'static>(&self, _: &str, _: &'a StackCipher, _: &Label, +/// # _: &DeclaredContext, _: &[u8], /// # ) -> Result, TargetError> { unreachable!() } /// # fn query<'a, K: 'static>(&self, _: &str, _: &IndexSpec, _: &'a KeysetCipher<'_, K>, -/// # _: &Label, _: ValueFrame, +/// # _: &Label, _: &DeclaredContext, _: ValueFrame, /// # ) -> Result, K>, TargetError> { unreachable!() } /// # } /// // A document field that orders `$.age`. @@ -2634,6 +2635,7 @@ mod tests { _: Option<&crate::dynamic::TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &crate::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("a query encrypts nothing") @@ -2643,6 +2645,7 @@ mod tests { _: &str, _: &'a crate::StackCipher, _: &Label, + _: &crate::target::DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("a query decrypts nothing") @@ -2653,6 +2656,7 @@ mod tests { _: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, _: &Label, + _: &crate::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { Ok(Pending::ready(keyset, Ok(br#"{"bf":[1,5,2047]}"#.to_vec()))) @@ -2792,6 +2796,7 @@ mod tests { _: Option<&crate::dynamic::TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &crate::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("a query encrypts nothing") @@ -2801,6 +2806,7 @@ mod tests { _: &str, _: &'a crate::StackCipher, _: &Label, + _: &crate::target::DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("a query decrypts nothing") @@ -2811,6 +2817,7 @@ mod tests { _: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, _: &Label, + _: &crate::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { Ok(Pending::ready(keyset, Ok(br#"{"hm":"00"}"#.to_vec()))) diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 7f25855c49..59876b175e 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -76,11 +76,15 @@ //! a target field whose label has any other number of segments //! ([`TargetError::Column`]) — [`FieldPlan::with_target`] itself takes any //! label, as every field constructor does; the segment rules are the -//! plan's — and an extended plan (a tenant part on every -//! label) has no column for it and is refused with -//! [`TargetError::Extended`] rather than silently dropping the extension, -//! as is a plan with a context field, whose labels are identities alone -//! under whatever table each record names ([`TargetError::ContextField`]). +//! plan's. A plan with a context field is refused too: its labels are +//! identities alone, under whatever table each record names +//! ([`TargetError::ContextField`]). +//! +//! The scopes and the bindings of the plan and of the call come after the +//! label, as they do for a field with outputs: a tenant part on every +//! label, a row ID. The resolver runs the type under the label, then +//! those parts. The EQL value stores the column alone, so whoever reads +//! the value supplies the parts again. //! The field's `"type"`, when declared, must be the kind the EQL type is //! produced from ([`TargetError::Kind`]); undeclared, it is that kind, so //! every value is checked against it as any typed field's is. @@ -743,7 +747,8 @@ impl Plan { /// rule, so a parsed and a hand-built plan are refused alike. /// [`Error::Target`] if a target field names a type the /// resolver does not know or cannot produce, declares a `"type"` other - /// than the kind that type is produced from, or sits in an extended plan. + /// than the kind that type is produced from, or has a label that is not + /// a column. pub fn new_with( mut fields: Vec, resolver: &(impl TargetResolver + ?Sized), @@ -752,7 +757,6 @@ impl Plan { return Err(Error::bad_plan(Reason::NoFields)); }; let context = first.prefix()?; - let extension = first.extension.clone(); for field in &fields { // `prefix` refuses a one-segment label, which has nothing to // sit under; a longer one must sit under the first field's. @@ -766,13 +770,6 @@ impl Plan { for field in fields.iter_mut().filter(|field| field.is_target()) { let name = field.target.clone().unwrap_or_default(); let descriptor = resolver.resolve(&name)?; - if !extension.is_empty() { - return Err(TargetError::Extended { - name: field.name.clone(), - label: field.label.to_string(), - } - .into()); - } // An EQL value is stored under a table and a column, so the // label is exactly two segments. Decided here, where the plan is // built and se_plan_check reports it, not at the first value: a @@ -893,7 +890,7 @@ impl Plan { // A target field's label must be a column, `/`, // which a context field's one-segment identity is not: the table // is each record's own, and an EQL value stores one fixed by the - // declaration. The same refusal as an extended plan's. + // declaration. if let Some(target) = fields.iter().find(|field| field.is_target()) { return Err(TargetError::ContextField { name: target.name.clone(), @@ -1020,27 +1017,24 @@ impl Plan { /// Unreachable for a plan from [`plan`], [`Plan::new`] or /// [`Plan::with_context_field`]: a parsed plan always composes. pub fn contexts(&self) -> Result { - let lowered = crate::contexts::under_declared( - compose::<()>(self, &Absent::new())?.shapes(), - &self.declared_context(), - ); + let shapes = self.placed(compose::<()>(self, &Absent::new())?.shapes()); Ok(crate::contexts::resolve( - self.placed(lowered), + crate::contexts::under_declared(shapes, &self.declared_context()), crate::contexts::CallerShape::none(), )) } /// The shape of every field's context, in plan order: the `lowered` - /// fields' shapes, and each target field under its label alone. An EQL - /// value is sealed under its table and column by the resolver, and - /// takes no part from the caller: the plan refuses an extension for it - /// before it runs. + /// fields' shapes, and each target field under its label, then the + /// context it is handed. The resolver runs an EQL type under its label + /// and the plan's parts, as the lowering runs a field with outputs, so + /// the two kinds of field show the same parts. fn placed(&self, lowered: crate::contexts::Shapes) -> crate::contexts::Shapes { let mut lowered = lowered.into_iter().peekable(); let mut shapes = crate::contexts::Shapes::with_capacity(self.fields.len()); for field in &self.fields { if field.is_target() { - shapes.push(crate::contexts::known_leaf( + shapes.push(crate::contexts::leaf_under( &field.name, field.label.clone().into_context(), )); @@ -1070,23 +1064,11 @@ impl Plan { /// /// [`Error::Plan`] with [`Reason::EmptyBinding`] for an empty part: a /// row ID not yet assigned would bind every row to one context, and - /// the typed path refuses the same. [`Error::Target`] if a field names - /// an EQL type: an EQL value is stored under its table and column - /// alone, so a binding cannot extend it, as an extension cannot - /// ([`TargetError::Extended`]). + /// the typed path refuses the same. pub fn with_bindings(mut self, parts: Vec>) -> Result { if parts.iter().any(crate::MaybeEmpty::is_empty) { return Err(Error::bad_plan(Reason::EmptyBinding)); } - if let Some(target) = self.fields.iter().find(|field| field.is_target()) { - if !parts.is_empty() { - return Err(TargetError::Extended { - name: target.name.clone(), - label: target.label.to_string(), - } - .into()); - } - } self.bindings = parts; Ok(self) } @@ -1103,8 +1085,8 @@ impl Plan { /// plan's own extension, then the scopes. A call with no scope borrows /// the plan instead, and copies nothing. /// - /// A plan with a field that names an EQL type takes no scope. An EQL - /// value is stored under its table and column alone. + /// A field that names an EQL type is scoped as any other field is. Its + /// EQL value stores its table and column, and not the scope. /// /// The scope shows in the context of the call. Here a record under a /// one-field plan is encrypted under the scope `42u64`: @@ -1142,9 +1124,7 @@ impl Plan { /// /// # Errors /// - /// [`Error::Plan`] with [`Reason::EmptyContext`] for an empty part, and - /// [`Error::Target`] if a field names an EQL type - /// ([`TargetError::Extended`]), as [`with_bindings`](Self::with_bindings). + /// [`Error::Plan`] with [`Reason::EmptyContext`] for an empty part. pub(super) fn with_scopes( mut self, parts: impl IntoIterator>, @@ -1153,15 +1133,6 @@ impl Plan { if parts.iter().any(crate::MaybeEmpty::is_empty) { return Err(Error::bad_plan(Reason::EmptyContext)); } - if let Some(target) = self.fields.iter().find(|field| field.is_target()) { - if !parts.is_empty() { - return Err(TargetError::Extended { - name: target.name.clone(), - label: target.label.to_string(), - } - .into()); - } - } for field in &mut self.fields { for part in &parts { field.extend(part.clone()); @@ -1175,25 +1146,33 @@ impl Plan { /// then the context the caller hands a [`Planned`](super::Planned) /// record. pub(super) fn caller_shapes(&self) -> Result { - Ok(self.placed(crate::contexts::under_declared_then_caller( - compose::<()>(self, &Absent::new())?.shapes(), + Ok(crate::contexts::under_declared_then_caller( + self.placed(compose::<()>(self, &Absent::new())?.shapes()), &self.declared_context(), - ))) + )) } - /// The context every field's label is run under: the extension, as the - /// chain's `.extend(..)` would carry it, then the bindings. - fn declared_context(&self) -> DeclaredContext { - let scopes = self - .extension + /// The scopes every field's label is run under: the extension, as the + /// chain's `.extend(..)` would carry it. A query runs under these + /// alone. + fn scopes(&self) -> DeclaredContext { + self.extension .iter() .cloned() .fold(DeclaredContext::default(), |context, part| { context.with(CallerContext::from_piece(part)) - }); - self.bindings.iter().cloned().fold(scopes, |context, part| { - context.with(CallerContext::bind_piece(part)) - }) + }) + } + + /// The context every field's label is run under: the scopes, then the + /// bindings. + fn declared_context(&self) -> DeclaredContext { + self.bindings + .iter() + .cloned() + .fold(self.scopes(), |context, part| { + context.with(CallerContext::bind_piece(part)) + }) } fn shape(&self) -> Vec { @@ -1844,7 +1823,14 @@ pub fn encrypt_with<'a, K: 'static>( let name = field.target().unwrap_or_default(); pendings.push( resolver - .encrypt(name, field.target_options(), cipher, field.label(), value) + .encrypt( + name, + field.target_options(), + cipher, + field.label(), + &extend, + value, + ) .map_err(|error| Error::Target(name_target(error, &field.name)))?, ); count += 1; @@ -1951,7 +1937,8 @@ fn in_row_order( /// Derive the EQL query value of one target field for one plaintext: the /// operand that matches stored values of the field, as JSON bytes, through -/// the type's own query plan. A query derives no data key, so the pending +/// the type's own query plan. It runs under the field's label, then the +/// plan's scopes, and under no binding. A query derives no data key, so the pending /// settles without I/O; it is a [`Pending`] all the same, for one shape at /// the call site. /// @@ -2004,7 +1991,7 @@ pub fn query<'a, K: 'static>( check_field(&value, field)?; } resolver - .query(name, index, cipher, field.label(), value) + .query(name, index, cipher, field.label(), &plan.scopes(), value) .map_err(|error| Error::Target(name_target(error, &field.name))) } @@ -2137,7 +2124,7 @@ pub fn decrypt_with<'a, K: 'static>( // before any key is retrieved. pendings.push(confine( resolver - .decrypt(name, cipher, field.label(), &stored) + .decrypt(name, cipher, field.label(), &extend, &stored) .map_err(|error| Error::Target(name_target(error, &field.name)))?, keyset, )); @@ -6508,9 +6495,10 @@ mod tests { } /// A resolver shaped like the EQL one, over this engine: it seals a - /// string as one leaf under the field's label and writes it into a JSON - /// envelope with the label as its `i`, opens it back checking that `i`, - /// and derives an equality term for a query. What it proves is the + /// string as one leaf under the field's label, then the plan's parts, + /// and writes it into a JSON envelope with the label alone as its `i`, + /// opens it back checking that `i`, and derives an equality term for a + /// query under the label and the scopes. What it proves is the /// lowering's half — the target field rides in the record's request, /// is stored under `"eql"`, opens through the resolver, and every /// refusal is decided before a key is touched — not EQL's envelope, @@ -6631,14 +6619,16 @@ mod tests { _: Option<&crate::dynamic::TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &crate::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { let _ = self.resolve(name)?; let text = text_of_value(name, plaintext)?; let column = column(name, label)?; let stored_label = label.to_string(); + let context = AeadContext::from(parts.clone().under(column)); Ok(keyset - .encrypt_as::(&text, AeadContext::from(column)) + .encrypt_as::(&text, context) .try_map(move |sealed| { let CipherText::Single(leaf) = sealed else { return Err(crate::Error::UnsupportedShape); @@ -6657,6 +6647,7 @@ mod tests { name: &str, cipher: &'a StackCipher, label: &Label, + parts: &crate::target::DeclaredContext, stored: &[u8], ) -> Result, TargetError> { let _ = self.resolve(name)?; @@ -6682,8 +6673,9 @@ mod tests { crate::Error::Other("stored under another column".into()), )); } + let context = AeadContext::from(parts.clone().under(column)); let opening: Decryption = - crate::target::open(CipherText::Single(leaf), AeadContext::from(column)); + crate::target::open(CipherText::Single(leaf), context); Ok(cipher.run_decryption(opening).try_map(|text| { ValueFrame::of(text.as_str()).map_err(|e| crate::Error::Other(Box::new(e))) })) @@ -6695,6 +6687,7 @@ mod tests { _: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, label: &Label, + scopes: &crate::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { let _ = self.resolve(name)?; @@ -6702,7 +6695,7 @@ mod tests { let column = column(name, label)?; let stored_label = label.to_string(); Ok(keyset - .encrypt_as::(&text, CallerContext::from(column)) + .encrypt_as::(&text, scopes.clone().under(column)) .try_map(move |term| { serde_json::to_vec(&serde_json::json!({ "v": 3, @@ -6734,23 +6727,55 @@ mod tests { obj(vec![("age", Tree::UInt32(age)), ("email", s(email))]) } - /// An EQL value is stored under its table and column alone, so a - /// plan with a target field takes no binding, as it takes no - /// extension; no binding at all leaves it as it is. - #[test] - fn a_target_field_refuses_a_binding() { - let refused = mixed_plan() - .with_bindings(vec![ContextPiece::U64(9)]) - .unwrap_err(); - assert!( - matches!( - &refused, - Error::Target(TargetError::Extended { name, label }) - if name == "email" && label == "users/email" - ), - "{refused:?}" + /// A binding binds a target field as it binds any other: the + /// resolver seals the value under the label, then the binding. The + /// EQL value stores the label alone, so it opens only under the + /// same binding. + #[tokio::test] + async fn a_target_field_takes_a_binding() { + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + let bound = |row: u64| { + mixed_plan() + .with_bindings(vec![ContextPiece::U64(row)]) + .expect("a plan with a target field takes a binding") + }; + // `StackCipherText` is not `Clone`, so each check seals a row. + let seal = || async { + encrypt_with( + &keyset, + mixed_row(34, "ada@example.com"), + &bound(9), + &FakeEql, + ) + .unwrap() + .await + .unwrap() + }; + let mut record = map(seal().await); + assert_eq!( + eql_json(&mut record, "email")["i"], + "users/email", + "the value stores its column, and not the binding" ); - assert!(mixed_plan().with_bindings(vec![]).is_ok()); + + let opened = decrypt_with(&cipher, seal().await, &bound(9), None, &FakeEql) + .unwrap() + .await + .unwrap(); + assert_eq!( + Tree::from_frame(opened.risky_ref()).unwrap(), + mixed_row(34, "ada@example.com") + ); + // Another row, and no binding at all, do not open it. + for plan in [bound(10), mixed_plan()] { + let refused = decrypt_with(&cipher, seal().await, &plan, None, &FakeEql) + .unwrap() + .await; + assert!(refused.is_err()); + } + + // The plan's own `"bind"` key is the same binding. let wired = plan_with( obj(vec![ ("age", typed(label("age"), &["c", "eq"], "uint32")), @@ -6758,18 +6783,46 @@ mod tests { ("bind", Tree::Array(vec![Tree::UInt64(9)])), ]), &FakeEql, - ); - assert!( - matches!(wired, Err(Error::Target(TargetError::Extended { .. }))), - "{wired:?}" + ) + .expect("a bound plan with a target field parses"); + let opened = decrypt_with(&cipher, seal().await, &wired, None, &FakeEql) + .unwrap() + .await + .unwrap(); + assert_eq!( + Tree::from_frame(opened.risky_ref()).unwrap(), + mixed_row(34, "ada@example.com") ); } - /// The context view shows a target field under its label alone, in - /// plan order among the lowered fields: an EQL value takes no part - /// from the caller, so there is nothing to fill in. + /// The context view shows a target field in plan order among the + /// lowered fields, under its label and the same parts as they are: + /// the plan's extension, then its bindings. #[test] fn the_contexts_show_a_target_field_in_plan_order() { + let extended = |field: &str| Tree::Array(vec![label(field), Tree::UInt32(7)]); + let plan = plan_with( + obj(vec![ + ("age", typed(extended("age"), &["c", "eq"], "uint32")), + ("email", target_spec(extended("email"), TEXT_EQ)), + ]), + &FakeEql, + ) + .expect("an extended plan with a target parses") + .with_bindings(vec![ContextPiece::U64(9)]) + .unwrap(); + let contexts = plan.contexts().unwrap(); + let (age, email) = (contexts.get("age").unwrap(), contexts.get("email").unwrap()); + assert_eq!( + email.to_string().replace("email", "age"), + age.to_string().replace("email", "age"), + "a target field shows the parts a field with outputs shows" + ); + assert_eq!( + contexts.to_string(), + "age\n query context: (users / age) / 7u32\n stored context: ((users / age) / 7u32) / 9u64\nemail\n query context: (users / email) / 7u32\n stored context: ((users / email) / 7u32) / 9u64\n" + ); + let plan = plan_with( obj(vec![ ("age", typed(label("age"), &["c", "eq"], "uint32")), @@ -7525,27 +7578,90 @@ mod tests { assert_eq!(generates(&cipher), 0); } - #[test] - fn an_extended_plan_refuses_a_target_field_rather_than_dropping_the_extension() { - let extended = |field: &str| Tree::Array(vec![label(field), Tree::UInt32(7)]); - let value = obj(vec![ - ("age", spec(extended("age"), &["c"])), - ("email", target_spec(extended("email"), TEXT_EQ)), - ]); - let error = target_error(plan_with(value, &FakeEql).unwrap_err()); - assert!( - matches!(&error, TargetError::Extended { name, label } if name == "email" && label == "users/email"), - "{error}" - ); - // The same plan without the target field extends as before. - let value = obj(vec![("age", spec(extended("age"), &["c"]))]); - assert!(plan_with(value, &FakeEql).is_ok()); + /// An extended plan runs a target field under its label, then the + /// extension, as it runs a field with outputs. The EQL value stores + /// the label alone. A query under the same extension derives the + /// term of the label and the extension. + #[tokio::test] + async fn an_extended_plan_runs_a_target_field_under_the_extension() { + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + let extended = + |field: &str, part: u32| Tree::Array(vec![label(field), Tree::UInt32(part)]); + let plan = |part: u32| { + plan_with( + obj(vec![ + ("age", spec(extended("age", part), &["c"])), + ("email", target_spec(extended("email", part), TEXT_EQ)), + ]), + &FakeEql, + ) + .expect("an extended plan with a target field parses") + }; + let row = || { + obj(vec![ + ("age", Tree::UInt32(34)), + ("email", s("ada@example.com")), + ]) + }; + // `StackCipherText` is not `Clone`, so each check seals a row. + let seal = || async { + encrypt_with(&keyset, row(), &plan(7), &FakeEql) + .unwrap() + .await + .unwrap() + }; + let mut record = map(seal().await); + assert_eq!(eql_json(&mut record, "email")["i"], "users/email"); + + let opened = decrypt_with(&cipher, seal().await, &plan(7), None, &FakeEql) + .unwrap() + .await + .unwrap(); + assert_eq!(Tree::from_frame(opened.risky_ref()).unwrap(), row()); + // Under another extension the value does not open. + let refused = decrypt_with(&cipher, seal().await, &plan(8), None, &FakeEql) + .unwrap() + .await; + assert!(refused.is_err()); + + // The query term is the equality term under the label, then the + // extension, and names the label alone. + let term = |part: u32| { + let (keyset, plan) = (&keyset, plan(part)); + async move { + let json = query( + keyset, + &plan, + "email", + &IndexSpec::Equality, + "ada@example.com", + &FakeEql, + ) + .unwrap() + .await + .unwrap(); + serde_json::from_slice::(&json).unwrap() + } + }; + let under = |part: u32| { + CallerContext::from(crate::target::Scope::new(part)) + .extend(NonEmpty::from(Label::parse("users/email").unwrap())) + }; + let direct = keyset + .encrypt_as::(&"ada@example.com".to_owned(), under(7)) + .await + .unwrap(); + let seven = term(7).await; + assert_eq!(seven["i"], "users/email"); + assert_eq!(seven["hm"], hex(direct.as_bytes())); + assert_ne!(seven["hm"], term(8).await["hm"]); } /// A plan with a context field has no table of its own: each /// record names one. An EQL value stores a table the declaration - /// fixes, so a target field is refused there as it is in an extended - /// plan, and before the resolver is asked. + /// fixes, so a target field is refused there, before the resolver is + /// asked. #[test] fn a_context_field_plan_refuses_a_target_field() { let identity = |field: &str| strings(&[field]); diff --git a/packages/stack-encrypt/src/dynamic/target.rs b/packages/stack-encrypt/src/dynamic/target.rs index 6462bc9a85..2809bc4818 100644 --- a/packages/stack-encrypt/src/dynamic/target.rs +++ b/packages/stack-encrypt/src/dynamic/target.rs @@ -32,7 +32,7 @@ use super::{Op, ValueFrame, ValueKind}; use crate::json::JsonOptions; use crate::sem::MatchOptions; -use crate::target::IndexSpec; +use crate::target::{DeclaredContext, IndexSpec}; use crate::{KeysetCipher, Label, Pending, StackCipher}; /// One EQL type a plan may name as a target, as the host describes it. @@ -333,21 +333,6 @@ pub enum TargetError { /// The type's name. name: String, }, - /// The plan extends every field's label by the caller's parts (a tenant, - /// a region), and an EQL value stores a table and a column only: there - /// is no column for the extended label. A plan with a target field is - /// not extended. - #[error( - "{name}: an EQL value is stored under a table and a column, so the label {label} \ - cannot be extended by the caller's parts" - )] - #[diagnostic(code(stack_encrypt::target_extended))] - Extended { - /// The target field's name. - name: String, - /// The field's label, before the extension. - label: String, - }, /// The plan takes its context from a field of each record (the /// plan-level `"context_field"`), so a field's label is its identity /// alone and the table is whatever each record names; an EQL value @@ -465,7 +450,6 @@ impl crate::ErrorPayload for TargetError { | Self::NoQuery { .. } | Self::Other(_) => serde_json::Map::new(), Self::Unproducible { reason, .. } => payload([("reason", reason.as_str().into())]), - Self::Extended { label, .. } => payload([("label", label.as_str().into())]), Self::ContextField { context_field, .. } => { payload([("context_field", context_field.as_str().into())]) } @@ -511,8 +495,7 @@ impl crate::ErrorPayload for TargetError { | Self::Unproducible { name, .. } => { let _ = fields.insert("target".to_owned(), name.as_str().into()); } - Self::Extended { name, .. } - | Self::ContextField { name, .. } + Self::ContextField { name, .. } | Self::Kind { name, .. } | Self::Column { name, .. } | Self::Plaintext { name, .. } @@ -537,11 +520,18 @@ impl crate::ErrorPayload for TargetError { /// calls it once per target field, with the field's label and value, and /// zips the returned [`Pending`] into the record's. /// -/// The three operations take the field's **label** — the plan's context and -/// the field's identity, `users/email` — and never an extension: an EQL -/// value is stored under a table and a column, and -/// [`record::Plan`](super::record::Plan) refuses a plan that both extends and -/// names a target ([`TargetError::Extended`]). +/// The three operations take the field's **label**, and the **parts** that +/// come after it. +/// +/// - The label is the plan's context and the field's identity, +/// `users/email`. It is the column an EQL value stores. +/// - The parts are the scopes and the bindings of the plan and of the call, +/// such as a tenant or a row ID. An EQL value does not store them. A +/// resolver runs the type under the label, then the parts +/// (`parts.clone().under(label)`), as a field with outputs runs. So the +/// terms derive under the label and the scopes, the value is sealed under +/// the bindings too, and whoever reads the value supplies the parts +/// again. pub trait TargetResolver { /// Every EQL type this build knows of, producible or not, in a fixed /// order: what `se_targets` lists. @@ -580,7 +570,8 @@ pub trait TargetResolver { } /// Run the named type's own encryption plan over one value under - /// `label`, resolving to the EQL value's JSON bytes. `options` are the + /// `label`, then `parts`, resolving to the EQL value's JSON bytes. The + /// value stores `label`'s column, and not the parts. `options` are the /// ones the plan resolved for the field ([`TargetOptions`]): the JSON /// index's for a type that carries it, `None` for every other type. /// @@ -596,13 +587,14 @@ pub trait TargetResolver { options: Option<&TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError>; /// Open a stored value of the named type back to its plaintext, checking - /// it was stored under `label`'s column. Opens through the client; the - /// lowering confines the pending to a keyset when the caller's scope is - /// one. + /// it was stored under `label`'s column. The value opens under `label`, + /// then `parts`. Opens through the client; the lowering confines the + /// pending to a keyset when the caller's scope is one. /// /// # Errors /// @@ -614,11 +606,13 @@ pub trait TargetResolver { name: &str, cipher: &'a StackCipher, label: &Label, + parts: &DeclaredContext, stored: &[u8], ) -> Result, TargetError>; /// Run the named type's query twin over one value: the operand that - /// matches stored values under `label`'s column, as JSON bytes. + /// matches stored values under `label`'s column and `scopes`, as JSON + /// bytes. `scopes` holds no binding: a binding is in no query context. /// /// `index` is the type's index that answers the query's operator, one of /// the descriptor's [`indexes`](TargetDescriptor::indexes): @@ -639,6 +633,7 @@ pub trait TargetResolver { index: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, label: &Label, + scopes: &DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError>; } @@ -669,6 +664,7 @@ impl TargetResolver for NoTargets { _: Option<&TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { Self::refuse(name) @@ -679,6 +675,7 @@ impl TargetResolver for NoTargets { name: &str, _: &'a StackCipher, _: &Label, + _: &DeclaredContext, _: &[u8], ) -> Result, TargetError> { Self::refuse(name) @@ -690,6 +687,7 @@ impl TargetResolver for NoTargets { _: &IndexSpec, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { Self::refuse(name) @@ -760,6 +758,7 @@ mod tests { _: Option<&TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("not run here") @@ -769,6 +768,7 @@ mod tests { _: &str, _: &'a StackCipher, _: &Label, + _: &DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("not run here") @@ -779,6 +779,7 @@ mod tests { _: &IndexSpec, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("not run here") @@ -895,10 +896,5 @@ mod tests { error.to_string(), "email: TextEq is produced from a string plaintext, not a value with no kind" ); - let error = TargetError::Extended { - name: "email".into(), - label: "users/email".into(), - }; - assert!(error.to_string().contains("cannot be extended"), "{error}"); } } diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index c6c386a5dc..8f292fb51a 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -662,6 +662,7 @@ impl stack_encrypt::dynamic::TargetResolver for Documents { _: Option<&stack_encrypt::dynamic::TargetOptions>, _: &'a stack_encrypt::KeysetCipher<'_, K>, _: &stack_encrypt::Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, stack_encrypt::dynamic::TargetError> { unreachable!("a check seals nothing") @@ -671,6 +672,7 @@ impl stack_encrypt::dynamic::TargetResolver for Documents { _: &str, _: &'a stack_encrypt::StackCipher, _: &stack_encrypt::Label, + _: &stack_encrypt::target::DeclaredContext, _: &[u8], ) -> Result, stack_encrypt::dynamic::TargetError> { @@ -682,6 +684,7 @@ impl stack_encrypt::dynamic::TargetResolver for Documents { _: &stack_encrypt::target::IndexSpec, _: &'a stack_encrypt::KeysetCipher<'_, K>, _: &stack_encrypt::Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, stack_encrypt::dynamic::TargetError> { unreachable!("a document's operators are the engine's") diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index dfade99fdd..cd9a27eb4e 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -23,7 +23,7 @@ use stack_encrypt::dynamic::{ TargetResolver, ValueFrame, ValueKind, }; use stack_encrypt::json::{JsonDocument, Tag}; -use stack_encrypt::target::{Borrowed, CallerContext, IndexSpec}; +use stack_encrypt::target::{Borrowed, IndexSpec}; use stack_encrypt::{CipherText, Encrypt, KeysetCipher, Label, NonEmpty, Pending, StackCipher}; use stack_kms::{DataKeySource, IndexKeySource}; @@ -63,6 +63,7 @@ impl TargetResolver for Documents { options: Option<&TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &stack_encrypt::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { let options = options @@ -75,7 +76,7 @@ impl TargetResolver for Documents { .run( stack_encrypt::target::json_document::<_, Borrowed>(options), document.value(), - CallerContext::from(NonEmpty::from(label.clone())), + parts.clone().under(NonEmpty::from(label.clone())), ) .try_map(|doc| { serde_json::to_vec(&doc).map_err(|e| stack_encrypt::Error::Other(Box::new(e))) @@ -87,6 +88,7 @@ impl TargetResolver for Documents { _: &str, _: &'a StackCipher, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("these tests open documents through reads") @@ -98,6 +100,7 @@ impl TargetResolver for Documents { _: &IndexSpec, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("the JSON operators are the engine's") @@ -1511,18 +1514,20 @@ mod element_match { options: Option<&TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &stack_encrypt::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { - Documents.encrypt(name, options, keyset, label, plaintext) + Documents.encrypt(name, options, keyset, label, parts, plaintext) } fn decrypt<'a, K: 'static>( &self, name: &str, cipher: &'a StackCipher, label: &Label, + parts: &stack_encrypt::target::DeclaredContext, bytes: &[u8], ) -> Result, TargetError> { - Documents.decrypt(name, cipher, label, bytes) + Documents.decrypt(name, cipher, label, parts, bytes) } fn query<'a, K: 'static>( &self, @@ -1530,9 +1535,10 @@ mod element_match { index: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, label: &Label, + scopes: &stack_encrypt::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { - Documents.query(name, index, keyset, label, plaintext) + Documents.query(name, index, keyset, label, scopes, plaintext) } } @@ -2330,18 +2336,20 @@ mod compiled_match { options: Option<&TargetOptions>, keyset: &'a KeysetCipher<'_, K>, label: &Label, + parts: &stack_encrypt::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { - Documents.encrypt(name, options, keyset, label, plaintext) + Documents.encrypt(name, options, keyset, label, parts, plaintext) } fn decrypt<'a, K: 'static>( &self, name: &str, cipher: &'a StackCipher, label: &Label, + parts: &stack_encrypt::target::DeclaredContext, bytes: &[u8], ) -> Result, TargetError> { - Documents.decrypt(name, cipher, label, bytes) + Documents.decrypt(name, cipher, label, parts, bytes) } fn query<'a, K: 'static>( &self, @@ -2349,9 +2357,10 @@ mod compiled_match { index: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, label: &Label, + scopes: &stack_encrypt::target::DeclaredContext, plaintext: ValueFrame, ) -> Result, K>, TargetError> { - Documents.query(name, index, keyset, label, plaintext) + Documents.query(name, index, keyset, label, scopes, plaintext) } } diff --git a/packages/stack-encrypt/tests/planned.rs b/packages/stack-encrypt/tests/planned.rs index bdd8d51c52..3e9ba05c13 100644 --- a/packages/stack-encrypt/tests/planned.rs +++ b/packages/stack-encrypt/tests/planned.rs @@ -21,8 +21,8 @@ use stack_encrypt::kms::FakeDataKeySource; use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::{DeclaredContext, DecryptSource, EncryptTarget, IndexSpec, Scope}; use stack_encrypt::{ - nonempty, AsProtectedRef, DecryptFrom, EncryptInto, Encrypted, Error, KeysetCipher, Label, - Pending, PlanError, StackCipher, StackCipherText, + nonempty, AsProtectedRef, DecryptFrom, Descriptor, EncryptInto, Encrypted, Error, KeysetCipher, + Label, NonEmpty, Pending, PlanError, StackCipher, StackCipherText, }; use zeroize::Zeroize; @@ -68,8 +68,10 @@ fn plan() -> record::Plan { })) } -/// A resolver holding one EQL type, `Some`, that answers `eq`, whose query -/// is a fixed JSON value: what a target field's query term carries. +/// A resolver holding one EQL type, `Some`, that answers `eq`. Its query +/// is a JSON value that names the query context it was run under: the +/// field's label, then the scopes. That is what a target field's query +/// term carries. struct OneType; impl TargetResolver for OneType { @@ -93,6 +95,7 @@ impl TargetResolver for OneType { _: Option<&dynamic::TargetOptions>, _: &'a KeysetCipher<'_, K>, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { unreachable!("these tests query, and encrypt nothing") @@ -102,6 +105,7 @@ impl TargetResolver for OneType { _: &str, _: &'a StackCipher, _: &Label, + _: &stack_encrypt::target::DeclaredContext, _: &[u8], ) -> Result, TargetError> { unreachable!("these tests query, and decrypt nothing") @@ -111,10 +115,14 @@ impl TargetResolver for OneType { _: &str, _: &IndexSpec, keyset: &'a KeysetCipher<'_, K>, - _: &Label, + label: &Label, + scopes: &stack_encrypt::target::DeclaredContext, _: ValueFrame, ) -> Result, K>, TargetError> { - Ok(Pending::ready(keyset, Ok(br#"{"hm":"00"}"#.to_vec()))) + let context = scopes.clone().under(NonEmpty::from(label.clone())); + let under = Descriptor::from_piece(&context.query()); + let query = format!(r#"{{"hm":"{}"}}"#, under.as_str()); + Ok(Pending::ready(keyset, Ok(query.into_bytes()))) } } @@ -134,16 +142,6 @@ fn ada() -> ValueFrame { ]) } -/// The dynamic error inside an owned-path failure. -fn dynamic_error(error: &Error) -> &dynamic::Error { - match error { - Error::Other(inner) => inner - .downcast_ref::() - .unwrap_or_else(|| panic!("not a dynamic error: {inner}")), - other => panic!("not an owned-path failure: {other}"), - } -} - // The typed record the data plan above describes, for the equivalence // checks: the derive seals `email` under `("users", "email")` extended by // the caller's tenant, as the plan's field is extended by the caller's @@ -623,7 +621,7 @@ mod a_target_field { .unwrap(); assert_eq!( through_handle.operand(), - &Operand::One(br#"{"hm":"00"}"#.to_vec()) + &Operand::One(br#"{"hm":"users/email"}"#.to_vec()) ); assert_eq!(through_handle.domain(), Some("eql_v3.query_some")); let by_email = plan.query_with("email", Op::Eq, &OneType).unwrap(); @@ -635,21 +633,23 @@ mod a_target_field { } #[test] - fn shows_its_context_under_its_label_alone() { + fn shows_its_context_as_a_field_with_outputs_does() { let plan = target_plan(); - // An EQL value is sealed under its label by the resolver, and takes - // no caller part, so the view shows the label and no placeholder. + // The resolver runs an EQL type under its label, then the caller's + // parts. So the view shows a placeholder for the scope and for the + // binding, as it does for a field with outputs. assert_eq!( Planned::new(&plan, frame("a")) .contexts() .unwrap() .to_string(), - "email\n context: users / email\n" + "email\n query context: (users / email) / {scope?: CallerContext}\n \ + stored context: ((users / email) / {scope?: CallerContext}) / {bind?: CallerContext}\n" ); let by_email = plan.query_with("email", Op::Eq, &OneType).unwrap(); assert_eq!( by_email.contexts().unwrap().to_string(), - "context: users / email\n" + "context: (users / email) / {scope?: CallerContext}\n" ); } @@ -664,23 +664,32 @@ mod a_target_field { )); } + /// A scope goes to the resolver, after the field's label: the query is + /// derived under both, as a query on a field with indexes is. #[tokio::test] - async fn refuses_a_scope_it_cannot_be_stored_under() { + async fn takes_a_scope_and_runs_the_type_under_it() { let cipher = cipher().await; let keyset = cipher.default_keyset(); let plan = target_plan(); let by_email = plan.query_with("email", Op::Eq, &OneType).unwrap(); - let refused = Planned::with_resolver(&by_email, frame("a"), OneType) - .encrypt_into_with_context::(&keyset, Scope::new(1u64)) + let scoped: QueryTerm = Planned::with_resolver(&by_email, frame("a"), OneType) + .encrypt_into_with_context(&keyset, Scope::new(1u64)) .await - .unwrap_err(); - assert!( - matches!( - dynamic_error(&refused), - dynamic::Error::Target(TargetError::Extended { name, .. }) if name == "email" - ), - "{refused}" + .unwrap(); + assert_eq!( + scoped.operand(), + &Operand::One(br#"{"hm":"(users/email)/1u64"}"#.to_vec()) ); + let through_handle: QueryTerm = plan + .field_with("email", &OneType) + .unwrap() + .eq(frame("a")) + .unwrap() + .scope(Scope::new(1u64)) + .encrypt(&keyset) + .await + .unwrap(); + assert_eq!(through_handle, scoped); } } From 91ff9610a8c37b989718a684d1dda135851ea169 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 15:28:05 +1100 Subject: [PATCH 08/13] docs(eql-bindings): run the JSON document example The example on `EncryptTarget for JsonTreeDocument` was a `no_run` doctest: compiled, and never executed. This crate's doctests have no key source and no runtime, by design. The example is now a program of its own, `encryption/json_example.rs`, as the crate's other two examples are. The encryption test crate runs it (`cargo test -p eql-encryption-tests --test json_example`), and the docs include its source. --- .../src/encryption/json_example.rs | 30 ++++++++++++++++ .../crates/eql-bindings/src/v4/json_tree.rs | 34 ++++--------------- packages/eql/tests/encryption/Cargo.toml | 6 ++++ 3 files changed, 42 insertions(+), 28 deletions(-) create mode 100644 packages/eql/crates/eql-bindings/src/encryption/json_example.rs 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/v4/json_tree.rs b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs index ad35402874..5865053ab4 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -564,35 +564,13 @@ impl JsonTreeDocument { /// A [`JsonPlaintext`] seals into a document as a `serde_json::Value` does, /// under the default options ([`JsonTree::default`]), with the column as -/// its context: +/// its context. /// -/// ```no_run -/// use eql_bindings::{v4::json_tree::JsonTreeDocument, Identifier}; -/// use stack_encrypt::json::JsonPlaintext; -/// use stack_encrypt::kms::{DataKeySource, IndexKeySource}; -/// use stack_encrypt::{DecryptFrom, EncryptInto, KeysetCipher}; -/// -/// # async fn example(keyset: &KeysetCipher<'_, K>) -> Result<(), Box> -/// # where -/// # K: DataKeySource + IndexKeySource + Sync + 'static, -/// # { -/// let column = Identifier::for_column("customers", "profile")?; -/// let profile = JsonPlaintext::from(serde_json::json!({"name": "Ada", "age": 36})); -/// let document: JsonTreeDocument = profile -/// .encrypt_into_with_context(keyset, column.clone()) -/// .await?; -/// assert_eq!(document.i, *column.get()); -/// -/// // The column is checked against the one the document stores. -/// let opened = JsonPlaintext::decrypt_from_with_context(document, keyset, column).await?; -/// assert_eq!(opened.value()["name"], "Ada"); -/// # Ok(()) -/// # } -/// ``` -/// -/// The example is compiled, and not run: this crate's doctests have no key -/// source. `record_fields.rs` in the encryption test crate runs the same -/// calls. +/// 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 diff --git a/packages/eql/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index d40e902f5f..0aed47a950 100644 --- a/packages/eql/tests/encryption/Cargo.toml +++ b/packages/eql/tests/encryption/Cargo.toml @@ -17,6 +17,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 From a167e79fb22917f02c8a4dbc24a8e6271e4501c9 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 16:19:56 +1100 Subject: [PATCH 09/13] refactor(stack-encrypt): name the context a record decrypts under `ExpectedContext::opening` is now `decryption_context`. It checks the context a row stores, and returns the context the record decrypts under. The old name did not say that. Its doc gains a scenario and an example that runs: a `TextEq` in `members.email`, on its own and as a field of a record with a tenant scope and a row binding. The doc also says what a rename does in each case. A new test covers a renamed EQL field: `identity` keeps its column, and without it the old rows are refused before any key is requested. `ExpectedContext` is hidden from the docs. Only the derive and `JsonTreeDocument` call the method. --- .../crates/eql-bindings/src/v4/json_tree.rs | 2 +- .../tests/encryption/tests/record_fields.rs | 76 +++++++++ .../stack-encrypt-derive/src/owned_decrypt.rs | 4 +- packages/stack-encrypt/src/target/context.rs | 149 +++++++++++++++--- 4 files changed, 210 insertions(+), 21 deletions(-) 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 5865053ab4..5e40b6a10e 100644 --- a/packages/eql/crates/eql-bindings/src/v4/json_tree.rs +++ b/packages/eql/crates/eql-bindings/src/v4/json_tree.rs @@ -551,7 +551,7 @@ impl JsonTreeDocument { /// of a record, it opens under the scopes and bindings of the record /// too. fn open(self, context: ExpectedContext) -> Decryption { - let context = match context.opening(self.i.clone()) { + let context = match context.decryption_context(self.i.clone()) { Ok(context) => context, Err(error) => return Decryption::failed(error), }; diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index 49b0773e04..022e7950f4 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -24,6 +24,8 @@ //! - 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. @@ -833,6 +835,80 @@ async fn a_field_that_stores_another_column_is_refused() { ); } +/// `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"]}) } diff --git a/packages/stack-encrypt-derive/src/owned_decrypt.rs b/packages/stack-encrypt-derive/src/owned_decrypt.rs index cf35737c54..11a7882c29 100644 --- a/packages/stack-encrypt-derive/src/owned_decrypt.rs +++ b/packages/stack-encrypt-derive/src/owned_decrypt.rs @@ -230,7 +230,7 @@ fn struct_body( /// 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::opening`). +/// scopes and bindings of that record (`ExpectedContext::decryption_context`). fn value_body( record: &Record, plaintext: &Type, @@ -244,7 +244,7 @@ fn value_body( let stored = record.context_field().map(|field| { let member = &field.member; quote! { - let __context = match __context.opening(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/src/target/context.rs b/packages/stack-encrypt/src/target/context.rs index cb440cafba..289dc56eee 100644 --- a/packages/stack-encrypt/src/target/context.rs +++ b/packages/stack-encrypt/src/target/context.rs @@ -1013,9 +1013,10 @@ where } impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { /// Check the stored context against this expectation and prove it - /// nonempty. It returns the stored context alone. A record opens under - /// the context [`opening`](Self::opening) returns: a record field also - /// opens under the scopes and bindings of its record. + /// nonempty. It returns the stored context alone. A record decrypts + /// under the context [`decryption_context`](Self::decryption_context) + /// returns: a record field also decrypts under the scopes and bindings + /// of its record. /// /// # Errors /// @@ -1042,17 +1043,129 @@ impl<'c, T: MaybeEmpty + PartialEq + IntoContext<'c>> ExpectedContext { nonempty(stored) } - /// Check the stored context as [`validate`](Self::validate) does, and - /// return the context the record opens under. + /// Check the context that a row stores, and return the context the + /// record decrypts under. /// - /// On its own, a record opens under the context it stores. As a field - /// of another record, it opens under that context, then the scopes and - /// bindings of the record, which the field does not store. + /// The two contexts are the same for a record on its own. They differ + /// for a record that is a field of another record. + /// + /// For example, take a `TextEq` value in the column `email` of the + /// table `members`. Its row stores `i = {"t": "members", "c": "email"}`. + /// + /// - **On its own**, the value decrypts under what the row stores: + /// `members/email`. + /// - If the reader passes the column it expects, a row that stores + /// another column is refused. + /// - If the reader passes no column, any stored column is accepted. + /// So a row written before the column was renamed still decrypts. + /// - **As the field `email` of a record** with + /// `scope = "members", scope(tenant: u64), bind(row: u128)`, the row + /// stores the same `i`. The tenant and the row ID are not in it. + /// - The reader passes them again, such as tenant 7 and row 9. The + /// value decrypts under `members/email`, then tenant 7, then row 9. + /// - The row must store the field's own column. A row that stores + /// `members/name` is refused: it was written for another field. + /// - So a renamed field does not decrypt the rows written under its + /// old name. That is true of a field of any type, because the name + /// is part of the field's context. Keep the old name with + /// `#[stash(identity = "old_name")]`. + /// + /// [`validate`](Self::validate) makes the same check, and returns the + /// stored context in place of the context to decrypt under. + /// + /// # Example + /// + /// `Column` stores a table and a column, as an EQL type does. It is the + /// type in the example on [`ContextFromField`]. + /// + /// ``` + /// use stack_encrypt::target::{ContextFromField, DeclaredContext, ExpectedContext, Scope}; + /// use stack_encrypt::{ + /// nonempty, CallerContext, ContextPiece, Descriptor, Error, IntoContext, MaybeEmpty, + /// NonEmpty, + /// }; + /// + /// #[derive(Clone, Debug, PartialEq)] + /// struct Column { + /// table: String, + /// column: String, + /// } + /// # impl MaybeEmpty for Column { + /// # fn is_empty(&self) -> bool { + /// # self.table.is_empty() || self.column.is_empty() + /// # } + /// # } + /// # impl<'a> IntoContext<'a> for Column { + /// # fn into_context(self) -> ContextPiece<'a> { + /// # ContextPiece::List(vec![ + /// # ContextPiece::Text(self.table.into()), + /// # ContextPiece::Text(self.column.into()), + /// # ]) + /// # } + /// # } + /// # impl ContextFromField for Column { + /// # 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; + /// # }; + /// # NonEmpty::new(Self { + /// # table: table.to_string(), + /// # column: column.to_string(), + /// # }) + /// # .ok() + /// # } + /// # } + /// // What a row of `members` stores in a column of this type. + /// fn stored_in(column: &str) -> Column { + /// Column { + /// table: "members".into(), + /// column: column.into(), + /// } + /// } + /// // A context, as the descriptor that names it. + /// fn named(context: &ContextPiece<'_>) -> String { + /// Descriptor::from_piece(context).as_str().to_owned() + /// } + /// + /// // On its own: the reader expects `members/email`. The row stores + /// // it, and the value decrypts under it. + /// let expected = ExpectedContext::from(NonEmpty::new(stored_in("email"))?); + /// let context = expected.decryption_context(stored_in("email"))?; + /// assert_eq!(named(&context.stored()), "members/email"); + /// + /// // On its own, with no expected column: a row written before the + /// // column was renamed decrypts under the name it stores. + /// let context = ExpectedContext::default().decryption_context(stored_in("old_email"))?; + /// assert_eq!(named(&context.stored()), "members/old_email"); + /// + /// // As the field `email` of a record with the scope `members`, a + /// // tenant scope and a row binding. The reader passes tenant 7 and + /// // row 9 again. + /// let field = DeclaredContext::default() + /// .with(CallerContext::from(Scope::new(7u64).bind(9u128))) + /// .under(nonempty!("members").with("email")); + /// let expected = ExpectedContext::::from(field); + /// + /// // The row stores `members/email` alone. The value decrypts under + /// // more. Its search terms derive under the column, then the tenant. + /// // Its ciphertext is sealed under the row too. + /// let context = expected.clone().decryption_context(stored_in("email"))?; + /// assert_eq!(named(&context.query()), "(members/email)/7u64"); + /// assert_eq!(named(&context.stored()), "((members/email)/7u64)/9u128"); + /// + /// // A row that stores another column was written for another field. + /// let refused = expected.decryption_context(stored_in("name")); + /// assert!(matches!(refused, Err(Error::ContextMismatch { .. }))); + /// # Ok::<(), Box>(()) + /// ``` /// /// # Errors /// /// As [`validate`](Self::validate), before any key is requested. - pub fn opening(self, stored: T) -> Result { + pub fn decryption_context(self, stored: T) -> Result { let context = match &self.0 { Expected::Field { context, .. } => Some(context.clone()), Expected::Any | Expected::Exactly(_) => None, @@ -1357,12 +1470,12 @@ mod tests { // On decrypt the stored context must be the field's own, and the // field opens under the same whole context. - let opening = ExpectedContext::::from(field.clone()) - .opening(stored) + let decrypts_under = ExpectedContext::::from(field.clone()) + .decryption_context(stored) .unwrap(); - assert_eq!(opening.stored(), field.stored()); + assert_eq!(decrypts_under.stored(), field.stored()); let elsewhere = ExpectedContext::::from(field) - .opening(Pair("users".into(), "name".into())) + .decryption_context(Pair("users".into(), "name".into())) .unwrap_err(); assert!(matches!(elsewhere, Error::ContextMismatch { .. })); } @@ -1376,10 +1489,10 @@ mod tests { assert_eq!(stored, *passed.get()); assert_eq!(context.stored(), passed.clone().into_context()); - let opening = ExpectedContext::from(passed.clone()) - .opening(stored) + let decrypts_under = ExpectedContext::from(passed.clone()) + .decryption_context(stored) .unwrap(); - assert_eq!(opening.stored(), passed.into_context()); + assert_eq!(decrypts_under.stored(), passed.into_context()); } /// A type that cannot store the field's own context is refused, and the @@ -1395,7 +1508,7 @@ mod tests { assert_eq!(not_storable(refused), "(users/email)/x"); let stored = Pair("users".into(), "email".into()); let refused = ExpectedContext::::from(three) - .opening(stored.clone()) + .decryption_context(stored.clone()) .unwrap_err(); assert_eq!(not_storable(refused), "(users/email)/x"); @@ -1405,7 +1518,7 @@ mod tests { .unwrap_err(); assert_eq!(not_storable(refused), "users/email"); let refused = ExpectedContext::::from(field) - .opening(Swapped(stored)) + .decryption_context(Swapped(stored)) .unwrap_err(); assert_eq!(not_storable(refused), "users/email"); } From 61869c0d2442c15c9ebb4b2ce24de1a7c806d5f6 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 16:19:57 +1100 Subject: [PATCH 10/13] docs(eql-bindings): run every Rust example in the README No Rust block in the README is marked `ignore` now. Each of the six is a complete program, and `cargo test -p eql-encryption-tests --doc` runs it, as part of `mise run test:encryption`. The encryption test crate gains a library with no code. It includes the README as documentation when doctests are built. That crate already has the key source and the async runtime the examples need, so eql-bindings gains no dependency. A failing example is reported at its line in the README. A new test fails if a Rust block is marked `ignore` or `no_run`. Running the examples found one that no longer compiled: `targets::query` takes the index that answers the operator. The README also still said that an extended query is refused. The scope and binding example writes `Scope::new(tenant).bind(row)` at each call, in place of a closure that built it twice. The record fields section says how a renamed field keeps its column. --- AGENTS.md | 2 +- packages/eql/crates/eql-bindings/README.md | 329 +++++++++++++----- packages/eql/tests/encryption/Cargo.toml | 10 + packages/eql/tests/encryption/src/lib.rs | 14 + .../tests/encryption/tests/readme_examples.rs | 47 +++ 5 files changed, 319 insertions(+), 83 deletions(-) create mode 100644 packages/eql/tests/encryption/src/lib.rs create mode 100644 packages/eql/tests/encryption/tests/readme_examples.rs 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/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index 89c0aa1a88..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 @@ -404,10 +473,12 @@ 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,ignore +```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}; +use stack_encrypt::{DecryptFrom, DecryptSource, EncryptInto, EncryptTarget, StackCipher}; +use stack_kms::FakeDataKeySource; #[derive(zeroize::Zeroize)] struct Member { @@ -422,42 +493,110 @@ struct Member { 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"} + email: TextEq, // i = {"t": "members", "c": "email"} + age: IntegerOrd, // i = {"t": "members", "c": "age"} + profile: JsonTreeDocument, // i = {"t": "members", "c": "profile"} } -let stored: EncryptedMember = member.encrypt_into(&keyset).await?; -let query = EncryptedMember::EMAIL.eq("alice@example.com").encrypt(&keyset).await?; -let opened = Member::decrypt_from(stored, &keyset).await?; +#[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. +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: -A record can also list a scope or a binding, such as a tenant or a row ID: +```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, +} -```rust,ignore #[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"} - age: IntegerOrd, // i = {"t": "members", "c": "age"} - profile: JsonTreeDocument, // i = {"t": "members", "c": "profile"} + email: TextEq, // i = {"t": "members", "c": "email"} } -let parts = || Scope::new(tenant).bind(row); -let stored: EncryptedMember = member.encrypt_into_with_context(&keyset, parts()).await?; -let query = EncryptedMember::EMAIL - .eq("alice@example.com") - .scope(Scope::new(tenant)) - .encrypt(&keyset) - .await?; -let opened = Member::decrypt_from_with_context(stored, &keyset, parts()).await?; +#[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 @@ -493,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 diff --git a/packages/eql/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index 0aed47a950..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]] 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/readme_examples.rs b/packages/eql/tests/encryption/tests/readme_examples.rs new file mode 100644 index 0000000000..97a9f13265 --- /dev/null +++ b/packages/eql/tests/encryption/tests/readme_examples.rs @@ -0,0 +1,47 @@ +//! 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. + +const README: &str = include_str!("../../../crates/eql-bindings/README.md"); + +/// 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 +} + +#[test] +fn every_rust_block_in_the_readme_is_run() { + // rustdoc reads a block with no language as Rust too. + let rust: Vec<_> = code_blocks(README) + .into_iter() + .filter(|(_, info)| info.is_empty() || info.starts_with("rust")) + .collect(); + assert!(!rust.is_empty(), "the README has no Rust code block"); + for (line, info) in rust { + assert_eq!( + info, "rust", + "README line {line}: mark the block `rust` alone, so that it is run" + ); + } +} + +#[test] +fn the_scan_finds_a_marked_block() { + 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, "")]); +} From 942648c7e6183ab3c3c1fc9e69149573a7f3229a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 15 Nov 2026 17:18:10 +1100 Subject: [PATCH 11/13] fix(stack-encrypt,golang): query and read a JSON document under its scope A data plan with a scope can now hold a JSON document field. The document was sealed under its column, then the scope. Its JSON operators and its reads still derived under the column alone. So a query under a scope found nothing, and reported no error. CodeRabbit found it. A document field now runs under the contexts it was sealed under: - `dynamic::query_term` derives a JSON operand under the field's label, then the plan's scopes. - `dynamic::json_open` derives its selector or read key in the same way, and opens each entry under the plan's bindings too. So it takes a plan with a binding, where it refused one. A query still refuses a binding. - In Go, `Cipher.JSONOpen` opens a read's rows through a cipher with a binding, where it refused one. New tests seal a document under a tenant and a row. 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. The engine tests fail without the fix. Go's generated readers (`Select`, `Subtree`) open with the cipher that prepared the read, and preparing a read takes no binding. So they still do not open a document sealed with a binding. The READMEs and the CHANGELOGs say so. --- languages/golang/CHANGELOG.md | 9 + languages/golang/encrypt/README.md | 7 +- languages/golang/encrypt/json.go | 10 +- languages/golang/encrypt/json_tree_test.go | 123 +++++++++++ languages/golang/encrypt/records.go | 20 ++ .../encryption/tests/json_tree_data_plan.rs | 114 +++++++++- packages/stack-encrypt/CHANGELOG.md | 9 + .../src/dynamic/json_predicate.rs | 8 +- .../stack-encrypt/src/dynamic/json_query.rs | 119 ++++++---- packages/stack-encrypt/src/dynamic/query.rs | 71 +++--- packages/stack-encrypt/src/dynamic/record.rs | 2 +- .../stack-encrypt/tests/json_operators.rs | 208 +++++++++++++++++- 12 files changed, 625 insertions(+), 75 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index fa0c49b760..db52243656 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -261,6 +261,15 @@ sends queries: 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 `Select` 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. + - `Select` and `Subtree` open with the cipher that prepared the read, + and preparing a read takes no binding. So they read a document sealed + with a scope, and do not open one sealed with a binding. Open that + document whole, through the cipher with the binding. ## [0.1.0-rc.4] - 2026-11-13 diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 66a1763c57..475f744bee 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -634,7 +634,12 @@ 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. +- query it through a cipher with the same scope. A binding is in no query; +- read part of a `JsonSearch` document (`Select`, `Subtree`) through a + cipher with the same scope. These readers open with the cipher that + prepared the read, and preparing a read takes no binding. So they do not + open a document sealed with a binding: open that document whole, through + the cipher with the binding. ### Encrypted JSON documents diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index 2e9b15d801..7948bd8b74 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -36,11 +36,19 @@ 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. The selector or the key derives +// under the scope alone, as a query's term does: prepare the read through +// a cipher with 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 } diff --git a/languages/golang/encrypt/json_tree_test.go b/languages/golang/encrypt/json_tree_test.go index 9fd49a5037..499ec14e3f 100644 --- a/languages/golang/encrypt/json_tree_test.go +++ b/languages/golang/encrypt/json_tree_test.go @@ -262,6 +262,129 @@ 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. 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 is prepared with the scope and no binding, and opened + // 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) + } + } + }) + } + + // Preparing a read is a query, and a query takes no binding. + if _, err := bound.QueryTerm(ctx, jsonPlan(), "profile", "selector", vcvalue.Object{{Key: "path", Value: "$.name"}}); !errors.Is(err, encrypt.ErrEncoding) { + t.Errorf("a selector through a cipher with a binding: %v", 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/records.go b/languages/golang/encrypt/records.go index bb19e369c7..f28a0c2875 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -185,6 +185,26 @@ 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) +} + +// 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/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/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 8565f501b5..b10400a4e3 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -255,6 +255,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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 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