From de9d08c8bb63bd241f38c0f1e84b45481a1df3ad Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 01:26:00 +1100 Subject: [PATCH 01/10] feat(stack-encrypt): convert a stored record to a frame and back A binding moves the stored record to its language and back. Until now, each binding walked the tree itself, and the TypeScript binding renamed its keys. Stack Encrypt now does this once, for every binding. dynamic::record::stored_frame writes a stored record, or a batch, as a frame under the record's own keys. read_stored reads the frame back. It takes the plan, because only the plan says which output is sealed. Two more functions do the same for one field's node. vitaminc-aead gains Frame::entries. It reads a map's entries with no copy, as Frame::elements reads a sequence's elements. Closes #2029. --- packages/recipher-frame/CHANGELOG.md | 1 + packages/recipher-frame/src/lib.rs | 4 +- packages/stack-encrypt/CHANGELOG.md | 30 + .../docs/language-integration.md | 35 + packages/stack-encrypt/src/dynamic/record.rs | 90 +- .../src/dynamic/record/stored.rs | 487 +++++++++ .../src/dynamic/record/stored/tests.rs | 993 ++++++++++++++++++ packages/stack-encrypt/src/refusal.rs | 23 +- packages/vitaminc-aead/CHANGELOG.md | 4 + packages/vitaminc-aead/src/frame.rs | 120 +++ 10 files changed, 1780 insertions(+), 7 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/record/stored.rs create mode 100644 packages/stack-encrypt/src/dynamic/record/stored/tests.rs diff --git a/packages/recipher-frame/CHANGELOG.md b/packages/recipher-frame/CHANGELOG.md index c1db7722a..0f87cc3f8 100644 --- a/packages/recipher-frame/CHANGELOG.md +++ b/packages/recipher-frame/CHANGELOG.md @@ -9,6 +9,7 @@ ### Added - `OwnedFrame` is re-exported from `vitaminc-aead`, with the rest of the frame. +- `Entries` is re-exported from `vitaminc-aead`, beside `Elements`: what `Frame::entries` returns. ## [0.10.0] - 2026-11-19 diff --git a/packages/recipher-frame/src/lib.rs b/packages/recipher-frame/src/lib.rs index 0ec153c12..ec29db060 100644 --- a/packages/recipher-frame/src/lib.rs +++ b/packages/recipher-frame/src/lib.rs @@ -43,8 +43,8 @@ pub use transport::{decode_ciphertext, encode_ciphertext, CodecError}; /// `vitaminc-aead` next to the leaf codec they share, and are re-exported /// here so a binding that depends on this crate has the whole transport. pub use vitaminc_aead::frame::{ - Elements, FrameError, FrameWriteError, OwnedFrameContainer, OwnedFrameSink, ARRAY, MAX_DEPTH, - OBJECT, PASSTHROUGH, + Elements, Entries, FrameError, FrameWriteError, OwnedFrameContainer, OwnedFrameSink, ARRAY, + MAX_DEPTH, OBJECT, PASSTHROUGH, }; /// The leaf tag table, which lives with the leaf codec in `vitaminc-aead`. pub use vitaminc_aead::tags; diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7ab0bf090..0f723025c 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **A stored record as a frame, and back** (#2029). Every binding moves the + stored record to its language and back with these functions, so no + binding walks the tree or renames a key itself. + - `dynamic::record::stored_frame(&stored, &plan)` writes a stored record, + or a batch, as a frame in a buffer wiped when it drops. Each field is an + object of its outputs, under the record's own keys (`c`, `eq`, `match`, + `ore`, `ope`, `passthrough`, `eql`). A sealed value is its bytes + (`SealedValue::to_bytes`). A term or an EQL value is its bytes, and a + passthrough field's value is the value. A list or a map under `c` is an + array or an object. The marker of an empty list or map is the array + `["empty_seq", ]` or `["empty_map", ]`. + - `dynamic::record::read_stored(frame, &plan)` reads the frame back as the + `StackCipherText` to decrypt. It takes the plan, because only the plan + says which output is sealed and which is in the clear. A + `"null": "sql"` field that is left out, or given as null, has no entry. + - `dynamic::record::stored_field_frame` and `read_stored_field` do the + same for one field's node, the map of its outputs. + - The frame is a transport form, not a storage format. Store the bytes + inside it. + - Each refusal is `Error::Record` and names the field. Two new reasons + say what was wrong. `undeclared_output` is for an output that the field + does not declare. `not_sealed` is for a node under `c` that is not in + the frame form. - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` @@ -1806,6 +1829,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **The message for `Reason::Unframeable` no longer says "passthrough".** + The message was "a passthrough value nests deeper, or holds a longer + value, than a frame carries". The message is now "a value nests deeper, + or holds a longer value, than a frame carries". The reason is also given + for a value to encrypt, and for a stored record written as a frame. The + name `unframeable` is unchanged. + - **The `Debug` text of `OpaqueBlob` and `JsonPlaintext` has changed.** Both types now derive vitaminc's `OpaqueDebug`, as the crate's other secret types do. The text starts with the type's full path and masks the diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 064f5c2b0..8b4b8cf3b 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -135,6 +135,26 @@ and never needs the field's type. Anything else of another type is refused with the reason `field_type`, and JavaScript's `undefined` with the reason `undefined`. A field that declares no type takes its value as it is. +A binding gives the stored record to its language as a frame. +[`crate::dynamic::record::stored_frame`]`(&stored, &plan)` writes the +frame, in a buffer that is wiped when it is dropped. The frame keeps the +record's keys as they are. Each field is an object of its outputs: + +- A sealed value under `c` is its bytes. +- An index term is its bytes. +- A passthrough field's value is the value itself. +- A field with `"null": "sql"` and no value has no entry. + +The binding builds its language's value from this frame, as it does for a +decrypted value. So in JavaScript the record `{ email, id }` is +`{ email: { c: Uint8Array, eq: Uint8Array }, id: { passthrough: 7n } }`. +The binding walks no tree and renames no key. +[`crate::dynamic::record::stored_field_frame`] does the same for one +field's node. + +The frame is how the record crosses to the language, not how it is +stored. Store the bytes inside the frame. + ### Derive a query term A query is planned before any value exists: @@ -170,6 +190,21 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. +A binding reads the stored record back from its language's value as a +frame. [`crate::dynamic::record::read_stored`]`(frame, &plan)` returns the +[`crate::StackCipherText`] to decrypt. The function takes the plan. A +sealed value and an index term are both bytes in the frame, and only the +plan says which output is sealed. + +- For a column that contains SQL `NULL`, leave the field out or send a + null. Either works only for a field with `"null": "sql"`. +- The binding does not have to send the index terms. Decrypt reads only + `c`, `passthrough`, and `eql`. +- A field or output that the plan does not declare is refused. The error + names the field. + +[`crate::dynamic::record::read_stored_field`] reads one field's node. + ### One value as one ciphertext A record is not the only stored form. Rust's `keyset.encrypt(value)` diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 30acdc750..00d254c51 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -143,6 +143,89 @@ //! `"c"` subtree with a passthrough carrying forged plaintext and have it //! reported as a successful decrypt. The encrypt-side refusal is what makes //! that a round-trip invariant rather than data loss. +//! +//! # The stored record as a frame +//! +//! [`encrypt`] returns a stored record, a +//! [`StackCipherText`], and [`decrypt`] takes one. A binding +//! moves the stored record to its language and back as a frame. A frame is +//! the encoding that a value crosses in. [`stored_frame`] writes the frame, +//! and [`read_stored`] reads it back. [`stored_field_frame`] and +//! [`read_stored_field`] do the same for one field's node. +//! +//! The binding builds its language's value from the frame, as it does for +//! any value. So the binding walks no tree and renames no key. +//! +//! ## The frame form +//! +//! | In the stored record | In the frame | +//! |---|---| +//! | the record | an object with one entry for each field, in the record's order | +//! | a batch | an array of records | +//! | a field | an object with one entry for each output, under the stored record's key: `c`, an index key such as `eq` or `ore`, `passthrough`, or `eql` | +//! | a term, a passthrough field's value, or an EQL value | the value in the node, as it is: bytes for a term or an EQL value, and the field's value for `passthrough` | +//! | a sealed value under `c` | its bytes ([`SealedValue::to_bytes`](crate::SealedValue::to_bytes)) | +//! | a list of sealed nodes under `c` | an array of them | +//! | a map of sealed nodes under `c` | an object of them, in the stored order | +//! | the marker of an empty list under `c` | the array `["empty_seq", ]` | +//! | the marker of an empty map under `c` | the array `["empty_map", ]` | +//! +//! Take a plan that seals and indexes `email`, and passes `id` through. A +//! row sealed from `{ "email": "ada@example.com", "id": "u-7" }` has this +//! frame: +//! +//! ```text +//! { "email": { "c": , "eq": }, "id": { "passthrough": "u-7" } } +//! ``` +//! +//! An array under `c` that starts with the text `empty_seq` or `empty_map` +//! is a marker. A sealed node is never text, so the form has only one +//! reading. +//! +//! The frame is a transport form, not a storage format. A binding stores +//! the bytes inside the frame. A sealed value's bytes and a term's bytes +//! are stable. The frame around them can change between releases, as any +//! frame can. +//! +//! ## Why the plan is an argument +//! +//! A sealed value and a term are both bytes in the frame. Only the plan says +//! which output of a field is sealed. The sealed output is `c`. Every other +//! output is in the clear. +//! +//! So [`read_stored`] takes the plan, and never decides what a node is from +//! its bytes. [`stored_frame`] takes the plan too, and refuses a record that +//! the plan could not read back. +//! +//! ## A field with no value +//! +//! A field with `"null": "sql"` has no entry in a stored record when it has +//! no value. So it has no entry in the frame. [`read_stored`] reads such a +//! field as a missing entry when the frame leaves it out, or gives it as +//! null. [`decrypt`] opens a missing entry as a null. +//! +//! So for a column that contains SQL `NULL`, a binding leaves the field out +//! or sends a null. [`read_stored`] refuses a null for any other field. +//! +//! ## Refusals +//! +//! Each refusal is [`Error::Record`], and names the field. The one +//! exception is [`Error::Plan`], for a field that the plan does not have, +//! given to a function for one field. The [`Reason`] says which output is +//! at fault: +//! +//! - [`Reason::NotSealed`] and [`Reason::Passthrough`] are about `c`. +//! - [`Reason::NotPassthrough`] is about an output in the clear. +//! - [`Reason::UndeclaredOutput`] is about an output that the field does +//! not declare. +//! +//! No refusal contains a value, or the text of a key inside a sealed node. +//! +//! [`read_stored`] refuses a frame that is not in the frame form. It also +//! refuses a field or output that the plan does not declare, because it +//! cannot tell what that node is. [`decrypt`] makes every +//! other check, once. For example, `decrypt` refuses a sealed field with no +//! `c`, and a passthrough value of the wrong type. use std::collections::BTreeSet; use std::fmt; @@ -171,6 +254,9 @@ use crate::{ }; use vitaminc_aead::IntoContext as _; +mod stored; +pub use stored::{read_stored, read_stored_field, stored_field_frame, stored_frame}; + /// The map key a target field's EQL value rides under in a stored record: /// wire format, like the output keys (see the /// [module docs](self#the-stored-record-is-wire-format)). @@ -6891,13 +6977,13 @@ mod tests { /// is stored under `"eql"`, opens through the resolver, and every /// refusal is decided before a key is touched — not EQL's envelope, /// which is `eql-bindings`' to prove. - mod given_a_target_field { + pub(in crate::dynamic::record) mod given_a_target_field { use super::*; use crate::dynamic::{NoTargets, TargetDescriptor, TargetError, TargetResolver}; use crate::target::{CallerContext, Decryption}; use crate::SealedValue; - struct FakeEql; + pub(in crate::dynamic::record) struct FakeEql; const TEXT_EQ: &str = "TextEq"; diff --git a/packages/stack-encrypt/src/dynamic/record/stored.rs b/packages/stack-encrypt/src/dynamic/record/stored.rs new file mode 100644 index 000000000..d3049486b --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/record/stored.rs @@ -0,0 +1,487 @@ +//! A stored record as a frame, and a frame back as a stored record. The +//! form, and why the plan is an argument, are in the +//! [`record` module docs](super#the-stored-record-as-a-frame). + +use std::collections::HashSet; + +use vitaminc_aead::frame::{Entries, Frame, FrameWriteError, FrameWriter, OwnedFrame}; +use vitaminc_aead::plaintext::{Logical, MapSink, Physical, SeqSink, Sink}; +use vitaminc_aead::Encrypt as _; +use vitaminc_protected::Buffer; + +use super::{stored_kind, FieldPlan, NullMode, Output, Plan, EQL_KEY}; +use crate::dynamic::term::OneScalar; +use crate::dynamic::{Error, Found, Reason}; +use crate::{CipherText, PassthroughFrame, SealedValue, StackCipherText}; + +/// The text before the bytes of an empty list's marker under `c`. +const EMPTY_SEQUENCE: &str = "empty_seq"; + +/// The text before the bytes of an empty map's marker under `c`. +const EMPTY_MAP: &str = "empty_map"; + +/// Write a stored record, or a batch of records, as a frame. +/// +/// `record` is what [`encrypt`](super::encrypt) returned under `plan`. The +/// result has the frame form that the [module docs](super#the-frame-form) +/// describe. The frame is in a buffer that is wiped when it is dropped, +/// because a passthrough field's value is caller plaintext. +/// +/// # Examples +/// +/// ``` +/// use std::collections::BTreeMap; +/// +/// use stack_encrypt::dynamic::{frame::OwnedFrame, record}; +/// use stack_encrypt::{AsProtectedRef, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// let declaration = recipher_frame::serde::to_vec(&serde_json::json!({ +/// "email": { "context": ["users", "email"], "outputs": ["c", "eq"], "type": "string" }, +/// "id": { "context": ["users", "id"], "outputs": ["passthrough"] }, +/// }))?; +/// let plan = record::plan(declaration.as_protected_ref())?; +/// +/// let row = BTreeMap::from([("email", "ada@example.com"), ("id", "u-7")]); +/// let row = OwnedFrame::of(&row)?; +/// let stored = record::encrypt(&keyset, &row, &plan)?.await?; +/// +/// // The stored record as a frame. The binding builds its language's value +/// // from it: `{ email: { c: , eq: }, id: { passthrough: "u-7" } }`. +/// let frame = record::stored_frame(&stored, &plan)?; +/// let fields = frame.frame().entries().expect("an object of fields"); +/// let names: Vec<&str> = fields.map(|(name, _)| name).collect(); +/// assert_eq!(names, ["email", "id"]); +/// +/// // The binding reads its value back as a frame, and the record in it +/// // decrypts. +/// let stored = record::read_stored(frame.frame(), &plan)?; +/// let opened = record::decrypt(&cipher, stored, &plan, None)?.await?; +/// assert_eq!(opened.frame(), row.frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// [`Error::Record`] when `plan` could not read the record back. The error +/// names the field when there is one. The reasons are: +/// +/// - [`Reason::NotAnObject`]: the record is not a map, or not a sequence of +/// maps. +/// - [`Reason::UnknownField`]: the record has a field that the plan does +/// not name. +/// - [`Reason::FieldRepeated`]: the record has a field twice. +/// - [`Reason::OutputsNotMap`]: a field is not a map of outputs. +/// - [`Reason::UndeclaredOutput`]: a field has an output that it does not +/// declare. +/// - [`Reason::RepeatedKey`]: a field has an output twice, or a map under +/// `c` repeats a key. +/// - [`Reason::Passthrough`]: a passthrough is under `c`. +/// - [`Reason::NotPassthrough`]: an output in the clear is not a +/// passthrough that contains one frame. +/// - [`Reason::Unframeable`]: the frame would nest deeper than a frame can. +/// +/// The frame has one more level than the value, for each field's outputs. +/// An empty list or map under `c` adds one more. So a value nested to the +/// frame's limit can be sealed, and still be refused here. +pub fn stored_frame(record: &StackCipherText, plan: &Plan) -> Result { + let mut out = Buffer::new(); + let writer = FrameWriter::new(&mut out); + match record { + CipherText::Map(fields) => write_record(writer, fields, plan)?, + CipherText::Sequence(records) => { + let unframeable = |_| Error::bad_record(Reason::Unframeable); + let mut batch = writer.seq(Some(records.len())).map_err(unframeable)?; + for (at, record) in records.iter().enumerate() { + let CipherText::Map(fields) = record else { + return Err(not_an_object(Some(at), stored_kind(record))); + }; + write_record(batch.element().map_err(unframeable)?, fields, plan)?; + } + batch.end().map_err(unframeable)?; + } + other => return Err(not_an_object(None, stored_kind(other))), + } + // The writer checked each container as it ended, so the buffer + // contains one frame. + OwnedFrame::from_buffer(out).map_err(|_| Error::Internal) +} + +/// Read a stored record, or a batch of records, back from its frame. +/// +/// `frame` has the frame form that the [module docs](super#the-frame-form) +/// describe. It is what [`stored_frame`] wrote, or the same frame written +/// from a binding's value. The result is the record to give to +/// [`decrypt`](super::decrypt) under the same `plan`. Each sealed value is +/// read from its bytes ([`SealedValue::from_bytes`]). Each output in the +/// clear keeps its frame as it is. +/// +/// A field with `"null": "sql"` has no entry in the result when the frame +/// leaves it out, or gives it as null. `decrypt` opens it as a null. +/// +/// # Errors +/// +/// [`Error::Record`]. The error names the field when there is one. The +/// reasons are: +/// +/// - [`Reason::NotAnObject`]: the frame is not an object, or not an array +/// of objects. The error names the kind found, and the row in an array. +/// - [`Reason::UnknownField`]: the frame has a field that the plan does not +/// name. +/// - [`Reason::OutputsNotMap`]: a field is not an object of outputs. A null +/// is refused in the same way, unless the field has `"null": "sql"`. +/// - [`Reason::UndeclaredOutput`]: a field has an output that it does not +/// declare. +/// - [`Reason::Passthrough`]: a node under `c` is a passthrough. +/// - [`Reason::NotSealed`]: a node under `c` is not in the frame form. +/// +/// `decrypt` makes every other check, such as the check for a missing `c`. +pub fn read_stored(frame: Frame<'_>, plan: &Plan) -> Result { + if let Some(fields) = frame.entries() { + return read_record(fields, plan).map(CipherText::Map); + } + let Some(records) = frame.elements() else { + return Err(not_an_object(None, Found::of_frame(frame))); + }; + records + .enumerate() + .map(|(at, record)| match record.entries() { + Some(fields) => read_record(fields, plan).map(CipherText::Map), + None => Err(not_an_object(Some(at), Found::of_frame(record))), + }) + .collect::>() + .map(CipherText::Sequence) +} + +/// Write one field's node as a frame. The node is the map of the field's +/// outputs. The frame is the field's entry in the frame that +/// [`stored_frame`] writes. +/// +/// # Errors +/// +/// [`Error::Plan`] with [`Reason::NoSuchField`] if `plan` has no field +/// named `field`. Otherwise, the errors for a field's node that +/// [`stored_frame`] lists. +pub fn stored_field_frame( + node: &StackCipherText, + plan: &Plan, + field: &str, +) -> Result { + let field = plan_field(plan, field)?; + let mut out = Buffer::new(); + write_outputs(FrameWriter::new(&mut out), node, field)?; + OwnedFrame::from_buffer(out).map_err(|_| Error::Internal) +} + +/// Read one field's node back from its frame. The node is the map of the +/// field's outputs. The frame is the field's entry in the frame that +/// [`read_stored`] reads. +/// +/// A null is refused, whatever the field's null mode, because a field with +/// no value has no node. +/// +/// # Errors +/// +/// [`Error::Plan`] with [`Reason::NoSuchField`] if `plan` has no field +/// named `field`. Otherwise, the errors for a field's node that +/// [`read_stored`] lists. +pub fn read_stored_field( + frame: Frame<'_>, + plan: &Plan, + field: &str, +) -> Result { + read_outputs(frame, plan_field(plan, field)?) +} + +/// What a field's output contains, as the plan declares it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Content { + /// A sealed node: `c`. + Sealed, + /// A passthrough node: a term, a passthrough field's value, or an EQL + /// value. + Clear, +} + +/// What the output under `key` contains. `None` if `field` declares no such +/// output. +fn content(field: &FieldPlan, key: &str) -> Option { + if field.is_target() { + return (key == EQL_KEY).then_some(Content::Clear); + } + field + .outputs + .iter() + .find(|output| output.key() == key) + .map(|output| match output { + Output::Ciphertext => Content::Sealed, + Output::Term(_) | Output::Passthrough => Content::Clear, + }) +} + +/// The plan field named `name`. +fn plan_field<'p>(plan: &'p Plan, name: &str) -> Result<&'p FieldPlan, Error> { + plan.fields + .iter() + .find(|field| field.name == name) + .ok_or_else(|| Error::bad_plan(Reason::NoSuchField).in_field(name)) +} + +/// The plan field named `name`, for a field of a stored record. +fn record_field<'p>(plan: &'p Plan, name: &str) -> Result<&'p FieldPlan, Error> { + plan.fields + .iter() + .find(|field| field.name == name) + .ok_or_else(|| misfit(name, Reason::UnknownField)) +} + +/// A stored record that does not fit the plan, at `field`. +fn misfit(field: &str, reason: Reason) -> Error { + Error::bad_record(reason).in_field(field) +} + +/// A record, or the row `at` of a batch, that is `found` and not a map. +fn not_an_object(row: Option, found: Found) -> Error { + Error::Record { + field: None, + row, + reason: Reason::NotAnObject, + found: Some(found), + } +} + +/// The reason for a frame writer's refusal of a node. A map that repeats a +/// key is [`Reason::RepeatedKey`]. Any other refusal is a node that a frame +/// cannot contain. +fn written(error: FrameWriteError) -> Reason { + match error { + FrameWriteError::DuplicateKey => Reason::RepeatedKey, + _ => Reason::Unframeable, + } +} + +// ============================================================================= +// The stored record as a frame +// ============================================================================= + +fn write_record( + writer: FrameWriter<'_>, + fields: &[(String, StackCipherText)], + plan: &Plan, +) -> Result<(), Error> { + let mut record = writer + .map(Some(fields.len())) + .map_err(|error| Error::bad_record(written(error)))?; + let mut seen = HashSet::with_capacity(fields.len()); + for (name, node) in fields { + let field = record_field(plan, name)?; + if !seen.insert(name.as_str()) { + return Err(misfit(name, Reason::FieldRepeated)); + } + let entry = record + .entry(name) + .map_err(|error| misfit(name, written(error)))?; + write_outputs(entry, node, field)?; + } + record + .end() + .map_err(|error| Error::bad_record(written(error))) +} + +fn write_outputs( + writer: FrameWriter<'_>, + node: &StackCipherText, + field: &FieldPlan, +) -> Result<(), Error> { + let at_fault = |reason| misfit(&field.name, reason); + let CipherText::Map(outputs) = node else { + return Err(at_fault(Reason::OutputsNotMap)); + }; + let mut map = writer + .map(Some(outputs.len())) + .map_err(|error| at_fault(written(error)))?; + let mut seen = HashSet::with_capacity(outputs.len()); + for (key, node) in outputs { + let content = content(field, key).ok_or_else(|| at_fault(Reason::UndeclaredOutput))?; + if !seen.insert(key.as_str()) { + return Err(at_fault(Reason::RepeatedKey)); + } + let entry = map.entry(key).map_err(|error| at_fault(written(error)))?; + match content { + Content::Sealed => write_sealed(entry, node).map_err(at_fault)?, + Content::Clear => { + let CipherText::Passthrough(payload) = node else { + return Err(at_fault(Reason::NotPassthrough)); + }; + let value = payload + .parse() + .map_err(|_| at_fault(Reason::NotPassthrough))?; + value + .visit(entry) + .map_err(|error| at_fault(written(error)))?; + } + } + } + map.end().map_err(|error| at_fault(written(error))) +} + +/// Write the sealed node under `c`. A passthrough anywhere in it is +/// refused, because it would be handed back as if it had been opened. +fn write_sealed(writer: FrameWriter<'_>, node: &StackCipherText) -> Result<(), Reason> { + match node { + CipherText::Single(leaf) => writer + .scalar(None, Physical::Bytes(&leaf.to_bytes())) + .map_err(written), + CipherText::Sequence(items) => { + let mut sequence = writer.seq(Some(items.len())).map_err(written)?; + for item in items { + write_sealed(sequence.element().map_err(written)?, item)?; + } + sequence.end().map_err(written) + } + CipherText::Map(entries) => { + let mut map = writer.map(Some(entries.len())).map_err(written)?; + for (key, item) in entries { + write_sealed(map.entry(key).map_err(written)?, item)?; + } + map.end().map_err(written) + } + CipherText::EmptySequence(leaf) => write_marker(writer, EMPTY_SEQUENCE, leaf), + CipherText::EmptyMap(leaf) => write_marker(writer, EMPTY_MAP, leaf), + CipherText::Passthrough(_) => Err(Reason::Passthrough), + } +} + +fn write_marker(writer: FrameWriter<'_>, tag: &str, leaf: &SealedValue) -> Result<(), Reason> { + let mut marker = writer.seq(Some(2)).map_err(written)?; + marker + .element() + .map_err(written)? + .scalar(None, Physical::Text(tag)) + .map_err(written)?; + marker + .element() + .map_err(written)? + .scalar(None, Physical::Bytes(&leaf.to_bytes())) + .map_err(written)?; + marker.end().map_err(written) +} + +// ============================================================================= +// The frame as a stored record +// ============================================================================= + +fn read_record(fields: Entries<'_>, plan: &Plan) -> Result, Error> { + let mut record = Vec::with_capacity(fields.len()); + for (name, value) in fields { + let field = record_field(plan, name)?; + // The column contains SQL `NULL`. The record has no entry for the + // field. `decrypt` opens a missing entry as a null. + if value.is_null() && field.null == Some(NullMode::Sql) { + continue; + } + record.push((name.to_owned(), read_outputs(value, field)?)); + } + Ok(record) +} + +fn read_outputs(frame: Frame<'_>, field: &FieldPlan) -> Result { + let at_fault = |reason| misfit(&field.name, reason); + let entries = frame + .entries() + .ok_or_else(|| at_fault(Reason::OutputsNotMap))?; + let mut outputs = Vec::with_capacity(entries.len()); + for (key, node) in entries { + let node = match content(field, key).ok_or_else(|| at_fault(Reason::UndeclaredOutput))? { + Content::Sealed => read_sealed(node).map_err(at_fault)?, + // A passthrough is in the clear by contract. Its frame is kept + // as it is, as `encrypt` keeps it. + Content::Clear => CipherText::Passthrough(PassthroughFrame(node.as_bytes().to_vec())), + }; + outputs.push((key.to_owned(), node)); + } + Ok(CipherText::Map(outputs)) +} + +/// Read the sealed node under `c`. The kind of each frame node decides how +/// it is read. Its bytes never do. +fn read_sealed(frame: Frame<'_>) -> Result { + if let Some(entries) = frame.entries() { + return entries + .map(|(key, item)| Ok((key.to_owned(), read_sealed(item)?))) + .collect::>() + .map(CipherText::Map); + } + if let Some(mut items) = frame.elements() { + // A sealed node is never text, so an array that starts with a + // marker's text is a marker. Any other text is refused below, as + // an element that is not sealed. + if let Some(marker) = items.clone().next().and_then(marker) { + let (Some(_), Some(leaf), None) = (items.next(), items.next(), items.next()) else { + return Err(Reason::NotSealed); + }; + let leaf = sealed_value(leaf).ok_or(Reason::NotSealed)?; + return Ok(match marker { + Marker::Sequence => CipherText::EmptySequence(leaf), + Marker::Map => CipherText::EmptyMap(leaf), + }); + } + return items + .map(read_sealed) + .collect::>() + .map(CipherText::Sequence); + } + if Found::of_frame(frame) == Found::Passthrough { + return Err(Reason::Passthrough); + } + sealed_value(frame) + .map(CipherText::Single) + .ok_or(Reason::NotSealed) +} + +/// The marker that the text at the start of an array under `c` names. +enum Marker { + /// `empty_seq`: an empty list. + Sequence, + /// `empty_map`: an empty map. + Map, +} + +/// The marker that a frame of text names. `None` if the frame is not the +/// text of a marker. +fn marker(frame: Frame<'_>) -> Option { + frame + .visit(OneScalar::new( + |ty: Option, value: Physical<'_>| match (ty, value) { + (None, Physical::Text(EMPTY_SEQUENCE)) => Ok(Marker::Sequence), + (None, Physical::Text(EMPTY_MAP)) => Ok(Marker::Map), + _ => Err(None), + }, + )) + .ok() +} + +/// The sealed value in a frame of bytes. `None` if the frame is not bytes, +/// or the bytes are not a sealed value's. +fn sealed_value(frame: Frame<'_>) -> Option { + frame + .visit(OneScalar::new( + |ty: Option, value: Physical<'_>| match (ty, value) { + (None, Physical::Bytes(bytes)) => SealedValue::from_bytes(bytes).map_err(|_| None), + _ => Err(None), + }, + )) + .ok() +} + +#[cfg(test)] +mod tests; diff --git a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs new file mode 100644 index 000000000..f617956ec --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs @@ -0,0 +1,993 @@ +use proptest::prelude::*; +use proptest::test_runner::{Config, TestRunner}; +use stack_kms::FakeDataKeySource; +use vitaminc_protected::{AsProtectedRef as _, Controlled as _}; + +use super::*; +use crate::dynamic::record::tests::given_a_target_field::FakeEql; +use crate::dynamic::record::{decrypt, decrypt_with, encrypt, encrypt_with, plan, plan_with}; +use crate::dynamic::test_frame::{frame_of, Tree}; +use crate::{KeysetCipher, StackCipher}; + +// ---- the plan and the values, as a binding spells them ------------------------ + +fn s(text: &str) -> Tree { + Tree::String(text.to_owned()) +} + +fn obj(entries: Vec<(&str, Tree)>) -> Tree { + Tree::Object( + entries + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(), + ) +} + +fn strings(items: &[&str]) -> Tree { + Tree::Array(items.iter().map(|item| s(item)).collect()) +} + +fn label(field: &str) -> Tree { + strings(&["users", field]) +} + +fn spec(field: &str, outputs: &[&str]) -> Tree { + obj(vec![ + ("context", label(field)), + ("outputs", strings(outputs)), + ]) +} + +fn typed(field: &str, outputs: &[&str], ty: &str) -> Tree { + obj(vec![ + ("context", label(field)), + ("outputs", strings(outputs)), + ("type", s(ty)), + ]) +} + +fn nullable(field: &str, outputs: &[&str], ty: &str, null: &str) -> Tree { + obj(vec![ + ("context", label(field)), + ("outputs", strings(outputs)), + ("type", s(ty)), + ("null", s(null)), + ]) +} + +fn plan_of(declaration: Tree) -> Plan { + plan(frame_of(&declaration).as_protected_ref().as_deref()).expect("the plan parses") +} + +/// Every output a field declares: sealed and indexed, matched, ordered +/// both ways, sealed alone, indexed alone and passed through. +fn every_output() -> Plan { + plan_of(obj(vec![ + ("age", typed("age", &["c", "eq", "ore"], "uint32")), + ("score", typed("score", &["c", "ope"], "int64")), + ("email", typed("email", &["c", "match"], "string")), + ("bio", spec("bio", &["c"])), + ("nick", typed("nick", &["match"], "string")), + ("id", spec("id", &["passthrough"])), + ])) +} + +fn every_output_row() -> Tree { + obj(vec![ + ("age", Tree::UInt32(34)), + ("score", Tree::Int64(-7)), + ("email", s("ada@example.com")), + ("bio", s("a secret bio")), + ("nick", s("al smith")), + ("id", Tree::UInt64(7)), + ]) +} + +// ---- running the engine --------------------------------------------------------- + +async fn cipher() -> StackCipher { + StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .expect("build cipher") +} + +async fn seal( + keyset: &KeysetCipher<'_, FakeDataKeySource>, + source: &Tree, + plan: &Plan, +) -> StackCipherText { + encrypt(keyset, source, plan) + .expect("the source fits the plan") + .await + .expect("encrypt") +} + +async fn open( + cipher: &StackCipher, + record: StackCipherText, + plan: &Plan, +) -> Tree { + let opened = decrypt(cipher, record, plan, None) + .expect("the record fits the plan") + .await + .expect("decrypt"); + tree(&opened) +} + +fn tree(frame: &OwnedFrame) -> Tree { + Tree::from_frame(frame.frame().as_bytes()).expect("a value") +} + +/// The frame of `record`, its bytes. +fn frame_bytes(record: &StackCipherText, plan: &Plan) -> Vec { + stored_frame(record, plan) + .expect("written") + .frame() + .as_bytes() + .to_vec() +} + +/// `record` through its frame and back: what a binding hands `decrypt`. +fn through_frame(record: &StackCipherText, plan: &Plan) -> StackCipherText { + let frame = stored_frame(record, plan).expect("written"); + let back = read_stored(frame.frame(), plan).expect("read back"); + assert_eq!( + frame_bytes(&back, plan), + frame.frame().as_bytes(), + "the record read back writes the same frame" + ); + back +} + +/// The frame that `node` is expected to have. Each sealed value is its +/// bytes, each container is its frame, and each passthrough is its value. +fn expected(node: &StackCipherText) -> Tree { + match node { + CipherText::Single(leaf) => Tree::Bytes(leaf.to_bytes()), + CipherText::Sequence(items) => Tree::Array(items.iter().map(expected).collect()), + CipherText::Map(entries) => Tree::Object( + entries + .iter() + .map(|(key, item)| (key.clone(), expected(item))) + .collect(), + ), + CipherText::EmptySequence(leaf) => { + Tree::Array(vec![s("empty_seq"), Tree::Bytes(leaf.to_bytes())]) + } + CipherText::EmptyMap(leaf) => { + Tree::Array(vec![s("empty_map"), Tree::Bytes(leaf.to_bytes())]) + } + CipherText::Passthrough(payload) => Tree::from_frame(&payload.0).expect("a value"), + } +} + +fn entries(node: StackCipherText) -> Vec<(String, StackCipherText)> { + match node { + CipherText::Map(entries) => entries, + _ => panic!("expected a map node"), + } +} + +fn take(entries: &mut Vec<(String, StackCipherText)>, key: &str) -> StackCipherText { + let at = entries + .iter() + .position(|(name, _)| name == key) + .unwrap_or_else(|| panic!("no {key} node")); + entries.remove(at).1 +} + +/// A sealed value's bytes, from a record the engine sealed. +async fn leaf_bytes(keyset: &KeysetCipher<'_, FakeDataKeySource>) -> Vec { + let plan = plan_of(obj(vec![("bio", spec("bio", &["c"]))])); + let sealed = seal(keyset, &obj(vec![("bio", s("x"))]), &plan).await; + match take(&mut entries(take(&mut entries(sealed), "bio")), "c") { + CipherText::Single(leaf) => leaf.to_bytes(), + _ => panic!("a scalar seals as one leaf"), + } +} + +fn leaf(bytes: &[u8]) -> SealedValue { + SealedValue::from_bytes(bytes).expect("a sealed value") +} + +/// A passthrough node carrying `value`. +fn clear(value: &Tree) -> StackCipherText { + CipherText::Passthrough(PassthroughFrame(frame_of(value).risky_unwrap())) +} + +// ---- the frame form --------------------------------------------------------- + +mod given_a_record_with_every_output { + use super::*; + + #[tokio::test] + async fn its_frame_keeps_every_key_and_carries_each_node_as_its_bytes_or_value() { + let cipher = cipher().await; + let plan = every_output(); + let stored = seal(&cipher.default_keyset(), &every_output_row(), &plan).await; + + let frame = stored_frame(&stored, &plan).expect("written"); + let written = tree(&frame); + assert_eq!(written, expected(&stored)); + + let Tree::Object(fields) = written else { + panic!("an object of fields") + }; + let keys: Vec<(&str, Vec<&str>)> = fields + .iter() + .map(|(name, outputs)| match outputs { + Tree::Object(outputs) => ( + name.as_str(), + outputs.iter().map(|(key, _)| key.as_str()).collect(), + ), + _ => panic!("an object of outputs"), + }) + .collect(); + assert_eq!( + keys, + [ + ("age", vec!["c", "eq", "ore"]), + ("score", vec!["c", "ope"]), + ("email", vec!["c", "match"]), + ("bio", vec!["c"]), + ("nick", vec!["match"]), + ("id", vec!["passthrough"]), + ], + "the keys are the plan's, unchanged" + ); + let id = &fields[5].1; + assert_eq!(id, &obj(vec![("passthrough", Tree::UInt64(7))])); + } + + #[tokio::test] + async fn its_frame_reads_back_to_a_record_that_decrypts_as_the_original() { + let cipher = cipher().await; + let plan = every_output(); + let stored = seal(&cipher.default_keyset(), &every_output_row(), &plan).await; + + let back = through_frame(&stored, &plan); + let original = open(&cipher, stored, &plan).await; + let opened = open(&cipher, back, &plan).await; + assert_eq!(opened, original); + assert_eq!( + opened, + obj(vec![ + ("age", Tree::UInt32(34)), + ("score", Tree::Int64(-7)), + ("email", s("ada@example.com")), + ("bio", s("a secret bio")), + ("id", Tree::UInt64(7)), + ]) + ); + } + + #[tokio::test] + async fn each_fields_node_converts_as_its_entry_in_the_records_frame() { + let cipher = cipher().await; + let plan = every_output(); + let stored = seal(&cipher.default_keyset(), &every_output_row(), &plan).await; + let Tree::Object(fields) = tree(&stored_frame(&stored, &plan).expect("written")) else { + panic!("an object of fields") + }; + + for ((name, node), (_, in_record)) in entries(stored).into_iter().zip(fields) { + let frame = stored_field_frame(&node, &plan, &name).expect("written"); + assert_eq!(tree(&frame), in_record, "{name}"); + let back = read_stored_field(frame.frame(), &plan, &name).expect("read back"); + assert_eq!( + stored_field_frame(&back, &plan, &name) + .expect("written") + .frame() + .as_bytes(), + frame.frame().as_bytes(), + "{name}" + ); + } + } + + /// The fields read back keep the frame's order, and a field the record + /// stores without `c` (an index alone) converts like any other. + #[tokio::test] + async fn a_record_whose_frame_leaves_out_an_index_alone_still_decrypts() { + let cipher = cipher().await; + let plan = every_output(); + let stored = seal(&cipher.default_keyset(), &every_output_row(), &plan).await; + let mut fields = entries(stored); + let _ = take(&mut fields, "nick"); + let back = through_frame(&CipherText::Map(fields), &plan); + let opened = open(&cipher, back, &plan).await; + assert_eq!(opened, open_row_without_nick()); + } + + fn open_row_without_nick() -> Tree { + obj(vec![ + ("age", Tree::UInt32(34)), + ("score", Tree::Int64(-7)), + ("email", s("ada@example.com")), + ("bio", s("a secret bio")), + ("id", Tree::UInt64(7)), + ]) + } +} + +mod given_a_composite_field { + use super::*; + + fn plan() -> Plan { + plan_of(obj(vec![ + ("doc", typed("doc", &["c"], "object")), + ("list", typed("list", &["c"], "array")), + ("loose", spec("loose", &["c"])), + ])) + } + + fn row() -> Tree { + obj(vec![ + ( + "doc", + obj(vec![ + ("home", s("a@x")), + ("tags", Tree::Array(vec![])), + ("extra", obj(vec![])), + ( + "nested", + Tree::Array(vec![ + Tree::Array(vec![]), + obj(vec![]), + Tree::Array(vec![s("x"), Tree::Null]), + ]), + ), + ]), + ), + ("list", Tree::Array(vec![])), + ("loose", obj(vec![])), + ]) + } + + #[tokio::test] + async fn its_lists_maps_and_empty_markers_take_the_frame_form() { + let cipher = cipher().await; + let plan = plan(); + let stored = seal(&cipher.default_keyset(), &row(), &plan).await; + let written = tree(&stored_frame(&stored, &plan).expect("written")); + assert_eq!(written, expected(&stored)); + + let Tree::Object(fields) = written else { + panic!("an object of fields") + }; + let c = |at: usize| match &fields[at].1 { + Tree::Object(outputs) => outputs[0].1.clone(), + _ => panic!("an object of outputs"), + }; + let marker = |tree: &Tree| match tree { + Tree::Array(items) => match &items[..] { + [Tree::String(tag), Tree::Bytes(_)] => tag.clone(), + _ => panic!("a marker is its tag and its bytes"), + }, + _ => panic!("a marker is an array"), + }; + assert_eq!(marker(&c(1)), "empty_seq"); + assert_eq!(marker(&c(2)), "empty_map"); + let Tree::Object(doc) = c(0) else { + panic!("an object field's c is an object") + }; + assert!(matches!(doc[0].1, Tree::Bytes(_))); + assert_eq!(marker(&doc[1].1), "empty_seq"); + assert_eq!(marker(&doc[2].1), "empty_map"); + } + + #[tokio::test] + async fn it_reads_back_and_decrypts_as_the_original() { + let cipher = cipher().await; + let plan = plan(); + let stored = seal(&cipher.default_keyset(), &row(), &plan).await; + let back = through_frame(&stored, &plan); + let original = open(&cipher, stored, &plan).await; + assert_eq!(open(&cipher, back, &plan).await, original); + assert_eq!(original, row()); + } +} + +mod given_a_null { + use super::*; + + fn plan() -> Plan { + plan_of(obj(vec![ + ("email", nullable("email", &["c", "eq"], "string", "sql")), + ("age", nullable("age", &["c", "eq"], "uint32", "sealed")), + ("id", spec("id", &["passthrough"])), + ])) + } + + fn row() -> Tree { + obj(vec![ + ("email", Tree::Null), + ("age", Tree::Null), + ("id", Tree::Null), + ]) + } + + #[tokio::test] + async fn a_sql_null_has_no_entry_and_a_sealed_one_is_sealed() { + let cipher = cipher().await; + let plan = plan(); + let stored = seal(&cipher.default_keyset(), &row(), &plan).await; + let Tree::Object(fields) = tree(&stored_frame(&stored, &plan).expect("written")) else { + panic!("an object of fields") + }; + let names: Vec<&str> = fields.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!(names, ["age", "id"], "the sql null has no entry"); + assert!(matches!(&fields[0].1, Tree::Object(outputs) if outputs.len() == 2)); + assert_eq!(fields[1].1, obj(vec![("passthrough", Tree::Null)])); + } + + #[tokio::test] + async fn a_sql_field_left_out_or_given_as_null_reads_as_no_entry() { + let cipher = cipher().await; + let plan = plan(); + let stored = seal(&cipher.default_keyset(), &row(), &plan).await; + let left_out = stored_frame(&stored, &plan).expect("written"); + + let Tree::Object(mut fields) = tree(&left_out) else { + panic!("an object of fields") + }; + fields.insert(0, ("email".to_owned(), Tree::Null)); + let as_null = frame_of(&Tree::Object(fields)); + let as_null = Frame::parse(as_null.risky_ref()).expect("a frame"); + + for frame in [left_out.frame(), as_null] { + let back = read_stored(frame, &plan).expect("read back"); + assert_eq!(frame_bytes(&back, &plan), left_out.frame().as_bytes()); + assert_eq!(open(&cipher, back, &plan).await, row()); + } + } + + #[test] + fn a_null_for_a_field_with_no_sql_null_is_refused() { + let plan = plan(); + for field in ["age", "id"] { + let frame = frame_of(&obj(vec![(field, Tree::Null)])); + let frame = Frame::parse(frame.risky_ref()).expect("a frame"); + let error = read_stored(frame, &plan).expect_err("refused"); + assert_refused(&error, Some(field), Reason::OutputsNotMap); + } + let frame = frame_of(&Tree::Null); + let frame = Frame::parse(frame.risky_ref()).expect("a frame"); + let error = read_stored_field(frame, &plan, "email").expect_err("no node"); + assert_refused(&error, Some("email"), Reason::OutputsNotMap); + } +} + +mod given_a_batch { + use super::*; + + #[tokio::test] + async fn its_frame_is_an_array_of_records_that_reads_back() { + let cipher = cipher().await; + let plan = every_output(); + let rows = Tree::Array(vec![every_output_row(), every_output_row()]); + let stored = seal(&cipher.default_keyset(), &rows, &plan).await; + + let written = tree(&stored_frame(&stored, &plan).expect("written")); + assert!(matches!(&written, Tree::Array(items) if items.len() == 2)); + assert_eq!(written, expected(&stored)); + + let back = through_frame(&stored, &plan); + let original = open(&cipher, stored, &plan).await; + assert_eq!(open(&cipher, back, &plan).await, original); + } + + #[tokio::test] + async fn an_empty_batch_is_an_empty_array() { + let cipher = cipher().await; + let plan = every_output(); + let stored = seal(&cipher.default_keyset(), &Tree::Array(vec![]), &plan).await; + assert_eq!( + tree(&stored_frame(&stored, &plan).expect("written")), + Tree::Array(vec![]) + ); + assert!(matches!( + through_frame(&stored, &plan), + CipherText::Sequence(rows) if rows.is_empty() + )); + } +} + +mod given_a_target_field { + use super::*; + + fn plan() -> Plan { + let declaration = obj(vec![ + ( + "email", + obj(vec![("context", label("email")), ("target", s("TextEq"))]), + ), + ("id", spec("id", &["passthrough"])), + ]); + plan_with( + frame_of(&declaration).as_protected_ref().as_deref(), + &FakeEql, + ) + .expect("the plan parses") + } + + fn row() -> Tree { + obj(vec![ + ("email", s("ada@example.com")), + ("id", Tree::UInt64(7)), + ]) + } + + #[tokio::test] + async fn its_eql_value_is_bytes_in_the_frame_and_reads_back() { + let cipher = cipher().await; + let plan = plan(); + let stored = encrypt_with(&cipher.default_keyset(), row(), &plan, &FakeEql) + .expect("fits") + .await + .expect("encrypt"); + + let written = tree(&stored_frame(&stored, &plan).expect("written")); + let Tree::Object(fields) = &written else { + panic!("an object of fields") + }; + assert!(matches!( + &fields[0].1, + Tree::Object(outputs) if matches!(&outputs[..], [(key, Tree::Bytes(_))] if key == "eql") + )); + + let back = through_frame(&stored, &plan); + let opened = decrypt_with(&cipher, back, &plan, None, &FakeEql) + .expect("fits") + .await + .expect("decrypt"); + assert_eq!(tree(&opened), row()); + } + + #[test] + fn a_c_output_on_it_is_undeclared() { + let frame = frame_of(&obj(vec![( + "email", + obj(vec![("c", Tree::Bytes(vec![1]))]), + )])); + let frame = Frame::parse(frame.risky_ref()).expect("a frame"); + let error = read_stored(frame, &plan()).expect_err("refused"); + assert_refused(&error, Some("email"), Reason::UndeclaredOutput); + } +} + +// ---- any value ------------------------------------------------------------------- + +/// Any value that a frame can contain and a record can seal. The values +/// are every scalar kind, the logical kinds, and lists and maps of them. +/// Empty lists and maps are included. +fn value() -> impl Strategy { + use vitaminc_aead::plaintext::{Logical, TimeUnit}; + let typed = |logical: Logical, value: Tree| Tree::Typed(logical, Box::new(value)); + let scalar = prop_oneof![ + Just(Tree::Null), + Just(Tree::Undefined), + any::().prop_map(Tree::Bool), + any::().prop_map(Tree::Int8), + any::().prop_map(Tree::Int16), + any::().prop_map(Tree::Int32), + any::().prop_map(Tree::Int64), + any::().prop_map(Tree::Int128), + any::().prop_map(Tree::UInt8), + any::().prop_map(Tree::UInt16), + any::().prop_map(Tree::UInt32), + any::().prop_map(Tree::UInt64), + any::().prop_map(Tree::UInt128), + any::().prop_map(Tree::Float32), + any::().prop_map(Tree::Float64), + ".{0,12}".prop_map(Tree::String), + proptest::collection::vec(any::(), 0..12).prop_map(Tree::Bytes), + (-3_000_000i32..3_000_000).prop_map(move |days| typed(Logical::Date, Tree::Int32(days))), + (-1_000_000_000_000_000_000i128..1_000_000_000_000_000_000) + .prop_map(move |at| typed(Logical::Timestamp(TimeUnit::Nanos), Tree::Int128(at))), + (0u8..=28, any::()).prop_map(move |(scale, int)| typed( + Logical::Decimal { scale }, + Tree::Int128(i128::from(int)) + )), + any::<[u8; 16]>().prop_map(move |id| typed(Logical::Uuid, Tree::Bytes(id.to_vec()))), + ]; + scalar.prop_recursive(4, 32, 4, |inner| { + prop_oneof![ + proptest::collection::vec(inner.clone(), 0..4).prop_map(Tree::Array), + proptest::collection::btree_map(".{0,6}", inner, 0..4) + .prop_map(|entries| Tree::Object(entries.into_iter().collect())), + ] + }) +} + +/// A value sealed under `c` and the same value passed through comes back +/// from a frame read back as the original record decrypts. +#[test] +fn any_value_sealed_or_passed_through_decrypts_the_same_after_the_frame() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime"); + let cipher = runtime.block_on(cipher()); + let keyset = cipher.default_keyset(); + let plan = plan_of(obj(vec![ + ("sealed", spec("sealed", &["c"])), + ("clear", spec("clear", &["passthrough"])), + ])); + let mut runner = TestRunner::new(Config { + cases: 64, + ..Config::default() + }); + runner + .run(&(value(), value()), |(sealed, clear)| { + let row = obj(vec![("sealed", sealed), ("clear", clear)]); + let stored = runtime.block_on(seal(&keyset, &row, &plan)); + let back = through_frame(&stored, &plan); + let original = runtime.block_on(open(&cipher, stored, &plan)); + let opened = runtime.block_on(open(&cipher, back, &plan)); + prop_assert_eq!(&opened, &original); + prop_assert_eq!(&opened, &row); + Ok(()) + }) + .expect("every value round-trips"); +} + +/// Any shape of sealed node under `c`, built from one sealed value: the +/// frame reads back to a record that writes the same frame. Lists and maps +/// with no entries are among them, beside the empty markers. +#[test] +fn any_sealed_shape_reads_back_from_its_frame() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime"); + let bytes = runtime.block_on(async { leaf_bytes(&cipher().await.default_keyset()).await }); + + #[derive(Debug, Clone)] + enum Shape { + Leaf, + EmptySequence, + EmptyMap, + Sequence(Vec), + Map(std::collections::BTreeMap), + } + fn build(shape: &Shape, bytes: &[u8]) -> StackCipherText { + match shape { + Shape::Leaf => CipherText::Single(leaf(bytes)), + Shape::EmptySequence => CipherText::EmptySequence(leaf(bytes)), + Shape::EmptyMap => CipherText::EmptyMap(leaf(bytes)), + Shape::Sequence(items) => { + CipherText::Sequence(items.iter().map(|item| build(item, bytes)).collect()) + } + Shape::Map(entries) => CipherText::Map( + entries + .iter() + .map(|(key, item)| (key.clone(), build(item, bytes))) + .collect(), + ), + } + } + let shape = prop_oneof![ + Just(Shape::Leaf), + Just(Shape::EmptySequence), + Just(Shape::EmptyMap), + ] + .prop_recursive(5, 48, 4, |inner| { + prop_oneof![ + proptest::collection::vec(inner.clone(), 0..4).prop_map(Shape::Sequence), + proptest::collection::btree_map(".{0,6}", inner, 0..4).prop_map(Shape::Map), + ] + }); + + let plan = plan_of(obj(vec![("bio", spec("bio", &["c"]))])); + let mut runner = TestRunner::new(Config { + cases: 256, + ..Config::default() + }); + runner + .run(&shape, |shape| { + let node = build(&shape, &bytes); + let written = expected(&node); + let record = CipherText::Map(vec![( + "bio".to_owned(), + CipherText::Map(vec![("c".to_owned(), node)]), + )]); + let frame = stored_frame(&record, &plan).expect("written"); + prop_assert_eq!(tree(&frame), obj(vec![("bio", obj(vec![("c", written)]))])); + let back = through_frame(&record, &plan); + prop_assert_eq!(frame_bytes(&back, &plan), frame.frame().as_bytes().to_vec()); + Ok(()) + }) + .expect("every shape reads back"); +} + +// ---- refusals -------------------------------------------------------------------- + +/// Text a refusal must never contain: a passthrough's value, and a key +/// inside a sealed node. +const SECRET: &str = "forged-secret"; + +fn assert_refused(error: &Error, field: Option<&str>, reason: Reason) { + assert_eq!(error.field(), field, "{error}"); + assert_eq!(error.reason(), Some(reason), "{error}"); + let message = error.to_string(); + assert!(!message.contains(SECRET), "{message}"); + assert!(!format!("{error:?}").contains(SECRET), "{error:?}"); +} + +mod reading_a_frame_back { + use super::*; + + fn refused(frame: &Tree) -> Error { + let bytes = frame_of(frame); + let frame = Frame::parse(bytes.risky_ref()).expect("a frame"); + read_stored(frame, &every_output()).expect_err("refused") + } + + /// A record whose `age` has `outputs` and nothing else. + fn age(outputs: Vec<(&str, Tree)>) -> Tree { + obj(vec![("age", obj(outputs))]) + } + + #[test] + fn it_refuses_a_frame_that_is_not_a_record_or_a_batch() { + let error = refused(&s(SECRET)); + assert_refused(&error, None, Reason::NotAnObject); + assert_eq!( + error.found(), + Some(Found::Kind(crate::dynamic::ValueKind::String)) + ); + assert_eq!(error.row(), None); + assert!(matches!(error, Error::Record { .. })); + + let error = refused(&Tree::Array(vec![obj(vec![]), Tree::Int32(5)])); + assert_refused(&error, None, Reason::NotAnObject); + assert_eq!(error.row(), Some(1)); + assert_eq!( + error.found(), + Some(Found::Kind(crate::dynamic::ValueKind::Int32)) + ); + + let error = refused(&Tree::Passthrough(Box::new(obj(vec![])))); + assert_eq!(error.found(), Some(Found::Passthrough)); + } + + #[test] + fn it_refuses_a_field_the_plan_does_not_name() { + let error = refused(&obj(vec![("zzz", obj(vec![]))])); + assert_refused(&error, Some("zzz"), Reason::UnknownField); + } + + #[test] + fn it_refuses_a_field_that_is_not_an_object_of_outputs() { + for value in [Tree::Bytes(vec![1]), Tree::Array(vec![]), s(SECRET)] { + let error = refused(&obj(vec![("age", value)])); + assert_refused(&error, Some("age"), Reason::OutputsNotMap); + } + } + + #[test] + fn it_refuses_an_output_the_field_does_not_declare() { + for key in ["ope", "passthrough", "eql", SECRET] { + let error = refused(&age(vec![(key, Tree::Bytes(vec![1]))])); + assert_refused(&error, Some("age"), Reason::UndeclaredOutput); + } + } + + #[test] + fn it_refuses_a_passthrough_anywhere_under_c() { + let forged = Tree::Passthrough(Box::new(s(SECRET))); + for c in [ + forged.clone(), + obj(vec![(SECRET, forged.clone())]), + Tree::Array(vec![forged]), + ] { + let error = refused(&age(vec![("c", c)])); + assert_refused(&error, Some("age"), Reason::Passthrough); + } + } + + #[tokio::test] + async fn it_refuses_a_node_under_c_that_is_not_sealed() { + let bytes = leaf_bytes(&cipher().await.default_keyset()).await; + let sealed = || Tree::Bytes(bytes.clone()); + for c in [ + s(SECRET), + Tree::UInt32(3), + Tree::Null, + Tree::Bytes(b"forged-secret, not a sealed value".to_vec()), + Tree::Array(vec![s("empty_seq")]), + Tree::Array(vec![s("empty_seq"), sealed(), sealed()]), + Tree::Array(vec![s(SECRET), sealed()]), + Tree::Array(vec![s("empty_map"), s("x")]), + Tree::Array(vec![s("empty_map"), Tree::Bytes(vec![0])]), + Tree::Array(vec![sealed(), s("empty_seq")]), + obj(vec![(SECRET, Tree::Int64(1))]), + ] { + let error = refused(&age(vec![("c", c.clone())])); + assert_refused(&error, Some("age"), Reason::NotSealed); + } + } + + #[test] + fn it_refuses_a_field_the_plan_does_not_have_for_one_fields_node() { + let bytes = frame_of(&obj(vec![])); + let frame = Frame::parse(bytes.risky_ref()).expect("a frame"); + let error = read_stored_field(frame, &every_output(), "zzz").expect_err("refused"); + assert!(matches!(error, Error::Plan { .. })); + assert_refused(&error, Some("zzz"), Reason::NoSuchField); + } +} + +mod writing_a_frame { + use super::*; + + async fn sealed_fields() -> Vec<(String, StackCipherText)> { + let cipher = cipher().await; + entries( + seal( + &cipher.default_keyset(), + &every_output_row(), + &every_output(), + ) + .await, + ) + } + + fn refused(record: &StackCipherText) -> Error { + stored_frame(record, &every_output()).expect_err("refused") + } + + /// The record with `age`'s outputs changed by `change`. + async fn with_age(change: impl FnOnce(&mut Vec<(String, StackCipherText)>)) -> StackCipherText { + let mut fields = sealed_fields().await; + let mut outputs = entries(take(&mut fields, "age")); + change(&mut outputs); + fields.push(("age".to_owned(), CipherText::Map(outputs))); + CipherText::Map(fields) + } + + #[tokio::test] + async fn it_refuses_a_record_that_is_not_a_map_or_a_sequence_of_maps() { + let mut fields = sealed_fields().await; + let mut age = entries(take(&mut fields, "age")); + let c = take(&mut age, "c"); + let error = refused(&c); + assert_refused(&error, None, Reason::NotAnObject); + assert_eq!(error.found(), Some(Found::Sealed)); + + let error = refused(&CipherText::Sequence(vec![CipherText::Map(fields), c])); + assert_refused(&error, None, Reason::NotAnObject); + assert_eq!(error.row(), Some(1)); + assert_eq!(error.found(), Some(Found::Sealed)); + } + + #[tokio::test] + async fn it_refuses_a_field_the_plan_does_not_name_or_a_field_twice() { + let mut fields = sealed_fields().await; + fields.push(("zzz".to_owned(), CipherText::Map(vec![]))); + assert_refused( + &refused(&CipherText::Map(fields)), + Some("zzz"), + Reason::UnknownField, + ); + + let mut fields = sealed_fields().await; + let mut again = sealed_fields().await; + fields.push(("age".to_owned(), take(&mut again, "age"))); + assert_refused( + &refused(&CipherText::Map(fields)), + Some("age"), + Reason::FieldRepeated, + ); + } + + #[tokio::test] + async fn it_refuses_a_field_that_is_not_a_map_of_outputs() { + let mut fields = sealed_fields().await; + let mut age = entries(take(&mut fields, "age")); + fields.push(("age".to_owned(), take(&mut age, "c"))); + let error = refused(&CipherText::Map(fields)); + assert_refused(&error, Some("age"), Reason::OutputsNotMap); + } + + #[tokio::test] + async fn it_refuses_an_output_undeclared_or_given_twice() { + let record = + with_age(|age| age.push((SECRET.to_owned(), clear(&Tree::Bytes(vec![1]))))).await; + assert_refused(&refused(&record), Some("age"), Reason::UndeclaredOutput); + + let mut again = entries(take(&mut sealed_fields().await, "age")); + let older = take(&mut again, "c"); + let record = with_age(|age| age.push(("c".to_owned(), older))).await; + assert_refused(&refused(&record), Some("age"), Reason::RepeatedKey); + } + + #[tokio::test] + async fn it_refuses_a_passthrough_anywhere_under_c() { + for nested in [false, true] { + let record = with_age(|age| { + let _ = take(age, "c"); + let forged = clear(&s(SECRET)); + let c = if nested { + CipherText::Sequence(vec![forged]) + } else { + forged + }; + age.push(("c".to_owned(), c)); + }) + .await; + assert_refused(&refused(&record), Some("age"), Reason::Passthrough); + } + } + + #[tokio::test] + async fn it_refuses_a_map_under_c_that_repeats_a_key() { + let mut again = entries(take(&mut sealed_fields().await, "age")); + let older = take(&mut again, "c"); + let record = with_age(|age| { + let current = take(age, "c"); + age.push(( + "c".to_owned(), + CipherText::Map(vec![ + (SECRET.to_owned(), current), + (SECRET.to_owned(), older), + ]), + )); + }) + .await; + assert_refused(&refused(&record), Some("age"), Reason::RepeatedKey); + } + + #[tokio::test] + async fn it_refuses_an_output_in_the_clear_that_is_not_one_frame() { + let mut again = entries(take(&mut sealed_fields().await, "age")); + let sealed = take(&mut again, "c"); + let record = with_age(|age| { + let _ = take(age, "eq"); + age.push(("eq".to_owned(), sealed)); + }) + .await; + assert_refused(&refused(&record), Some("age"), Reason::NotPassthrough); + + let record = with_age(|age| { + let _ = take(age, "eq"); + age.push(( + "eq".to_owned(), + CipherText::Passthrough(PassthroughFrame(SECRET.as_bytes().to_vec())), + )); + }) + .await; + assert_refused(&refused(&record), Some("age"), Reason::NotPassthrough); + } + + #[tokio::test] + async fn it_refuses_a_record_deeper_than_a_frame_carries() { + let mut again = entries(take(&mut sealed_fields().await, "age")); + let CipherText::Single(sealed) = take(&mut again, "c") else { + panic!("a scalar seals as one leaf") + }; + let deep = (0..vitaminc_aead::frame::MAX_DEPTH) + .fold(CipherText::Single(sealed), |inner, _| { + CipherText::Sequence(vec![inner]) + }); + let record = with_age(|age| { + let _ = take(age, "c"); + age.push(("c".to_owned(), deep)); + }) + .await; + assert_refused(&refused(&record), Some("age"), Reason::Unframeable); + } + + #[tokio::test] + async fn it_refuses_a_field_the_plan_does_not_have_for_one_fields_node() { + let mut fields = sealed_fields().await; + let age = take(&mut fields, "age"); + let error = stored_field_frame(&age, &every_output(), "zzz").expect_err("refused"); + assert!(matches!(error, Error::Plan { .. })); + assert_refused(&error, Some("zzz"), Reason::NoSuchField); + } +} diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index ed4bc34c5..b26ae0f84 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -962,9 +962,11 @@ reasons! { Undefined => "undefined", "a value is undefined where its field declares a type"; /// A passthrough sits where a sealed value, or a ciphertext, must be. Passthrough => "passthrough", "a passthrough where a sealed value must be"; - /// A passthrough value cannot be stored as a frame: it nests deeper, - /// or holds text, bytes or a key longer, than a frame carries. - Unframeable => "unframeable", "a passthrough value nests deeper, or holds a longer value, than a frame carries"; + /// A value cannot be written as a frame, because it nests too deep, + /// or has text, bytes, or a key that is too long. The value is a + /// value to encrypt, or a stored record written as a frame + /// ([`record::stored_frame`](crate::dynamic::record::stored_frame)). + Unframeable => "unframeable", "a value nests deeper, or holds a longer value, than a frame carries"; /// A value to encrypt as one ciphertext is not a scalar that is /// present. The value is an array, an object, a null, a /// passthrough, or `undefined`. The null can be plain or typed. @@ -1092,6 +1094,21 @@ reasons! { /// are a list, a number, a string, a boolean, or the JSON `null`. /// [`Error::found`] returns the kind. JsonVarsNotObject => "json_vars_not_object", "the vars of a match must be a JSON object"; + /// A stored field has an output that it does not declare. The + /// output's key is not one of the field's outputs, or is not + /// `"eql"` for a field that names an EQL type. Only the plan says + /// what an output contains. So a stored record with such an output + /// is not written as a frame + /// ([`record::stored_frame`](crate::dynamic::record::stored_frame)), + /// or read back from one + /// ([`record::read_stored`](crate::dynamic::record::read_stored)). + UndeclaredOutput => "undeclared_output", "a stored output that the field does not declare"; + /// A node under `"c"` in a stored record's frame is not in the + /// frame form that + /// [`record::read_stored`](crate::dynamic::record::read_stored) + /// reads. Under `c`, the form has sealed values' bytes, arrays and + /// objects of sealed nodes, and the markers of empty lists and maps. + NotSealed => "not_sealed", r#"a node under "c" is not a sealed value, a list or map of them, or an empty list's or map's marker"#; } } diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 69a8e68c2..6b5046851 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -52,6 +52,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). No frame or sealed byte changes: an `OwnedFrame` holds the bytes `to_frame` writes. - `Frame::kind`, `Frame::is_null` and `Frame::has_passthrough` read a frame in place, and `Frame::elements` lends a sequence's elements as `Frame`s, in order, through `frame::Elements`, with no copy. An element keeps the bytes it has in the sequence, so a typed null stays a typed null. +- `Frame::entries` lends a map's entries, in the map's order, through `frame::Entries`, with no copy. + Each entry is a key and its value's `Frame`. + `Frame::entries` is to a map what `Frame::elements` is to a sequence. A value keeps its bytes, so a typed null stays a typed null. + `Debug` on `Entries` shows nothing of the keys or the values. - `FrameWriter`, `FrameSeq` and `FrameMap` take a second type parameter, the error they report, which defaults to `FrameWriteError`. Code that names `FrameWriter<'_>` is unchanged. The decrypt sink of `OwnedFrame` writes through them, reporting `DecodeError`. diff --git a/packages/vitaminc-aead/src/frame.rs b/packages/vitaminc-aead/src/frame.rs index 0396d9a8b..8288ef465 100644 --- a/packages/vitaminc-aead/src/frame.rs +++ b/packages/vitaminc-aead/src/frame.rs @@ -179,6 +179,30 @@ impl<'a> Frame<'a> { Some(Elements { cursor, left }) } + /// The entries of a map, in the map's order, with nothing copied. Each + /// entry is a key and its value's frame, borrowed from this one. `None` + /// for any other value. + /// + /// ``` + /// use std::collections::BTreeMap; + /// use vitaminc_aead::{Frame, OwnedFrame}; + /// + /// let owned = OwnedFrame::of(BTreeMap::from([("a", 1u32), ("b", 2)]))?; + /// let entries = owned.frame().entries().expect("a map"); + /// let keys: Vec<&str> = entries.map(|(key, _)| key).collect(); + /// assert_eq!(keys, ["a", "b"]); + /// assert!(OwnedFrame::of(vec![1u32])?.frame().entries().is_none()); + /// # Ok::<(), Box>(()) + /// ``` + pub fn entries(&self) -> Option> { + let mut cursor = self.cursor(); + if cursor.byte().expect(VALIDATED) != OBJECT { + return None; + } + let left = cursor.count().expect(VALIDATED); + Some(Entries { cursor, left }) + } + fn cursor(&self) -> Cursor<'a> { Cursor { buf: self.bytes, @@ -220,6 +244,31 @@ impl<'a> Iterator for Elements<'a> { impl ExactSizeIterator for Elements<'_> {} +/// What [`Frame::entries`] returns: the entries of a map frame. Each entry +/// is a key and a [`Frame`] borrowed from the map. `Debug` shows nothing of +/// them. +#[derive(Clone, OpaqueDebug)] +pub struct Entries<'a> { + cursor: Cursor<'a>, + left: usize, +} + +impl<'a> Iterator for Entries<'a> { + type Item = (&'a str, Frame<'a>); + + fn next(&mut self) -> Option<(&'a str, Frame<'a>)> { + self.left = self.left.checked_sub(1)?; + let key = self.cursor.key().expect(VALIDATED); + Some((key, self.cursor.node(1).expect(VALIDATED))) + } + + fn size_hint(&self) -> (usize, Option) { + (self.left, Some(self.left)) + } +} + +impl ExactSizeIterator for Entries<'_> {} + /// Whether the node at the cursor, which `Frame::parse` accepted, holds a /// passthrough. Leaves the cursor after the node. fn holds_passthrough(cursor: &mut Cursor<'_>) -> bool { @@ -1320,6 +1369,77 @@ mod tests { } } + /// A map's entries are its keys and its values' frames, borrowed from + /// the map in its order. Each value keeps its bytes, so a typed null + /// stays a typed null. Any other value has no entries. + #[test] + fn entries_are_the_keys_and_childrens_frames_in_place() { + use crate::plaintext::Width; + let date = FixedType::new(Some(Logical::Date), Width::I32).expect("fixed"); + let entry = |key: &str, value: &[u8]| { + let mut out = u32::try_from(key.len()) + .expect("short") + .to_le_bytes() + .to_vec(); + out.extend_from_slice(key.as_bytes()); + out.extend_from_slice(value); + out + }; + // Written by hand, out of key order, so the order kept is the map's. + let mut map = vec![OBJECT, 3, 0, 0, 0]; + map.extend(entry("z", &frame_of("a"))); + map.extend(entry("when", &typed_null(date))); + map.extend(entry("", &frame_of(vec![1i32]))); + let frame = Frame::parse(&map).expect("parses"); + let entries = frame.entries().expect("a map"); + assert_eq!(entries.len(), 3); + assert_eq!(entries.size_hint(), (3, Some(3))); + let items: Vec<(&str, Frame<'_>)> = entries.clone().collect(); + let keys: Vec<&str> = items.iter().map(|(key, _)| *key).collect(); + assert_eq!(keys, ["z", "when", ""]); + assert_eq!(items[0].1.as_bytes(), &frame_of("a")[..]); + assert_eq!(items[1].1.as_bytes(), &typed_null(date)[..]); + assert!(items[1].1.is_null()); + assert_eq!(items[2].1.as_bytes(), &frame_of(vec![1i32])[..]); + // Borrowed from the map, not copied. The first key and value start + // after the tag, the count, and the key's length. + assert_eq!(items[0].0.as_ptr(), map[9..].as_ptr()); + assert_eq!(items[0].1.as_bytes().as_ptr(), map[10..].as_ptr()); + + let mut rest = frame.entries().expect("a map"); + assert!(rest.next().is_some()); + assert_eq!(rest.len(), 2); + assert!(rest.next().is_some()); + assert!(rest.next().is_some()); + assert_eq!(rest.len(), 0); + assert!(rest.next().is_none()); + assert!(rest.next().is_none(), "stays done"); + + let empty = frame_of(BTreeMap::<&str, u16>::new()); + let none = Frame::parse(&empty).expect("parses").entries(); + assert_eq!(none.map(|e| e.len()), Some(0)); + for other in [ + frame_of("a"), + frame_of(vec!["a"]), + frame_of(Pass(BTreeMap::<&str, u16>::new())), + ] { + assert!(Frame::parse(&other).expect("parses").entries().is_none()); + } + } + + #[test] + fn entries_debug_shows_nothing_of_them() { + let mut map = BTreeMap::new(); + map.insert("hidden", "secret"); + let bytes = frame_of(map); + let frame = Frame::parse(&bytes).expect("parses"); + let shown = format!("{:?}", frame.entries().expect("a map")); + assert!( + shown.contains("***") && !shown.contains("secret") && !shown.contains("hidden"), + "{shown}" + ); + } + #[test] fn elements_debug_shows_nothing_of_them() { let bytes = frame_of(vec!["secret"]); From 1c47a541e17628e0e8bfb13bdade3cc4fdaed40d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 02:13:15 +1100 Subject: [PATCH 02/10] docs(stack-encrypt): list the stored-record frame functions in the dynamic module docs --- packages/stack-encrypt/src/dynamic/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 23771176e..7af3b3f54 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -45,6 +45,8 @@ //! language is the same bytes. The one step that stays dynamic is //! dispatching a value whose type is known only at run time to the typed //! term operation, which [`IndexSpec`](crate::target::IndexSpec)'s `Index` impls do. +//! * [`record::stored_frame`] and [`record::read_stored`] — a stored record +//! as a frame, for a binding to move to its language, and back. //! * [`read_json`] and [`json_frame`] — a `json` field's document, from //! the JSON text a binding hands over and back to it. //! * [`TargetResolver`] — the EQL types a build holds, installed by the host From 8eb4d74443c5fa0b546b883e262bf34a38ec8451 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 02:45:20 +1100 Subject: [PATCH 03/10] fix(stack-encrypt): name the row and output of a stored-frame refusal A refusal of a stored record in a batch did not say which row was at fault. No refusal said which output was at fault. `Error::Record` now has an `output` field. `stored_frame` and `read_stored` set it, and they set the row in a batch. `decrypt` and `check_record` leave the output unset. So their payloads do not change. read_stored and stored_frame now refuse a term or an EQL value that is not bytes. The docs say where a refusal names the field, list Error::Internal, and say that a passthrough's frame is not wiped, as PassthroughFrame's contract says. The Go guest's test that builds an Error::Record sets the new field. A new guest test checks that the output reaches the host. --- languages/golang/encrypt/guest/src/status.rs | 21 +++ packages/stack-encrypt/CHANGELOG.md | 15 ++- .../docs/language-integration.md | 2 +- packages/stack-encrypt/src/codes.rs | 11 ++ packages/stack-encrypt/src/dynamic/record.rs | 23 ++-- .../src/dynamic/record/stored.rs | 125 ++++++++++++++---- .../src/dynamic/record/stored/tests.rs | 113 +++++++++++++++- packages/stack-encrypt/src/refusal.rs | 47 ++++++- 8 files changed, 308 insertions(+), 49 deletions(-) diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 258d39793..084debad4 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -612,6 +612,7 @@ mod tests { row: None, reason: Reason::NoCiphertextNode, found: None, + output: None, }, ), ( @@ -642,6 +643,26 @@ mod tests { ); } + /// A stored record's refusal reaches the host with every field of its + /// payload, the output at fault among them. + #[test] + fn a_stored_record_refusal_carries_its_output_to_the_host() { + use stack_encrypt::dynamic::{Error, Reason}; + let error = Error::Record { + field: Some("age".to_string()), + row: Some(1), + reason: Reason::NotSealed, + found: None, + output: Some("c".to_string()), + }; + assert_eq!(fail_dynamic(&error), STATUS_ENCODING); + let recorded = stack_guest_abi::last_error::take().expect("an error is recorded"); + let text = String::from_utf8_lossy(&recorded); + for part in ["output", "not_sealed", "field", "age", "row"] { + assert!(text.contains(part), "the recorded error carries {part}"); + } + } + #[test] fn term_errors_are_derivation_failures() { // An empty context never reaches a term — it is `STATUS_ENCODING` diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 0f723025c..31967e187 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -28,10 +28,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 same for one field's node, the map of its outputs. - The frame is a transport form, not a storage format. Store the bytes inside it. - - Each refusal is `Error::Record` and names the field. Two new reasons - say what was wrong. `undeclared_output` is for an output that the field - does not declare. `not_sealed` is for a node under `c` that is not in - the frame form. + - A refusal of the caller's input is `Error::Record`. It names the + field, the output, and the row of a batch, where there is one. Two new + reasons say what was wrong. `undeclared_output` is for an output that + the field does not declare. `not_sealed` is for a node under `c` that is + not in the frame form. A term or an EQL value that is not bytes is + `not_passthrough`. + - `Error::Record` has a new field, `output`: the key of the output at + fault, such as `c` or `eq`. `Error::output` returns it, and the payload + has it as `output`. The new functions set it. `decrypt` and + `check_record` leave it `None`, so their payloads do not change. Code + that builds an `Error::Record` must set the new field. - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 8b4b8cf3b..f0ed6a7c4 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -201,7 +201,7 @@ plan says which output is sealed. - The binding does not have to send the index terms. Decrypt reads only `c`, `passthrough`, and `eql`. - A field or output that the plan does not declare is refused. The error - names the field. + names the field, the output, and the row of a batch. [`crate::dynamic::record::read_stored_field`] reads one field's node. diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 3a5648e0b..6db880537 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -599,9 +599,20 @@ mod tests { row: Some(2), reason: Reason::NotAnObject, found: Some(crate::dynamic::Found::Sealed), + output: None, }), json!({ "reason": "not_an_object", "row": 2, "found": "sealed" }), ), + ( + Box::new(Error::Record { + field: Some("email".to_owned()), + row: Some(1), + reason: Reason::NotSealed, + found: None, + output: Some("c".to_owned()), + }), + json!({ "field": "email", "reason": "not_sealed", "row": 1, "output": "c" }), + ), ( Box::new(Error::SourceFailed { field: Some(name()), diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 00d254c51..9cecfa88f 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -209,15 +209,20 @@ //! //! ## Refusals //! -//! Each refusal is [`Error::Record`], and names the field. The one -//! exception is [`Error::Plan`], for a field that the plan does not have, -//! given to a function for one field. The [`Reason`] says which output is -//! at fault: +//! A refusal of the caller's input is [`Error::Record`]. It names what is +//! at fault, where there is one: //! -//! - [`Reason::NotSealed`] and [`Reason::Passthrough`] are about `c`. -//! - [`Reason::NotPassthrough`] is about an output in the clear. -//! - [`Reason::UndeclaredOutput`] is about an output that the field does -//! not declare. +//! - the field ([`Error::field`]), +//! - the output, such as `c` or `eq` ([`Error::output`]), and +//! - the row of a batch ([`Error::row`]). +//! +//! A refusal of a whole record or row names no field, such as a record +//! that is not a map. Two errors are not [`Error::Record`]: +//! +//! - [`Error::Plan`], for a field that the plan does not have, given to a +//! function for one field. +//! - [`Error::Internal`], for a defect in this crate, never the caller's +//! input. //! //! No refusal contains a value, or the text of a key inside a sealed node. //! @@ -2086,6 +2091,7 @@ pub fn check_record( reason, found: None, row: None, + output: None, } } }) @@ -2665,6 +2671,7 @@ pub(super) fn record_rows(tree: StackCipherText, plan: &Plan) -> Result Ok(Rows::One(record_row(row, plan)?)), diff --git a/packages/stack-encrypt/src/dynamic/record/stored.rs b/packages/stack-encrypt/src/dynamic/record/stored.rs index d3049486b..887b6f210 100644 --- a/packages/stack-encrypt/src/dynamic/record/stored.rs +++ b/packages/stack-encrypt/src/dynamic/record/stored.rs @@ -24,8 +24,8 @@ const EMPTY_MAP: &str = "empty_map"; /// /// `record` is what [`encrypt`](super::encrypt) returned under `plan`. The /// result has the frame form that the [module docs](super#the-frame-form) -/// describe. The frame is in a buffer that is wiped when it is dropped, -/// because a passthrough field's value is caller plaintext. +/// describe. The frame is in a buffer that is wiped when it is dropped, as +/// every frame that the engine returns is. /// /// # Examples /// @@ -73,7 +73,8 @@ const EMPTY_MAP: &str = "empty_map"; /// # Errors /// /// [`Error::Record`] when `plan` could not read the record back. The error -/// names the field when there is one. The reasons are: +/// names the field, the output, and the row of a batch, where there is +/// one. The reasons are: /// /// - [`Reason::NotAnObject`]: the record is not a map, or not a sequence of /// maps. @@ -87,9 +88,13 @@ const EMPTY_MAP: &str = "empty_map"; /// `c` repeats a key. /// - [`Reason::Passthrough`]: a passthrough is under `c`. /// - [`Reason::NotPassthrough`]: an output in the clear is not a -/// passthrough that contains one frame. +/// passthrough that contains one frame, or a term or an EQL value is not +/// bytes. /// - [`Reason::Unframeable`]: the frame would nest deeper than a frame can. /// +/// [`Error::Internal`] if the frame writer finishes without one frame. That +/// is a defect in this crate, never the caller's input. +/// /// The frame has one more level than the value, for each field's outputs. /// An empty list or map under `c` adds one more. So a value nested to the /// frame's limit can be sealed, and still be refused here. @@ -99,13 +104,16 @@ pub fn stored_frame(record: &StackCipherText, plan: &Plan) -> Result write_record(writer, fields, plan)?, CipherText::Sequence(records) => { - let unframeable = |_| Error::bad_record(Reason::Unframeable); + let unframeable = |error| Error::bad_record(written(error)); let mut batch = writer.seq(Some(records.len())).map_err(unframeable)?; for (at, record) in records.iter().enumerate() { let CipherText::Map(fields) = record else { return Err(not_an_object(Some(at), stored_kind(record))); }; - write_record(batch.element().map_err(unframeable)?, fields, plan)?; + let element = batch + .element() + .map_err(|error| in_row(unframeable(error), at))?; + write_record(element, fields, plan).map_err(|error| in_row(error, at))?; } batch.end().map_err(unframeable)?; } @@ -125,13 +133,18 @@ pub fn stored_frame(record: &StackCipherText, plan: &Plan) -> Result Result, plan: &Plan) -> Result { @@ -155,7 +169,9 @@ pub fn read_stored(frame: Frame<'_>, plan: &Plan) -> Result read_record(fields, plan).map(CipherText::Map), + Some(fields) => read_record(fields, plan) + .map(CipherText::Map) + .map_err(|error| in_row(error, at)), None => Err(not_an_object(Some(at), Found::of_frame(record))), }) .collect::>() @@ -207,16 +223,18 @@ pub fn read_stored_field( enum Content { /// A sealed node: `c`. Sealed, - /// A passthrough node: a term, a passthrough field's value, or an EQL - /// value. - Clear, + /// A passthrough node that contains bytes: a term or an EQL value. + Bytes, + /// A passthrough node that contains a passthrough field's value, of any + /// kind. + Value, } /// What the output under `key` contains. `None` if `field` declares no such /// output. fn content(field: &FieldPlan, key: &str) -> Option { if field.is_target() { - return (key == EQL_KEY).then_some(Content::Clear); + return (key == EQL_KEY).then_some(Content::Bytes); } field .outputs @@ -224,7 +242,8 @@ fn content(field: &FieldPlan, key: &str) -> Option { .find(|output| output.key() == key) .map(|output| match output { Output::Ciphertext => Content::Sealed, - Output::Term(_) | Output::Passthrough => Content::Clear, + Output::Term(_) => Content::Bytes, + Output::Passthrough => Content::Value, }) } @@ -249,6 +268,18 @@ fn misfit(field: &str, reason: Reason) -> Error { Error::bad_record(reason).in_field(field) } +/// A stored record that does not fit the plan, at the output `key` of +/// `field`. +fn output_misfit(field: &str, key: &str, reason: Reason) -> Error { + Error::Record { + field: Some(field.to_owned()), + row: None, + reason, + found: None, + output: Some(key.to_owned()), + } +} + /// A record, or the row `at` of a batch, that is `found` and not a map. fn not_an_object(row: Option, found: Found) -> Error { Error::Record { @@ -256,9 +287,42 @@ fn not_an_object(row: Option, found: Found) -> Error { row, reason: Reason::NotAnObject, found: Some(found), + output: None, + } +} + +/// `error`, as a refusal of the row `at` of a batch. +fn in_row(error: Error, at: usize) -> Error { + match error { + Error::Record { + field, + row: None, + reason, + found, + output, + } => Error::Record { + field, + row: Some(at), + reason, + found, + output, + }, + other => other, } } +/// Whether a frame is bytes. A term and an EQL value are bytes. +fn is_bytes(frame: Frame<'_>) -> bool { + frame + .visit(OneScalar::new( + |ty: Option, value: Physical<'_>| match (ty, value) { + (None, Physical::Bytes(_)) => Ok(()), + _ => Err(None), + }, + )) + .is_ok() +} + /// The reason for a frame writer's refusal of a node. A map that repeats a /// key is [`Reason::RepeatedKey`]. Any other refusal is a node that a frame /// cannot contain. @@ -311,23 +375,27 @@ fn write_outputs( .map_err(|error| at_fault(written(error)))?; let mut seen = HashSet::with_capacity(outputs.len()); for (key, node) in outputs { - let content = content(field, key).ok_or_else(|| at_fault(Reason::UndeclaredOutput))?; + let in_output = |reason| output_misfit(&field.name, key, reason); + let content = content(field, key).ok_or_else(|| in_output(Reason::UndeclaredOutput))?; if !seen.insert(key.as_str()) { - return Err(at_fault(Reason::RepeatedKey)); + return Err(in_output(Reason::RepeatedKey)); } - let entry = map.entry(key).map_err(|error| at_fault(written(error)))?; + let entry = map.entry(key).map_err(|error| in_output(written(error)))?; match content { - Content::Sealed => write_sealed(entry, node).map_err(at_fault)?, - Content::Clear => { + Content::Sealed => write_sealed(entry, node).map_err(in_output)?, + Content::Bytes | Content::Value => { let CipherText::Passthrough(payload) = node else { - return Err(at_fault(Reason::NotPassthrough)); + return Err(in_output(Reason::NotPassthrough)); }; let value = payload .parse() - .map_err(|_| at_fault(Reason::NotPassthrough))?; + .map_err(|_| in_output(Reason::NotPassthrough))?; + if content == Content::Bytes && !is_bytes(value) { + return Err(in_output(Reason::NotPassthrough)); + } value .visit(entry) - .map_err(|error| at_fault(written(error)))?; + .map_err(|error| in_output(written(error)))?; } } } @@ -401,11 +469,18 @@ fn read_outputs(frame: Frame<'_>, field: &FieldPlan) -> Result read_sealed(node).map_err(at_fault)?, + let in_output = |reason| output_misfit(&field.name, key, reason); + let content = content(field, key).ok_or_else(|| in_output(Reason::UndeclaredOutput))?; + if content == Content::Bytes && !is_bytes(node) { + return Err(in_output(Reason::NotPassthrough)); + } + let node = match content { + Content::Sealed => read_sealed(node).map_err(in_output)?, // A passthrough is in the clear by contract. Its frame is kept // as it is, as `encrypt` keeps it. - Content::Clear => CipherText::Passthrough(PassthroughFrame(node.as_bytes().to_vec())), + Content::Bytes | Content::Value => { + CipherText::Passthrough(PassthroughFrame(node.as_bytes().to_vec())) + } }; outputs.push((key.to_owned(), node)); } diff --git a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs index f617956ec..4992f8dfd 100644 --- a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs +++ b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs @@ -499,7 +499,7 @@ mod given_a_batch { mod given_a_target_field { use super::*; - fn plan() -> Plan { + pub(super) fn plan() -> Plan { let declaration = obj(vec![ ( "email", @@ -712,6 +712,11 @@ const SECRET: &str = "forged-secret"; fn assert_refused(error: &Error, field: Option<&str>, reason: Reason) { assert_eq!(error.field(), field, "{error}"); + assert_eq!( + error.output().is_some(), + format!("{error}").contains("(output "), + "the message names the output when the error does: {error}" + ); assert_eq!(error.reason(), Some(reason), "{error}"); let message = error.to_string(); assert!(!message.contains(SECRET), "{message}"); @@ -759,6 +764,7 @@ mod reading_a_frame_back { fn it_refuses_a_field_the_plan_does_not_name() { let error = refused(&obj(vec![("zzz", obj(vec![]))])); assert_refused(&error, Some("zzz"), Reason::UnknownField); + assert_eq!(error.output(), None); } #[test] @@ -766,14 +772,16 @@ mod reading_a_frame_back { for value in [Tree::Bytes(vec![1]), Tree::Array(vec![]), s(SECRET)] { let error = refused(&obj(vec![("age", value)])); assert_refused(&error, Some("age"), Reason::OutputsNotMap); + assert_eq!(error.output(), None); } } #[test] fn it_refuses_an_output_the_field_does_not_declare() { - for key in ["ope", "passthrough", "eql", SECRET] { + for key in ["ope", "passthrough", "eql", "foo"] { let error = refused(&age(vec![(key, Tree::Bytes(vec![1]))])); assert_refused(&error, Some("age"), Reason::UndeclaredOutput); + assert_eq!(error.output(), Some(key), "the error names the key"); } } @@ -787,6 +795,7 @@ mod reading_a_frame_back { ] { let error = refused(&age(vec![("c", c)])); assert_refused(&error, Some("age"), Reason::Passthrough); + assert_eq!(error.output(), Some("c")); } } @@ -809,9 +818,69 @@ mod reading_a_frame_back { ] { let error = refused(&age(vec![("c", c.clone())])); assert_refused(&error, Some("age"), Reason::NotSealed); + assert_eq!(error.output(), Some("c")); } } + /// A term and an EQL value are bytes. A passthrough field's value is + /// any value, so it is not checked. + #[tokio::test] + async fn it_refuses_a_term_or_an_eql_value_that_is_not_bytes() { + let bytes = leaf_bytes(&cipher().await.default_keyset()).await; + for term in [s(SECRET), Tree::Null, obj(vec![]), Tree::UInt32(1)] { + for key in ["eq", "ore"] { + let error = refused(&age(vec![ + ("c", Tree::Bytes(bytes.clone())), + (key, term.clone()), + ])); + assert_refused(&error, Some("age"), Reason::NotPassthrough); + assert_eq!(error.output(), Some(key)); + } + } + + let target = super::given_a_target_field::plan(); + let frame = frame_of(&obj(vec![("email", obj(vec![("eql", s(SECRET))]))])); + let frame = Frame::parse(frame.risky_ref()).expect("a frame"); + let error = read_stored(frame, &target).expect_err("refused"); + assert_refused(&error, Some("email"), Reason::NotPassthrough); + assert_eq!(error.output(), Some("eql")); + + let frame = frame_of(&obj(vec![( + "id", + obj(vec![("passthrough", s("any value"))]), + )])); + let frame = Frame::parse(frame.risky_ref()).expect("a frame"); + assert!(read_stored(frame, &every_output()).is_ok()); + } + + /// In a batch, every refusal names the row, as well as the field and + /// the output. + #[tokio::test] + async fn it_names_the_row_of_a_refusal_in_a_batch() { + let cipher = cipher().await; + let plan = every_output(); + let rows = Tree::Array(vec![every_output_row(), every_output_row()]); + let stored = seal(&cipher.default_keyset(), &rows, &plan).await; + let Tree::Array(mut rows) = tree(&stored_frame(&stored, &plan).expect("written")) else { + panic!("an array of records") + }; + let Tree::Object(fields) = &mut rows[1] else { + panic!("an object of fields") + }; + let Tree::Object(age) = &mut fields[0].1 else { + panic!("an object of outputs") + }; + age.push(("foo".to_owned(), Tree::Bytes(vec![1]))); + let error = refused(&Tree::Array(rows.clone())); + assert_refused(&error, Some("age"), Reason::UndeclaredOutput); + assert_eq!(error.row(), Some(1)); + assert_eq!(error.output(), Some("foo")); + + rows.swap(0, 1); + let error = refused(&Tree::Array(rows)); + assert_eq!(error.row(), Some(0)); + } + #[test] fn it_refuses_a_field_the_plan_does_not_have_for_one_fields_node() { let bytes = frame_of(&obj(vec![])); @@ -897,13 +966,17 @@ mod writing_a_frame { #[tokio::test] async fn it_refuses_an_output_undeclared_or_given_twice() { let record = - with_age(|age| age.push((SECRET.to_owned(), clear(&Tree::Bytes(vec![1]))))).await; - assert_refused(&refused(&record), Some("age"), Reason::UndeclaredOutput); + with_age(|age| age.push(("foo".to_owned(), clear(&Tree::Bytes(vec![1]))))).await; + let error = refused(&record); + assert_refused(&error, Some("age"), Reason::UndeclaredOutput); + assert_eq!(error.output(), Some("foo")); let mut again = entries(take(&mut sealed_fields().await, "age")); let older = take(&mut again, "c"); let record = with_age(|age| age.push(("c".to_owned(), older))).await; - assert_refused(&refused(&record), Some("age"), Reason::RepeatedKey); + let error = refused(&record); + assert_refused(&error, Some("age"), Reason::RepeatedKey); + assert_eq!(error.output(), Some("c")); } #[tokio::test] @@ -920,7 +993,9 @@ mod writing_a_frame { age.push(("c".to_owned(), c)); }) .await; - assert_refused(&refused(&record), Some("age"), Reason::Passthrough); + let error = refused(&record); + assert_refused(&error, Some("age"), Reason::Passthrough); + assert_eq!(error.output(), Some("c")); } } @@ -962,6 +1037,28 @@ mod writing_a_frame { }) .await; assert_refused(&refused(&record), Some("age"), Reason::NotPassthrough); + + // A term is bytes: a passthrough of another kind under `eq` is not + // one. + let record = with_age(|age| { + let _ = take(age, "eq"); + age.push(("eq".to_owned(), clear(&s(SECRET)))); + }) + .await; + let error = refused(&record); + assert_refused(&error, Some("age"), Reason::NotPassthrough); + assert_eq!(error.output(), Some("eq")); + } + + /// In a batch, every refusal names the row. + #[tokio::test] + async fn it_names_the_row_of_a_refusal_in_a_batch() { + let good = CipherText::Map(sealed_fields().await); + let mut fields = sealed_fields().await; + fields.push(("zzz".to_owned(), CipherText::Map(vec![]))); + let error = refused(&CipherText::Sequence(vec![good, CipherText::Map(fields)])); + assert_refused(&error, Some("zzz"), Reason::UnknownField); + assert_eq!(error.row(), Some(1)); } #[tokio::test] @@ -979,7 +1076,9 @@ mod writing_a_frame { age.push(("c".to_owned(), deep)); }) .await; - assert_refused(&refused(&record), Some("age"), Reason::Unframeable); + let error = refused(&record); + assert_refused(&error, Some("age"), Reason::Unframeable); + assert_eq!(error.output(), Some("c")); } #[tokio::test] diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index b26ae0f84..fc7a0d301 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -92,7 +92,11 @@ use crate::target::IndexSpec; /// /// An error from comparing the fields of a row with the plan names the /// field and no row. Examples are a missing field, a field that the plan -/// does not name, and a value of another type than the field declares. +/// does not name, and a value of another type than the field declares. The +/// one exception is a stored record converted to a frame or back +/// ([`record::stored_frame`](crate::dynamic::record::stored_frame), +/// [`record::read_stored`](crate::dynamic::record::read_stored)). In a +/// batch, every refusal of those functions names the row. /// /// Not every variant has a [`Reason`]. These variants have one: /// [`Context`](Error::Context), [`Plan`](Error::Plan), @@ -299,7 +303,7 @@ pub enum Error { /// fails with [`PlanError::FieldType`](crate::PlanError::FieldType) /// instead. #[error( - "{}", + "{}{}", misfit_text( "the record to decrypt does not match the plan", Subject::Record, @@ -307,14 +311,19 @@ pub enum Error { *found, *row, field - ) + ), + output_text(output) )] #[diagnostic(code(stack_encrypt::dynamic_record))] Record { /// The stored field at fault, if the fault is one field's. field: Option, /// The position of the row in a batch, counted from 0. `Some` when - /// the row is not a map. + /// the row is not a map. The functions that convert a stored record + /// to a frame and back + /// ([`record::stored_frame`](crate::dynamic::record::stored_frame), + /// [`record::read_stored`](crate::dynamic::record::read_stored)) also + /// name the row for every other refusal in a batch. row: Option, /// What was wrong with the stored record. reason: Reason, @@ -322,6 +331,11 @@ pub enum Error { /// is not a map of stored fields. `Some` only when `reason` is /// [`Reason::NotAnObject`]. found: Option, + /// The key of the field's output at fault, such as `"c"` or `"eq"`, + /// when the fault is one output's. The functions that convert a + /// stored record to a frame and back set it. `decrypt` and + /// `check_record` leave it `None`. + output: Option, }, /// A `match` predicate is refused at a place in its text: text the @@ -455,6 +469,15 @@ fn place_text(row: Option, field: &Option) -> String { } } +/// The end of the message of an [`Error::Record`] that names an output: +/// ` (output "c")`, or an empty string when the error names none. +fn output_text(output: &Option) -> String { + output + .as_deref() + .map(|output| format!(" (output {output:?})")) + .unwrap_or_default() +} + /// The message of an [`Error::SourceFailed`]. /// /// With a field, the message starts with "a value in the record to @@ -649,6 +672,7 @@ impl Error { row: None, reason, found: None, + output: None, } } @@ -730,6 +754,16 @@ impl Error { } } + /// The key of the field's output that a stored-record error is about, + /// such as `"c"` or `"eq"`. `None` for an error about a whole field, a + /// whole row, or a whole record. `None` for every other error. + pub fn output(&self) -> Option<&str> { + match self { + Self::Record { output, .. } => output.as_deref(), + _ => None, + } + } + /// The position of the row in a batch that the error is about, counted /// from 0. /// @@ -739,6 +773,8 @@ impl Error { /// - A value in the row returned an error of its own /// ([`SourceFailed`](Error::SourceFailed)). /// - The engine could not copy a value in the row of a record source. + /// - A stored record converted to a frame or back is refused, in a + /// batch. /// /// `None` when the input is one record and not a batch, and for every /// other error. @@ -795,6 +831,9 @@ impl crate::ErrorPayload for Error { if let Some(row) = self.row() { let _ = fields.insert("row".to_owned(), (row as u64).into()); } + if let Some(output) = self.output() { + let _ = fields.insert("output".to_owned(), output.into()); + } if let Some(found) = self.found() { let _ = fields.insert("found".to_owned(), found.as_str().into()); } From a2fd232707b5d122a7955739c342684ee4433f76 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 02:45:20 +1100 Subject: [PATCH 04/10] test(conformance): add the stored-frame profile, with the Go runner pending record-stored-frames-v1 fixes the frame form of a stored record for every binding. The cases cover these: - every output kind, and a passthrough of each value kind - a batch, and both null modes - lists, maps, and empty markers under c - the refusals, with their field, output, and row The Rust runner is stored_frame_conformance. The Go runner waits until the Go guest uses the frame form. --- conformance/stack-encrypt/README.md | 24 +- conformance/stack-encrypt/coverage.md | 1 + .../stack-encrypt/stored-frames-contract.md | 168 ++ .../v1/record-stored-frames-v1.cases.json | 2422 +++++++++++++++++ .../tests/stored_frame_conformance.rs | 450 +++ .../__tests__/stack-conformance-ci.test.mjs | 16 + scripts/stack-conformance.sh | 2 +- 7 files changed, 3080 insertions(+), 3 deletions(-) create mode 100644 conformance/stack-encrypt/stored-frames-contract.md create mode 100644 conformance/stack-encrypt/v1/record-stored-frames-v1.cases.json create mode 100644 packages/stack-encrypt/tests/stored_frame_conformance.rs diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 300bb29a6..10fdbfa75 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -46,6 +46,7 @@ these rules. | `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | | `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, issue #2010) | | `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, issue #2010) | +| `record-stored-frames-v1.cases.json` | cases | `tests/stored_frame_conformance.rs` | — (pending: the Go guest does not use the frame form yet) | | `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | | `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | | `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | @@ -92,8 +93,8 @@ fixtures described below. It ends with the fresh artifact exchange in both directions (`test:conformance:exchange`, which also needs the deterministic EQL guest). Set no fixture-update variables when checking conformance. -The task runs the single-value cases in native Rust only, because the Go -runner of that profile is pending. +The task runs the single-value cases and the stored-frame cases in native +Rust only, because the Go runners of those profiles are pending. The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface @@ -207,6 +208,25 @@ The native runner is `single_value_conformance` in the Rust crate. with the typed interface. The Go runner is pending. The Go runner will be written with the single-value calls of the Go SDK (issue #2010). +## A stored record as a frame + +The [stored-frame contract](stored-frames-contract.md) defines +`record-stored-frames-v1` in `v1/record-stored-frames-v1.cases.json`. A +binding moves a stored record to its language and back as a frame. Each +case encrypts rows under a plan, writes the stored record as a frame, and +checks the frame's form. It then reads the frame back, after a change where +the case has one, and decrypts it or checks the refusal. The cases cover: + +- every output kind, and a passthrough field of each value kind +- a batch, and an empty batch +- both null modes, and a `"null": "sql"` field left out or sent as null +- lists and maps under `c`, and the markers of an empty list and map +- the refusals, with the field, the output, and the row they name + +The native runner is `stored_frame_conformance` in the Rust crate, and +`test:conformance` runs it. The Go runner is pending until the Go guest uses +the frame form. + ## `record-reads-v1` contract The [read contract](read-contract.md) defines cases in `v1/record-reads-v1.cases.json` for diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 90b570655..e07dcd223 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -12,6 +12,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | | Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures | +| A stored record moved across a binding as a frame | The [stored-frame profile](stored-frames-contract.md), run by native Rust (`v1/record-stored-frames-v1.cases.json`: every output kind, a passthrough of each value kind, a batch, both null modes, lists, maps and empty markers under `c`, and the refusals with their field, output and row); `packages/stack-encrypt/src/dynamic/record/stored/tests.rs` (property tests over any value and any sealed shape, a field that names an EQL type, one field's node, and the refusals of a stored record that cannot be written as a frame) | The Go runner, once the Go guest uses the frame form; Python and TypeScript runners | | Fresh cross-language storage | `.github/workflows/tests-golang.yml` exports fresh Go EQL rows for Rust, the storage-only `Json` documents among them; initial scalar artifact exchange; fixed storage-blob vectors read by both Rust (`opaque_blob.rs`) and Go (`TestOpaqueReadsARustWrittenBlob`); the [exchange profile](exchange-contract.md): values, records, blobs and EQL rows written fresh and opened in both Rust/Go directions, with producer, engine, backend and storage versions in the report | Python/TypeScript pairs and backends when their runners exist; supported released versions once the compatibility policy is defined; fresh exchange of searchable JSON documents, and of `Json` documents from Rust to Go; a SQL lane storing one language's fresh rows through the other | | JSON queries, extraction and tampering | `packages/stack-encrypt/tests/json_tree_vectors.rs`; `packages/eql/tests/encryption/tests/json_tree.rs`; `languages/golang/encrypt/json_tree_test.go`, `json_postgres_test.go` | Formal operation profile; JSON vectors consumed by all runners | | Element and predicate matching | Go `json_elements_test.go`, `json_match_test.go` and corresponding PostgreSQL tests; Rust/SQL predicate suites | Map exact supported grammar and documented semantic differences to case IDs | diff --git a/conformance/stack-encrypt/stored-frames-contract.md b/conformance/stack-encrypt/stored-frames-contract.md new file mode 100644 index 000000000..fc55ae1fe --- /dev/null +++ b/conformance/stack-encrypt/stored-frames-contract.md @@ -0,0 +1,168 @@ +# Stored-frame profile + +`record-stored-frames-v1` is the conformance profile for a stored record +moved across a binding as a frame. The cases are in +`v1/record-stored-frames-v1.cases.json`. The profile is an experimental test +contract. + +A binding gets a stored record from `record::encrypt` and gives one to +`record::decrypt`. It moves the record to its language and back as a frame, +with `record::stored_frame` and `record::read_stored`. The cases fix the +form of that frame, so every binding builds and reads the same values. + +## Terms + +- A frame is one value written as bytes, in the format that the engine reads. +- A stored record is what `record::encrypt` returns. It has one entry for + each field. Each field has one entry for each output. +- An output is one of these: + - `c`, the sealed value + - an index term, such as `eq` + - `passthrough`, a field's value stored without encryption + - `eql`, the value of a field that names an EQL type +- A sealed value is the encrypted form of one scalar. Its bytes are stable. +- A marker is the sealed value that stands for an empty list or an empty + map under `c`. +- A refusal is an error that the engine returns for a frame it does not + accept. + +## Runners + +The Rust runner is `packages/stack-encrypt/tests/stored_frame_conformance.rs`. +The Go runner is pending: the Go guest does not use the frame form yet. The +Python and TypeScript runners are pending too. A missing runner is not a +passing result. + +## Cases + +Each case has these keys: + +| Key | Meaning | +|---|---| +| `id` | The name of the case | +| `plan` | The plan, in the [declaration grammar](declaration-grammar.md) | +| `batch` | Whether the rows are a batch. Without a batch, `rows` has one row. | +| `rows` | The rows to encrypt, as values | +| `frame` | The frame form that the stored record must have | +| `mutation` | A change to the frame before it is read back | +| `opened` | The rows that the frame, read back, decrypts to | +| `expected_error` | The `code` and the payload `fields` of the refusal that reading the frame back gives | + +A case has `opened` or `expected_error`, never both. + +### Values + +`rows` and `opened` write a value in one of these ways: + +| Form | The value | +|---|---| +| `{"type": ..., "text": ...}` | A scalar, as the [value profile](values-contract.md#cases) defines it | +| an array of values | A list | +| `{"$object": {...}}` | A map of values | +| `null` | A null | + +A row leaves out a field that it does not have. + +### Frame nodes + +`frame` and the `value` of a mutation write a node of the frame in one of +these ways: + +| Form | The node | +|---|---| +| `"$sealed"` | The bytes of a sealed value | +| `"$bytes"` | Any bytes, such as a term or an EQL value. `frame` only. | +| `{"$value": }` | The frame of a value, such as a passthrough field's value | +| `{"$hex": "..."}` | These bytes | +| `{"$passthrough": }` | A passthrough node of the frame, around another node. Mutations only. | +| other text | That text | +| `null` | A null | +| an array | An array of nodes | +| another object | An object of nodes | + +In a mutation, `"$sealed"` is the bytes of the first sealed value in the +frame that the runner wrote. + +Objects compare by key. The order of the keys in the corpus file is not +significant. The order of a frame's keys is the engine's. The runner does +not check it. + +### Mutations + +A mutation has a `path`, an `op`, and, for `set`, a `value`. Each step of +the path is a key of an object, or a position in an array, counted from 0. + +- `set` puts `value` at the path. It adds the key when the object has none. +- `remove` takes the key at the path out of its object. +- An empty path sets the whole frame. + +## Required behavior + +For each case, the runner does this: + +1. It reads the plan, and encrypts the rows, as one row or as a batch. +2. It writes the stored record as a frame. Where the case has `frame`, the + frame has that form. +3. It applies the mutation, where the case has one. +4. It reads the frame back. +5. For a case with `expected_error`, reading back is refused with the + `code`, and with a payload equal to `fields`. +6. For a case with `opened`, reading back succeeds. With no mutation, the + record read back writes the same frame again. The record decrypts to the + `opened` rows. + +The cases cover these things: + +- Every output kind: a sealed value, each index term, an index term alone, + and a passthrough field. +- A passthrough field of each value kind. +- A batch, and an empty batch. +- A field with `"null": "sql"` and no value. It has no entry. +- A field with `"null": "sealed"` and no value. It is sealed. +- A `"null": "sql"` field that the frame leaves out, or gives as null. It + decrypts as a null. +- Index terms left out of the frame. `decrypt` does not read them. +- A list and a map under `c`, nested, and the markers of an empty list and + an empty map. +- The refusals, listed in the next table. + +| Refusal | Reason | +|---|---| +| A frame that is not an object, or not an array of objects | `not_an_object` | +| A field the plan does not name | `unknown_field` | +| A field that is not an object of outputs | `outputs_not_map` | +| A null for a field without `"null": "sql"` | `outputs_not_map` | +| An output the field does not declare | `undeclared_output` | +| A passthrough under `c`, or inside it | `passthrough` | +| A node under `c` that is not sealed, or a wrong marker | `not_sealed` | +| A term that is not bytes | `not_passthrough` | +| A refusal in a batch | the refusal's reason, with the row | + +## Refusals + +The code of each refusal is `stack_encrypt::dynamic_record`. The payload has +these fields, where they apply: + +| Field | Meaning | +|---|---| +| `reason` | What was wrong, such as `undeclared_output` or `not_sealed` | +| `field` | The field at fault | +| `output` | The output at fault, such as `c` or `eq` | +| `row` | The row of a batch, counted from 0 | +| `found` | The kind of a frame, or a row, that is not an object | + +No refusal contains a value. + +## Scope and remaining work + +The profile does not cover these: + +- A stored record that the engine itself could not write as a frame. A + binding never builds a stored record. It only gets one from `encrypt`. + `packages/stack-encrypt/src/dynamic/record/stored/tests.rs` tests those + refusals natively. +- A field that names an EQL type. The EQL profile covers EQL values, and + the native tests cover their frame form. +- One field's node alone (`stored_field_frame` and `read_stored_field`). + The native tests cover it. +- Frames exchanged between languages. That needs a second runner. diff --git a/conformance/stack-encrypt/v1/record-stored-frames-v1.cases.json b/conformance/stack-encrypt/v1/record-stored-frames-v1.cases.json new file mode 100644 index 000000000..7326a50fa --- /dev/null +++ b/conformance/stack-encrypt/v1/record-stored-frames-v1.cases.json @@ -0,0 +1,2422 @@ +{ + "version": 1, + "profile": "record-stored-frames-v1", + "required_capabilities": ["records", "stored-frames", "refusals"], + "cases": [ + { + "id": "every-output", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "frame": { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + }, + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "passthrough-every-kind", + "plan": { + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "id": { + "type": "bool", + "text": "true" + } + }, + { + "id": { + "type": "int8", + "text": "-8" + } + }, + { + "id": { + "type": "int16", + "text": "-16" + } + }, + { + "id": { + "type": "int32", + "text": "-32" + } + }, + { + "id": { + "type": "int64", + "text": "-64" + } + }, + { + "id": { + "type": "int128", + "text": "-128" + } + }, + { + "id": { + "type": "uint8", + "text": "8" + } + }, + { + "id": { + "type": "uint16", + "text": "16" + } + }, + { + "id": { + "type": "uint32", + "text": "32" + } + }, + { + "id": { + "type": "uint64", + "text": "64" + } + }, + { + "id": { + "type": "uint128", + "text": "128" + } + }, + { + "id": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": { + "type": "float64", + "text": "-0.25" + } + }, + { + "id": { + "type": "string", + "text": "text" + } + }, + { + "id": { + "type": "string", + "text": "" + } + }, + { + "id": { + "type": "bytes", + "text": "00ff" + } + }, + { + "id": { + "type": "bytes", + "text": "" + } + }, + { + "id": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + }, + { + "id": { + "type": "decimal", + "text": "12.50" + } + }, + { + "id": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + }, + { + "id": { + "type": "null", + "text": "" + } + } + ], + "frame": [ + { + "id": { + "passthrough": { + "$value": { + "type": "bool", + "text": "true" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int8", + "text": "-8" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int16", + "text": "-16" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int32", + "text": "-32" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int64", + "text": "-64" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "int128", + "text": "-128" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint8", + "text": "8" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint16", + "text": "16" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint32", + "text": "32" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "64" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uint128", + "text": "128" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "float32", + "text": "1.5" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "float64", + "text": "-0.25" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "string", + "text": "text" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "string", + "text": "" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "bytes", + "text": "00ff" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "bytes", + "text": "" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "date", + "text": "2024-02-29" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "decimal", + "text": "12.50" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + } + } + }, + { + "id": { + "passthrough": { + "$value": { + "type": "null", + "text": "" + } + } + } + } + ], + "opened": [ + { + "id": { + "type": "bool", + "text": "true" + } + }, + { + "id": { + "type": "int8", + "text": "-8" + } + }, + { + "id": { + "type": "int16", + "text": "-16" + } + }, + { + "id": { + "type": "int32", + "text": "-32" + } + }, + { + "id": { + "type": "int64", + "text": "-64" + } + }, + { + "id": { + "type": "int128", + "text": "-128" + } + }, + { + "id": { + "type": "uint8", + "text": "8" + } + }, + { + "id": { + "type": "uint16", + "text": "16" + } + }, + { + "id": { + "type": "uint32", + "text": "32" + } + }, + { + "id": { + "type": "uint64", + "text": "64" + } + }, + { + "id": { + "type": "uint128", + "text": "128" + } + }, + { + "id": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": { + "type": "float64", + "text": "-0.25" + } + }, + { + "id": { + "type": "string", + "text": "text" + } + }, + { + "id": { + "type": "string", + "text": "" + } + }, + { + "id": { + "type": "bytes", + "text": "00ff" + } + }, + { + "id": { + "type": "bytes", + "text": "" + } + }, + { + "id": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": { + "type": "timestamp", + "text": "2024-02-29T12:00:00Z" + } + }, + { + "id": { + "type": "decimal", + "text": "12.50" + } + }, + { + "id": { + "type": "uuid", + "text": "0123abcd-4567-89ef-0123-456789abcdef" + } + }, + { + "id": { + "type": "null", + "text": "" + } + } + ] + }, + { + "id": "batch", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "35" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "frame": [ + { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + }, + { + "age": { + "c": "$sealed", + "eq": "$bytes", + "ore": "$bytes" + }, + "score": { + "c": "$sealed", + "ope": "$bytes" + }, + "email": { + "c": "$sealed", + "match": "$bytes" + }, + "bio": { + "c": "$sealed" + }, + "nick": { + "match": "$bytes" + }, + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "7" + } + } + } + } + ], + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "35" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "empty-batch", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [], + "frame": [], + "opened": [] + }, + { + "id": "sql-null", + "plan": { + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "eq"], + "type": "string", + "null": "sql" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "frame": { + "id": { + "passthrough": { + "$value": { + "type": "uint64", + "text": "1" + } + } + } + }, + "opened": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ] + }, + { + "id": "sealed-null", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq"], + "type": "uint32", + "null": "sealed" + } + }, + "batch": false, + "rows": [ + { + "age": null + } + ], + "frame": { + "age": { + "c": "$sealed", + "eq": "$bytes" + } + }, + "opened": [ + { + "age": null + } + ] + }, + { + "id": "sql-null-field-sent-as-null", + "plan": { + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "eq"], + "type": "string", + "null": "sql" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "email": { + "type": "string", + "text": "a@example.com" + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "mutation": { + "path": ["email"], + "op": "set", + "value": null + }, + "opened": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ] + }, + { + "id": "sql-null-field-left-out", + "plan": { + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "eq"], + "type": "string", + "null": "sql" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "email": { + "type": "string", + "text": "a@example.com" + }, + "id": { + "type": "uint64", + "text": "1" + } + } + ], + "mutation": { + "path": ["email"], + "op": "remove" + }, + "opened": [ + { + "email": null, + "id": { + "type": "uint64", + "text": "1" + } + } + ] + }, + { + "id": "index-terms-left-out", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "eq"], + "op": "remove" + }, + "opened": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ] + }, + { + "id": "lists-maps-and-empty-markers", + "plan": { + "doc": { + "context": ["conformance", "doc"], + "outputs": ["c"], + "type": "object" + }, + "list": { + "context": ["conformance", "list"], + "outputs": ["c"], + "type": "array" + }, + "loose": { + "context": ["conformance", "loose"], + "outputs": ["c"] + }, + "nested": { + "context": ["conformance", "nested"], + "outputs": ["c"] + } + }, + "batch": false, + "rows": [ + { + "doc": { + "$object": { + "home": { + "type": "string", + "text": "a@example.com" + }, + "tags": [], + "extra": { + "$object": {} + } + } + }, + "list": [], + "loose": { + "$object": {} + }, + "nested": [ + { + "type": "string", + "text": "a" + }, + [], + { + "$object": {} + }, + [ + { + "type": "uint32", + "text": "1" + } + ] + ] + } + ], + "frame": { + "doc": { + "c": { + "home": "$sealed", + "tags": ["empty_seq", "$sealed"], + "extra": ["empty_map", "$sealed"] + } + }, + "list": { + "c": ["empty_seq", "$sealed"] + }, + "loose": { + "c": ["empty_map", "$sealed"] + }, + "nested": { + "c": [ + "$sealed", + ["empty_seq", "$sealed"], + ["empty_map", "$sealed"], + ["$sealed"] + ] + } + }, + "opened": [ + { + "doc": { + "$object": { + "home": { + "type": "string", + "text": "a@example.com" + }, + "tags": [], + "extra": { + "$object": {} + } + } + }, + "list": [], + "loose": { + "$object": {} + }, + "nested": [ + { + "type": "string", + "text": "a" + }, + [], + { + "$object": {} + }, + [ + { + "type": "uint32", + "text": "1" + } + ] + ] + } + ] + }, + { + "id": "frame-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [], + "op": "set", + "value": "text" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "found": "string" + } + } + }, + { + "id": "batch-row-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [1], + "op": "set", + "value": { + "$value": { + "type": "uint32", + "text": "5" + } + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_an_object", + "row": 1, + "found": "uint32" + } + } + }, + { + "id": "unknown-field", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["zzz"], + "op": "set", + "value": {} + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "unknown_field", + "field": "zzz" + } + } + }, + { + "id": "field-not-an-object", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "outputs_not_map", + "field": "age" + } + } + }, + { + "id": "null-for-a-field-without-sql-null", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age"], + "op": "set", + "value": null + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "outputs_not_map", + "field": "age" + } + } + }, + { + "id": "undeclared-index", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "ope"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "undeclared_output", + "field": "age", + "output": "ope" + } + } + }, + { + "id": "undeclared-key", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "foo"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "undeclared_output", + "field": "age", + "output": "foo" + } + } + }, + { + "id": "passthrough-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": { + "$passthrough": { + "$value": { + "type": "uint32", + "text": "99" + } + } + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "passthrough", + "field": "age", + "output": "c" + } + } + }, + { + "id": "passthrough-inside-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": { + "k": { + "$passthrough": { + "$value": { + "type": "string", + "text": "forged" + } + } + } + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "passthrough", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "text-under-c", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": "not sealed" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "age", + "output": "c" + } + } + }, + { + "id": "bytes-that-are-not-sealed", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "c"], + "op": "set", + "value": { + "$hex": "00ff" + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "age", + "output": "c" + } + } + }, + { + "id": "marker-without-bytes", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": ["empty_seq"] + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "marker-with-unknown-text", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["bio", "c"], + "op": "set", + "value": ["empty_list", "$sealed"] + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_sealed", + "field": "bio", + "output": "c" + } + } + }, + { + "id": "term-not-bytes", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": false, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": ["age", "eq"], + "op": "set", + "value": "not bytes" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "not_passthrough", + "field": "age", + "output": "eq" + } + } + }, + { + "id": "refusal-in-a-batch-names-the-row", + "plan": { + "age": { + "context": ["conformance", "age"], + "outputs": ["c", "eq", "ore"], + "type": "uint32" + }, + "score": { + "context": ["conformance", "score"], + "outputs": ["c", "ope"], + "type": "int64" + }, + "email": { + "context": ["conformance", "email"], + "outputs": ["c", "match"], + "type": "string" + }, + "bio": { + "context": ["conformance", "bio"], + "outputs": ["c"] + }, + "nick": { + "context": ["conformance", "nick"], + "outputs": ["match"], + "type": "string" + }, + "id": { + "context": ["conformance", "id"], + "outputs": ["passthrough"] + } + }, + "batch": true, + "rows": [ + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + }, + { + "age": { + "type": "uint32", + "text": "34" + }, + "score": { + "type": "int64", + "text": "-7" + }, + "email": { + "type": "string", + "text": "ada@example.com" + }, + "bio": { + "type": "string", + "text": "a note" + }, + "nick": { + "type": "string", + "text": "al smith" + }, + "id": { + "type": "uint64", + "text": "7" + } + } + ], + "mutation": { + "path": [1, "age", "ope"], + "op": "set", + "value": { + "$hex": "01" + } + }, + "expected_error": { + "code": "stack_encrypt::dynamic_record", + "fields": { + "reason": "undeclared_output", + "field": "age", + "output": "ope", + "row": 1 + } + } + } + ] +} diff --git a/packages/stack-encrypt/tests/stored_frame_conformance.rs b/packages/stack-encrypt/tests/stored_frame_conformance.rs new file mode 100644 index 000000000..a328690ae --- /dev/null +++ b/packages/stack-encrypt/tests/stored_frame_conformance.rs @@ -0,0 +1,450 @@ +//! The runner for the shared stored-frame conformance profile. +//! +//! Each case seals rows under a plan, writes the stored record as a frame +//! (`record::stored_frame`), and checks the frame's form. It then reads the +//! frame back (`record::read_stored`), after a mutation where the case has +//! one, and decrypts it, or checks the refusal. See +//! `conformance/stack-encrypt/stored-frames-contract.md`. +#![cfg(feature = "dynamic")] +mod common; + +use std::collections::BTreeSet; + +use common::conformance::Input; +use common::frames::frame; +use miette::Diagnostic as _; +use serde::Deserialize; +use serde_json::{Map, Value}; +use stack_encrypt::dynamic::frame::{Frame, OwnedFrame, ARRAY, OBJECT, PASSTHROUGH}; +use stack_encrypt::dynamic::record; +use stack_encrypt::kms::FakeDataKeySource; +use stack_encrypt::{AsProtectedRef as _, ErrorPayload as _, SealedValue, StackCipher}; + +const PROFILE: &str = "record-stored-frames-v1"; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Corpus { + version: u32, + profile: String, + required_capabilities: Vec, + cases: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Case { + id: String, + plan: Value, + batch: bool, + rows: Vec, + #[serde(default)] + frame: Option, + #[serde(default)] + mutation: Option, + #[serde(default)] + opened: Option>, + #[serde(default)] + expected_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Mutation { + path: Vec, + op: String, + #[serde(default)] + value: Value, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ExpectedError { + code: String, + fields: Map, +} + +/// A frame, split into its containers. A scalar, or a passthrough node, +/// keeps its frame bytes as they are. +#[derive(Clone, Debug, PartialEq)] +enum Node { + Leaf(Vec), + Object(Vec<(String, Node)>), + Array(Vec), +} + +impl Node { + fn of(frame: Frame<'_>) -> Self { + if let Some(entries) = frame.entries() { + return Node::Object( + entries + .map(|(key, item)| (key.to_owned(), Node::of(item))) + .collect(), + ); + } + if let Some(items) = frame.elements() { + return Node::Array(items.map(Node::of).collect()); + } + Node::Leaf(frame.as_bytes().to_vec()) + } + + fn write(&self, out: &mut Vec) { + let count = |len: usize| u32::try_from(len).expect("short").to_le_bytes(); + match self { + Node::Leaf(bytes) => out.extend_from_slice(bytes), + Node::Object(entries) => { + out.push(OBJECT); + out.extend_from_slice(&count(entries.len())); + for (key, item) in entries { + out.extend_from_slice(&count(key.len())); + out.extend_from_slice(key.as_bytes()); + item.write(out); + } + } + Node::Array(items) => { + out.push(ARRAY); + out.extend_from_slice(&count(items.len())); + for item in items { + item.write(out); + } + } + } + } + + fn bytes(&self) -> Vec { + let mut out = Vec::new(); + self.write(&mut out); + out + } + + /// The same value, with every object's keys sorted: objects compare by + /// key, as the contract says. + fn sorted(&self) -> Self { + match self { + Node::Leaf(bytes) => Node::Leaf(bytes.clone()), + Node::Array(items) => Node::Array(items.iter().map(Node::sorted).collect()), + Node::Object(entries) => { + let mut entries: Vec<_> = entries + .iter() + .map(|(key, item)| (key.clone(), item.sorted())) + .collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + Node::Object(entries) + } + } + } +} + +fn leaf(value: T) -> Node { + Node::Leaf(frame(value).frame().as_bytes().to_vec()) +} + +fn null() -> Node { + Node::Leaf(OwnedFrame::null().frame().as_bytes().to_vec()) +} + +/// A value as the profile spells it: `{type, text}`, an array of values, +/// `{"$object": {...}}`, or null. +fn plain(value: &Value) -> Node { + match value { + Value::Null => null(), + Value::Array(items) => Node::Array(items.iter().map(plain).collect()), + Value::Object(map) if map.contains_key("$object") => { + assert_eq!(map.len(), 1, "an $object has one key"); + let Value::Object(entries) = &map["$object"] else { + panic!("an $object is an object") + }; + Node::Object( + entries + .iter() + .map(|(key, item)| (key.clone(), plain(item))) + .collect(), + ) + } + Value::Object(_) => { + let input: Input = serde_json::from_value(value.clone()).expect("a typed value"); + Node::Leaf( + common::conformance::value(&input) + .frame() + .as_bytes() + .to_vec(), + ) + } + other => panic!("not a value: {other}"), + } +} + +/// A row: an object of its fields' values. +fn row(value: &Value) -> Node { + let Value::Object(fields) = value else { + panic!("a row is an object of fields") + }; + Node::Object( + fields + .iter() + .map(|(name, value)| (name.clone(), plain(value))) + .collect(), + ) +} + +/// A node as a mutation spells it. `$sealed` is the bytes of `sealed`. +fn shaped(shape: &Value, sealed: &[u8]) -> Node { + match shape { + Value::Null => null(), + Value::String(text) if text == "$sealed" => leaf(sealed), + Value::String(text) => { + assert!(!text.starts_with('$'), "{text} is not a mutation's node"); + leaf(text.clone()) + } + Value::Array(items) => Node::Array(items.iter().map(|item| shaped(item, sealed)).collect()), + Value::Object(map) => { + if let Some(input) = map.get("$value") { + return plain(input); + } + if let Some(hex) = map.get("$hex") { + return leaf(common::unhex(hex.as_str().expect("hex text"))); + } + if let Some(inner) = map.get("$passthrough") { + let mut bytes = vec![PASSTHROUGH]; + bytes.extend(shaped(inner, sealed).bytes()); + return Node::Leaf(bytes); + } + Node::Object( + map.iter() + .map(|(key, item)| (key.clone(), shaped(item, sealed))) + .collect(), + ) + } + other => panic!("not a node: {other}"), + } +} + +/// The bytes a bytes leaf holds. +fn bytes_of(node: &Node) -> Option> { + let Node::Leaf(frame) = node else { return None }; + recipher_frame::serde::from_slice::<&[u8]>(frame) + .ok() + .map(<[u8]>::to_vec) +} + +/// Check `node` against the frame form `shape`. Objects compare by key. +fn check(id: &str, shape: &Value, node: &Node, at: &str) { + match shape { + Value::String(text) if text == "$sealed" => { + let bytes = bytes_of(node).unwrap_or_else(|| panic!("{id}: {at} is not bytes")); + SealedValue::from_bytes(&bytes) + .unwrap_or_else(|_| panic!("{id}: {at} is not a sealed value's bytes")); + } + Value::String(text) if text == "$bytes" => { + assert!(bytes_of(node).is_some(), "{id}: {at} is not bytes"); + } + Value::String(text) => { + assert!(!text.starts_with('$'), "{id}: {text} is not a frame node"); + assert_eq!( + node, + &leaf(text.clone()), + "{id}: {at} is not the text {text:?}" + ); + } + Value::Null => assert_eq!(node, &null(), "{id}: {at} is not null"), + Value::Array(items) => { + let Node::Array(nodes) = node else { + panic!("{id}: {at} is not an array") + }; + assert_eq!(items.len(), nodes.len(), "{id}: {at} has another length"); + for (i, (item, node)) in items.iter().zip(nodes).enumerate() { + check(id, item, node, &format!("{at}[{i}]")); + } + } + Value::Object(map) if map.contains_key("$value") => { + assert_eq!(map.len(), 1, "{id}: a $value has one key"); + assert_eq!(node, &plain(&map["$value"]), "{id}: {at} is another value"); + } + Value::Object(map) => { + let Node::Object(entries) = node else { + panic!("{id}: {at} is not an object") + }; + let keys: BTreeSet<&str> = entries.iter().map(|(key, _)| key.as_str()).collect(); + let expected: BTreeSet<&str> = map.keys().map(String::as_str).collect(); + assert_eq!(keys, expected, "{id}: {at} has other keys"); + assert_eq!(keys.len(), entries.len(), "{id}: {at} repeats a key"); + for (key, item) in entries { + check(id, &map[key], item, &format!("{at}.{key}")); + } + } + other => panic!("{id}: not a frame node: {other}"), + } +} + +/// The first sealed value's bytes in a frame, for a mutation's `$sealed`. +fn first_sealed(node: &Node) -> Option> { + match node { + Node::Leaf(_) => bytes_of(node).filter(|bytes| SealedValue::from_bytes(bytes).is_ok()), + Node::Array(items) => items.iter().find_map(first_sealed), + Node::Object(entries) => entries.iter().find_map(|(_, item)| first_sealed(item)), + } +} + +/// Apply `mutation` to the frame. +fn mutate(root: &mut Node, mutation: &Mutation, sealed: &[u8]) { + let Some((last, path)) = mutation.path.split_last() else { + assert_eq!(mutation.op, "set", "the root can only be set"); + *root = shaped(&mutation.value, sealed); + return; + }; + let mut at = root; + for step in path { + at = match (at, step) { + (Node::Array(items), Value::Number(n)) => { + &mut items[usize::try_from(n.as_u64().expect("an index")).expect("index")] + } + (Node::Object(entries), Value::String(key)) => { + &mut entries + .iter_mut() + .find(|(name, _)| name == key) + .unwrap_or_else(|| panic!("no {key}")) + .1 + } + _ => panic!("a path step that does not fit the frame"), + }; + } + match (at, last, mutation.op.as_str()) { + (Node::Array(items), Value::Number(n), "set") => { + let at = usize::try_from(n.as_u64().expect("an index")).expect("index"); + items[at] = shaped(&mutation.value, sealed); + } + (Node::Object(entries), Value::String(key), op) => { + let found = entries.iter().position(|(name, _)| name == key); + match (op, found) { + ("remove", Some(at)) => { + let _ = entries.remove(at); + } + ("set", found) => { + let node = shaped(&mutation.value, sealed); + match found { + Some(at) => entries[at].1 = node, + None => entries.push((key.clone(), node)), + } + } + _ => panic!("an operation that does not fit the frame"), + } + } + _ => panic!("a mutation that does not fit the frame"), + } +} + +fn owned(bytes: &[u8]) -> OwnedFrame { + common::frames::owned(bytes) +} + +#[tokio::test] +async fn stored_frame_conformance() { + let corpus: Corpus = serde_json::from_str(include_str!( + "../../../conformance/stack-encrypt/v1/record-stored-frames-v1.cases.json" + )) + .expect("the corpus parses"); + assert_eq!(corpus.version, 1); + assert_eq!(corpus.profile, PROFILE); + assert_eq!( + corpus.required_capabilities, + ["records", "stored-frames", "refusals"] + ); + let mut ids = BTreeSet::new(); + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .expect("a cipher"); + let keyset = cipher.default_keyset(); + + for case in &corpus.cases { + let id = case.id.as_str(); + assert!(!id.is_empty() && ids.insert(id), "{id}: a unique id"); + assert!( + case.batch || case.rows.len() == 1, + "{id}: one row unless a batch" + ); + assert_eq!( + case.expected_error.is_some(), + case.opened.is_none(), + "{id}: a case either opens or is refused" + ); + let declaration = recipher_frame::serde::to_vec(&case.plan).expect("a plan frame"); + let plan = record::plan(declaration.as_protected_ref()).expect("the plan parses"); + + let rows: Vec = case.rows.iter().map(row).collect(); + let source = if case.batch { + Node::Array(rows) + } else { + rows.into_iter().next().expect("one row") + }; + let stored = record::encrypt(&keyset, owned(&source.bytes()), &plan) + .expect("the rows fit the plan") + .await + .expect("encrypt"); + let written = record::stored_frame(&stored, &plan).expect("written"); + let mut node = Node::of(written.frame()); + if let Some(shape) = &case.frame { + check(id, shape, &node, "frame"); + } + assert_eq!( + node.bytes(), + written.frame().as_bytes(), + "{id}: the frame splits and joins as it was" + ); + + if let Some(mutation) = &case.mutation { + let sealed = first_sealed(&node).unwrap_or_default(); + mutate(&mut node, mutation, &sealed); + } + let sent = owned(&node.bytes()); + let read = record::read_stored(sent.frame(), &plan); + + if let Some(expected) = &case.expected_error { + let error = match read { + Ok(_) => panic!("{id}: read_stored accepted the frame"), + Err(error) => error, + }; + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some(expected.code.as_str()), + "{id}: {error}" + ); + assert_eq!(error.payload(), expected.fields, "{id}: {error}"); + continue; + } + + let read = read.unwrap_or_else(|error| panic!("{id}: {error}")); + if case.mutation.is_none() { + assert_eq!( + record::stored_frame(&read, &plan) + .expect("written again") + .frame() + .as_bytes(), + written.frame().as_bytes(), + "{id}: the record read back writes the same frame" + ); + } + let opened = record::decrypt(&cipher, read, &plan, None) + .expect("the record fits the plan") + .await + .unwrap_or_else(|error| panic!("{id}: {error}")); + let expected: Vec = case + .opened + .as_ref() + .expect("opened rows") + .iter() + .map(row) + .collect(); + let expected = if case.batch { + Node::Array(expected) + } else { + expected.into_iter().next().expect("one row") + }; + assert_eq!( + Node::of(opened.frame()).sorted(), + expected.sorted(), + "{id}: the rows decrypt as expected" + ); + } +} diff --git a/scripts/__tests__/stack-conformance-ci.test.mjs b/scripts/__tests__/stack-conformance-ci.test.mjs index c26286286..8afed46b3 100644 --- a/scripts/__tests__/stack-conformance-ci.test.mjs +++ b/scripts/__tests__/stack-conformance-ci.test.mjs @@ -79,6 +79,22 @@ describe('shared Stack Encrypt conformance is required in CI', () => { ) }) + it('the conformance task runs the stored-frame profile in Rust, which has no Go runner yet', () => { + const script = conformanceScript() + expect(script).toMatch( + /cargo nextest run[^\n]*--test stored_frame_conformance/, + ) + // When the Go guest uses the frame form, write its runner, add it to + // `coreGoTests`, move the assertion above into the test of both + // languages, and delete this one. + const selected = goSelection(script) + expect(coreGoTests.some((test) => /StoredFrame/.test(test))).toBe(false) + expect(selected.test('TestStoredFrameConformance')).toBe(false) + expect(readRepo('conformance/stack-encrypt/README.md')).toMatch( + /record-stored-frames-v1\.cases\.json[^\n]*pending/, + ) + }) + it('selects exactly the core runners and indexed fixture tests', () => { const index = JSON.parse( readRepo('conformance/stack-encrypt/v1/fixture-enrollment.json'), diff --git a/scripts/stack-conformance.sh b/scripts/stack-conformance.sh index 600ba556c..4f34ca3b7 100644 --- a/scripts/stack-conformance.sh +++ b/scripts/stack-conformance.sh @@ -19,7 +19,7 @@ go_tests=$(node scripts/stack-conformance-selection.mjs) artifacts=$(mktemp -d) trap 'rm -rf "$artifacts"' EXIT -mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance --test single_value_conformance +mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance --test single_value_conformance --test stored_frame_conformance ( cd languages/golang STACK_CONFORMANCE_OUTPUT="$artifacts/go.json" CGO_ENABLED=0 \ From 95b5604c62a0a00f38b00ebcb9bc13a80dcc35d8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 02:49:49 +1100 Subject: [PATCH 05/10] test(stack-encrypt): keep generated dates and timestamps in the engine range The property test drew dates up to 3,000,000 days, past the last date the engine accepts (year 9999). A row with such a date was refused before it was sealed, so the test failed at random. It now draws dates and timestamps from the range that the engine accepts. --- packages/stack-encrypt/src/dynamic/record/stored/tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs index 4992f8dfd..ace80db80 100644 --- a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs +++ b/packages/stack-encrypt/src/dynamic/record/stored/tests.rs @@ -565,7 +565,7 @@ mod given_a_target_field { /// are every scalar kind, the logical kinds, and lists and maps of them. /// Empty lists and maps are included. fn value() -> impl Strategy { - use vitaminc_aead::plaintext::{Logical, TimeUnit}; + use vitaminc_aead::plaintext::{kinds, Logical, TimeUnit}; let typed = |logical: Logical, value: Tree| Tree::Typed(logical, Box::new(value)); let scalar = prop_oneof![ Just(Tree::Null), @@ -585,8 +585,9 @@ fn value() -> impl Strategy { any::().prop_map(Tree::Float64), ".{0,12}".prop_map(Tree::String), proptest::collection::vec(any::(), 0..12).prop_map(Tree::Bytes), - (-3_000_000i32..3_000_000).prop_map(move |days| typed(Logical::Date, Tree::Int32(days))), - (-1_000_000_000_000_000_000i128..1_000_000_000_000_000_000) + (kinds::MIN_DATE_DAYS..=kinds::MAX_DATE_DAYS) + .prop_map(move |days| typed(Logical::Date, Tree::Int32(days))), + (kinds::MIN_TIMESTAMP_NANOS..=kinds::MAX_TIMESTAMP_NANOS) .prop_map(move |at| typed(Logical::Timestamp(TimeUnit::Nanos), Tree::Int128(at))), (0u8..=28, any::()).prop_map(move |(scale, int)| typed( Logical::Decimal { scale }, From 0302e15725564923428b4f1bb1f40f913f0d3715 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 03:20:57 +1100 Subject: [PATCH 06/10] test(stack-encrypt): move the stored-frame unit tests into a tests directory The CRAP gate skips files under a tests directory. The unit tests of the stored-frame module were in stored/tests.rs, so the gate scored their helpers as source with no coverage, and one helper failed it. The tests now live in stored/tests/mod.rs. No test changed. --- conformance/stack-encrypt/coverage.md | 2 +- conformance/stack-encrypt/stored-frames-contract.md | 2 +- .../src/dynamic/record/stored/{tests.rs => tests/mod.rs} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename packages/stack-encrypt/src/dynamic/record/stored/{tests.rs => tests/mod.rs} (100%) diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index e07dcd223..35804565a 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -12,7 +12,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | | Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures | -| A stored record moved across a binding as a frame | The [stored-frame profile](stored-frames-contract.md), run by native Rust (`v1/record-stored-frames-v1.cases.json`: every output kind, a passthrough of each value kind, a batch, both null modes, lists, maps and empty markers under `c`, and the refusals with their field, output and row); `packages/stack-encrypt/src/dynamic/record/stored/tests.rs` (property tests over any value and any sealed shape, a field that names an EQL type, one field's node, and the refusals of a stored record that cannot be written as a frame) | The Go runner, once the Go guest uses the frame form; Python and TypeScript runners | +| A stored record moved across a binding as a frame | The [stored-frame profile](stored-frames-contract.md), run by native Rust (`v1/record-stored-frames-v1.cases.json`: every output kind, a passthrough of each value kind, a batch, both null modes, lists, maps and empty markers under `c`, and the refusals with their field, output and row); `packages/stack-encrypt/src/dynamic/record/stored/tests/mod.rs` (property tests over any value and any sealed shape, a field that names an EQL type, one field's node, and the refusals of a stored record that cannot be written as a frame) | The Go runner, once the Go guest uses the frame form; Python and TypeScript runners | | Fresh cross-language storage | `.github/workflows/tests-golang.yml` exports fresh Go EQL rows for Rust, the storage-only `Json` documents among them; initial scalar artifact exchange; fixed storage-blob vectors read by both Rust (`opaque_blob.rs`) and Go (`TestOpaqueReadsARustWrittenBlob`); the [exchange profile](exchange-contract.md): values, records, blobs and EQL rows written fresh and opened in both Rust/Go directions, with producer, engine, backend and storage versions in the report | Python/TypeScript pairs and backends when their runners exist; supported released versions once the compatibility policy is defined; fresh exchange of searchable JSON documents, and of `Json` documents from Rust to Go; a SQL lane storing one language's fresh rows through the other | | JSON queries, extraction and tampering | `packages/stack-encrypt/tests/json_tree_vectors.rs`; `packages/eql/tests/encryption/tests/json_tree.rs`; `languages/golang/encrypt/json_tree_test.go`, `json_postgres_test.go` | Formal operation profile; JSON vectors consumed by all runners | | Element and predicate matching | Go `json_elements_test.go`, `json_match_test.go` and corresponding PostgreSQL tests; Rust/SQL predicate suites | Map exact supported grammar and documented semantic differences to case IDs | diff --git a/conformance/stack-encrypt/stored-frames-contract.md b/conformance/stack-encrypt/stored-frames-contract.md index fc55ae1fe..3011c7d8c 100644 --- a/conformance/stack-encrypt/stored-frames-contract.md +++ b/conformance/stack-encrypt/stored-frames-contract.md @@ -159,7 +159,7 @@ The profile does not cover these: - A stored record that the engine itself could not write as a frame. A binding never builds a stored record. It only gets one from `encrypt`. - `packages/stack-encrypt/src/dynamic/record/stored/tests.rs` tests those + `packages/stack-encrypt/src/dynamic/record/stored/tests/mod.rs` tests those refusals natively. - A field that names an EQL type. The EQL profile covers EQL values, and the native tests cover their frame form. diff --git a/packages/stack-encrypt/src/dynamic/record/stored/tests.rs b/packages/stack-encrypt/src/dynamic/record/stored/tests/mod.rs similarity index 100% rename from packages/stack-encrypt/src/dynamic/record/stored/tests.rs rename to packages/stack-encrypt/src/dynamic/record/stored/tests/mod.rs From 113e136cce055d847f5d6ccf0043de7afa903097 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 13:46:56 +1100 Subject: [PATCH 07/10] feat(recipher-frame): write and read a raw frame node through serde serde has no model for a date, a decimal, a timestamp, a UUID, or a passthrough. So such a value could not cross the serde adapter. `recipher_frame::serde::raw` now writes one frame node as it is, and reads the next node back as its bytes. Writing checks that the bytes are one well-formed node, and counts its depth from where it is written. The storage profile and every other serde format refuse a raw node, so it never becomes another value. --- packages/recipher-frame/CHANGELOG.md | 5 + packages/recipher-frame/src/serde.rs | 19 +- packages/recipher-frame/src/serde/raw.rs | 153 ++++++++++++++++ .../recipher-frame/src/serde/raw/tests/mod.rs | 144 ++++++++++++++++ packages/recipher-frame/src/write.rs | 163 +++++++++++++++++- 5 files changed, 479 insertions(+), 5 deletions(-) create mode 100644 packages/recipher-frame/src/serde/raw.rs create mode 100644 packages/recipher-frame/src/serde/raw/tests/mod.rs diff --git a/packages/recipher-frame/CHANGELOG.md b/packages/recipher-frame/CHANGELOG.md index 0f87cc3f8..b6c8393ad 100644 --- a/packages/recipher-frame/CHANGELOG.md +++ b/packages/recipher-frame/CHANGELOG.md @@ -10,6 +10,11 @@ - `OwnedFrame` is re-exported from `vitaminc-aead`, with the rest of the frame. - `Entries` is re-exported from `vitaminc-aead`, beside `Elements`: what `Frame::entries` returns. +- `serde::raw` writes and reads one frame node as it is. + It is for a value that serde has no model for, such as a date, a timestamp, a decimal, a UUID, or a passthrough. + Use it with `#[serde(with = "recipher_frame::serde::raw")]` on a `Buffer` field, or call `serialize`, `serialize_bytes`, and `deserialize` from a `with` module of your own. + Writing checks that the bytes are one well-formed node, and counts the node's depth from where it is written. + The storage profile and every other serde format refuse a raw node, so it never becomes another value by mistake. ## [0.10.0] - 2026-11-19 diff --git a/packages/recipher-frame/src/serde.rs b/packages/recipher-frame/src/serde.rs index a1ee184ce..c43e8ee2a 100644 --- a/packages/recipher-frame/src/serde.rs +++ b/packages/recipher-frame/src/serde.rs @@ -149,6 +149,8 @@ use vitaminc_protected::Buffer; use crate::write::{write, AsTransport}; +pub mod raw; + // ============================================================================= // Errors // ============================================================================= @@ -750,12 +752,25 @@ impl<'de> de::Deserializer<'de> for &mut Deserializer<'de> { } } + /// A raw node ([`raw`]) is handed over as its bytes, in the transport + /// format only. Any other newtype is read as the value inside it. fn deserialize_newtype_struct>( self, - _name: &'static str, + name: &'static str, visitor: V, ) -> Result { - visitor.visit_newtype_struct(self) + if name != raw::TOKEN { + return visitor.visit_newtype_struct(self); + } + if self.profile != Profile::Transport { + return Err(Error::new( + "a raw frame node is not read from a storage blob", + )); + } + let start = self.pos; + self.skip()?; + let node = self.buf.get(start..self.pos).ok_or_else(malformed_frame)?; + raw::handing_over(|| visitor.visit_borrowed_bytes(node)) } fn deserialize_struct>( diff --git a/packages/recipher-frame/src/serde/raw.rs b/packages/recipher-frame/src/serde/raw.rs new file mode 100644 index 000000000..e118e9c5d --- /dev/null +++ b/packages/recipher-frame/src/serde/raw.rs @@ -0,0 +1,153 @@ +//! One frame node, written and read as it is. +//! +//! serde has no data model for some frame nodes: a date, a timestamp, a +//! decimal, a UUID, or a passthrough. To keep such a node as frame bytes, +//! put `#[serde(with = "recipher_frame::serde::raw")]` on a field whose +//! type is [`Buffer`]. Or call [`serialize`] and [`deserialize`] from a +//! `with` module of your own. The node crosses as its bytes, +//! and serde never reads inside it. +//! +//! - Writing, the bytes must be exactly one well-formed frame node. The +//! node's own depth counts towards the frame's depth limit +//! ([`MAX_DEPTH`](vitaminc_aead::frame::MAX_DEPTH)), from where it is +//! written. +//! - Reading takes the next node of the frame, whatever it is, as its bytes. +//! The frame was checked when it was parsed, so the node is well formed. +//! - Only this crate's transport format writes or reads a raw node. Another +//! serde format, and the storage profile, refuse it, so a raw node never +//! becomes some other value by mistake. +//! - An error never repeats the node's bytes. +//! +//! ``` +//! use serde::{Deserialize, Serialize}; +//! use vitaminc_protected::{Buffer, Controlled}; +//! +//! #[derive(Serialize, Deserialize)] +//! struct Row { +//! name: String, +//! #[serde(with = "recipher_frame::serde::raw")] +//! value: Buffer, +//! } +//! +//! // A date, which serde has no model for, as a frame node. +//! let date = recipher_frame::to_frame(vitaminc_aead::plaintext::Raw( +//! Some(vitaminc_aead::plaintext::Logical::Date), +//! vitaminc_aead::plaintext::Physical::Int(vitaminc_aead::plaintext::Int::I32(19_000)), +//! ))?; +//! let row = Row { name: "dob".into(), value: date }; +//! let bytes = recipher_frame::serde::to_vec(&row)?; +//! let back: Row = recipher_frame::serde::from_slice(bytes.risky_ref())?; +//! assert_eq!(back.value.risky_ref(), row.value.risky_ref()); +//! # Ok::<(), Box>(()) +//! ``` + +use std::cell::Cell; +use std::fmt; + +use ::serde::de::{self, Deserializer, Visitor}; +use ::serde::ser::{self, Serialize, Serializer}; +use vitaminc_aead::Frame; +use vitaminc_protected::{Buffer, Controlled}; + +/// The name a raw node is written and read under. Only this crate's +/// reader and writer know it. +pub(crate) const TOKEN: &str = "$recipher_frame::serde::raw"; + +thread_local! { + /// Set while this crate's writer takes a raw node's bytes, or its reader + /// hands them over. A raw node refuses to be written or read when it is + /// not set, so another serde format never sees one as plain bytes. + static HANDING_OVER: Cell = const { Cell::new(false) }; +} + +/// Run `f` while a raw node is being handed over. +pub(crate) fn handing_over(f: impl FnOnce() -> T) -> T { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + HANDING_OVER.with(|flag| flag.set(self.0)); + } + } + let _reset = Reset(HANDING_OVER.with(|flag| flag.replace(true))); + f() +} + +fn is_handing_over() -> bool { + HANDING_OVER.with(Cell::get) +} + +/// The message of a raw node that another format was asked to write or +/// read. +const ONLY_HERE: &str = "a raw frame node is written and read only by recipher_frame::serde"; + +/// Write `node`, the bytes of one frame node, as it is. +/// +/// # Errors +/// +/// Through `serializer`'s error, in these cases: +/// +/// - The bytes are not exactly one well-formed node. +/// - The node would nest deeper than a frame allows where it is written. +/// - The serializer is the storage profile's, or another format's. +pub fn serialize(node: &Buffer, serializer: S) -> Result { + serialize_bytes(node.risky_ref(), serializer) +} + +/// [`serialize`] for a node held in a slice. +/// +/// # Errors +/// +/// As [`serialize`]. +pub fn serialize_bytes(node: &[u8], serializer: S) -> Result { + serializer.serialize_newtype_struct(TOKEN, &Node(node)) +} + +/// Read the next node as it is, into a [`Buffer`] that is wiped when it is +/// dropped. +/// +/// # Errors +/// +/// Through `deserializer`'s error: the deserializer is the storage +/// profile's, or another format's. +pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + deserializer.deserialize_newtype_struct(TOKEN, NodeVisitor) +} + +/// A raw node's bytes. Only this crate's writer takes them. +struct Node<'a>(&'a [u8]); + +impl Serialize for Node<'_> { + fn serialize(&self, serializer: S) -> Result { + if !is_handing_over() { + return Err(::custom(ONLY_HERE)); + } + serializer.serialize_bytes(self.0) + } +} + +/// Takes a raw node's bytes from this crate's reader. +struct NodeVisitor; + +impl<'de> Visitor<'de> for NodeVisitor { + type Value = Buffer; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a frame node") + } + + fn visit_bytes(self, bytes: &[u8]) -> Result { + if !is_handing_over() { + return Err(E::custom(ONLY_HERE)); + } + // The reader hands over a node of a frame it has parsed, so this + // holds; it is checked again so the value is one node whatever + // handed it over. + Frame::parse(bytes).map_err(|_| E::custom("not one frame node"))?; + let mut node = Buffer::with_capacity(bytes.len()); + node.extend_from_slice(bytes); + Ok(node) + } +} + +#[cfg(test)] +mod tests; diff --git a/packages/recipher-frame/src/serde/raw/tests/mod.rs b/packages/recipher-frame/src/serde/raw/tests/mod.rs new file mode 100644 index 000000000..eaff1759f --- /dev/null +++ b/packages/recipher-frame/src/serde/raw/tests/mod.rs @@ -0,0 +1,144 @@ +use quickcheck_macros::quickcheck; +use serde::{Deserialize, Serialize}; +use vitaminc_aead::frame::{ARRAY, MAX_DEPTH, OBJECT, PASSTHROUGH}; +use vitaminc_aead::plaintext::{Int, Logical, Physical, Raw}; +use vitaminc_aead::to_frame; +use vitaminc_protected::{Buffer, Controlled}; + +use crate::serde::{from_slice, to_vec}; + +/// A row whose `value` is a raw node. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Row { + name: String, + #[serde(with = "crate::serde::raw")] + value: Buffer, +} + +fn buffer(bytes: &[u8]) -> Buffer { + let mut out = Buffer::new(); + out.extend_from_slice(bytes); + out +} + +fn row(value: &[u8]) -> Row { + Row { + name: "n".to_owned(), + value: buffer(value), + } +} + +/// A frame of `depth` nested arrays around a null: `depth` levels below +/// its root. +fn nested(depth: usize) -> Vec { + let mut out = Vec::new(); + for _ in 0..depth { + out.extend([ARRAY, 1, 0, 0, 0]); + } + out.extend(to_frame(None::).expect("a null").risky_ref()); + out +} + +/// Frames of nodes that serde has no model for, and of nodes that it has. +fn nodes() -> Vec> { + let frame = |value: Buffer| value.risky_ref().to_vec(); + let date = Raw(Some(Logical::Date), Physical::Int(Int::I32(19_000))); + let mut passthrough = vec![PASSTHROUGH]; + passthrough.extend(frame(to_frame("clear").expect("text"))); + vec![ + frame(to_frame(date).expect("a date")), + passthrough, + frame(to_frame(None::).expect("a null")), + frame(to_frame(vec![1u32, 2]).expect("an array")), + frame(to_frame(std::collections::BTreeMap::from([("k", "v")])).expect("an object")), + nested(MAX_DEPTH - 1), + ] +} + +#[test] +fn a_node_is_written_as_it_is_and_read_back_as_it_is() { + for node in nodes() { + let written = to_vec(&row(&node)).expect("written"); + let mut expected = vec![OBJECT, 2, 0, 0, 0]; + expected.extend(to_vec_fields(&node)); + assert_eq!(written.risky_ref().as_slice(), expected.as_slice()); + let back: Row = from_slice(written.risky_ref()).expect("read"); + assert_eq!(back.value.risky_ref().as_slice(), node.as_slice()); + assert_eq!(back.name, "n"); + } +} + +/// The two entries of a [`Row`], as the writer lays them out. +fn to_vec_fields(node: &[u8]) -> Vec { + let mut out = Vec::new(); + out.extend(4u32.to_le_bytes()); + out.extend(b"name"); + out.extend(to_frame("n").expect("text").risky_ref()); + out.extend(5u32.to_le_bytes()); + out.extend(b"value"); + out.extend(node); + out +} + +#[test] +fn bytes_that_are_not_one_node_are_refused_without_repeating_them() { + let text = to_frame("forged-secret") + .expect("text") + .risky_ref() + .to_vec(); + let mut two = text.clone(); + two.extend(&text); + let truncated = &text[..text.len() - 1]; + for bad in [&[][..], truncated, &two, &[0xEE][..]] { + let error = to_vec(&row(bad)).expect_err("refused"); + let message = error.to_string(); + assert!(message.contains("raw frame node"), "{message}"); + assert!(!message.contains("forged"), "{message}"); + assert_eq!(error.field(), Some("value")); + } +} + +/// A raw node at depth 1 may be at most `MAX_DEPTH - 1` levels deep. +#[test] +fn the_depth_limit_counts_the_node_where_it_is_written() { + assert!(to_vec(&row(&nested(MAX_DEPTH - 1))).is_ok()); + assert!(to_vec(&row(&nested(MAX_DEPTH))).is_err()); +} + +#[test] +fn the_storage_profile_refuses_a_raw_node() { + let node = to_frame(1u32).expect("a number"); + assert!(crate::storage::to_vec(&row(node.risky_ref())).is_err()); + + let written = to_vec(&row(node.risky_ref())).expect("written"); + let mut blob = crate::storage::HEADER.to_vec(); + blob.extend(written.risky_ref()); + assert!(crate::storage::from_slice::(&blob).is_err()); +} + +#[test] +fn another_format_refuses_a_raw_node() { + let node = to_frame(1u32).expect("a number"); + let error = serde_json::to_string(&row(node.risky_ref())).expect_err("refused"); + assert!(error.to_string().contains("raw frame node"), "{error}"); + assert!(serde_json::from_str::(r#"{"name":"n","value":[1]}"#).is_err()); + assert!(serde_json::from_str::(r#"{"name":"n","value":"AQ=="}"#).is_err()); +} + +#[quickcheck] +fn any_bytes_are_written_as_one_node_or_refused(bytes: Vec) -> bool { + match to_vec(&row(&bytes)) { + Ok(written) => { + let back: Row = from_slice(written.risky_ref()).expect("what was written reads"); + back.value.risky_ref().as_slice() == bytes.as_slice() + } + Err(_) => vitaminc_aead::Frame::parse(&bytes).is_err(), + } +} + +#[quickcheck] +fn any_frame_reads_as_a_row_or_is_refused(bytes: Vec) -> bool { + let _ = from_slice::(&bytes); + true +} diff --git a/packages/recipher-frame/src/write.rs b/packages/recipher-frame/src/write.rs index 435ea985e..2a3fa9e2d 100644 --- a/packages/recipher-frame/src/write.rs +++ b/packages/recipher-frame/src/write.rs @@ -32,9 +32,10 @@ use vitaminc_aead::frame::{FrameWriteError, ARRAY, MAX_DEPTH, OBJECT}; use vitaminc_aead::leaf::{self, Form, ScalarError}; use vitaminc_aead::plaintext::{Float, Int, Physical}; use vitaminc_aead::tags::{self, STORAGE_MAP, STORAGE_SOME}; +use vitaminc_aead::Frame; use vitaminc_protected::{Buffer, Controlled}; -use crate::serde::{At, Error, Profile}; +use crate::serde::{raw, At, Error, Profile}; use crate::storage::{distinct, Invalid, MapKey}; /// A [`Profile`] as a type, so the writer is compiled once for each @@ -428,12 +429,33 @@ impl<'o, P: Profiled> ser::Serializer for Writer<'o, P> { ) -> Result<(), Error> { self.scalar(Physical::Text(variant)) } + /// A raw node ([`raw`](crate::serde::raw)) is written as its bytes, in + /// the transport format only. The bytes are first checked to be one + /// node that fits the depth left. Any other newtype is written as the + /// value inside it. fn serialize_newtype_struct( self, - _name: &'static str, + name: &'static str, value: &T, ) -> Result<(), Error> { - value.serialize(self) + if name != raw::TOKEN { + return value.serialize(self); + } + if P::PROFILE != Profile::Transport { + return Err(Error::new( + "a raw frame node is not written in a storage blob", + )); + } + self.check_depth()?; + let start = self.out.len(); + raw::handing_over(|| value.serialize(Raw { out: self.out }))?; + let node = self.out.risky_ref().get(start..).unwrap_or_default(); + match Frame::parse_nested(node, self.depth) { + Ok((_, [])) => Ok(()), + _ => Err(Error::new( + "a raw frame node is not one well-formed node within the depth limit", + )), + } } fn serialize_newtype_variant( self, @@ -935,6 +957,141 @@ impl ser::Serializer for TextKeyWriter<'_> { } } +/// Takes a raw node's bytes onto the end of the frame, and refuses any +/// other value: a raw node holds bytes and nothing else. +struct Raw<'o> { + out: &'o mut Buffer, +} + +/// The refusal of anything but bytes in a raw node. +fn not_raw() -> Error { + Error::new("a raw frame node holds its bytes and nothing else") +} + +impl ser::Serializer for Raw<'_> { + type Ok = (); + type Error = Error; + type SerializeSeq = ser::Impossible<(), Error>; + type SerializeTuple = ser::Impossible<(), Error>; + type SerializeTupleStruct = ser::Impossible<(), Error>; + type SerializeTupleVariant = ser::Impossible<(), Error>; + type SerializeMap = ser::Impossible<(), Error>; + type SerializeStruct = ser::Impossible<(), Error>; + type SerializeStructVariant = ser::Impossible<(), Error>; + + fn serialize_bytes(self, v: &[u8]) -> Result<(), Error> { + self.out.extend_from_slice(v); + Ok(()) + } + fn serialize_bool(self, _: bool) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i8(self, _: i8) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i16(self, _: i16) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i32(self, _: i32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_i64(self, _: i64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u8(self, _: u8) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u16(self, _: u16) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u32(self, _: u32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_u64(self, _: u64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_f32(self, _: f32) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_f64(self, _: f64) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_char(self, _: char) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_str(self, _: &str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_none(self) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_some(self, _: &T) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit(self) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit_struct(self, _: &'static str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_newtype_struct( + self, + _: &'static str, + _: &T, + ) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: &T, + ) -> Result<(), Error> { + Err(not_raw()) + } + fn serialize_seq(self, _: Option) -> Result { + Err(not_raw()) + } + fn serialize_tuple(self, _: usize) -> Result { + Err(not_raw()) + } + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } + fn serialize_map(self, _: Option) -> Result { + Err(not_raw()) + } + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Err(not_raw()) + } + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(not_raw()) + } +} + #[cfg(test)] mod tests { use super::*; From cb63d84e24e6a78cfdf5fceb6f474f72550042d0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 13:46:57 +1100 Subject: [PATCH 08/10] feat(stack-encrypt): an encrypted record as typed values, through serde A language binding now asks record::encrypt for an EncryptedRecord, or a Vec of them, and gives either back to record::decrypt. The owned API takes them too. Each field has its outputs under Stack Encrypt's keys. The output c is one sealed value. A sealed field whose value is a list or a map is refused before any key is requested. The record moves to the binding's language as a frame through the serde adapter: EncryptedRecord::to_frame and from_frame. It replaces the hand-written stored-frame functions. Those are removed. The stored tree works as before. record::encrypt now takes the form as a type parameter, so a call that passes its result only to decrypt names the form. The tests that did so now name StackCipherText. --- .../encryption/tests/json_tree_data_plan.rs | 30 +- packages/stack-encrypt/CHANGELOG.md | 67 +- .../docs/language-integration.md | 45 +- packages/stack-encrypt/src/dynamic/mod.rs | 4 +- packages/stack-encrypt/src/dynamic/planned.rs | 149 ++- packages/stack-encrypt/src/dynamic/record.rs | 508 ++++++-- .../src/dynamic/record/encrypted.rs | 706 +++++++++++ .../src/dynamic/record/encrypted/tests/mod.rs | 929 ++++++++++++++ .../src/dynamic/record/stored.rs | 562 --------- .../src/dynamic/record/stored/tests/mod.rs | 1093 ----------------- packages/stack-encrypt/src/dynamic/term.rs | 5 + packages/stack-encrypt/src/refusal.rs | 62 +- packages/stack-encrypt/tests/audit.rs | 14 +- .../tests/binding_conformance.rs | 2 +- .../tests/context_conformance.rs | 2 +- ...nce.rs => encrypted_record_conformance.rs} | 164 ++- packages/stack-encrypt/tests/heap_hygiene.rs | 30 +- .../tests/lifecycle_conformance.rs | 8 +- packages/stack-encrypt/tests/plan_grammar.rs | 13 +- .../stack-encrypt/tests/value_conformance.rs | 10 +- packages/stack-encrypt/tests/value_kinds.rs | 2 +- 21 files changed, 2397 insertions(+), 2008 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/record/encrypted.rs create mode 100644 packages/stack-encrypt/src/dynamic/record/encrypted/tests/mod.rs delete mode 100644 packages/stack-encrypt/src/dynamic/record/stored.rs delete mode 100644 packages/stack-encrypt/src/dynamic/record/stored/tests/mod.rs rename packages/stack-encrypt/tests/{stored_frame_conformance.rs => encrypted_record_conformance.rs} (72%) 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 ea52886ec..1ea9d2dff 100644 --- a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs +++ b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs @@ -175,10 +175,15 @@ async fn a_batch_of_documents_round_trips_in_one_request() { .iter() .map(|text| BTreeMap::from([("profile", text.as_str())])) .collect(); - let sealed = record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) - .unwrap() - .await - .unwrap(); + let sealed = record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets, + ) + .unwrap() + .await + .unwrap(); assert_eq!( calls.lock().unwrap().generate.len(), 1, @@ -331,7 +336,7 @@ async fn a_document_does_not_open_under_another_column() { let (cipher, calls) = common::cipher().await; let keyset = cipher.default_keyset(); let text = documents()[0].to_string(); - let sealed = record::encrypt_with( + let sealed = record::encrypt_with::( &keyset, frame(BTreeMap::from([("profile", text.as_str())])), &plan(), @@ -383,7 +388,12 @@ async fn text_that_is_not_a_document_is_refused_before_any_key() { let text = case["text"].as_str().unwrap(); let code = case["reason"].as_str().unwrap(); let source = BTreeMap::from([("profile", text)]); - let error = match record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets) { + let error = match record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets, + ) { Err(error) => error, Ok(_) => panic!("{text:?} was accepted"), }; @@ -399,7 +409,13 @@ async fn text_that_is_not_a_document_is_refused_before_any_key() { } // A value of another kind is not a document either. let source = BTreeMap::from([("profile", 7u32)]); - assert!(record::encrypt_with(&keyset, frame(&source), &plan, &EqlTargets).is_err()); + assert!(record::encrypt_with::( + &keyset, + frame(&source), + &plan, + &EqlTargets + ) + .is_err()); assert!( calls.lock().unwrap().generate.is_empty(), "no key was requested" diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 31967e187..3fa579609 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,36 +9,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **A stored record as a frame, and back** (#2029). Every binding moves the - stored record to its language and back with these functions, so no - binding walks the tree or renames a key itself. - - `dynamic::record::stored_frame(&stored, &plan)` writes a stored record, - or a batch, as a frame in a buffer wiped when it drops. Each field is an - object of its outputs, under the record's own keys (`c`, `eq`, `match`, - `ore`, `ope`, `passthrough`, `eql`). A sealed value is its bytes - (`SealedValue::to_bytes`). A term or an EQL value is its bytes, and a - passthrough field's value is the value. A list or a map under `c` is an - array or an object. The marker of an empty list or map is the array - `["empty_seq", ]` or `["empty_map", ]`. - - `dynamic::record::read_stored(frame, &plan)` reads the frame back as the - `StackCipherText` to decrypt. It takes the plan, because only the plan - says which output is sealed and which is in the clear. A - `"null": "sql"` field that is left out, or given as null, has no entry. - - `dynamic::record::stored_field_frame` and `read_stored_field` do the - same for one field's node, the map of its outputs. +- **An encrypted record as typed values** (#2029). A language binding asks + for the encrypted record as typed values, and moves it to its language + and back as a frame. No binding walks a tree or renames a key itself. + - `dynamic::record::EncryptedRecord` has one `EncryptedField` for each + field, in the plan's order. A field with `"null": "sql"` and no value + has no entry. A field has its outputs under Stack Encrypt's keys: + - `c`, a `Ciphertext` + - `eq`, `match`, `ore`, `ope`, and `ore_block`, each a `TermBytes` + - `passthrough`, a `PassthroughFrame` + - `target`, the bytes that a target type returned + - `record::encrypt` and `encrypt_with` return the form the caller names: + `StackCipherText`, `EncryptedRecord`, or `Vec` for a + batch (`EncryptedForm`). `record::decrypt` and `decrypt_with` take any + of them (`StoredForm`). So does the owned API, through `Planned`. + - A typed record has one sealed value under `c`. A sealed field whose + value is a list or a map is refused before any key is requested. An + empty list or map is refused too. The new reason is `not_one_value`. + The stored tree still takes such a value. + - Three pairs of functions move a record, a batch, or one field as a + frame: + - `EncryptedRecord::to_frame` and `EncryptedRecord::from_frame` + - `EncryptedRecord::batch_to_frame` and `batch_from_frame` + - `EncryptedField::to_frame` and `EncryptedField::from_frame` + + They use `recipher_frame::serde`. `c` is the sealed + value's stable bytes. A term and a target value are their bytes. A + passthrough is its frame node, as it is. - The frame is a transport form, not a storage format. Store the bytes inside it. - - A refusal of the caller's input is `Error::Record`. It names the - field, the output, and the row of a batch, where there is one. Two new - reasons say what was wrong. `undeclared_output` is for an output that - the field does not declare. `not_sealed` is for a node under `c` that is - not in the frame form. A term or an EQL value that is not bytes is - `not_passthrough`. + - Reading a frame checks its structure only. A refusal names the field, + the output, and the row of a batch, where there is one. Three new + reasons say what was wrong: + - `not_an_output`: a key that is not an output + - `not_sealed`: anything under `c` but one sealed value's bytes + - `batch_shape`: one record where a batch is asked for, or a batch + where one record is - `Error::Record` has a new field, `output`: the key of the output at fault, such as `c` or `eq`. `Error::output` returns it, and the payload - has it as `output`. The new functions set it. `decrypt` and - `check_record` leave it `None`, so their payloads do not change. Code - that builds an `Error::Record` must set the new field. + has it as `output`. A typed record sets it. `decrypt` and + `check_record` leave it `None` for the stored tree, so their payloads + do not change. Code that builds an `Error::Record` must set the new + field. + - A call that does not name its form, and passes the result only to + `decrypt`, now needs one: `record::encrypt::(..)`, + or a type on the variable. - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index f0ed6a7c4..d2eb2d578 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -135,13 +135,16 @@ and never needs the field's type. Anything else of another type is refused with the reason `field_type`, and JavaScript's `undefined` with the reason `undefined`. A field that declares no type takes its value as it is. -A binding gives the stored record to its language as a frame. -[`crate::dynamic::record::stored_frame`]`(&stored, &plan)` writes the -frame, in a buffer that is wiped when it is dropped. The frame keeps the -record's keys as they are. Each field is an object of its outputs: - -- A sealed value under `c` is its bytes. -- An index term is its bytes. +A binding asks for the record as a +[`crate::dynamic::record::EncryptedRecord`]: `Planned::new(&plan, +row).encrypt_into(&keyset)` and [`crate::dynamic::record::encrypt`] return +the form the caller names, and a batch is a `Vec`. +[`crate::dynamic::record::EncryptedRecord::to_frame`] writes the record +as a frame, in a buffer that is wiped when it is dropped. The frame keeps +Stack Encrypt's keys. Each field is an object of its outputs: + +- `c` is the sealed value's bytes. +- An index term, and a `target` value, is its bytes. - A passthrough field's value is the value itself. - A field with `"null": "sql"` and no value has no entry. @@ -149,8 +152,10 @@ The binding builds its language's value from this frame, as it does for a decrypted value. So in JavaScript the record `{ email, id }` is `{ email: { c: Uint8Array, eq: Uint8Array }, id: { passthrough: 7n } }`. The binding walks no tree and renames no key. -[`crate::dynamic::record::stored_field_frame`] does the same for one -field's node. + +A typed record has one sealed value under `c`. A sealed field whose +value is a list or a map is refused before any key is requested, with the +reason `not_one_value`. The frame is how the record crosses to the language, not how it is stored. Store the bytes inside the frame. @@ -190,20 +195,18 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. -A binding reads the stored record back from its language's value as a -frame. [`crate::dynamic::record::read_stored`]`(frame, &plan)` returns the -[`crate::StackCipherText`] to decrypt. The function takes the plan. A -sealed value and an index term are both bytes in the frame, and only the -plan says which output is sealed. +A binding reads the record back from its language's value as a frame. +[`crate::dynamic::record::EncryptedRecord::from_frame`] returns the record +to decrypt, and `decrypt` takes it as it takes the stored tree. Reading +the frame checks its structure only: `decrypt` checks that the record fits +the plan. -- For a column that contains SQL `NULL`, leave the field out or send a - null. Either works only for a field with `"null": "sql"`. +- For a column that contains SQL `NULL`, leave the field out. That works + only for a field with `"null": "sql"`. - The binding does not have to send the index terms. Decrypt reads only - `c`, `passthrough`, and `eql`. -- A field or output that the plan does not declare is refused. The error - names the field, the output, and the row of a batch. - -[`crate::dynamic::record::read_stored_field`] reads one field's node. + `c`, `passthrough`, and `target`. +- A key that is not an output is refused with the reason `not_an_output`. + The error names the field, and the row of a batch. ### One value as one ciphertext diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 7af3b3f54..f42ebaaec 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -45,8 +45,8 @@ //! language is the same bytes. The one step that stays dynamic is //! dispatching a value whose type is known only at run time to the typed //! term operation, which [`IndexSpec`](crate::target::IndexSpec)'s `Index` impls do. -//! * [`record::stored_frame`] and [`record::read_stored`] — a stored record -//! as a frame, for a binding to move to its language, and back. +//! * [`record::EncryptedRecord`] — an encrypted record as typed outputs. A +//! binding moves it to its language and back as a frame. //! * [`read_json`] and [`json_frame`] — a `json` field's document, from //! the JSON text a binding hands over and back to it. //! * [`TargetResolver`] — the EQL types a build holds, installed by the host diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 8f38d5a04..6e694c8bb 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -81,9 +81,10 @@ use std::sync::Arc; use zeroize::Zeroize; use super::query::{field_operators, find, query_term, QueryTerm}; +use super::record::encrypted::form::{Shape, Shaped}; use super::record::{ - self, name_target, open_record, shape_record, write_record, Absent, Context, FieldPlan, Plan, - Rows, Verb, + self, in_form, name_target, open_record, shape_batch, shape_row, write_record, Absent, Context, + EncryptedForm, EncryptedRecord, FieldPlan, Plan, Rows, StoredForm, Verb, }; use super::target::{NoTargets, TargetResolver}; use super::{Error, Op, Reason, TermBytes}; @@ -96,9 +97,7 @@ use crate::target::{ Indexes, OptionalContext, Owned, Pending, }; use crate::target::{Step, YIELD_EVERY}; -use crate::{ - CipherRef, CipherText, Encrypt, KeysetCipher, Label, NonEmpty, PlanError, StackCipherText, -}; +use crate::{CipherRef, Encrypt, KeysetCipher, Label, NonEmpty, PlanError, StackCipherText}; use vitaminc_aead::frame::{Frame, OwnedFrame}; /// The resolver of a build without EQL types, for [`Plan::field`]. @@ -345,83 +344,96 @@ impl Plan { } } -/// A record under a plan encrypts to the stored row: every field under its -/// own context, the caller's scope and then its bindings after the plan's -/// own. The value is an [`OwnedFrame`], or a [`Frame`] borrowed from bytes -/// the caller keeps. The borrowed form reads the frame in place; the owned -/// form consumes it. -impl<'p, V, R> EncryptTarget> for StackCipherText -where - V: Encrypt + 'p, - for<'x> &'x V: Encrypt, - Planned<'p, Plan, V, R>: Zeroize, - R: TargetResolver + 'p, -{ - type ContextInput = OptionalContext; - fn encryption<'s, K: 'static>( - ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput> - where - Planned<'p, Plan, V, R>: 's, - { - Encryption::from_build( - contexts::caller_leaf(), - move |source: &Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { - encrypt_record( - cipher, - source.plan, - &source.value, - &source.resolver, - context, +/// A record under a plan encrypts to a stored record, in the form that the +/// caller names. The form is the stored tree ([`StackCipherText`]), one +/// typed record ([`EncryptedRecord`]), or a batch of them +/// (`Vec`). Every field is sealed under its own context, +/// then the caller's scope, and then its bindings after the plan's own. +/// +/// The value is an [`OwnedFrame`], or a +/// [`Frame`] borrowed from bytes the caller keeps. The borrowed form reads +/// the frame in place; the owned form consumes it. +macro_rules! encrypts_to { + ($form:ty) => { + impl<'p, V, R> EncryptTarget> for $form + where + V: Encrypt + 'p, + for<'x> &'x V: Encrypt, + Planned<'p, Plan, V, R>: Zeroize, + R: TargetResolver + 'p, + { + type ContextInput = OptionalContext; + fn encryption<'s, K: 'static>( + ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput> + where + Planned<'p, Plan, V, R>: 's, + { + Encryption::from_build( + contexts::caller_leaf(), + move |source: &Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { + encrypt_record( + cipher, + source.plan, + &source.value, + &source.resolver, + context, + ) + }, ) - }, - ) - } - fn owned_encryption<'s, K: 'static>( - ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput, Owned> - where - Planned<'p, Plan, V, R>: 's, - { - Encryption::from_owned_build( - contexts::caller_leaf(), - move |source: Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { - let Planned { - plan, - value, - resolver, - } = source; - encrypt_record(cipher, plan, value, &resolver, context) - }, - ) - } + } + fn owned_encryption<'s, K: 'static>( + ) -> Encryption<'s, Planned<'p, Plan, V, R>, Self, K, Self::ContextInput, Owned> + where + Planned<'p, Plan, V, R>: 's, + { + Encryption::from_owned_build( + contexts::caller_leaf(), + move |source: Planned<'p, Plan, V, R>, cipher, context: Self::ContextInput| { + let Planned { + plan, + value, + resolver, + } = source; + encrypt_record(cipher, plan, value, &resolver, context) + }, + ) + } + } + }; } -/// The record lowered under the plan extended by the caller's context, or -/// the refusal. -fn encrypt_record<'a, K: 'static>( +encrypts_to!(StackCipherText); +encrypts_to!(EncryptedRecord); +encrypts_to!(Vec); + +/// The record lowered under the plan extended by the caller's context, in +/// the form `T`, or the refusal. +fn encrypt_record<'a, K: 'static, T: EncryptedForm>( cipher: &'a KeysetCipher<'_, K>, plan: &Plan, value: impl Encrypt, resolver: &(impl TargetResolver + ?Sized), context: OptionalContext, -) -> Pending<'a, StackCipherText, K> { +) -> Pending<'a, T, K> { let plan = match plan.under_caller(context.into_inner()) { Ok(plan) => plan, Err(error) => return Pending::failed(cipher, wrap(error)), }; - match Planned::with_resolver(&*plan, value, resolver).run_encrypt(cipher) { - Ok(pending) => pending, + match Planned::with_resolver(&*plan, value, resolver).run_encrypt(cipher, T::SHAPE) { + Ok(pending) => in_form(pending), Err(error) => Pending::failed(cipher, wrap(error)), } } -/// A stored row under a plan decrypts to its values, under the caller's -/// scope and bindings. A row from another keyset than the one the call +/// A stored record under a plan, in any of its forms ([`StoredForm`]), +/// decrypts to its values, under the caller's scope and bindings. A row from another keyset than the one the call /// names is refused before any key is retrieved. The opening is a closure /// the cipher runs later, which owns the plan, the row and the resolver, /// so the resolver is `Send + Sync + 'static` here where the encrypt side /// borrows it. -impl<'p, R> DecryptSource for Planned<'p, Plan, StackCipherText, R> +impl<'p, S, R> DecryptSource for Planned<'p, Plan, S, R> where + S: StoredForm, R: TargetResolver + Send + Sync + 'static, { type ContextInput = OptionalContext; @@ -470,13 +482,15 @@ where pub(super) fn run_encrypt<'a, K: 'static>( self, cipher: &'a KeysetCipher<'_, K>, - ) -> Result, Error> { + form: Shape, + ) -> Result, Error> { let Planned { plan, value, resolver, } = self; let rows = record::source_rows(value, plan)?; + record::check_form(&rows, plan, form)?; let extend = plan.declared_context(); let shape = plan.shape(); // Every target field of every row, in row-major order, run by the @@ -515,7 +529,7 @@ where cipher .run(description, values, extend) .zip(eql) - .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) + .try_map(move |(values, eql)| shape_row(form, values, eql, &shape, &absent)) } Rows::Batch(rows) => { let rows = rows @@ -566,10 +580,10 @@ where .zip(per_row) .map(|(values, (absent, count))| { let own: Vec> = eql.by_ref().take(count).collect(); - shape_record(values, own, &shape, &absent) + shape_row(form, values, own, &shape, &absent) }) .collect::, _>>() - .map(CipherText::Sequence) + .and_then(|rows| shape_batch(form, rows)) }) }; built_in_chunks(cipher, groups, row, finish) @@ -578,8 +592,9 @@ where } } -impl<'p, 'r, R> Planned<'p, Plan, StackCipherText, &'r R> +impl<'p, 'r, S, R> Planned<'p, Plan, S, &'r R> where + S: StoredForm, R: TargetResolver + ?Sized, { /// Lower the plan and open the stored row, or batch of rows, through @@ -613,7 +628,7 @@ where resolver, } = self; let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); - let rows = record::record_rows(value, plan)?; + let rows = record::stored_rows(value.into_stored(), plan)?; let extend = plan.declared_context(); let shape = plan.shape(); let cipher = cipher_ref.cipher(); diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 9cecfa88f..56dfcb5c8 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -144,93 +144,50 @@ //! reported as a successful decrypt. The encrypt-side refusal is what makes //! that a round-trip invariant rather than data loss. //! -//! # The stored record as a frame +//! # An encrypted record as a type //! -//! [`encrypt`] returns a stored record, a -//! [`StackCipherText`], and [`decrypt`] takes one. A binding -//! moves the stored record to its language and back as a frame. A frame is -//! the encoding that a value crosses in. [`stored_frame`] writes the frame, -//! and [`read_stored`] reads it back. [`stored_field_frame`] and -//! [`read_stored_field`] do the same for one field's node. +//! [`encrypt`] returns the record in the form the caller names, and +//! [`decrypt`] takes any of them back: //! -//! The binding builds its language's value from the frame, as it does for -//! any value. So the binding walks no tree and renames no key. +//! - [`StackCipherText`], the stored tree. +//! - [`EncryptedRecord`], one record of typed outputs. +//! - `Vec`, a batch of them. //! -//! ## The frame form +//! An [`EncryptedRecord`] has one [`EncryptedField`] for each field, in the +//! plan's order. A field has its outputs under Stack Encrypt's keys: `c`, +//! `eq`, `match`, `ore`, `ope`, `ore_block`, `passthrough`, and `target`. A +//! field with `"null": "sql"` and no value has no entry. //! -//! | In the stored record | In the frame | -//! |---|---| -//! | the record | an object with one entry for each field, in the record's order | -//! | a batch | an array of records | -//! | a field | an object with one entry for each output, under the stored record's key: `c`, an index key such as `eq` or `ore`, `passthrough`, or `eql` | -//! | a term, a passthrough field's value, or an EQL value | the value in the node, as it is: bytes for a term or an EQL value, and the field's value for `passthrough` | -//! | a sealed value under `c` | its bytes ([`SealedValue::to_bytes`](crate::SealedValue::to_bytes)) | -//! | a list of sealed nodes under `c` | an array of them | -//! | a map of sealed nodes under `c` | an object of them, in the stored order | -//! | the marker of an empty list under `c` | the array `["empty_seq", ]` | -//! | the marker of an empty map under `c` | the array `["empty_map", ]` | +//! A typed record has one sealed value under `c`. A sealed field whose +//! value is a list or a map, an empty one included, is refused before any +//! key is requested ([`Reason::NotOneValue`]). The stored tree takes such a +//! value as it is. //! -//! Take a plan that seals and indexes `email`, and passes `id` through. A -//! row sealed from `{ "email": "ada@example.com", "id": "u-7" }` has this -//! frame: +//! A language binding moves a typed record to its language and back as a +//! frame, with [`EncryptedRecord::to_frame`] and +//! [`EncryptedRecord::from_frame`]. It builds its language's value from the +//! frame, as it does for any value. So it walks no tree and renames no +//! key. Take a plan that seals and indexes `email`, and passes `id` +//! through. A row sealed from `{ "email": "ada@example.com", "id": "u-7" }` +//! has this frame: //! //! ```text //! { "email": { "c": , "eq": }, "id": { "passthrough": "u-7" } } //! ``` //! -//! An array under `c` that starts with the text `empty_seq` or `empty_map` -//! is a marker. A sealed node is never text, so the form has only one -//! reading. +//! - `c` is the sealed value's stable bytes +//! ([`Ciphertext::to_bytes`](crate::Ciphertext::to_bytes)). +//! - A term, and a `target` value, is its bytes. +//! - `passthrough` is the field's value, as it is. //! //! The frame is a transport form, not a storage format. A binding stores -//! the bytes inside the frame. A sealed value's bytes and a term's bytes -//! are stable. The frame around them can change between releases, as any -//! frame can. +//! the bytes inside it. The sealed value's bytes and a term's bytes are +//! stable. The frame around them can change between releases, as any frame +//! can. //! -//! ## Why the plan is an argument -//! -//! A sealed value and a term are both bytes in the frame. Only the plan says -//! which output of a field is sealed. The sealed output is `c`. Every other -//! output is in the clear. -//! -//! So [`read_stored`] takes the plan, and never decides what a node is from -//! its bytes. [`stored_frame`] takes the plan too, and refuses a record that -//! the plan could not read back. -//! -//! ## A field with no value -//! -//! A field with `"null": "sql"` has no entry in a stored record when it has -//! no value. So it has no entry in the frame. [`read_stored`] reads such a -//! field as a missing entry when the frame leaves it out, or gives it as -//! null. [`decrypt`] opens a missing entry as a null. -//! -//! So for a column that contains SQL `NULL`, a binding leaves the field out -//! or sends a null. [`read_stored`] refuses a null for any other field. -//! -//! ## Refusals -//! -//! A refusal of the caller's input is [`Error::Record`]. It names what is -//! at fault, where there is one: -//! -//! - the field ([`Error::field`]), -//! - the output, such as `c` or `eq` ([`Error::output`]), and -//! - the row of a batch ([`Error::row`]). -//! -//! A refusal of a whole record or row names no field, such as a record -//! that is not a map. Two errors are not [`Error::Record`]: -//! -//! - [`Error::Plan`], for a field that the plan does not have, given to a -//! function for one field. -//! - [`Error::Internal`], for a defect in this crate, never the caller's -//! input. -//! -//! No refusal contains a value, or the text of a key inside a sealed node. -//! -//! [`read_stored`] refuses a frame that is not in the frame form. It also -//! refuses a field or output that the plan does not declare, because it -//! cannot tell what that node is. [`decrypt`] makes every -//! other check, once. For example, `decrypt` refuses a sealed field with no -//! `c`, and a passthrough value of the wrong type. +//! Reading a frame checks its structure only. [`decrypt`] checks whether the +//! record fits a plan. It ignores outputs that the plan does not open, as it +//! does for the stored tree. use std::collections::BTreeSet; use std::fmt; @@ -259,8 +216,10 @@ use crate::{ }; use vitaminc_aead::IntoContext as _; -mod stored; -pub use stored::{read_stored, read_stored_field, stored_field_frame, stored_frame}; +pub(super) mod encrypted; +use encrypted::form::{Shape, Shaped, Stored}; +use encrypted::in_row; +pub use encrypted::{EncryptedField, EncryptedForm, EncryptedRecord, StoredForm}; /// The map key a target field's EQL value rides under in a stored record: /// wire format, like the output keys (see the @@ -1757,15 +1716,22 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// awaited, however many rows and fields there are. Its failure is the /// engine's [`Error`](crate::Error). /// -/// The result is per record a map of `field → { output-key → node }` (see -/// the [module docs](self#the-stored-record-is-wire-format)): `"c"` first, -/// then each term in the order the plan named its indexes. A batch is a -/// sequence of such maps. +/// The caller names the form of the result `T` ([`EncryptedForm`]): +/// +/// - [`StackCipherText`]: for each record, a map from each field to a map +/// of its outputs (see the +/// [module docs](self#the-stored-record-is-wire-format)). `"c"` is first, +/// then each term in the order the plan named its indexes. A batch is a +/// sequence of such maps. +/// - [`EncryptedRecord`]: one record of typed outputs, for a source that is +/// one record. +/// - `Vec`: a batch of them, for a source that is a batch. /// /// # Examples /// /// ``` -/// use stack_encrypt::dynamic::{record, frame::OwnedFrame}; +/// use stack_encrypt::dynamic::record::{self, EncryptedRecord}; +/// use stack_encrypt::dynamic::frame::OwnedFrame; /// use stack_encrypt::{AsProtectedRef, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { @@ -1787,7 +1753,12 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// // map writes it; a binding's codec writes the same bytes. /// let row = std::collections::BTreeMap::from([("age", 34u32)]); /// let frame = OwnedFrame::of(&row)?; -/// let sealed = record::encrypt(&keyset, &frame, &plan)?.await?; +/// let sealed: EncryptedRecord = record::encrypt(&keyset, &frame, &plan)?.await?; +/// +/// // A language binding builds its value from the record's frame. Here +/// // the frame is read straight back. +/// let stored = sealed.to_frame()?; +/// let sealed = EncryptedRecord::from_frame(stored.frame())?; /// /// // Only the ciphertext comes back, as the record's frame; the term is /// // one-way. @@ -1806,14 +1777,19 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { /// declares its kind and the kind check comes first. Decided here, before /// the pending exists. A failure of the pending itself is the engine's. /// +/// For a typed form, also [`Error::Source`] with [`Reason::BatchShape`] for +/// a batch given for one [`EncryptedRecord`], or one record for a batch, +/// and with [`Reason::NotOneValue`] for a sealed field whose value is a list +/// or a map, naming the field and the row of a batch. +/// /// A plan with a target field needs the resolver that built it: /// [`encrypt_with`]. This runs under [`NoTargets`], so such a plan is /// refused ([`Error::Target`]). -pub fn encrypt<'a, K: 'static>( +pub fn encrypt<'a, T: EncryptedForm, K: 'static>( cipher: &'a KeysetCipher<'_, K>, source: impl Encrypt, plan: &Plan, -) -> Result, Error> { +) -> Result, Error> { encrypt_with(cipher, source, plan, &NoTargets) } @@ -1834,13 +1810,23 @@ pub fn encrypt<'a, K: 'static>( /// /// As [`encrypt`], plus [`Error::Target`] for a target value of another /// kind than the type takes, or a name the resolver refuses. -pub fn encrypt_with<'a, K: 'static>( +pub fn encrypt_with<'a, T: EncryptedForm, K: 'static>( cipher: &'a KeysetCipher<'_, K>, source: impl Encrypt, plan: &Plan, resolver: &(impl TargetResolver + ?Sized), -) -> Result, Error> { - Planned::with_resolver(plan, source, resolver).run_encrypt(cipher) +) -> Result, Error> { + Planned::with_resolver(plan, source, resolver) + .run_encrypt(cipher, T::SHAPE) + .map(in_form) +} + +/// A record path's result, as the form `T` the caller asked for. The path +/// shapes its result as `T` asked, so another form is a defect here. +pub(super) fn in_form<'a, T: EncryptedForm, K: 'static>( + pending: Pending<'a, Shaped, K>, +) -> Pending<'a, T, K> { + pending.try_map(|shaped| T::from_shaped(shaped).ok_or(crate::Error::ResponseShape)) } /// Derive the EQL query value of one target field for one plaintext: the @@ -1940,6 +1926,11 @@ pub(super) fn name_target(error: TargetError, field: &str) -> TargetError { /// Decrypt a record — or a batch — produced by [`encrypt`] under the same /// plan. /// +/// `record` is in any of the forms [`encrypt`] returns ([`StoredForm`]): +/// the stored tree, one [`EncryptedRecord`], or a batch of them. A typed +/// record is checked against the plan as the stored tree is. A refusal of a +/// row of a typed batch names the row. +/// /// Only the `"c"` and `"passthrough"` outputs participate: terms are /// one-way. The stored tree is checked and read here, with no cipher: that /// is [`check_record`], and it is where [`Error::Record`] comes from. What @@ -1988,7 +1979,7 @@ pub(super) fn name_target(error: TargetError, field: &str) -> TargetError { /// refused ([`Error::Target`]). pub fn decrypt<'a, K: 'static>( cipher_ref: impl Into>, - record: StackCipherText, + record: impl StoredForm, plan: &Plan, expected: Option