From 97cd2b761fe29f89f716c683c5b7db42fdbff207 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:31:10 +1100 Subject: [PATCH 01/23] refactor(stack-encrypt): rename split_source to into_source_records The function returns the records of a source, one per row. The old name said how it worked and not what it returned. --- packages/stack-encrypt/src/dynamic/found.rs | 4 +- packages/stack-encrypt/src/dynamic/record.rs | 8 ++-- packages/stack-encrypt/src/dynamic/source.rs | 39 +++++++++++--------- 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs index 61b2dc976..a63d928b2 100644 --- a/packages/stack-encrypt/src/dynamic/found.rs +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -312,7 +312,7 @@ mod tests { } /// The same rule applies through a record source. A row of a batch has - /// the logical type date and a null value. `split_source` reports the + /// the logical type date and a null value. `into_source_records` reports the /// row as a null, and not as `Unknown`. #[test] fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { @@ -325,7 +325,7 @@ mod tests { } } let Ok(super::super::source::SplitSource::Batch(rows)) = - super::super::source::split_source(&Rows) + super::super::source::into_source_records(&Rows) else { panic!("a batch"); }; diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 30acdc750..dcc5ad5ef 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -150,7 +150,7 @@ use std::fmt; use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; -use super::source::{split_source, SourceRecord, SplitRefusal, SplitSource}; +use super::source::{into_source_records, SourceRecord, SplitRefusal, SplitSource}; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; @@ -2170,7 +2170,7 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { /// field is present exactly once in every row and no row carries a field /// the plan does not name, and each value fits its field ([`check_field`]). /// -/// The source is walked once ([`split_source`]): each field's value is written +/// The source is walked once ([`into_source_records`]): each field's value is written /// into an [`OwnedFrame`] of its own as the walk reaches it, and nothing else /// is copied. A value the frame cannot carry, or that holds a repeated key, /// is refused naming its field. @@ -2184,7 +2184,7 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result found: Some(found), }), }; - match split_source(source).map_err(split_refusal)? { + match into_source_records(source).map_err(split_refusal)? { SplitSource::One(one) => Ok(Rows::One(row(None, one)?)), SplitSource::Batch(rows) => Ok(Rows::Batch( rows.into_iter() @@ -2195,7 +2195,7 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result } } -/// Converts the error from [`split_source`] into the [`Error`] that the +/// Converts the error from [`into_source_records`] into the [`Error`] that the /// caller gets. The result keeps the field and the row that the split /// names. /// diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index f0944ec74..e8beba48d 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -6,7 +6,7 @@ //! encrypts each field on its own, with that field's settings from the //! plan, so the engine first needs each field's value separately. //! -//! [`split_source`] reads the value once, from start to end. As the split +//! [`into_source_records`] reads the value once, from start to end. As the split //! reaches each field, it writes that field's value into an //! [`OwnedFrame`] of its own. The split copies nothing else. //! @@ -24,7 +24,7 @@ //! `record::source_rows`, refuses a value that is not a record, a missing //! field, an extra field, and a value of the wrong type. //! -//! [`split_source`] returns an error in two cases: +//! [`into_source_records`] returns an error in two cases: //! //! * The split cannot write a field's value into a frame. Examples are a //! date out of range, and a map that repeats a key. @@ -54,7 +54,7 @@ use crate::refusal::Found; /// record. pub(super) type SourceRecord = Result, Found>; -/// A source split by [`split_source`]: one record, or a batch of them. +/// A source split by [`into_source_records`]: one record, or a batch of them. pub(super) enum SplitSource { /// The source was a map, or a value that is not a record. One(SourceRecord), @@ -62,7 +62,7 @@ pub(super) enum SplitSource { Batch(Vec), } -/// Why [`split_source`] failed, and where. +/// Why [`into_source_records`] failed, and where. /// /// - `error` is the error from [`FrameWriter`], or the error that the /// source returned. `FrameWriter` writes a value into a frame. @@ -81,7 +81,7 @@ pub(super) struct SplitRefusal { /// Split a source into its records, writing each field's value into a /// frame of its own. The [module documentation](self) says what counts as /// a record and when the split fails. -pub(super) fn split_source(source: P) -> Result { +pub(super) fn into_source_records(source: P) -> Result { let place = Place::default(); source.visit(TopSink(&place)).map_err(|error| SplitRefusal { row: place.row.get(), @@ -572,7 +572,7 @@ mod tests { ("a", obj(vec![("k", s("v"))])), ("b", Tree::Passthrough(Box::new(s("p")))), ]); - let Ok(SplitSource::One(record)) = split_source(&source) else { + let Ok(SplitSource::One(record)) = into_source_records(&source) else { panic!("one record"); }; assert_eq!( @@ -602,7 +602,7 @@ mod tests { Tree::Undefined, Tree::UInt32(7), ]); - let Ok(SplitSource::Batch(records)) = split_source(&source) else { + let Ok(SplitSource::Batch(records)) = into_source_records(&source) else { panic!("a batch"); }; let records: Vec<_> = records.iter().map(bytes).collect(); @@ -626,7 +626,7 @@ mod tests { (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), ] { assert!( - matches!(split_source(&top), Ok(SplitSource::One(Err(kind))) if kind == found), + matches!(into_source_records(&top), Ok(SplitSource::One(Err(kind))) if kind == found), "{found:?} at the top is not a record" ); } @@ -636,7 +636,10 @@ mod tests { vitaminc_aead::leaf::write_typed_null(ty, &mut one); let top = Frame::parse(&one).expect("a frame"); assert!( - matches!(split_source(top), Ok(SplitSource::One(Err(Found::Null)))), + matches!( + into_source_records(top), + Ok(SplitSource::One(Err(Found::Null))) + ), "a typed null at the top is a null" ); let mut batch = vec![ARRAY, 2, 0, 0, 0]; @@ -645,7 +648,7 @@ mod tests { let batch = Frame::parse(&batch).expect("a frame"); assert!( matches!( - split_source(batch), + into_source_records(batch), Ok(SplitSource::Batch(records)) if records.len() == 2 && records.iter().all(|r| matches!(r, Err(Found::Null))) ), @@ -657,7 +660,7 @@ mod tests { /// that value. For a batch, the error also names the row. #[test] fn a_refusal_names_the_field_and_row_being_written() { - let refused = |source: &Tree| split_source(source).err().expect("refused"); + let refused = |source: &Tree| into_source_records(source).err().expect("refused"); let bad_date = Tree::Typed(Logical::Date, Box::new(Tree::Int64(i64::MAX))); let one = refused(&obj(vec![ @@ -693,7 +696,7 @@ mod tests { // A batch element that is not a record is read past, not written: // a value inside it that no frame could hold is not refused here. // The caller refuses the element itself, as not a record. - let Ok(SplitSource::Batch(records)) = split_source(Tree::Array(vec![ + let Ok(SplitSource::Batch(records)) = into_source_records(Tree::Array(vec![ obj(vec![("a", Tree::Int32(1))]), Tree::Array(vec![bad_date]), ])) else { @@ -743,7 +746,7 @@ mod tests { } } - let failed = split_source(&Fails { + let failed = into_source_records(&Fails { rows: 3, after_the_record: false, }) @@ -757,7 +760,7 @@ mod tests { assert_eq!(failed.field.as_deref(), Some("a"), "the field being read"); assert_eq!(failed.row, Some(2), "the row being read"); - let after = split_source(&Fails { + let after = into_source_records(&Fails { rows: 2, after_the_record: true, }) @@ -834,7 +837,7 @@ mod tests { (At::AfterAMap, None, Some(0)), (At::BetweenRows, None, None), ] { - let failed = split_source(&at).err().expect("refused"); + let failed = into_source_records(&at).err().expect("refused"); assert!( matches!(failed.error, FrameWriteError::Source(_)), "{at:?}: {:?}", @@ -871,7 +874,9 @@ mod tests { } } for dropped in [0, 1] { - let refused = split_source(&DropsARow { dropped }).err().expect("refused"); + let refused = into_source_records(&DropsARow { dropped }) + .err() + .expect("refused"); assert!( matches!(refused.error, FrameWriteError::Unwritten), "row {dropped}: {:?}", @@ -895,7 +900,7 @@ mod tests { map.end() } } - let refused = split_source(&DropsAnEntry).err().expect("refused"); + let refused = into_source_records(&DropsAnEntry).err().expect("refused"); assert_eq!( refused.field.as_deref(), Some("dropped"), From fa00e1bf6171939b65a25fe676a0ac2e12428355 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:34:07 +1100 Subject: [PATCH 02/23] refactor(stack-encrypt): SplitRefusal becomes SourceRecordError The type is an error, so it is named as one and implements std::error::Error through thiserror, as the crate's other errors do. The function that converted it is now From for the dynamic Error, so the caller uses the ? operator. --- packages/stack-encrypt/src/dynamic/record.rs | 46 ++++++++++---------- packages/stack-encrypt/src/dynamic/source.rs | 20 +++++---- 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index dcc5ad5ef..96aedd31b 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -150,7 +150,7 @@ use std::fmt; use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; -use super::source::{into_source_records, SourceRecord, SplitRefusal, SplitSource}; +use super::source::{into_source_records, SourceRecord, SourceRecordError, SplitSource}; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; @@ -2184,7 +2184,7 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result found: Some(found), }), }; - match into_source_records(source).map_err(split_refusal)? { + match into_source_records(source)? { SplitSource::One(one) => Ok(Rows::One(row(None, one)?)), SplitSource::Batch(rows) => Ok(Rows::Batch( rows.into_iter() @@ -2195,7 +2195,7 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result } } -/// Converts the error from [`into_source_records`] into the [`Error`] that the +/// Converts the error from `into_source_records` into the [`Error`] that the /// caller gets. The result keeps the field and the row that the split /// names. /// @@ -2219,21 +2219,23 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result /// - The source started a row and never wrote it. /// - The source kept an error from the frame writer and returned it after /// the field ended. -fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { - let error = match error { - FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, - error => error, - }; - let reason = match (error, field.is_some()) { - (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, - (FrameWriteError::Invalid, true) => Reason::FieldType, - _ => Reason::Unframeable, - }; - Error::Source { - field, - row, - reason, - found: None, +impl From for Error { + fn from(SourceRecordError { row, field, error }: SourceRecordError) -> Self { + let error = match error { + FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, + error => error, + }; + let reason = match (error, field.is_some()) { + (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, + (FrameWriteError::Invalid, true) => Reason::FieldType, + _ => Reason::Unframeable, + }; + Error::Source { + field, + row, + reason, + found: None, + } } } @@ -9138,16 +9140,16 @@ mod tests { /// kept an error from the frame writer and returned it after the /// field ended. #[test] - fn a_split_refusal_names_its_field_and_cause() { + fn a_source_record_error_names_its_field_and_cause() { let refusal = |field: Option<&str>, error| { - split_refusal(SplitRefusal { + Error::from(SourceRecordError { row: None, field: field.map(str::to_owned), error, }) }; let in_row = |row, error| { - split_refusal(SplitRefusal { + Error::from(SourceRecordError { row: Some(row), field: Some("age".to_owned()), error, @@ -9182,7 +9184,7 @@ mod tests { // An error for a row that the source left unwritten names no // field. The error is still about the caller's input. The error // is not a bug in this module. - let unwritten = split_refusal(SplitRefusal { + let unwritten = Error::from(SourceRecordError { row: Some(1), field: None, error: FrameWriteError::Unwritten, diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index e8beba48d..e694c491a 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -71,23 +71,27 @@ pub(super) enum SplitSource { /// between two rows. /// - `field` is the field whose value the split was writing. `None` when /// the split was not writing the value of a field. -#[derive(Debug)] -pub(super) struct SplitRefusal { +#[derive(Debug, thiserror::Error)] +#[error("the source could not be read into records")] +pub(super) struct SourceRecordError { pub(super) row: Option, pub(super) field: Option, + #[source] pub(super) error: FrameWriteError, } /// Split a source into its records, writing each field's value into a /// frame of its own. The [module documentation](self) says what counts as /// a record and when the split fails. -pub(super) fn into_source_records(source: P) -> Result { +pub(super) fn into_source_records(source: P) -> Result { let place = Place::default(); - source.visit(TopSink(&place)).map_err(|error| SplitRefusal { - row: place.row.get(), - field: place.field.take(), - error, - }) + source + .visit(TopSink(&place)) + .map_err(|error| SourceRecordError { + row: place.row.get(), + field: place.field.take(), + error, + }) } /// The current position of the split in the source. From c2dbb1142561770da9b8db80c3399441072a3988 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:37:43 +1100 Subject: [PATCH 03/23] chore(vscode): turn on stack-encrypt's dynamic feature for rust-analyzer The dynamic module is behind a cargo feature, so rust-analyzer skipped it and showed no types or errors there. --- .vscode/settings.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index eb7dfff52..8643ea1b8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "conventionalCommits.scopes": ["protect", "examples"] + "conventionalCommits.scopes": ["protect", "examples"], + "rust-analyzer.cargo.features": ["stack-encrypt/dynamic"] } From 866c0361a7cf4d984c6760cbe33e64929f33ffa0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:41:12 +1100 Subject: [PATCH 04/23] refactor(stack-encrypt): one OneOrMany type for a record or a batch SplitSource and Rows were the same shape under two names, and source_rows matched on one to build the other. Both are now OneOrMany. --- packages/stack-encrypt/src/dynamic/found.rs | 2 +- packages/stack-encrypt/src/dynamic/mod.rs | 1 + .../stack-encrypt/src/dynamic/one_or_many.rs | 15 ++++++ packages/stack-encrypt/src/dynamic/planned.rs | 15 +++--- packages/stack-encrypt/src/dynamic/record.rs | 41 +++++++------- packages/stack-encrypt/src/dynamic/source.rs | 54 +++++++++---------- 6 files changed, 70 insertions(+), 58 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/one_or_many.rs diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs index a63d928b2..2d4c8a52c 100644 --- a/packages/stack-encrypt/src/dynamic/found.rs +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -324,7 +324,7 @@ mod tests { seq.end() } } - let Ok(super::super::source::SplitSource::Batch(rows)) = + let Ok(super::super::one_or_many::OneOrMany::Many(rows)) = super::super::source::into_source_records(&Rows) else { panic!("a batch"); diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 23771176e..2b38f79eb 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -104,6 +104,7 @@ mod found; mod json; mod json_query; mod kind; +mod one_or_many; pub mod planned; mod query; pub mod record; diff --git a/packages/stack-encrypt/src/dynamic/one_or_many.rs b/packages/stack-encrypt/src/dynamic/one_or_many.rs new file mode 100644 index 000000000..0d728da5e --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/one_or_many.rs @@ -0,0 +1,15 @@ +//! One value or many: the shape of a call that takes one record or a +//! batch of them, and answers in the shape it was asked in. + +/// One `T`, or many of them. +/// +/// A caller encrypts or decrypts one record, or a batch in one call. Each +/// step of the call keeps that shape, so the result is one record for one +/// record and a batch for a batch. +pub(super) enum OneOrMany { + /// One value: the call was given one record. + One(T), + /// A batch: one value for each record, in the order the caller gave + /// them. It can be empty. + Many(Vec), +} diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 8f38d5a04..2e7d1f2c0 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -80,10 +80,11 @@ use std::sync::Arc; use zeroize::Zeroize; +use super::one_or_many::OneOrMany; use super::query::{field_operators, find, query_term, QueryTerm}; use super::record::{ self, name_target, open_record, shape_record, write_record, Absent, Context, FieldPlan, Plan, - Rows, Verb, + Verb, }; use super::target::{NoTargets, TargetResolver}; use super::{Error, Op, Reason, TermBytes}; @@ -508,7 +509,7 @@ where Ok((row.absent, row.values, count)) }; Ok(match rows { - Rows::One(row) => { + OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; let description = compose::(plan, &absent).map_err(|_| Error::Internal)?; let eql = Pending::all(cipher, pendings); @@ -517,7 +518,7 @@ where .zip(eql) .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) } - Rows::Batch(rows) => { + OneOrMany::Many(rows) => { let rows = rows .into_iter() .map(&mut targets) @@ -639,7 +640,7 @@ where Ok((row.absent, row.values, count)) }; Ok(match rows { - Rows::One(row) => { + OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; let eql = Pending::all(cipher, pendings); confine( @@ -648,10 +649,10 @@ where ) .zip(eql) .try_map(move |(values, eql)| { - write_record(Rows::One(open_record(values, eql, &shape, &absent)?)) + write_record(OneOrMany::One(open_record(values, eql, &shape, &absent)?)) }) } - Rows::Batch(rows) => { + OneOrMany::Many(rows) => { let rows = rows .into_iter() .map(&mut targets) @@ -697,7 +698,7 @@ where open_record(values, own, &shape, &absent) }) .collect::, _>>()?; - write_record(Rows::Batch(rows)) + write_record(OneOrMany::Many(rows)) }) }; built_in_chunks(cipher_ref, groups, row, finish) diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 96aedd31b..1402bcfcf 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -150,7 +150,8 @@ use std::fmt; use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; -use super::source::{into_source_records, SourceRecord, SourceRecordError, SplitSource}; +use super::one_or_many::OneOrMany; +use super::source::{into_source_records, SourceRecord, SourceRecordError}; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; @@ -1959,8 +1960,8 @@ pub fn check_source(source: impl Encrypt, plan: &Plan) -> Result<(), Error> { }) }; match &rows { - Rows::One(row) => check(row), - Rows::Batch(rows) => rows.iter().try_for_each(check), + OneOrMany::One(row) => check(row), + OneOrMany::Many(rows) => rows.iter().try_for_each(check), } } @@ -2005,8 +2006,8 @@ pub fn check_record( }) }; match &rows { - Rows::One(row) => check(row), - Rows::Batch(rows) => rows.iter().try_for_each(check), + OneOrMany::One(row) => check(row), + OneOrMany::Many(rows) => rows.iter().try_for_each(check), } } @@ -2061,13 +2062,6 @@ impl RecordTree for StackCipherText { } } -/// The rows of a call, as the engine's records: one, or a batch, so the -/// result takes the shape the input had. -pub(super) enum Rows { - One(R), - Batch(Vec), -} - /// One source row: the lowered plan's values, each target field's value in /// plan order, for the resolver, and the fields the row leaves out. pub(super) struct Row { @@ -2174,7 +2168,7 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { /// into an [`OwnedFrame`] of its own as the walk reaches it, and nothing else /// is copied. A value the frame cannot carry, or that holds a repeated key, /// is refused naming its field. -pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result, Error> { +pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result, Error> { let row = |at: Option, record: SourceRecord| match record { Ok(fields) => source_row(fields, plan), Err(found) => Err(Error::Source { @@ -2185,8 +2179,8 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result }), }; match into_source_records(source)? { - SplitSource::One(one) => Ok(Rows::One(row(None, one)?)), - SplitSource::Batch(rows) => Ok(Rows::Batch( + OneOrMany::One(one) => Ok(OneOrMany::One(row(None, one)?)), + OneOrMany::Many(rows) => Ok(OneOrMany::Many( rows.into_iter() .enumerate() .map(|(at, record)| row(Some(at), record)) @@ -2531,7 +2525,7 @@ pub(super) fn open_record( /// which wipes it; the result is the only copy of the record's plaintext /// left. pub(super) fn write_record( - rows: Rows>, + rows: OneOrMany>, ) -> Result { fn row>( mut map: S, @@ -2545,10 +2539,10 @@ pub(super) fn write_record( let mut out = vitaminc_protected::Buffer::new(); let writer = FrameWriter::new(&mut out); let written = match rows { - Rows::One(fields) => writer + OneOrMany::One(fields) => writer .map(Some(fields.len())) .and_then(|map| row(map, fields)), - Rows::Batch(rows) => writer.seq(Some(rows.len())).and_then(|mut seq| { + OneOrMany::Many(rows) => writer.seq(Some(rows.len())).and_then(|mut seq| { for fields in rows { let element = seq.element()?; row(element.map(Some(fields.len()))?, fields)?; @@ -2575,7 +2569,10 @@ pub(super) fn write_record( /// each passthrough field is present exactly once with exactly one /// `"passthrough"` node carrying a value of the field's kind. Terms, and /// entries the plan does not open, are ignored: comparands, not ciphertext. -pub(super) fn record_rows(tree: StackCipherText, plan: &Plan) -> Result, Error> { +pub(super) fn record_rows( + tree: StackCipherText, + plan: &Plan, +) -> Result, Error> { let not_an_object = |row, tree: &StackCipherText| Error::Record { field: None, row, @@ -2583,8 +2580,8 @@ pub(super) fn record_rows(tree: StackCipherText, plan: &Plan) -> Result Ok(Rows::One(record_row(row, plan)?)), - CipherText::Sequence(items) => Ok(Rows::Batch( + CipherText::Map(row) => Ok(OneOrMany::One(record_row(row, plan)?)), + CipherText::Sequence(items) => Ok(OneOrMany::Many( items .into_iter() .enumerate() @@ -6657,7 +6654,7 @@ mod tests { fn slot(ty: &str, sent: Tree) -> Vec { let rows = source_rows(obj(vec![("v", sent)]), &plan_of(ty, &["c"])) .expect("the value converts"); - let Rows::One(mut row) = rows else { + let OneOrMany::One(mut row) = rows else { panic!("one row") }; let value: OwnedFrame = row.values.take("v").expect("a slot"); diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index e694c491a..f876a8f14 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -43,6 +43,7 @@ use vitaminc_aead::plaintext::{ }; use vitaminc_protected::Buffer; +use super::one_or_many::OneOrMany; use crate::refusal::Found; /// One entry of the result: a record, or the kind of a value that is not @@ -54,14 +55,6 @@ use crate::refusal::Found; /// record. pub(super) type SourceRecord = Result, Found>; -/// A source split by [`into_source_records`]: one record, or a batch of them. -pub(super) enum SplitSource { - /// The source was a map, or a value that is not a record. - One(SourceRecord), - /// The source was a sequence. Each element is one record. - Batch(Vec), -} - /// Why [`into_source_records`] failed, and where. /// /// - `error` is the error from [`FrameWriter`], or the error that the @@ -83,7 +76,9 @@ pub(super) struct SourceRecordError { /// Split a source into its records, writing each field's value into a /// frame of its own. The [module documentation](self) says what counts as /// a record and when the split fails. -pub(super) fn into_source_records(source: P) -> Result { +pub(super) fn into_source_records( + source: P, +) -> Result, SourceRecordError> { let place = Place::default(); source .visit(TopSink(&place)) @@ -130,9 +125,9 @@ trait PutRecord { struct TopRecord; impl PutRecord for TopRecord { - type Ok = SplitSource; - fn put(self, record: SourceRecord) -> SplitSource { - SplitSource::One(record) + type Ok = OneOrMany; + fn put(self, record: SourceRecord) -> OneOrMany { + OneOrMany::One(record) } } @@ -155,7 +150,7 @@ impl PutRecord for BatchRecord<'_> { struct TopSink<'f>(&'f Place); impl<'f> Sink for TopSink<'f> { - type Ok = SplitSource; + type Ok = OneOrMany; type Error = FrameWriteError; type Seq = BatchSink<'f>; type Map = RecordMap<'f, TopRecord>; @@ -164,12 +159,12 @@ impl<'f> Sink for TopSink<'f> { self, logical: Option, value: Physical<'_>, - ) -> Result { - Ok(SplitSource::One(Err(Found::scalar(logical, &value)))) + ) -> Result, FrameWriteError> { + Ok(OneOrMany::One(Err(Found::scalar(logical, &value)))) } - fn typed_null(self, _: FixedType) -> Result { - Ok(SplitSource::One(Err(Found::Null))) + fn typed_null(self, _: FixedType) -> Result, FrameWriteError> { + Ok(OneOrMany::One(Err(Found::Null))) } fn seq(self, _: Option) -> Result, FrameWriteError> { @@ -184,8 +179,11 @@ impl<'f> Sink for TopSink<'f> { Ok(RecordMap::new(self.0, TopRecord)) } - fn passthrough(self, _: &P) -> Result { - Ok(SplitSource::One(Err(Found::Passthrough))) + fn passthrough( + self, + _: &P, + ) -> Result, FrameWriteError> { + Ok(OneOrMany::One(Err(Found::Passthrough))) } } @@ -216,7 +214,7 @@ impl BatchSink<'_> { } impl<'f> SeqSink for BatchSink<'f> { - type Ok = SplitSource; + type Ok = OneOrMany; type Error = FrameWriteError; type Element<'s> = ElementSink<'f, 's> @@ -236,9 +234,9 @@ impl<'f> SeqSink for BatchSink<'f> { }) } - fn end(self) -> Result { + fn end(self) -> Result, FrameWriteError> { self.check_written()?; - Ok(SplitSource::Batch(self.records)) + Ok(OneOrMany::Many(self.records)) } } @@ -576,7 +574,7 @@ mod tests { ("a", obj(vec![("k", s("v"))])), ("b", Tree::Passthrough(Box::new(s("p")))), ]); - let Ok(SplitSource::One(record)) = into_source_records(&source) else { + let Ok(OneOrMany::One(record)) = into_source_records(&source) else { panic!("one record"); }; assert_eq!( @@ -606,7 +604,7 @@ mod tests { Tree::Undefined, Tree::UInt32(7), ]); - let Ok(SplitSource::Batch(records)) = into_source_records(&source) else { + let Ok(OneOrMany::Many(records)) = into_source_records(&source) else { panic!("a batch"); }; let records: Vec<_> = records.iter().map(bytes).collect(); @@ -630,7 +628,7 @@ mod tests { (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), ] { assert!( - matches!(into_source_records(&top), Ok(SplitSource::One(Err(kind))) if kind == found), + matches!(into_source_records(&top), Ok(OneOrMany::One(Err(kind))) if kind == found), "{found:?} at the top is not a record" ); } @@ -642,7 +640,7 @@ mod tests { assert!( matches!( into_source_records(top), - Ok(SplitSource::One(Err(Found::Null))) + Ok(OneOrMany::One(Err(Found::Null))) ), "a typed null at the top is a null" ); @@ -653,7 +651,7 @@ mod tests { assert!( matches!( into_source_records(batch), - Ok(SplitSource::Batch(records)) + Ok(OneOrMany::Many(records)) if records.len() == 2 && records.iter().all(|r| matches!(r, Err(Found::Null))) ), "a typed null in a batch is a null" @@ -700,7 +698,7 @@ mod tests { // A batch element that is not a record is read past, not written: // a value inside it that no frame could hold is not refused here. // The caller refuses the element itself, as not a record. - let Ok(SplitSource::Batch(records)) = into_source_records(Tree::Array(vec![ + let Ok(OneOrMany::Many(records)) = into_source_records(Tree::Array(vec![ obj(vec![("a", Tree::Int32(1))]), Tree::Array(vec![bad_date]), ])) else { From 3c6e1a29be92a7bad615756e20d5cc08d10f36e2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:51:04 +1100 Subject: [PATCH 05/23] refactor(stack-encrypt): rename Place to Cursor in the source reader The type holds the row and the field the reader is at, which is what a cursor is. The variables that hold one are renamed with it. --- packages/stack-encrypt/src/dynamic/source.rs | 72 ++++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index f876a8f14..c0e292f96 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -79,12 +79,12 @@ pub(super) struct SourceRecordError { pub(super) fn into_source_records( source: P, ) -> Result, SourceRecordError> { - let place = Place::default(); + let cursor = Cursor::default(); source - .visit(TopSink(&place)) + .visit(TopSink(&cursor)) .map_err(|error| SourceRecordError { - row: place.row.get(), - field: place.field.take(), + row: cursor.row.get(), + field: cursor.field.take(), error, }) } @@ -97,17 +97,17 @@ pub(super) fn into_source_records( /// The split sets each one when the source starts it, and clears it when /// the source finishes it. So an error between two rows names no row, and /// an error between two fields names no field. Every sink in one split -/// shares one `Place`. +/// shares one `Cursor`. /// /// Field names are not secret. The plan and the stored record both contain /// them unencrypted. So the code does not wipe the name. #[derive(Default)] -struct Place { +struct Cursor { row: Cell>, field: RefCell>, } -impl Place { +impl Cursor { /// Clears the field, because the source has finished writing its value. fn field_done(&self) { *self.field.borrow_mut() = None; @@ -132,22 +132,22 @@ impl PutRecord for TopRecord { } /// The next record of a batch. [`put`](PutRecord::put) adds the record to -/// the batch and clears the row in [`Place`], because the row is finished. +/// the batch and clears the row in [`Cursor`], because the row is finished. struct BatchRecord<'s> { records: &'s mut Vec, - place: &'s Place, + cursor: &'s Cursor, } impl PutRecord for BatchRecord<'_> { type Ok = (); fn put(self, record: SourceRecord) { self.records.push(record); - self.place.row.set(None); + self.cursor.row.set(None); } } /// The top of a source. -struct TopSink<'f>(&'f Place); +struct TopSink<'f>(&'f Cursor); impl<'f> Sink for TopSink<'f> { type Ok = OneOrMany; @@ -169,7 +169,7 @@ impl<'f> Sink for TopSink<'f> { fn seq(self, _: Option) -> Result, FrameWriteError> { Ok(BatchSink { - place: self.0, + cursor: self.0, records: Vec::new(), begun: 0, }) @@ -195,7 +195,7 @@ impl<'f> Sink for TopSink<'f> { /// split returns an error for that batch instead /// ([`check_written`](Self::check_written)). struct BatchSink<'f> { - place: &'f Place, + cursor: &'f Cursor, records: Vec, begun: usize, } @@ -208,7 +208,7 @@ impl BatchSink<'_> { if self.records.len() == self.begun { return Ok(()); } - self.place.row.set(Some(self.records.len())); + self.cursor.row.set(Some(self.records.len())); Err(FrameWriteError::Unwritten) } } @@ -223,13 +223,13 @@ impl<'f> SeqSink for BatchSink<'f> { fn element(&mut self) -> Result, FrameWriteError> { self.check_written()?; - self.place.row.set(Some(self.begun)); + self.cursor.row.set(Some(self.begun)); self.begun += 1; Ok(ElementSink { - place: self.place, + cursor: self.cursor, record: BatchRecord { records: &mut self.records, - place: self.place, + cursor: self.cursor, }, }) } @@ -243,7 +243,7 @@ impl<'f> SeqSink for BatchSink<'f> { /// One element of a batch. A map is a record. Anything else is not a /// record, and the sink reads past its content. struct ElementSink<'f, 's> { - place: &'f Place, + cursor: &'f Cursor, record: BatchRecord<'s>, } @@ -270,7 +270,7 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { } fn map(self, _: Option) -> Result>, FrameWriteError> { - Ok(RecordMap::new(self.place, self.record)) + Ok(RecordMap::new(self.cursor, self.record)) } fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { @@ -372,7 +372,7 @@ impl MapSink for Discard { /// One record's fields, each value written into its own frame. struct RecordMap<'f, O> { - place: &'f Place, + cursor: &'f Cursor, out: O, // The keys are field names. Field names are not secret, so they are // not wiped. @@ -380,9 +380,9 @@ struct RecordMap<'f, O> { } impl<'f, O> RecordMap<'f, O> { - fn new(place: &'f Place, out: O) -> Self { + fn new(cursor: &'f Cursor, out: O) -> Self { Self { - place, + cursor, out, entries: Vec::new(), } @@ -398,7 +398,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { Self: 's; fn entry(&mut self, key: &str) -> Result, FrameWriteError> { - *self.place.field.borrow_mut() = Some(key.to_owned()); + *self.cursor.field.borrow_mut() = Some(key.to_owned()); self.entries.push((key.to_owned(), Buffer::new())); let buffer = match self.entries.last_mut() { Some((_, buffer)) => buffer, @@ -407,7 +407,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { }; Ok(FieldWriter { writer: FrameWriter::new(buffer), - place: self.place, + cursor: self.cursor, }) } @@ -417,7 +417,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { // A source that dropped an entry's sink without writing to it // left no frame. let value = OwnedFrame::from_buffer(buffer).map_err(|_| { - *self.place.field.borrow_mut() = Some(key.clone()); + *self.cursor.field.borrow_mut() = Some(key.clone()); FrameWriteError::Unwritten })?; record.push((key, value)); @@ -429,11 +429,11 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { /// Writes the value of one field into a frame of its own. /// /// The writer passes every call on to [`FrameWriter`]. When the value is -/// complete, the writer clears the field in [`Place`]. So an error after +/// complete, the writer clears the field in [`Cursor`]. So an error after /// the value of one field and before the next names no field. struct FieldWriter<'s, 'f> { writer: FrameWriter<'s>, - place: &'f Place, + cursor: &'f Cursor, } impl<'s, 'f> Sink for FieldWriter<'s, 'f> { @@ -444,33 +444,33 @@ impl<'s, 'f> Sink for FieldWriter<'s, 'f> { fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { self.writer.scalar(logical, value)?; - self.place.field_done(); + self.cursor.field_done(); Ok(()) } fn typed_null(self, ty: FixedType) -> Result<(), FrameWriteError> { self.writer.typed_null(ty)?; - self.place.field_done(); + self.cursor.field_done(); Ok(()) } fn seq(self, len: Option) -> Result, FrameWriteError> { Ok(FieldSeq { inner: self.writer.seq(len)?, - place: self.place, + cursor: self.cursor, }) } fn map(self, len: Option) -> Result, FrameWriteError> { Ok(FieldMap { inner: self.writer.map(len)?, - place: self.place, + cursor: self.cursor, }) } fn passthrough(self, value: &P) -> Result<(), FrameWriteError> { self.writer.passthrough(value)?; - self.place.field_done(); + self.cursor.field_done(); Ok(()) } } @@ -479,7 +479,7 @@ impl<'s, 'f> Sink for FieldWriter<'s, 'f> { /// sequence ends. struct FieldSeq<'s, 'f> { inner: FrameSeq<'s>, - place: &'f Place, + cursor: &'f Cursor, } impl<'s> SeqSink for FieldSeq<'s, '_> { @@ -496,7 +496,7 @@ impl<'s> SeqSink for FieldSeq<'s, '_> { fn end(self) -> Result<(), FrameWriteError> { self.inner.end()?; - self.place.field_done(); + self.cursor.field_done(); Ok(()) } } @@ -505,7 +505,7 @@ impl<'s> SeqSink for FieldSeq<'s, '_> { /// ends. struct FieldMap<'s, 'f> { inner: FrameMap<'s>, - place: &'f Place, + cursor: &'f Cursor, } impl<'s> MapSink for FieldMap<'s, '_> { @@ -522,7 +522,7 @@ impl<'s> MapSink for FieldMap<'s, '_> { fn end(self) -> Result<(), FrameWriteError> { self.inner.end()?; - self.place.field_done(); + self.cursor.field_done(); Ok(()) } } From 5364c6f96c4af6f1d5b11236f5605e18593ee206 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 21:53:12 +1100 Subject: [PATCH 06/23] refactor(stack-encrypt): rename TopSink to SourceSink It is the sink the whole source is walked into. --- packages/stack-encrypt/src/dynamic/source.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index c0e292f96..6aec9f531 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -81,7 +81,7 @@ pub(super) fn into_source_records( ) -> Result, SourceRecordError> { let cursor = Cursor::default(); source - .visit(TopSink(&cursor)) + .visit(SourceSink(&cursor)) .map_err(|error| SourceRecordError { row: cursor.row.get(), field: cursor.field.take(), @@ -147,9 +147,9 @@ impl PutRecord for BatchRecord<'_> { } /// The top of a source. -struct TopSink<'f>(&'f Cursor); +struct SourceSink<'f>(&'f Cursor); -impl<'f> Sink for TopSink<'f> { +impl<'f> Sink for SourceSink<'f> { type Ok = OneOrMany; type Error = FrameWriteError; type Seq = BatchSink<'f>; From 6e918979eab4868a00b3e3a81a5493dc95278e74 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:04:53 +1100 Subject: [PATCH 07/23] refactor(stack-encrypt): rename the NotARecord sink to RecordSequence It is the sink for a row of a batch that is a sequence, as RecordMap is the sink for a row that is a map. The old name is wanted for an error type. --- packages/stack-encrypt/src/dynamic/source.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 6aec9f531..8cb4a9a43 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -250,7 +250,7 @@ struct ElementSink<'f, 's> { impl<'f, 's> Sink for ElementSink<'f, 's> { type Ok = (); type Error = FrameWriteError; - type Seq = NotARecord<'s>; + type Seq = RecordSequence<'s>; type Map = RecordMap<'f, BatchRecord<'s>>; fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { @@ -263,8 +263,8 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { Ok(()) } - fn seq(self, _: Option) -> Result, FrameWriteError> { - Ok(NotARecord { + fn seq(self, _: Option) -> Result, FrameWriteError> { + Ok(RecordSequence { record: self.record, }) } @@ -283,11 +283,11 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { /// describes its elements, and [`Discard`] reads past them without copying /// them. When the sequence ends, the batch records that the element was an /// array. -struct NotARecord<'s> { +struct RecordSequence<'s> { record: BatchRecord<'s>, } -impl SeqSink for NotARecord<'_> { +impl SeqSink for RecordSequence<'_> { type Ok = (); type Error = FrameWriteError; type Element<'e> From f4b913f8fa463b097794306ce943988b17dcaa69 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:08:54 +1100 Subject: [PATCH 08/23] refactor(stack-encrypt): NotARecord is the error of a SourceRecord A SourceRecord was Result<_, Found>, with a description of a value in the place of an error. Its error is now NotARecord, which holds the Found and implements std::error::Error. --- packages/stack-encrypt/src/dynamic/found.rs | 5 +- packages/stack-encrypt/src/dynamic/record.rs | 4 +- packages/stack-encrypt/src/dynamic/source.rs | 58 ++++++++++++-------- 3 files changed, 41 insertions(+), 26 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs index 2d4c8a52c..52b072f01 100644 --- a/packages/stack-encrypt/src/dynamic/found.rs +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -330,7 +330,10 @@ mod tests { panic!("a batch"); }; assert!( - matches!(rows.as_slice(), [Err(Found::Null)]), + matches!( + rows.as_slice(), + [Err(super::super::source::NotARecord(Found::Null))] + ), "the row is a null" ); } diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 1402bcfcf..dd4295d4e 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -151,7 +151,7 @@ use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; use super::one_or_many::OneOrMany; -use super::source::{into_source_records, SourceRecord, SourceRecordError}; +use super::source::{into_source_records, NotARecord, SourceRecord, SourceRecordError}; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; @@ -2171,7 +2171,7 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result, Error> { let row = |at: Option, record: SourceRecord| match record { Ok(fields) => source_row(fields, plan), - Err(found) => Err(Error::Source { + Err(NotARecord(found)) => Err(Error::Source { field: None, row: at, reason: Reason::NotAnObject, diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 8cb4a9a43..7d8524811 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -46,14 +46,22 @@ use vitaminc_protected::Buffer; use super::one_or_many::OneOrMany; use crate::refusal::Found; -/// One entry of the result: a record, or the kind of a value that is not +/// One entry of the result: a record, or the error for a value that is not /// a record. /// /// `Ok` contains the fields of one record, in the order the source lists /// them. Each field is a name and a value. Each value is in a frame of its -/// own. `Err` contains the kind of a value that is not a map, so is not a -/// record. -pub(super) type SourceRecord = Result, Found>; +/// own. `Err` is [`NotARecord`], for a value that is not a map. +pub(super) type SourceRecord = Result, NotARecord>; + +/// A value in the place of a record that is not a record. A record is a +/// map, and this value is not one. +/// +/// The error contains the kind of the value, as a [`Found`]. It never +/// contains the value. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("expected a record, found {0}")] +pub(super) struct NotARecord(pub(super) Found); /// Why [`into_source_records`] failed, and where. /// @@ -160,11 +168,13 @@ impl<'f> Sink for SourceSink<'f> { logical: Option, value: Physical<'_>, ) -> Result, FrameWriteError> { - Ok(OneOrMany::One(Err(Found::scalar(logical, &value)))) + Ok(OneOrMany::One(Err(NotARecord(Found::scalar( + logical, &value, + ))))) } fn typed_null(self, _: FixedType) -> Result, FrameWriteError> { - Ok(OneOrMany::One(Err(Found::Null))) + Ok(OneOrMany::One(Err(NotARecord(Found::Null)))) } fn seq(self, _: Option) -> Result, FrameWriteError> { @@ -183,7 +193,7 @@ impl<'f> Sink for SourceSink<'f> { self, _: &P, ) -> Result, FrameWriteError> { - Ok(OneOrMany::One(Err(Found::Passthrough))) + Ok(OneOrMany::One(Err(NotARecord(Found::Passthrough)))) } } @@ -254,12 +264,13 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { type Map = RecordMap<'f, BatchRecord<'s>>; fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { - self.record.put(Err(Found::scalar(logical, &value))); + self.record + .put(Err(NotARecord(Found::scalar(logical, &value)))); Ok(()) } fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { - self.record.put(Err(Found::Null)); + self.record.put(Err(NotARecord(Found::Null))); Ok(()) } @@ -274,7 +285,7 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { } fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { - self.record.put(Err(Found::Passthrough)); + self.record.put(Err(NotARecord(Found::Passthrough))); Ok(()) } } @@ -300,7 +311,8 @@ impl SeqSink for RecordSequence<'_> { } fn end(self) -> Result<(), FrameWriteError> { - self.record.put(Err(Found::Kind(ValueKind::Array))); + self.record + .put(Err(NotARecord(Found::Kind(ValueKind::Array)))); Ok(()) } } @@ -549,8 +561,8 @@ mod tests { /// The fields of a record as the bytes of their frames, in source /// order. For a value that is not a record, the kind of that value. - fn bytes(record: &SourceRecord) -> Result)>, Found> { - record.as_ref().map_err(|found| *found).map(|entries| { + fn bytes(record: &SourceRecord) -> Result)>, NotARecord> { + record.as_ref().map_err(|error| *error).map(|entries| { entries .iter() .map(|(key, value)| (key.clone(), value.frame().as_bytes().to_vec())) @@ -612,13 +624,13 @@ mod tests { records, [ Ok(vec![("a".to_owned(), owned(&Tree::Int32(1)))]), - Err(Found::Kind(ValueKind::String)), - Err(Found::Kind(ValueKind::Array)), - Err(Found::Passthrough), + Err(NotARecord(Found::Kind(ValueKind::String))), + Err(NotARecord(Found::Kind(ValueKind::Array))), + Err(NotARecord(Found::Passthrough)), Ok(vec![]), - Err(Found::Null), - Err(Found::Undefined), - Err(Found::Kind(ValueKind::UInt32)), + Err(NotARecord(Found::Null)), + Err(NotARecord(Found::Undefined)), + Err(NotARecord(Found::Kind(ValueKind::UInt32))), ], "a record per map, and the kind of every other element" ); @@ -628,7 +640,7 @@ mod tests { (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), ] { assert!( - matches!(into_source_records(&top), Ok(OneOrMany::One(Err(kind))) if kind == found), + matches!(into_source_records(&top), Ok(OneOrMany::One(Err(NotARecord(kind)))) if kind == found), "{found:?} at the top is not a record" ); } @@ -640,7 +652,7 @@ mod tests { assert!( matches!( into_source_records(top), - Ok(OneOrMany::One(Err(Found::Null))) + Ok(OneOrMany::One(Err(NotARecord(Found::Null)))) ), "a typed null at the top is a null" ); @@ -652,7 +664,7 @@ mod tests { matches!( into_source_records(batch), Ok(OneOrMany::Many(records)) - if records.len() == 2 && records.iter().all(|r| matches!(r, Err(Found::Null))) + if records.len() == 2 && records.iter().all(|r| matches!(r, Err(NotARecord(Found::Null)))) ), "a typed null in a batch is a null" ); @@ -707,7 +719,7 @@ mod tests { assert!( matches!( records.as_slice(), - [Ok(_), Err(Found::Kind(ValueKind::Array))] + [Ok(_), Err(NotARecord(Found::Kind(ValueKind::Array)))] ), "the second element is an array" ); From 31d9d561051b7640f7275e4b415200211eac4fbe Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:29:30 +1100 Subject: [PATCH 09/23] refactor(stack-encrypt): shorten RecordSequence to RecordSeq The file's other sinks use the short form: FieldSeq, SeqSink. --- packages/stack-encrypt/src/dynamic/source.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 7d8524811..804d3c313 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -260,7 +260,7 @@ struct ElementSink<'f, 's> { impl<'f, 's> Sink for ElementSink<'f, 's> { type Ok = (); type Error = FrameWriteError; - type Seq = RecordSequence<'s>; + type Seq = RecordSeq<'s>; type Map = RecordMap<'f, BatchRecord<'s>>; fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { @@ -274,8 +274,8 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { Ok(()) } - fn seq(self, _: Option) -> Result, FrameWriteError> { - Ok(RecordSequence { + fn seq(self, _: Option) -> Result, FrameWriteError> { + Ok(RecordSeq { record: self.record, }) } @@ -294,11 +294,11 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { /// describes its elements, and [`Discard`] reads past them without copying /// them. When the sequence ends, the batch records that the element was an /// array. -struct RecordSequence<'s> { +struct RecordSeq<'s> { record: BatchRecord<'s>, } -impl SeqSink for RecordSequence<'_> { +impl SeqSink for RecordSeq<'_> { type Ok = (); type Error = FrameWriteError; type Element<'e> From c8ae92f0a1de10c8d19251332b5d0bb459c2e57b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:35:12 +1100 Subject: [PATCH 10/23] refactor(stack-encrypt): the source reader is a submodule of record Only dynamic::record reads a source into records, so the reader now lives at dynamic/record/source.rs and its items are visible to record alone. The one test that reached it from dynamic::found moves with it. --- packages/stack-encrypt/src/dynamic/found.rs | 29 +------------------ packages/stack-encrypt/src/dynamic/mod.rs | 1 - packages/stack-encrypt/src/dynamic/record.rs | 4 ++- .../src/dynamic/{ => record}/source.rs | 24 ++++++++++++++- 4 files changed, 27 insertions(+), 31 deletions(-) rename packages/stack-encrypt/src/dynamic/{ => record}/source.rs (97%) diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs index 52b072f01..e82a81660 100644 --- a/packages/stack-encrypt/src/dynamic/found.rs +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -271,7 +271,7 @@ impl<'c> MapSink for Lookup<'_, 'c> { #[cfg(test)] mod tests { use super::*; - use vitaminc_aead::plaintext::{Int, Raw}; + use vitaminc_aead::plaintext::Int; /// [`Found::scalar`] returns the kind of a scalar, `Undefined`, or /// `Unknown` for a logical type that this build does not define. For a @@ -310,31 +310,4 @@ mod tests { ); } } - - /// The same rule applies through a record source. A row of a batch has - /// the logical type date and a null value. `into_source_records` reports the - /// row as a null, and not as `Unknown`. - #[test] - fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { - struct Rows; - impl vitaminc_aead::plaintext::Encrypt for &Rows { - fn visit(self, sink: S) -> Result { - let mut seq = sink.seq(Some(1))?; - Raw(Some(Logical::Date), Physical::Null).visit(seq.element()?)?; - seq.end() - } - } - let Ok(super::super::one_or_many::OneOrMany::Many(rows)) = - super::super::source::into_source_records(&Rows) - else { - panic!("a batch"); - }; - assert!( - matches!( - rows.as_slice(), - [Err(super::super::source::NotARecord(Found::Null))] - ), - "the row is a null" - ); - } } diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 2b38f79eb..1cf995b19 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -108,7 +108,6 @@ mod one_or_many; pub mod planned; mod query; pub mod record; -mod source; /// How to build a language integration on this module: the binding, what /// crosses it, the operations, the plan grammar, plaintext hygiene, keys and diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index dd4295d4e..dd28d2be1 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -150,8 +150,8 @@ use std::fmt; use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; +use self::source::{into_source_records, NotARecord, SourceRecord, SourceRecordError}; use super::one_or_many::OneOrMany; -use super::source::{into_source_records, NotARecord, SourceRecord, SourceRecordError}; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; @@ -172,6 +172,8 @@ use crate::{ }; use vitaminc_aead::IntoContext as _; +mod source; + /// 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)). diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs similarity index 97% rename from packages/stack-encrypt/src/dynamic/source.rs rename to packages/stack-encrypt/src/dynamic/record/source.rs index 804d3c313..c40bb9488 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -43,7 +43,7 @@ use vitaminc_aead::plaintext::{ }; use vitaminc_protected::Buffer; -use super::one_or_many::OneOrMany; +use crate::dynamic::one_or_many::OneOrMany; use crate::refusal::Found; /// One entry of the result: a record, or the error for a value that is not @@ -926,4 +926,26 @@ mod tests { refused.error ); } + + /// The same rule applies through a record source. A row of a batch has + /// the logical type date and a null value. `into_source_records` reports the + /// row as a null, and not as `Unknown`. + #[test] + fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { + struct Rows; + impl vitaminc_aead::plaintext::Encrypt for &Rows { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(1))?; + Raw(Some(Logical::Date), Physical::Null).visit(seq.element()?)?; + seq.end() + } + } + let Ok(OneOrMany::Many(rows)) = into_source_records(&Rows) else { + panic!("a batch"); + }; + assert!( + matches!(rows.as_slice(), [Err(NotARecord(Found::Null))]), + "the row is a null" + ); + } } From 3c26eff74987cc211ae86d071479b340dc65b434 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:52:45 +1100 Subject: [PATCH 11/23] refactor(stack-encrypt): into_source_records returns records that fit the plan Row is renamed SourceRecord, and source_rows is renamed into_source_records and takes the plan. They move into record::source with source_row (now source_record) and check_field, so record sees one function and one type for reading a source. The reader that runs before the plan is applied is private to the module: into_raw_fields, which returns RawFields. --- packages/stack-encrypt/src/dynamic/planned.rs | 49 +-- packages/stack-encrypt/src/dynamic/record.rs | 218 +----------- .../src/dynamic/record/source.rs | 309 +++++++++++++++--- 3 files changed, 301 insertions(+), 275 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 2e7d1f2c0..345ff3d52 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -477,7 +477,7 @@ where value, resolver, } = self; - let rows = record::source_rows(value, plan)?; + let rows = record::into_source_records(value, plan)?; let extend = plan.declared_context(); let shape = plan.shape(); // Every target field of every row, in row-major order, run by the @@ -485,29 +485,30 @@ where // below. A row runs the target fields it does not leave out, so each // row's count is its own. let mut pendings = Vec::new(); - let mut targets = |row: record::Row| -> Result<(Absent, FieldValues, usize), Error> { - let fields = plan - .target_fields() - .filter(|field| !row.absent.contains(field.name())); - let mut count = 0; - for (field, value) in fields.zip(row.targets) { - let name = field.target().unwrap_or_default(); - pendings.push( - resolver - .encrypt( - name, - field.target_options(), - cipher, - field.label(), - &extend, - value.frame(), - ) - .map_err(|error| Error::Target(name_target(error, field.name())))?, - ); - count += 1; - } - Ok((row.absent, row.values, count)) - }; + let mut targets = + |row: record::SourceRecord| -> Result<(Absent, FieldValues, usize), Error> { + let fields = plan + .target_fields() + .filter(|field| !row.absent.contains(field.name())); + let mut count = 0; + for (field, value) in fields.zip(row.targets) { + let name = field.target().unwrap_or_default(); + pendings.push( + resolver + .encrypt( + name, + field.target_options(), + cipher, + field.label(), + &extend, + value.frame(), + ) + .map_err(|error| Error::Target(name_target(error, field.name())))?, + ); + count += 1; + } + Ok((row.absent, row.values, count)) + }; Ok(match rows { OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index dd28d2be1..5b1e57bfe 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -150,16 +150,20 @@ use std::fmt; use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; -use self::source::{into_source_records, NotARecord, SourceRecord, SourceRecordError}; +use self::source::check_field; +#[cfg(test)] +use self::source::SourceRecordError; +pub(super) use self::source::{into_source_records, SourceRecord}; use super::one_or_many::OneOrMany; use super::term::{IndexWire, JsonWire, MatchWire}; use super::{TargetOptions, ValueKind}; -use vitaminc_aead::frame::{Frame, FrameWriteError, FrameWriter, OwnedFrame}; -use vitaminc_aead::plaintext::{Logical, MapSink, Physical, SealedNull, SeqSink, Sink}; +#[cfg(test)] +use vitaminc_aead::frame::FrameWriteError; +use vitaminc_aead::frame::{Frame, FrameWriter, OwnedFrame}; +use vitaminc_aead::plaintext::{Logical, MapSink, Physical, SeqSink, Sink}; use vitaminc_aead::Encrypt; use vitaminc_protected::{Controlled, Protected}; -use super::kind::convert; use super::planned::{check_stored, check_values, compose, opening_base, Planned}; use super::{ not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes, @@ -1949,8 +1953,8 @@ pub fn decrypt_with<'a, K: 'static>( /// /// As [`encrypt`], minus the cipher. pub fn check_source(source: impl Encrypt, plan: &Plan) -> Result<(), Error> { - let rows = source_rows(source, plan)?; - let check = |row: &Row| { + let rows = into_source_records(source, plan)?; + let check = |row: &SourceRecord| { check_values(plan, &row.values, &row.absent).map_err(|error| { let (field, reason) = refusal(error); Error::Source { @@ -2064,14 +2068,6 @@ impl RecordTree for StackCipherText { } } -/// One source row: the lowered plan's values, each target field's value in -/// plan order, for the resolver, and the fields the row leaves out. -pub(super) struct Row { - pub(super) values: FieldValues, - pub(super) targets: Vec, - pub(super) absent: Absent, -} - /// One stored row: the lowered plan's ciphertexts, each target field's EQL /// bytes in plan order, for the resolver, and the fields the row leaves /// out. @@ -2156,198 +2152,6 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { } } -// ============================================================================= -// Encrypt side: the source as the engine's record -// ============================================================================= - -/// The rows of a record source, each as the [`FieldValues`] the lowered -/// plan runs over, with everything that can be checked without a cipher -/// checked: the source is one object or an array of objects, every plan -/// field is present exactly once in every row and no row carries a field -/// the plan does not name, and each value fits its field ([`check_field`]). -/// -/// The source is walked once ([`into_source_records`]): each field's value is written -/// into an [`OwnedFrame`] of its own as the walk reaches it, and nothing else -/// is copied. A value the frame cannot carry, or that holds a repeated key, -/// is refused naming its field. -pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result, Error> { - let row = |at: Option, record: SourceRecord| match record { - Ok(fields) => source_row(fields, plan), - Err(NotARecord(found)) => Err(Error::Source { - field: None, - row: at, - reason: Reason::NotAnObject, - found: Some(found), - }), - }; - match into_source_records(source)? { - OneOrMany::One(one) => Ok(OneOrMany::One(row(None, one)?)), - OneOrMany::Many(rows) => Ok(OneOrMany::Many( - rows.into_iter() - .enumerate() - .map(|(at, record)| row(Some(at), record)) - .collect::, _>>()?, - )), - } -} - -/// Converts the error from `into_source_records` into the [`Error`] that the -/// caller gets. The result keeps the field and the row that the split -/// names. -/// -/// An error that the source returned becomes [`Error::SourceFailed`], with -/// the source's error as its cause. -/// -/// An error from the frame writer becomes [`Error::Source`]. When the -/// split names a field, the reason is: -/// -/// - [`Reason::RepeatedKey`] for a map that repeats a key. -/// - [`Reason::FieldType`] for a scalar that its logical type does not -/// allow. -/// - [`Reason::Unframeable`] for anything else. Examples are a value that -/// is nested too deep or is too long for a frame, and a value that the -/// source never wrote. -/// -/// When the split names no field, the reason is always -/// [`Reason::Unframeable`], with the row, because the error cannot name -/// the value at fault. That happens in two cases: -/// -/// - The source started a row and never wrote it. -/// - The source kept an error from the frame writer and returned it after -/// the field ended. -impl From for Error { - fn from(SourceRecordError { row, field, error }: SourceRecordError) -> Self { - let error = match error { - FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, - error => error, - }; - let reason = match (error, field.is_some()) { - (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, - (FrameWriteError::Invalid, true) => Reason::FieldType, - _ => Reason::Unframeable, - }; - Error::Source { - field, - row, - reason, - found: None, - } - } -} - -fn source_row(mut row: Vec<(String, OwnedFrame)>, plan: &Plan) -> Result { - let misfit = |field: &str, reason| Error::bad_source(reason).in_field(field); - let mut values = FieldValues::new(); - let mut targets = Vec::new(); - let mut absent = Absent::new(); - for field in &plan.fields { - let Some((_, value)) = take(&mut row, &field.name) else { - let reason = absence( - &row, - &field.name, - Reason::FieldMissing, - Reason::FieldRepeated, - ); - if reason == Reason::FieldMissing && field.null == Some(NullMode::Sql) { - let _ = absent.insert(field.name.clone()); - continue; - } - return Err(misfit(&field.name, reason)); - }; - let value = match field.null { - Some(NullMode::Sql) if value.frame().is_null() => { - let _ = absent.insert(field.name.clone()); - continue; - } - // A null the field seals: as a typed null of its type, as long - // as a value of it, or as the plain null for a boolean, which - // is already as long as one. `Plan::build` refuses a sealed - // null on any other type, and on a field with a term other than - // equality's, which a null has. - Some(NullMode::Sealed) if value.frame().is_null() => { - match field.field_type.and_then(ValueKind::sealed_null) { - Some(SealedNull::Typed(ty)) => OwnedFrame::typed_null(ty), - _ => value, - } - } - _ => check_field(value, field)?, - }; - if field.is_target() { - targets.push(value); - } else { - let _ = values.insert(&field.name, value); - } - } - // Every plan field is taken; anything left is a field the plan does not - // name, which would otherwise be dropped unencrypted. - if let Some((extra, _)) = row.first() { - return Err(misfit(extra, Reason::UnknownField)); - } - Ok(Row { - values, - targets, - absent, - }) -} - -/// A source value against its plan field, as the value the field takes: a -/// typed field's value is read as its type, converted when the conversion -/// is exact ([`read`](super::read)); every term output needs a scalar the -/// scheme defines the term for ([`IndexSpec::defines`]); and a ciphertext -/// refuses a passthrough anywhere in the value. An [`OwnedFrame`] holds no -/// repeated key, and is a frame already, so a passthrough output needs -/// nothing more. -/// -/// This is where a write meets its field's type, once: every write path -/// (`encrypt`, `encrypt_with`, `check_source`, [`Planned`]) splits its -/// source into rows here, and a target field's query reads its value here -/// too. What comes back is what is sealed: a value already of the type, -/// as it came, or the converted one, with the value it came as wiped. -fn check_field(value: OwnedFrame, field: &FieldPlan) -> Result { - let misfit = |reason| Error::bad_source(reason).in_field(&field.name); - let value = match field.field_type { - Some(declared) => convert(declared, value.frame()) - .map_err(|error| error.in_field(&field.name))? - .unwrap_or(value), - None => value, - }; - let frame = value.frame(); - // A document is read by the engine's rules here, before any key, so a - // check refuses what encrypt refuses, and no resolver has to. The - // parse is kept to a check and the document dropped (wiped, as every - // `JsonPlaintext` is): the resolver parses it again when it seals, so - // a large document is parsed twice. Deliberate: the check runs before - // any key or keyset load and needs no resolver, and a resolver takes - // the field's value as a frame, as it does for every target, so it - // reads the text it is handed. - if field.field_type == Some(ValueKind::Json) { - if let Err(error) = super::read_json(frame) { - return Err(Error::Target(TargetError::Json { - name: field.name.clone(), - target: field.target().unwrap_or_default().to_owned(), - reason: error.code(), - })); - } - } - // A target field's value is sealed by the type's own plan, which - // refuses a passthrough as any ciphertext does. - let sealed = field.is_target() || field.outputs.contains(&Output::Ciphertext); - if sealed && frame.has_passthrough() { - return Err(misfit(Reason::Passthrough)); - } - for output in &field.outputs { - if let Output::Term(kind) = output { - if !kind.defines(frame) { - return Err(Error::Term { - field: Some(field.name.clone()), - kind: kind.clone(), - }); - } - } - } - Ok(value) -} - // ============================================================================= // Output adapters: the engine's record as the stored shape, and back // ============================================================================= @@ -6654,7 +6458,7 @@ mod tests { /// The frame a record's slot holds for `sent` under a field of /// type `ty`. fn slot(ty: &str, sent: Tree) -> Vec { - let rows = source_rows(obj(vec![("v", sent)]), &plan_of(ty, &["c"])) + let rows = into_source_records(obj(vec![("v", sent)]), &plan_of(ty, &["c"])) .expect("the value converts"); let OneOrMany::One(mut row) = rows else { panic!("one row") diff --git a/packages/stack-encrypt/src/dynamic/record/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs index c40bb9488..5f219a73f 100644 --- a/packages/stack-encrypt/src/dynamic/record/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -1,4 +1,4 @@ -//! Splits the value a caller asks to encrypt into one value per field. +//! Reads the value a caller asks to encrypt into records that fit the plan. //! //! A language SDK hands the engine a record as one value: a map from field //! names to values, such as `{"email": "a@example.com", "age": 34}`. The @@ -6,8 +6,8 @@ //! encrypts each field on its own, with that field's settings from the //! plan, so the engine first needs each field's value separately. //! -//! [`into_source_records`] reads the value once, from start to end. As the split -//! reaches each field, it writes that field's value into an +//! The module works in two steps. `into_raw_fields` reads the value once, +//! from start to end. As the split reaches each field, it writes that field's value into an //! [`OwnedFrame`] of its own. The split copies nothing else. //! //! The result has one entry for each record: @@ -20,11 +20,12 @@ //! kind of the value, as a [`Found`]. Nothing inside the value is copied //! or checked. //! -//! This module does not compare the fields with the plan. The caller, -//! `record::source_rows`, refuses a value that is not a record, a missing -//! field, an extra field, and a value of the wrong type. +//! The first step does not compare the fields with the plan. The second +//! step does: [`into_source_records`] refuses a value that is not a +//! record, a missing field, an extra field, and a value of the wrong type. +//! What it returns for each record is a [`SourceRecord`]. //! -//! [`into_source_records`] returns an error in two cases: +//! `into_raw_fields` returns an error in two cases: //! //! * The split cannot write a field's value into a frame. Examples are a //! date out of range, and a map that repeats a key. @@ -43,16 +44,230 @@ use vitaminc_aead::plaintext::{ }; use vitaminc_protected::Buffer; +use super::{absence, take, Absent, FieldPlan, NullMode, Output, Plan}; +use crate::dynamic::kind::convert; use crate::dynamic::one_or_many::OneOrMany; +use crate::dynamic::{Error, Reason, TargetError}; +use crate::plan::FieldValues; use crate::refusal::Found; +use vitaminc_aead::plaintext::SealedNull; -/// One entry of the result: a record, or the error for a value that is not -/// a record. +// ============================================================================= +// The source as records that fit the plan +// ============================================================================= + +/// One record of a source, after it is compared with the plan. +/// +/// - `values` holds the value of each field that the lowered plan runs. +/// - `targets` holds the value of each target field, in plan order, for +/// the resolver. +/// - `absent` names the fields that the record leaves out. +pub(in crate::dynamic) struct SourceRecord { + pub(in crate::dynamic) values: FieldValues, + pub(in crate::dynamic) targets: Vec, + pub(in crate::dynamic) absent: Absent, +} + +/// The rows of a record source, each as the [`FieldValues`] the lowered +/// plan runs over, with everything that can be checked without a cipher +/// checked: the source is one object or an array of objects, every plan +/// field is present exactly once in every row and no row carries a field +/// the plan does not name, and each value fits its field ([`check_field`]). +/// +/// The source is walked once (`into_raw_fields`): each field's value is written +/// into an [`OwnedFrame`] of its own as the walk reaches it, and nothing else +/// is copied. A value the frame cannot carry, or that holds a repeated key, +/// is refused naming its field. +pub(in crate::dynamic) fn into_source_records( + source: impl Encrypt, + plan: &Plan, +) -> Result, Error> { + let row = |at: Option, record: Result| match record { + Ok(fields) => source_record(fields, plan), + Err(NotARecord(found)) => Err(Error::Source { + field: None, + row: at, + reason: Reason::NotAnObject, + found: Some(found), + }), + }; + match into_raw_fields(source)? { + OneOrMany::One(one) => Ok(OneOrMany::One(row(None, one)?)), + OneOrMany::Many(rows) => Ok(OneOrMany::Many( + rows.into_iter() + .enumerate() + .map(|(at, record)| row(Some(at), record)) + .collect::, _>>()?, + )), + } +} + +/// Converts the error from `into_raw_fields` into the [`Error`] that the +/// caller gets. The result keeps the field and the row that the split +/// names. +/// +/// An error that the source returned becomes [`Error::SourceFailed`], with +/// the source's error as its cause. +/// +/// An error from the frame writer becomes [`Error::Source`]. When the +/// split names a field, the reason is: +/// +/// - [`Reason::RepeatedKey`] for a map that repeats a key. +/// - [`Reason::FieldType`] for a scalar that its logical type does not +/// allow. +/// - [`Reason::Unframeable`] for anything else. Examples are a value that +/// is nested too deep or is too long for a frame, and a value that the +/// source never wrote. +/// +/// When the split names no field, the reason is always +/// [`Reason::Unframeable`], with the row, because the error cannot name +/// the value at fault. That happens in two cases: +/// +/// - The source started a row and never wrote it. +/// - The source kept an error from the frame writer and returned it after +/// the field ended. +impl From for Error { + fn from(SourceRecordError { row, field, error }: SourceRecordError) -> Self { + let error = match error { + FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, + error => error, + }; + let reason = match (error, field.is_some()) { + (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, + (FrameWriteError::Invalid, true) => Reason::FieldType, + _ => Reason::Unframeable, + }; + Error::Source { + field, + row, + reason, + found: None, + } + } +} + +fn source_record(mut row: RawFields, plan: &Plan) -> Result { + let misfit = |field: &str, reason| Error::bad_source(reason).in_field(field); + let mut values = FieldValues::new(); + let mut targets = Vec::new(); + let mut absent = Absent::new(); + for field in &plan.fields { + let Some((_, value)) = take(&mut row, &field.name) else { + let reason = absence( + &row, + &field.name, + Reason::FieldMissing, + Reason::FieldRepeated, + ); + if reason == Reason::FieldMissing && field.null == Some(NullMode::Sql) { + let _ = absent.insert(field.name.clone()); + continue; + } + return Err(misfit(&field.name, reason)); + }; + let value = match field.null { + Some(NullMode::Sql) if value.frame().is_null() => { + let _ = absent.insert(field.name.clone()); + continue; + } + // A null the field seals: as a typed null of its type, as long + // as a value of it, or as the plain null for a boolean, which + // is already as long as one. `Plan::build` refuses a sealed + // null on any other type, and on a field with a term other than + // equality's, which a null has. + Some(NullMode::Sealed) if value.frame().is_null() => { + match field.field_type.and_then(ValueKind::sealed_null) { + Some(SealedNull::Typed(ty)) => OwnedFrame::typed_null(ty), + _ => value, + } + } + _ => check_field(value, field)?, + }; + if field.is_target() { + targets.push(value); + } else { + let _ = values.insert(&field.name, value); + } + } + // Every plan field is taken; anything left is a field the plan does not + // name, which would otherwise be dropped unencrypted. + if let Some((extra, _)) = row.first() { + return Err(misfit(extra, Reason::UnknownField)); + } + Ok(SourceRecord { + values, + targets, + absent, + }) +} + +/// A source value against its plan field, as the value the field takes: a +/// typed field's value is read as its type, converted when the conversion +/// is exact ([`read`](crate::dynamic::read)); every term output needs a scalar the +/// scheme defines the term for ([`IndexSpec::defines`](crate::target::IndexSpec::defines)); and a ciphertext +/// refuses a passthrough anywhere in the value. An [`OwnedFrame`] holds no +/// repeated key, and is a frame already, so a passthrough output needs +/// nothing more. /// -/// `Ok` contains the fields of one record, in the order the source lists -/// them. Each field is a name and a value. Each value is in a frame of its -/// own. `Err` is [`NotARecord`], for a value that is not a map. -pub(super) type SourceRecord = Result, NotARecord>; +/// This is where a write meets its field's type, once: every write path +/// (`encrypt`, `encrypt_with`, `check_source`, [`Planned`](crate::dynamic::Planned)) splits its +/// source into rows here, and a target field's query reads its value here +/// too. What comes back is what is sealed: a value already of the type, +/// as it came, or the converted one, with the value it came as wiped. +pub(super) fn check_field(value: OwnedFrame, field: &FieldPlan) -> Result { + let misfit = |reason| Error::bad_source(reason).in_field(&field.name); + let value = match field.field_type { + Some(declared) => convert(declared, value.frame()) + .map_err(|error| error.in_field(&field.name))? + .unwrap_or(value), + None => value, + }; + let frame = value.frame(); + // A document is read by the engine's rules here, before any key, so a + // check refuses what encrypt refuses, and no resolver has to. The + // parse is kept to a check and the document dropped (wiped, as every + // `JsonPlaintext` is): the resolver parses it again when it seals, so + // a large document is parsed twice. Deliberate: the check runs before + // any key or keyset load and needs no resolver, and a resolver takes + // the field's value as a frame, as it does for every target, so it + // reads the text it is handed. + if field.field_type == Some(ValueKind::Json) { + if let Err(error) = crate::dynamic::read_json(frame) { + return Err(Error::Target(TargetError::Json { + name: field.name.clone(), + target: field.target().unwrap_or_default().to_owned(), + reason: error.code(), + })); + } + } + // A target field's value is sealed by the type's own plan, which + // refuses a passthrough as any ciphertext does. + let sealed = field.is_target() || field.outputs.contains(&Output::Ciphertext); + if sealed && frame.has_passthrough() { + return Err(misfit(Reason::Passthrough)); + } + for output in &field.outputs { + if let Output::Term(kind) = output { + if !kind.defines(frame) { + return Err(Error::Term { + field: Some(field.name.clone()), + kind: kind.clone(), + }); + } + } + } + Ok(value) +} + +// ============================================================================= +// The source as raw fields, before the plan +// ============================================================================= + +/// The fields of one record as the source lists them, before they are +/// compared with the plan. Each field is a name and a value, and each +/// value is in a frame of its own. A field name that the source gives +/// twice is here twice. +type RawFields = Vec<(String, OwnedFrame)>; /// A value in the place of a record that is not a record. A record is a /// map, and this value is not one. @@ -61,9 +276,9 @@ pub(super) type SourceRecord = Result, NotARecord>; /// contains the value. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[error("expected a record, found {0}")] -pub(super) struct NotARecord(pub(super) Found); +struct NotARecord(Found); -/// Why [`into_source_records`] failed, and where. +/// Why [`into_raw_fields`] failed, and where. /// /// - `error` is the error from [`FrameWriter`], or the error that the /// source returned. `FrameWriter` writes a value into a frame. @@ -84,9 +299,9 @@ pub(super) struct SourceRecordError { /// Split a source into its records, writing each field's value into a /// frame of its own. The [module documentation](self) says what counts as /// a record and when the split fails. -pub(super) fn into_source_records( +fn into_raw_fields( source: P, -) -> Result, SourceRecordError> { +) -> Result>, SourceRecordError> { let cursor = Cursor::default(); source .visit(SourceSink(&cursor)) @@ -126,15 +341,18 @@ impl Cursor { /// batch. trait PutRecord { type Ok; - fn put(self, record: SourceRecord) -> Self::Ok; + fn put(self, record: Result) -> Self::Ok; } /// The top of a source: the record is the result. struct TopRecord; impl PutRecord for TopRecord { - type Ok = OneOrMany; - fn put(self, record: SourceRecord) -> OneOrMany { + type Ok = OneOrMany>; + fn put( + self, + record: Result, + ) -> OneOrMany> { OneOrMany::One(record) } } @@ -142,13 +360,13 @@ impl PutRecord for TopRecord { /// The next record of a batch. [`put`](PutRecord::put) adds the record to /// the batch and clears the row in [`Cursor`], because the row is finished. struct BatchRecord<'s> { - records: &'s mut Vec, + records: &'s mut Vec>, cursor: &'s Cursor, } impl PutRecord for BatchRecord<'_> { type Ok = (); - fn put(self, record: SourceRecord) { + fn put(self, record: Result) { self.records.push(record); self.cursor.row.set(None); } @@ -158,7 +376,7 @@ impl PutRecord for BatchRecord<'_> { struct SourceSink<'f>(&'f Cursor); impl<'f> Sink for SourceSink<'f> { - type Ok = OneOrMany; + type Ok = OneOrMany>; type Error = FrameWriteError; type Seq = BatchSink<'f>; type Map = RecordMap<'f, TopRecord>; @@ -167,13 +385,16 @@ impl<'f> Sink for SourceSink<'f> { self, logical: Option, value: Physical<'_>, - ) -> Result, FrameWriteError> { + ) -> Result>, FrameWriteError> { Ok(OneOrMany::One(Err(NotARecord(Found::scalar( logical, &value, ))))) } - fn typed_null(self, _: FixedType) -> Result, FrameWriteError> { + fn typed_null( + self, + _: FixedType, + ) -> Result>, FrameWriteError> { Ok(OneOrMany::One(Err(NotARecord(Found::Null)))) } @@ -192,7 +413,7 @@ impl<'f> Sink for SourceSink<'f> { fn passthrough( self, _: &P, - ) -> Result, FrameWriteError> { + ) -> Result>, FrameWriteError> { Ok(OneOrMany::One(Err(NotARecord(Found::Passthrough)))) } } @@ -206,7 +427,7 @@ impl<'f> Sink for SourceSink<'f> { /// ([`check_written`](Self::check_written)). struct BatchSink<'f> { cursor: &'f Cursor, - records: Vec, + records: Vec>, begun: usize, } @@ -224,7 +445,7 @@ impl BatchSink<'_> { } impl<'f> SeqSink for BatchSink<'f> { - type Ok = OneOrMany; + type Ok = OneOrMany>; type Error = FrameWriteError; type Element<'s> = ElementSink<'f, 's> @@ -244,7 +465,7 @@ impl<'f> SeqSink for BatchSink<'f> { }) } - fn end(self) -> Result, FrameWriteError> { + fn end(self) -> Result>, FrameWriteError> { self.check_written()?; Ok(OneOrMany::Many(self.records)) } @@ -561,7 +782,7 @@ mod tests { /// The fields of a record as the bytes of their frames, in source /// order. For a value that is not a record, the kind of that value. - fn bytes(record: &SourceRecord) -> Result)>, NotARecord> { + fn bytes(record: &Result) -> Result)>, NotARecord> { record.as_ref().map_err(|error| *error).map(|entries| { entries .iter() @@ -586,7 +807,7 @@ mod tests { ("a", obj(vec![("k", s("v"))])), ("b", Tree::Passthrough(Box::new(s("p")))), ]); - let Ok(OneOrMany::One(record)) = into_source_records(&source) else { + let Ok(OneOrMany::One(record)) = into_raw_fields(&source) else { panic!("one record"); }; assert_eq!( @@ -616,7 +837,7 @@ mod tests { Tree::Undefined, Tree::UInt32(7), ]); - let Ok(OneOrMany::Many(records)) = into_source_records(&source) else { + let Ok(OneOrMany::Many(records)) = into_raw_fields(&source) else { panic!("a batch"); }; let records: Vec<_> = records.iter().map(bytes).collect(); @@ -640,7 +861,7 @@ mod tests { (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), ] { assert!( - matches!(into_source_records(&top), Ok(OneOrMany::One(Err(NotARecord(kind)))) if kind == found), + matches!(into_raw_fields(&top), Ok(OneOrMany::One(Err(NotARecord(kind)))) if kind == found), "{found:?} at the top is not a record" ); } @@ -651,7 +872,7 @@ mod tests { let top = Frame::parse(&one).expect("a frame"); assert!( matches!( - into_source_records(top), + into_raw_fields(top), Ok(OneOrMany::One(Err(NotARecord(Found::Null)))) ), "a typed null at the top is a null" @@ -662,7 +883,7 @@ mod tests { let batch = Frame::parse(&batch).expect("a frame"); assert!( matches!( - into_source_records(batch), + into_raw_fields(batch), Ok(OneOrMany::Many(records)) if records.len() == 2 && records.iter().all(|r| matches!(r, Err(NotARecord(Found::Null)))) ), @@ -674,7 +895,7 @@ mod tests { /// that value. For a batch, the error also names the row. #[test] fn a_refusal_names_the_field_and_row_being_written() { - let refused = |source: &Tree| into_source_records(source).err().expect("refused"); + let refused = |source: &Tree| into_raw_fields(source).err().expect("refused"); let bad_date = Tree::Typed(Logical::Date, Box::new(Tree::Int64(i64::MAX))); let one = refused(&obj(vec![ @@ -710,7 +931,7 @@ mod tests { // A batch element that is not a record is read past, not written: // a value inside it that no frame could hold is not refused here. // The caller refuses the element itself, as not a record. - let Ok(OneOrMany::Many(records)) = into_source_records(Tree::Array(vec![ + let Ok(OneOrMany::Many(records)) = into_raw_fields(Tree::Array(vec![ obj(vec![("a", Tree::Int32(1))]), Tree::Array(vec![bad_date]), ])) else { @@ -760,7 +981,7 @@ mod tests { } } - let failed = into_source_records(&Fails { + let failed = into_raw_fields(&Fails { rows: 3, after_the_record: false, }) @@ -774,7 +995,7 @@ mod tests { assert_eq!(failed.field.as_deref(), Some("a"), "the field being read"); assert_eq!(failed.row, Some(2), "the row being read"); - let after = into_source_records(&Fails { + let after = into_raw_fields(&Fails { rows: 2, after_the_record: true, }) @@ -851,7 +1072,7 @@ mod tests { (At::AfterAMap, None, Some(0)), (At::BetweenRows, None, None), ] { - let failed = into_source_records(&at).err().expect("refused"); + let failed = into_raw_fields(&at).err().expect("refused"); assert!( matches!(failed.error, FrameWriteError::Source(_)), "{at:?}: {:?}", @@ -888,7 +1109,7 @@ mod tests { } } for dropped in [0, 1] { - let refused = into_source_records(&DropsARow { dropped }) + let refused = into_raw_fields(&DropsARow { dropped }) .err() .expect("refused"); assert!( @@ -914,7 +1135,7 @@ mod tests { map.end() } } - let refused = into_source_records(&DropsAnEntry).err().expect("refused"); + let refused = into_raw_fields(&DropsAnEntry).err().expect("refused"); assert_eq!( refused.field.as_deref(), Some("dropped"), @@ -928,7 +1149,7 @@ mod tests { } /// The same rule applies through a record source. A row of a batch has - /// the logical type date and a null value. `into_source_records` reports the + /// the logical type date and a null value. `into_raw_fields` reports the /// row as a null, and not as `Unknown`. #[test] fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { @@ -940,7 +1161,7 @@ mod tests { seq.end() } } - let Ok(OneOrMany::Many(rows)) = into_source_records(&Rows) else { + let Ok(OneOrMany::Many(rows)) = into_raw_fields(&Rows) else { panic!("a batch"); }; assert!( From 23d8f59c51f386ad6c92fb92c21b544a683babf9 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 22:56:05 +1100 Subject: [PATCH 12/23] refactor(stack-encrypt): rename StoredRow to EncryptedRecord It is the encrypted form of a record, and pairs with SourceRecord. A caller may not have stored it. --- packages/stack-encrypt/src/dynamic/planned.rs | 41 ++++++++++--------- packages/stack-encrypt/src/dynamic/record.rs | 23 +++++++---- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 345ff3d52..a23eaaed3 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -620,26 +620,27 @@ where let shape = plan.shape(); let cipher = cipher_ref.cipher(); let mut pendings = Vec::new(); - let mut targets = |row: record::StoredRow| -> Result<(Absent, FieldValues, usize), Error> { - let fields = plan - .target_fields() - .filter(|field| !row.absent.contains(field.name())); - let mut count = 0; - for (field, stored) in fields.zip(row.targets) { - let name = field.target().unwrap_or_default(); - // Confined to the caller's keyset, as the lowered plan's - // leaves are: a target value sealed under another keyset is - // refused before any key is retrieved. - pendings.push(confine( - resolver - .decrypt(name, cipher, field.label(), &extend, &stored) - .map_err(|error| Error::Target(name_target(error, field.name())))?, - &cipher_ref, - )); - count += 1; - } - Ok((row.absent, row.values, count)) - }; + let mut targets = + |row: record::EncryptedRecord| -> Result<(Absent, FieldValues, usize), Error> { + let fields = plan + .target_fields() + .filter(|field| !row.absent.contains(field.name())); + let mut count = 0; + for (field, stored) in fields.zip(row.targets) { + let name = field.target().unwrap_or_default(); + // Confined to the caller's keyset, as the lowered plan's + // leaves are: a target value sealed under another keyset is + // refused before any key is retrieved. + pendings.push(confine( + resolver + .decrypt(name, cipher, field.label(), &extend, &stored) + .map_err(|error| Error::Target(name_target(error, field.name())))?, + &cipher_ref, + )); + count += 1; + } + Ok((row.absent, row.values, count)) + }; Ok(match rows { OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 5b1e57bfe..b16d7da37 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -1995,7 +1995,7 @@ pub fn check_record( expected: Option<&Label>, ) -> Result<(), Error> { let rows = record_rows(record, plan)?; - let check = |row: &StoredRow| { + let check = |row: &EncryptedRecord| { check_stored(plan, &row.values, &row.absent) .and_then(|()| opening_base(plan, &row.values, expected.cloned()).map(drop)) .map_err(|error| match error { @@ -2068,10 +2068,14 @@ impl RecordTree for StackCipherText { } } -/// One stored row: the lowered plan's ciphertexts, each target field's EQL -/// bytes in plan order, for the resolver, and the fields the row leaves -/// out. -pub(super) struct StoredRow { +/// One encrypted record, after it is compared with the plan. +/// +/// - `values` holds the ciphertext of each field that the lowered plan +/// opens. +/// - `targets` holds the stored bytes of each target field, in plan order, +/// for the resolver. +/// - `absent` names the fields that the record leaves out. +pub(super) struct EncryptedRecord { pub(super) values: FieldValues, pub(super) targets: Vec>, pub(super) absent: Absent, @@ -2378,7 +2382,7 @@ pub(super) fn write_record( pub(super) fn record_rows( tree: StackCipherText, plan: &Plan, -) -> Result, Error> { +) -> Result, Error> { let not_an_object = |row, tree: &StackCipherText| Error::Record { field: None, row, @@ -2414,7 +2418,10 @@ fn stored_kind(tree: &StackCipherText) -> Found { } } -fn record_row(mut row: Vec<(String, StackCipherText)>, plan: &Plan) -> Result { +fn record_row( + mut row: Vec<(String, StackCipherText)>, + plan: &Plan, +) -> Result { let mut values = FieldValues::new(); let mut targets = Vec::new(); let mut absent = Absent::new(); @@ -2478,7 +2485,7 @@ fn record_row(mut row: Vec<(String, StackCipherText)>, plan: &Plan) -> Result Date: Mon, 30 Nov 2026 23:08:13 +1100 Subject: [PATCH 13/23] refactor(stack-encrypt): the plan has a module of its own, dynamic::plan Plan, FieldPlan, Output, NullMode, Verb, the parser and its wire types move out of dynamic/record.rs into dynamic/plan.rs. record keeps the entry points and the conversions between a record's forms. No public path changes: record re-exports the plan's public items, so dynamic::record::plan and dynamic::record::Plan still resolve. Code outside the new module reads a plan through its accessors where it read private fields before. The tests stay in record.rs for now. --- packages/stack-encrypt/src/dynamic/mod.rs | 1 + packages/stack-encrypt/src/dynamic/plan.rs | 1496 ++++++++++++++++ packages/stack-encrypt/src/dynamic/record.rs | 1545 +---------------- .../src/dynamic/record/source.rs | 36 +- 4 files changed, 1549 insertions(+), 1529 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/plan.rs diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 1cf995b19..f90590532 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -105,6 +105,7 @@ mod json; mod json_query; mod kind; mod one_or_many; +mod plan; pub mod planned; mod query; pub mod record; diff --git a/packages/stack-encrypt/src/dynamic/plan.rs b/packages/stack-encrypt/src/dynamic/plan.rs new file mode 100644 index 000000000..f252a3c07 --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/plan.rs @@ -0,0 +1,1496 @@ +//! The plan of a record, as data: what each field stores, and the parser +//! that reads a plan from a frame. +//! +//! The grammar of a plan and what each key decides are described in the +//! [`record`](super::record) module's documentation. + +use std::fmt; + +use serde::de::{Deserializer, MapAccess, Visitor}; +use serde::Deserialize; + +use super::planned::compose; +use super::record::{Absent, FieldShape}; +use super::term::{IndexWire, JsonWire, MatchWire}; +use super::{not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver}; +use super::{TargetOptions, ValueKind}; +use crate::target::{CallerContext, DeclaredContext, IndexSpec}; +use crate::{ContextPiece, Label, NonEmpty}; +use vitaminc_aead::frame::Frame; +use vitaminc_aead::IntoContext as _; + +/// 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](crate::dynamic::record#the-stored-record-is-wire-format)). +pub const EQL_KEY: &str = "eql"; + +/// What a plan field asks for. +/// +/// The keys are wire format twice over: they are how a binding spells an +/// output, *and* the keys of the per-field output map in the stored result. +/// That is why this enum is exhaustive — see the [module docs](super#stability). +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum Output { + /// `"c"` — the field's [`StackCipherText`](crate::StackCipherText). + Ciphertext, + /// An index term, keyed `"eq"`, `"match"`, `"ore"` or `"ope"`: the + /// index, with its options, that derives it. + Term(IndexSpec), + /// `"passthrough"` — the field carried as it is, **unsealed and + /// unauthenticated**, so the record is whole. A field's only output + /// when it has it. + Passthrough, +} + +impl Output { + /// The output a bare key names, or `None` for a key that is not one. A + /// `"match"` key names the match index under default options; a plan + /// spells other options in the object form (see [`plan`]). + pub fn parse(s: &str) -> Option { + match s { + "c" => Some(Output::Ciphertext), + "passthrough" => Some(Output::Passthrough), + _ => IndexSpec::parse(s).map(Output::Term), + } + } + + /// The map key this output rides under. + pub fn key(&self) -> &'static str { + match self { + Output::Ciphertext => "c", + Output::Term(kind) => kind.key(), + Output::Passthrough => "passthrough", + } + } +} + +/// The verb a field's outputs lower to: one of the four combinators, or a +/// target, which the resolver runs beside the lowered fields. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Verb { + Encrypt, + EncryptIndex, + Index, + Passthrough, + Target, +} + +/// How a field stores a value that is not there: what a plan's `"null"` +/// says. A field with no `"null"` needs every row to have it, and +/// refuses a null where it declares a type. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +pub enum NullMode { + /// `"sealed"`: a null is sealed like a value, under the field's label, + /// as a typed null as long as a value of the field's type (vitaminc + /// 0.8), so the stored record does not say which rows are absent. It + /// opens as a null. An equality index stores a null's term beside it, + /// the one term every null of the field shares, so an `eq` query of a + /// null finds the absent rows; no other index has a term for a null. + /// A field can use this mode only when it declares a type of fixed + /// width. Those types are a boolean, a number, a date, a timestamp, a + /// decimal, and a UUID. Equality must also be the only index of the + /// field. For a target field, equality must be the only index of its + /// EQL type. + Sealed, + /// `"sql"`: a null, or a row with no entry for the field, produces + /// nothing: the stored record has no entry for the field, so the host + /// stores SQL `NULL` in its columns, which shows that the value is + /// absent. A stored record with no entry for the field opens it as a + /// null. Any field but a passthrough takes it. + Sql, +} + +impl NullMode { + /// How a plan spells the mode: `"sealed"` or `"sql"`. Frozen wire + /// format. + pub const fn name(self) -> &'static str { + match self { + NullMode::Sealed => "sealed", + NullMode::Sql => "sql", + } + } +} + +/// One field of a record plan: what to call it, what label to seal it +/// under, what to produce for it, and, optionally, what type its values are. +/// +/// A field may declare the type of its values (a [`ValueKind`]), and must +/// when it has a term output: [`Plan::new_with`] refuses the plan otherwise +/// ([`Error::UntypedIndex`]). A typed field admits only the indexes that +/// kind is defined for ([`admits`](super::admits), checked when the plan is built), seals +/// only values of that kind and opens only to one (checked per value), so +/// the engine verifies what a binding hands it rather than trusting the +/// binding's tagging. A field that only seals, or only carries its value +/// through, may leave the type out; see the +/// [module docs](crate::dynamic::record#what-a-fields-type-decides-and-what-it-does-not). +#[derive(Clone, Debug)] +pub struct FieldPlan { + name: String, + context: NonEmpty>, + label: Label, + extension: Vec>, + outputs: Vec, + target: Option, + target_options: Option, + field_type: Option, + null: Option, +} + +impl FieldPlan { + /// A field plan. + /// + /// `context` is the field's whole context as a binding spells it: its + /// label, a list of plain segments, extended by zero or more scalar + /// parts nested to the left (see the + /// [module docs](crate::dynamic::record#what-a-fields-context-must-be)). Build one from a + /// value with [`super::context`](super::context()). How many segments + /// the label needs is the plan's rule, not the field's: two or more + /// under a plan with a context of its own ([`Plan::new`]), exactly one + /// under a plan that takes its context from a field + /// ([`Plan::with_context_field`]). + /// + /// # Errors + /// + /// [`Error::Plan`] if `outputs` is empty, names an output twice (two + /// outputs with the same [key](Output::key) are the same output — two + /// match indexes under different options would both ride under + /// `"match"`), or names [`Output::Passthrough`] beside another output; + /// or if `context` is not a label, optionally extended. + pub fn new( + name: impl Into, + context: NonEmpty>, + outputs: Vec, + ) -> Result { + let name = name.into(); + let refuse = |reason| Error::bad_plan(reason).in_field(&name); + if outputs.is_empty() { + return Err(refuse(Reason::NoOutputs)); + } + for (at, output) in outputs.iter().enumerate() { + if outputs[..at] + .iter() + .any(|prior| prior.key() == output.key()) + { + return Err(refuse(Reason::DuplicateOutput)); + } + } + if outputs.contains(&Output::Passthrough) && outputs.len() > 1 { + return Err(refuse(Reason::PassthroughWithOutputs)); + } + // At most one index per operator, as the typed plan refuses + // (`PlanError::IndexOverlap`): `ore` beside `ope` would store a + // term no query uses. + let indexes: Vec = outputs + .iter() + .filter_map(|output| match output { + Output::Term(index) => Some(index.clone()), + _ => None, + }) + .collect(); + if crate::target::index::overlapping(&indexes).is_some() { + return Err(refuse(Reason::OverlappingOutputs)); + } + let (label, extension) = field_context(&name, context.get())?; + Ok(Self { + name, + context, + label, + extension, + outputs, + target: None, + target_options: None, + field_type: None, + null: None, + }) + } + + /// A field plan that names an EQL type as its target instead of + /// outputs: the type's own plan decides what is sealed and which terms + /// sit beside it. Whether the name is one this build can run is decided + /// when the plan is built ([`Plan::new_with`]), against the resolver. + /// + /// # Errors + /// + /// [`Error::Plan`] if `target` is empty, or if `context` is not a label, + /// optionally extended. How many segments the label needs is the plan's + /// rule ([`Plan::new_with`]), as it is for [`new`](Self::new). + pub fn with_target( + name: impl Into, + context: NonEmpty>, + target: impl Into, + ) -> Result { + let name = name.into(); + let target = target.into(); + if target.is_empty() { + return Err(Error::bad_plan(Reason::InvalidTarget).in_field(&name)); + } + let (label, extension) = field_context(&name, context.get())?; + Ok(Self { + name, + context, + label, + extension, + outputs: Vec::new(), + target: Some(target), + target_options: None, + field_type: None, + null: None, + }) + } + + /// Give the field's target its options: the options of the index the + /// target carries, such as a JSON document's sealed root and ordered + /// paths. Whether the target takes them is decided when the plan is + /// built ([`Plan::new_with`]), against the resolver; a target that + /// carries the JSON index and is given none takes the index's + /// defaults. Options on a field with no target are refused there too. + #[must_use] + pub fn with_target_options(mut self, options: TargetOptions) -> Self { + self.target_options = Some(options); + self + } + + /// The options the field's target runs under: the ones given, or for a + /// target that carries the JSON index and was given none, the index's + /// defaults, once the plan is built. `None` for a target that takes + /// none, and for a field with no target. + pub fn target_options(&self) -> Option<&TargetOptions> { + self.target_options.as_ref() + } + + /// Declare the type of this field's values. + /// + /// # Errors + /// + /// [`Error::Plan`] if the field asks for an index the kind is not + /// defined for ([`admits`](super::admits)), with the reason [`not_admitted`] gives: + /// [`Reason::IndexNotAdmitted`] for match on an integer, equality or an + /// order index on a boolean, an order index on an 8-bit integer or on + /// bytes, any index on a composite. + pub fn with_type(mut self, field_type: ValueKind) -> Result { + for output in &self.outputs { + if let Output::Term(index) = output { + if let Some(reason) = not_admitted(field_type, index) { + return Err(Error::bad_plan(reason).in_field(&self.name)); + } + } + } + self.field_type = Some(field_type); + Ok(self) + } + + /// Say how the field stores a value that is not there ([`NullMode`]). + /// Whether the field can is decided when the plan is built + /// ([`Plan::new_with`]), once its type is known. + pub fn with_null(mut self, null: NullMode) -> Self { + self.null = Some(null); + self + } + + /// How the field stores a value that is not there, if the plan says. + pub fn null(&self) -> Option { + self.null + } + + /// The field's name — its key in the source and in the result. + pub fn name(&self) -> &str { + &self.name + } + + /// The field's whole context as it was declared: its label, extended + /// by the call's parts if any. What a probe for the field takes. + pub fn context(&self) -> &NonEmpty> { + &self.context + } + + /// The label the field is sealed and indexed under before any + /// extension: the plan's context, then the field's identity — or the + /// identity alone, under a plan that takes its context from a field. + pub fn label(&self) -> &Label { + &self.label + } + + /// The label segment the field's data is keyed under: the last segment + /// of its label. + pub fn identity(&self) -> &str { + // A label has at least one segment by construction (`new`), so + // this never falls back. + self.label.segments().last().unwrap_or("") + } + + /// What the field produces. Empty for a field that names a target: its + /// outputs are the EQL type's own. + pub fn outputs(&self) -> &[Output] { + &self.outputs + } + + /// The EQL type this field names as its target, if it does. + pub fn target(&self) -> Option<&str> { + self.target.as_deref() + } + + /// The declared type of the field's values, if the plan declares one. + /// A host with no types of its own reads this to know what a decrypted + /// value is. + pub fn field_type(&self) -> Option { + self.field_type + } + + /// Whether the field has a ciphertext to seal and open. + pub fn has_ciphertext(&self) -> bool { + self.outputs.contains(&Output::Ciphertext) + } + + /// Whether the field comes back from [`decrypt`](crate::dynamic::record::decrypt): sealed and passthrough + /// fields do, index-only fields do not. + pub(super) fn opens(&self) -> bool { + self.verb() != Verb::Index + } + + pub(super) fn verb(&self) -> Verb { + if self.target.is_some() { + Verb::Target + } else if self.outputs.contains(&Output::Passthrough) { + Verb::Passthrough + } else if self.has_ciphertext() { + if self.indexes().is_empty() { + Verb::Encrypt + } else { + Verb::EncryptIndex + } + } else { + Verb::Index + } + } + + /// The indexes the field declares, in output order. + pub(super) fn indexes(&self) -> Vec { + self.outputs + .iter() + .filter_map(|output| match output { + Output::Term(index) => Some(index.clone()), + Output::Ciphertext | Output::Passthrough => None, + }) + .collect() + } + + /// The plan context the field's label sits under: every segment but + /// the last. + fn prefix(&self) -> Result { + let segments: Vec<&str> = self.label.segments().collect(); + let Some((_, prefix)) = segments.split_last() else { + return Err(Error::Internal); + }; + Label::new(prefix) + .map_err(|_| Error::bad_plan(Reason::ContextNotLabel).in_field(&self.name)) + } + + /// What the output adapters need of the field: no context, which is the + /// engine's by then. + fn shape(&self) -> FieldShape { + FieldShape { + name: self.name.clone(), + verb: self.verb(), + keys: self.indexes().iter().map(IndexSpec::key).collect(), + kind: self.field_type, + null: self.null, + } + } + + /// Why the field cannot store a null as its [`NullMode`] says, if it + /// cannot: a passthrough carries a null as it is; a sealed null needs + /// a type of fixed width and no term. A target field's terms are its + /// type's, which [`Plan::new_with`] checks. + fn null_refusal(&self) -> Option { + let null = self.null?; + if self.verb() == Verb::Passthrough { + return Some(Reason::NullPassthrough); + } + if null == NullMode::Sql { + return None; + } + if self + .indexes() + .iter() + .any(|index| !matches!(index, IndexSpec::Equality)) + { + return Some(Reason::SealedNullIndex); + } + match self.field_type.and_then(ValueKind::sealed_null) { + Some(_) => None, + None => Some(Reason::SealedNullType), + } + } + + /// Whether the field is run by the resolver rather than the lowered plan. + pub(super) fn is_target(&self) -> bool { + self.target.is_some() + } + + /// Extend the field's context by `part`, nested to the left as a + /// binding spells it (`[[..label], part]`), and record it in the + /// extension: what [`Plan::with_scopes`] does to every field. + fn extend(&mut self, part: ContextPiece<'static>) { + let own = self.context.get().clone(); + let nested = ContextPiece::List(vec![own, part.clone()]); + self.context = NonEmpty::new(nested) + .unwrap_or_else(|_| unreachable!("a list of two parts is not empty")); + self.extension.push(part); + } +} + +/// The text of a text part. +fn text_of<'a>(piece: &'a ContextPiece<'_>) -> Option<&'a str> { + match piece { + ContextPiece::Text(text) => Some(text.as_ref()), + _ => None, + } +} + +/// A field's declared context, taken apart into its label and the +/// extension parts around it. +/// +/// A non-empty list of plain text segments is the label. A two-element list +/// whose second element is a scalar is a context extended by that part, +/// nested to the left, so the first element is taken apart in turn. +/// Anything else — a bare part, an empty list, a list mixing segments and +/// other parts, a part that is itself a list — is not a context a fields +/// plan can give a field. A one-segment label is a label here; whether the +/// plan admits one is [`Plan::new`]'s and [`Plan::with_context_field`]'s +/// rule. +fn split_context(piece: &ContextPiece<'_>) -> Option<(Label, Vec>)> { + let ContextPiece::List(parts) = piece else { + return None; + }; + if let Some(segments) = parts.iter().map(text_of).collect::>>() { + if !segments.is_empty() { + let label = Label::new(segments).ok()?; + return Some((label, Vec::new())); + } + } + match parts.as_slice() { + [inner, part] if !matches!(part, ContextPiece::List(_)) => { + let (label, mut extension) = split_context(inner)?; + extension.push(part.clone().into_owned()); + Some((label, extension)) + } + _ => None, + } +} + +/// [`split_context`] for the field `name`, refusing a context that is not +/// a label, optionally extended, as that field's. +fn field_context( + name: &str, + piece: &ContextPiece<'_>, +) -> Result<(Label, Vec>), Error> { + split_context(piece).ok_or_else(|| Error::bad_plan(Reason::ContextNotLabel).in_field(name)) +} + +/// A refusal of the lowering or the engine's own check, as the field it +/// names and the nearest [`Reason`]. Matched exhaustively, so a new +/// [`PlanError`](crate::PlanError) says here which reason it reads as; an +/// engine failure that is not a plan refusal is [`Reason::Refused`]. +pub(super) fn refusal(error: crate::Error) -> (Option, Reason) { + use crate::PlanError as P; + let crate::Error::Plan(error) = error else { + return (None, Reason::Refused); + }; + match error { + P::ContextLabel(_) => (None, Reason::ContextNotLabel), + P::FieldLabel { field, .. } => (Some(field), Reason::ContextNotLabel), + P::DuplicateField { field } => (Some(field), Reason::DuplicateField), + P::SharedIdentity { second, .. } => (Some(second), Reason::SharedIdentity), + P::DuplicateIndex { at, .. } => (Some(at), Reason::DuplicateOutput), + P::IndexOverlap { at, .. } => (Some(at), Reason::OverlappingOutputs), + P::EmptyIndexes => (None, Reason::NoOutputs), + P::NotInPlan { field } => (Some(field), Reason::UnknownField), + P::NotInValue { field } => (Some(field), Reason::FieldMissing), + P::FieldType { field, .. } => (Some(field), Reason::FieldType), + P::NoSuchField { field } => (Some(field), Reason::NoSuchField), + P::BindInQuery => (None, Reason::BindInQuery), + P::EmptyPart => (None, Reason::EmptyBinding), + P::TwoContextSources { .. } | P::ContextNotStorable { .. } => (None, Reason::Refused), + } +} + +/// A record plan: the fields a record has, each with what to call it, what +/// label to seal it under, and what to produce for it. +/// +/// Opaque, because the operations over a plan rely on properties of the +/// whole that no single [`FieldPlan`] can carry: there is at least one +/// field, no two fields share a name, every field's label sits under the +/// one plan context (or, under a context field, is its identity alone) and +/// carries the one extension, and no two keyed fields share an identity, +/// so the whole composes. Both the parser ([`plan`]) and the +/// manual constructors ([`Plan::new`], [`Plan::with_context_field`]) go +/// through the one check, so a plan in hand is a plan that holds them, +/// whichever way it was built. +#[derive(Clone, Debug)] +pub struct Plan { + context: Context, + extension: Vec>, + /// The caller's bindings, in order: in the stored context of every + /// field, after the scopes, and in no query context. The plan-level + /// `"bind"` key. + bindings: Vec>, + fields: Vec, +} + +/// Where a data plan takes its context from: the plan, or a field of each +/// record. A binding names the context in the declaration it sends. +#[derive(Clone, Debug)] +pub(super) enum Context { + /// The plan's own label, which every field's label extends. + Label(Label), + /// The named field of each record, whose value is the context. + Field(String), +} + +impl Plan { + /// A plan over `fields`, in the order given — which is the order of the + /// fields in every result — under the context every field's label + /// shares, for a build without EQL types: [`new_with`](Self::new_with) + /// under [`NoTargets`], so a field that names a target is refused. + /// + /// # Errors + /// + /// As [`new_with`](Self::new_with). + pub fn new(fields: Vec) -> Result { + Self::new_with(fields, &NoTargets) + } + + /// A plan over `fields`, in the order given — which is the order of the + /// fields in every result — under the context every field's label + /// shares, resolving each target field's name through `resolver`. + /// + /// # Errors + /// + /// [`Error::Plan`] if `fields` is empty, names a field twice, has a + /// field whose label has fewer than two segments, has fields whose + /// labels sit under different contexts or carry different extensions, + /// or does not build as a fields plan: two sealed or indexed fields + /// keyed under one identity, for instance, whose terms would be + /// interchangeable. [`Error::UntypedIndex`], naming the field, if a field + /// with a term output declares no type: every constructor shares that + /// rule, so a parsed and a hand-built plan are refused alike. + /// [`Error::Target`] if a target field names a type the + /// resolver does not know or cannot produce, declares a `"type"` other + /// than the kind that type is produced from, or has a label that is not + /// a column. + pub fn new_with( + mut fields: Vec, + resolver: &(impl TargetResolver + ?Sized), + ) -> Result { + let Some(first) = fields.first() else { + return Err(Error::bad_plan(Reason::NoFields)); + }; + let context = first.prefix()?; + for field in &fields { + // `prefix` refuses a one-segment label, which has nothing to + // sit under; a longer one must sit under the first field's. + if field.prefix()? != context { + return Err(Error::bad_plan(Reason::MixedContexts).in_field(&field.name)); + } + } + for field in fields.iter_mut().filter(|field| field.is_target()) { + let name = field.target.clone().unwrap_or_default(); + let descriptor = resolver.resolve(&name)?; + // An EQL value is stored under a table and a column, so the + // label is exactly two segments. Decided here, where the plan is + // built and se_plan_check reports it, not at the first value: a + // generator that asks the engine must be told before it writes + // the code. The resolver re-checks, since it is public API. + if field.label.segments().len() != 2 { + return Err(TargetError::Column { + name: field.name.clone(), + label: field.label.to_string(), + reason: "an EQL column is a two-segment label: table and column".to_owned(), + } + .into()); + } + match (field.field_type, descriptor.plaintext) { + (Some(declared), expected) if expected != Some(declared) => { + return Err(TargetError::Kind { + name: field.name.clone(), + target: name, + expected, + declared, + } + .into()); + } + (None, Some(kind)) => field.field_type = Some(kind), + _ => {} + } + // A target takes the options of the index it carries, the JSON + // index's alone today. Defaults are filled in here, once, so + // every write, query and read of the field runs under one + // resolved definition. + let carries_json = descriptor + .indexes + .iter() + .any(|index| index == IndexSpec::Json(Default::default()).key()); + field.target_options = match (field.target_options.take(), carries_json) { + (None, false) => None, + (None, true) => Some(TargetOptions::Json(Default::default())), + (Some(TargetOptions::Json(options)), true) => { + options.check().map_err(|_| { + Error::bad_plan(Reason::InvalidTarget).in_field(&field.name) + })?; + Some(TargetOptions::Json(options)) + } + (Some(_), false) => { + return Err(Error::bad_plan(Reason::TargetOptions).in_field(&field.name)) + } + }; + // A null has an equality term and no other, so a sealed null + // needs a type whose terms are equality's alone. + if field.null == Some(NullMode::Sealed) + && descriptor + .indexes + .iter() + .any(|index| index != IndexSpec::Equality.key()) + { + return Err(Error::bad_plan(Reason::SealedNullIndex).in_field(&field.name)); + } + } + Self::build(Context::Label(context), fields) + } + + /// A plan over `fields` that takes its context from the field named + /// `context_field`. That + /// field's value in each record is the context every other field is + /// sealed under, and the field is carried as a passthrough of type + /// string. Each field's label is its identity alone, a one-segment + /// label, optionally extended; see the + /// [module docs](crate::dynamic::record#a-plan-whose-context-is-a-field-of-the-record). + /// + /// # Errors + /// + /// [`Error::Plan`] as [`new`](Self::new) refuses, and if no field is + /// named `context_field`, that field asks for anything but + /// [`Output::Passthrough`] (a context is not sealed, and indexing it + /// would derive a term from a value that is not secret), declares a + /// type other than [`ValueKind::String`], or any field's label has + /// more than one segment. [`Error::UntypedIndex`], naming the field, as + /// [`new_with`](Self::new_with) refuses. [`Error::Target`] + /// ([`TargetError::ContextField`]) if a field names an EQL type as its + /// target: an EQL value is stored under a table the declaration fixes, + /// and a plan with a context field has none. + pub fn with_context_field( + context_field: impl Into, + fields: Vec, + ) -> Result { + let context_field = context_field.into(); + let refuse = |reason| Error::bad_plan(reason).in_field(&context_field); + let Some(field) = fields.iter().find(|field| field.name == context_field) else { + return Err(refuse(Reason::NoSuchField)); + }; + if field.outputs != [Output::Passthrough] + || field + .field_type + .is_some_and(|kind| kind != ValueKind::String) + { + return Err(refuse(Reason::ContextField)); + } + if let Some(field) = fields + .iter() + .find(|field| field.label.segments().count() != 1) + { + return Err(Error::bad_plan(Reason::ContextNotLabel).in_field(&field.name)); + } + // A target field's label must be a column, `/`, + // which a context field's one-segment identity is not: the table + // is each record's own, and an EQL value stores one fixed by the + // declaration. + if let Some(target) = fields.iter().find(|field| field.is_target()) { + return Err(TargetError::ContextField { + name: target.name.clone(), + context_field, + } + .into()); + } + let fields = fields + .into_iter() + .map(|mut field| { + if field.name == context_field { + // A string whether or not the declaration says so: the + // value is read as a label, and the opener checks the + // stored one is text before any key is requested. + field.field_type = Some(ValueKind::String); + } + field + }) + .collect(); + Self::build(Context::Field(context_field), fields) + } + + /// The rules both constructors share: fields named once, one extension, + /// every field with a term output typed, no two keyed fields under one + /// identity. + fn build(context: Context, fields: Vec) -> Result { + let Some(first) = fields.first() else { + return Err(Error::bad_plan(Reason::NoFields)); + }; + let extension = first.extension.clone(); + for (at, field) in fields.iter().enumerate() { + let refuse = |reason| Error::bad_plan(reason).in_field(&field.name); + if fields[..at].iter().any(|prior| prior.name == field.name) { + return Err(refuse(Reason::DuplicateField)); + } + if field.extension != extension { + return Err(refuse(Reason::MixedContexts)); + } + if let Some(reason) = field.null_refusal() { + return Err(refuse(reason)); + } + // A JSON document is stored through a target that stores one; + // a target's options belong to a target. + if !field.is_target() && field.field_type == Some(ValueKind::Json) { + return Err(refuse(Reason::JsonNeedsTarget)); + } + if !field.is_target() && field.target_options.is_some() { + return Err(refuse(Reason::TargetOptions)); + } + // An indexed field declares its type: every value's term derives + // from the one declared kind, never from whatever tag each value + // arrived with. A target field's kind is the type's own. + if !field.is_target() && !field.indexes().is_empty() && field.field_type.is_none() { + return Err(Error::UntypedIndex { + field: field.name.clone(), + }); + } + // Two fields that key something, sealed or indexed or a target, + // cannot share one identity: their data would share one + // descriptor. A passthrough keys nothing (the context field is + // one), so two may share a label, and one may share a sealed + // field's. A target shares with nothing. + let keys = |f: &FieldPlan| f.verb() != Verb::Passthrough; + if fields[..at].iter().any(|prior| { + prior.identity() == field.identity() + && (prior.is_target() || field.is_target() || (keys(prior) && keys(field))) + }) { + return Err(refuse(Reason::SharedIdentity)); + } + } + let plan = Self { + context, + extension, + bindings: Vec::new(), + fields, + }; + Ok(plan) + } + + /// The plan's fields, in result order. Never empty, and no two share a + /// name. Under a context field, that field is among them. + pub fn fields(&self) -> &[FieldPlan] { + &self.fields + } + + /// The plan's one context: the label every field's label extends. + /// `None` for a plan that takes its context from a field + /// ([`context_field`](Self::context_field)). + pub fn label(&self) -> Option<&Label> { + match &self.context { + Context::Label(label) => Some(label), + Context::Field(_) => None, + } + } + + /// The field the plan takes its context from, if it has one. + pub fn context_field(&self) -> Option<&str> { + match &self.context { + Context::Field(name) => Some(name), + Context::Label(_) => None, + } + } + + /// The parts every field's label is extended by, in order; empty when + /// the declaration carries none. + pub fn extension(&self) -> &[ContextPiece<'static>] { + &self.extension + } + + /// The contexts this plan's fields are sealed and indexed under, with + /// the plan's extension applied and a placeholder for a context read + /// from a field of each record. No key is requested. The same view as + /// a derived record's `contexts()`, so a binding can show a record's + /// contexts, and a test in that language can pin them. + /// + /// # Errors + /// + /// Unreachable for a plan from [`plan`], [`Plan::new`] or + /// [`Plan::with_context_field`]: a parsed plan always composes. + pub fn contexts(&self) -> Result { + let shapes = self.placed(compose::<()>(self, &Absent::new())?.shapes()); + Ok(crate::contexts::resolve( + crate::contexts::under_declared(shapes, &self.declared_context()), + crate::contexts::CallerShape::none(), + )) + } + + /// The shape of every field's context, in plan order: the `lowered` + /// fields' shapes, and each target field under its label, then the + /// context it is handed. The resolver runs an EQL type under its label + /// and the plan's parts, as the lowering runs a field with outputs, so + /// the two kinds of field show the same parts. + fn placed(&self, lowered: crate::contexts::Shapes) -> crate::contexts::Shapes { + let mut lowered = lowered.into_iter().peekable(); + let mut shapes = crate::contexts::Shapes::with_capacity(self.fields.len()); + for field in &self.fields { + if field.is_target() { + shapes.push(crate::contexts::leaf_under( + &field.name, + field.label.clone().into_context(), + )); + continue; + } + while lowered + .peek() + .is_some_and(|leaf| leaf.name() == Some(field.name.as_str())) + { + shapes.extend(lowered.next()); + } + } + shapes.extend(lowered); + shapes + } + + /// Where this plan takes its context from. + pub(super) fn context_source(&self) -> &Context { + &self.context + } + + /// This plan with the caller's bindings `parts`, each in the stored + /// context of every field after the scopes, and in no query context. + /// What a binding's `"bind"` key carries. + /// + /// # Errors + /// + /// [`Error::Plan`] with [`Reason::EmptyBinding`] for an empty part: a + /// row ID not yet assigned would bind every row to one context, and + /// the typed path refuses the same. + pub fn with_bindings(mut self, parts: Vec>) -> Result { + if parts.iter().any(crate::MaybeEmpty::is_empty) { + return Err(Error::bad_plan(Reason::EmptyBinding)); + } + self.bindings = parts; + Ok(self) + } + + /// The caller's bindings, in order. Empty for a plan with none. + pub fn bindings(&self) -> &[ContextPiece<'static>] { + &self.bindings + } + + /// Add a caller's scopes to this plan. Each scope becomes one more part + /// at the end of every field's context, after the parts the plan + /// already has, in the order given. A scoped call runs the plan this + /// returns. So a field is sealed and indexed under its label, then the + /// plan's own extension, then the scopes. A call with no scope borrows + /// the plan instead, and copies nothing. + /// + /// A field that names an EQL type is scoped as any other field is. Its + /// EQL value stores its table and column, and not the scope. + /// + /// The scope shows in the context of the call. Here a record under a + /// one-field plan is encrypted under the scope `42u64`: + /// + /// ``` + /// use stack_encrypt::dynamic::{record, Planned, frame::OwnedFrame}; + /// use stack_encrypt::target::Scope; + /// use stack_encrypt::{AsProtectedRef, EncryptInto, Pending, StackCipher, StackCipherText}; + /// use recipher_frame::serde::to_vec; + /// + /// # 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 = to_vec(&serde_json::json!({ + /// "email": { "context": ["users", "email"], "outputs": ["c"], "type": "string" }, + /// }))?; + /// let plan = record::plan(declaration.as_protected_ref())?; + /// let values = OwnedFrame::from_buffer(to_vec(&serde_json::json!({"email": "ada@example.com"}))?)?; + /// let call: Pending<'_, StackCipherText, _> = + /// Planned::new(&plan, values).encrypt_into_with_context(&keyset, Scope::new(42u64)); + /// // The field's context is its label, then the scope. + /// # #[cfg(feature = "testing")] + /// stack_encrypt::assert_context!(call.context(), [["users", "email"], 42u64]); + /// let _row = call.await?; + /// # Ok::<(), Box>(()) + /// # }).unwrap(); + /// ``` + /// + /// # Errors + /// + /// [`Error::Plan`] with [`Reason::EmptyContext`] for an empty part. + pub(super) fn with_scopes( + mut self, + parts: impl IntoIterator>, + ) -> Result { + let parts: Vec<_> = parts.into_iter().collect(); + if parts.iter().any(crate::MaybeEmpty::is_empty) { + return Err(Error::bad_plan(Reason::EmptyContext)); + } + for field in &mut self.fields { + for part in &parts { + field.extend(part.clone()); + } + } + self.extension.extend(parts); + Ok(self) + } + + /// The shapes of every field's leaf, run under this plan's context and + /// then the context the caller hands a [`Planned`](crate::dynamic::Planned) + /// record. + pub(super) fn caller_shapes(&self) -> Result { + Ok(crate::contexts::under_declared_then_caller( + self.placed(compose::<()>(self, &Absent::new())?.shapes()), + &self.declared_context(), + )) + } + + /// The scopes every field's label is run under: the extension. A + /// query runs under these alone. + pub(super) fn scopes(&self) -> DeclaredContext { + self.extension + .iter() + .cloned() + .fold(DeclaredContext::default(), |context, part| { + context.with(CallerContext::from_piece(part)) + }) + } + + /// The context every field's label is run under: the scopes, then the + /// bindings. + pub(super) fn declared_context(&self) -> DeclaredContext { + self.bindings + .iter() + .cloned() + .fold(self.scopes(), |context, part| { + context.with(CallerContext::bind_piece(part)) + }) + } + + pub(super) fn shape(&self) -> Vec { + self.fields.iter().map(FieldPlan::shape).collect() + } + + /// The fields that name a target, in plan order: the resolver's. + pub(super) fn target_fields(&self) -> impl Iterator + '_ { + self.fields.iter().filter(|field| field.is_target()) + } +} + +/// Read a record plan from its frame, for a build without EQL types: +/// [`plan_with`] under [`NoTargets`], so a field that names a `"target"` is +/// refused ([`TargetError::NoTargets`]). +/// +/// # Errors +/// +/// As [`plan_with`]. +pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result { + plan_with(frame, &NoTargets) +} + +/// Read a record plan from its frame, resolving each target field's name +/// through `resolver`. +/// +/// The plan is a frame object, read by serde +/// (`recipher_frame::serde`): +/// +/// ```text +/// { : { "context": , "outputs": [ "c" | "passthrough" | , ... ], "type": }, ... } +/// ``` +/// +/// with one optional key beside the field specs, `"context_field": +/// ""`, which makes the plan take its context from that field +/// of each record ([`Plan::with_context_field`]; the +/// [module docs](crate::dynamic::record#a-plan-whose-context-is-a-field-of-the-record) give +/// the shape), and one more, `"bind": [, ...]`, the caller's +/// bindings ([`Plan::with_bindings`]). Both keys are reserved: a top-level +/// `"context_field"` whose value is not a string, or a `"bind"` whose +/// value is not a list of context parts, is refused rather than read as a +/// field of that name ([`Reason::ContextField`], [`Reason::Bind`]). +/// +/// A field may name an EQL type as its target instead of outputs: +/// +/// ```text +/// { : { "context": , "target": "", "type": }, ... } +/// ``` +/// +/// A field has `"outputs"` or `"target"`, never both. `"target"` is the +/// type's name as the resolver lists it (`"TextEq"`), resolved when the plan +/// is built so a name the build cannot run fails here and not at the first +/// value; its `"type"`, when given, must be the kind the type is produced +/// from. See the [module docs](crate::dynamic::record#a-field-that-names-an-eql-type). A +/// target field needs a column for its label, so it is refused under a +/// context field ([`TargetError::ContextField`]). +/// +/// `"target"` may instead be an object of the name and the options of the +/// index the type carries: a type that stores a JSON document +/// (`JsonSearch`) takes the JSON index's options object, as the +/// `{"json": ...}` output spells it, and no other type takes any. +/// +/// ```text +/// "target": { "name": "JsonSearch", +/// "options": { "sealed_root": , "ordered": [, ...] } } +/// ``` +/// +/// Such a field declares the `"json"` type (or leaves it to the target), +/// hands each document over as UTF-8 JSON text, and stores a null as SQL +/// `NULL` (`"null": "sql"`): a document has no length to pad. +/// +/// `` is an index in its wire form, which is its key — `"eq"`, +/// `"match"`, `"ore"` or `"ope"` — save for a match index with options other +/// than the defaults, which is a one-entry object mapping `"match"` to them: +/// +/// ```text +/// { "match": { "tokenizer": "standard" | { "ngram": }, +/// "downcase": , "short_words": , +/// "k": , "m": } } +/// ``` +/// +/// A bare `"match"` is the default options ([`MatchOptions::default`]: +/// 3-grams, downcased, no short-word tokens, `k = 3`, `m = 256`), so a plan +/// written before options had a wire form means what it always meant. In +/// the object form each option is optional and defaults the same way; an +/// unknown or repeated option, or a set the match scheme refuses (`k` +/// outside `3..=16`, `m` not a power of two in `32..=65536`, a zero n-gram +/// length, `short_words` beside the standard tokenizer or an n-gram length +/// under 3), is refused. The +/// other three indexes have no options and no object form. A field names +/// each output key at most once, so it carries at most one match index. +/// [`IndexSpec`] serializes to this form and [`IndexSpec::from_frame`] +/// reads it. `"passthrough"` is a field's only output when it has it. +/// +/// [`MatchOptions::default`]: crate::sem::MatchOptions::default +/// +/// `"type"` names a [`ValueKind`] (`"int64"`, `"string"`, …; see +/// [`ValueKind::name`]): vitaminc's vocabulary, not one of this crate's. It +/// is **required on every field with a term output** (`"eq"`, `"match"`, +/// `"ore"`, `"ope"`): the field's terms derive from that one kind, and every +/// value is checked against it on the way in and on the way out, so a +/// binding is never trusted to have tagged each value alike (a `34` sent once +/// as a `Float64` and once as an `Int64` would store two terms under one +/// field). A field with term outputs and no `"type"` is refused when the plan +/// is built ([`Error::UntypedIndex`], naming the field). It is optional on a +/// field whose only output is `"c"` or +/// `"passthrough"`, and on a target field, whose kind is the EQL type's own. +/// Declared, it is checked against the field's outputs here ([`admits`](super::admits)) and +/// decides nothing about the bytes (see the +/// [module docs](crate::dynamic::record#what-a-fields-type-decides-and-what-it-does-not)). +/// +/// `"null"`, when given, is `"sealed"` or `"sql"`: how the field stores a +/// value that is not there ([`NullMode`]). Without it a row must +/// have the field, and a typed field refuses a null. `"sealed"` seals a +/// null as a typed null as long as a value, so the stored record does not +/// show it, and beside an equality index stores a null's equality term, the +/// one every null of the field shares, which an `eq` query of a null finds. +/// The field must declare a type of fixed width: a bool, a number, a date, a +/// timestamp, a decimal, or a UUID. Equality must be the only index of the +/// field, or of a target field's EQL type. `"sql"` stores nothing for a null +/// or a missing field, so the host's columns hold SQL `NULL`; any field but +/// a passthrough takes it. +/// +/// `` is read by [`super::context`](super::context()) and must be +/// the field's label, optionally extended; the +/// [module docs](crate::dynamic::record#what-a-fields-context-must-be) give the shape. +/// +/// # Examples +/// +/// ``` +/// use stack_encrypt::dynamic::{record, NoTargets, Output}; +/// use stack_encrypt::target::IndexSpec; +/// use stack_encrypt::AsProtectedRef; +/// +/// // As a binding sends it: seal `age` under the label users/age and index +/// // it for equality. +/// let frame = recipher_frame::serde::to_vec(&serde_json::json!({ +/// "age": { +/// "context": ["users", "age"], +/// "outputs": ["c", "eq"], +/// "type": "uint32", +/// }, +/// }))?; +/// let plan = record::plan_with(frame.as_protected_ref(), &NoTargets)?; +/// +/// assert_eq!(plan.fields().len(), 1); +/// assert_eq!(plan.fields()[0].name(), "age"); +/// assert_eq!(plan.label().map(ToString::to_string).as_deref(), Some("users")); +/// assert_eq!( +/// plan.fields()[0].outputs(), +/// [Output::Ciphertext, Output::Term(IndexSpec::Equality)] +/// ); +/// # Ok::<(), Box>(()) +/// ``` +/// +/// # Errors +/// +/// [`Error::Plan`] for a plan that is not an object of field specs +/// (including bytes that are not one frame, which is how a field or key +/// given twice is refused: the frame refuses it), an empty plan, a spec with +/// a key other than `"context"`, `"outputs"`, `"target"`, `"type"` and +/// `"null"`, a `"null"` other than `"sealed"` or `"sql"`, a field that cannot +/// store a null as its `"null"` says ([`NullMode`]), +/// missing `"context"`, having neither `"outputs"` nor `"target"` or having +/// both, an output list that is not a list of outputs (above), is empty, +/// names an output key twice or names `"passthrough"` beside another +/// output, a `"target"` that is not a non-empty string, a `"type"` that is +/// not a string naming a [`ValueKind`], a type that does not admit one of +/// the field's index outputs, a context that is not a label of at least two +/// segments (optionally extended), fields under different contexts or +/// extensions, or a plan [`Plan::new`] refuses; with +/// `"context_field"`, a value that is not a string, naming no field of the +/// plan, or a plan [`Plan::with_context_field`] refuses. +/// [`Error::UntypedIndex`], naming the field, for a field with a term output +/// and no `"type"`. [`Error::Context`] for a `"context"` that is present but +/// is not a context at all, or renders empty. [`Error::Target`] for a +/// target the resolver refuses ([`Plan::new_with`]). +pub fn plan_with( + frame: vitaminc_protected::ProtectedRef<'_, [u8]>, + resolver: &(impl TargetResolver + ?Sized), +) -> Result { + let frame = frame.risky_ref(); + let wire: PlanWire = + recipher_frame::serde::from_slice(frame).map_err(|e| plan_refusal(&e, frame))?; + let mut fields: Vec = Vec::with_capacity(wire.fields.len()); + for (name, spec) in wire.fields { + let spec = + FieldSpec::try_from(spec).map_err(|reason| Error::bad_plan(reason).in_field(&name))?; + let context = super::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; + let field = match spec.what { + What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, + What::Target(target, options) => { + let field = FieldPlan::with_target(name, context, target)?; + match options { + Some(options) => field.with_target_options(options), + None => field, + } + } + }; + let field = match spec.field_type { + Some(KindName(field_type)) => field.with_type(field_type)?, + None => field, + }; + fields.push(match spec.null { + Some(NullName(null)) => field.with_null(null), + None => field, + }); + } + // The whole-plan rules are the constructors', so a parsed plan and a + // hand-built one are refused alike. + let plan = match wire.context_field { + Some(name) => Plan::with_context_field(name, fields), + None => Plan::new_with(fields, resolver), + }?; + // The grammar's `bind` is a nonempty list of scalar parts: an explicit + // empty list is not an absent key, and a grouped part is not a part Go + // can supply through `Bind`. + match wire.bindings { + None => Ok(plan), + Some(parts) if parts.is_empty() => Err(Error::bad_plan(Reason::EmptyBinding)), + Some(parts) + if parts + .iter() + .any(|part| matches!(part, ContextPiece::List(_))) => + { + Err(Error::bad_plan(Reason::Bind)) + } + Some(parts) => plan.with_bindings(parts), + } +} + +/// A plan as a binding writes it: an object of field specs, in order, with +/// two reserved keys beside them, `"context_field"` and `"bind"`. A visitor +/// only to tell those keys from a field's name; every value below it is +/// derived. +struct PlanWire { + context_field: Option, + /// `None` when the plan has no `"bind"` key: an explicit empty list is + /// kept apart from an absent key, and refused. + bindings: Option>>, + fields: Vec<(String, FieldSpecWire)>, +} + +impl<'de> Deserialize<'de> for PlanWire { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = PlanWire; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a plan: an object of field specs") + } + fn visit_map>(self, mut map: A) -> Result { + let mut plan = PlanWire { + context_field: None, + bindings: None, + fields: Vec::with_capacity(super::context::reserved(map.size_hint())), + }; + while let Some(name) = map.next_key::<&'de str>()? { + if name == CONTEXT_FIELD { + plan.context_field = Some(map.next_value()?); + } else if name == BIND { + let parts: Vec = map.next_value()?; + plan.bindings = Some(parts.into_iter().map(|part| part.0).collect()); + } else { + plan.fields.push((name.to_owned(), map.next_value()?)); + } + } + Ok(plan) + } + } + d.deserialize_map(V) + } +} + +/// The key of the `position`th entry of the object `frame` holds, or `None` +/// when it is not an object of that many entries. +fn entry_key(frame: &[u8], position: usize) -> Option { + let root = Frame::parse(frame).ok()?; + super::found::object_keys(root)?.into_iter().nth(position) +} + +/// The keys a field's spec reads ([`FieldSpecWire`]). +const SPEC_KEYS: [&str; 5] = ["context", "outputs", "target", "type", "null"]; + +/// The plan-level key naming the field a plan takes its context from. +const CONTEXT_FIELD: &str = "context_field"; +/// The plan-level key listing the caller's bindings: a list of parts, each +/// a context as [`context`](super::context()) reads one. +const BIND: &str = "bind"; + +/// One field's spec: a context, and exactly one of `"outputs"` and +/// `"target"` (checked in `TryFrom`, once the field's name is known, so the +/// refusal names it), and optionally a `"type"`. A key that is present must +/// hold its kind of value: a null is refused. +struct FieldSpec { + context: super::context::Context, + what: What, + field_type: Option, + null: Option, +} + +enum What { + Outputs(Vec), + Target(String, Option), +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FieldSpecWire { + context: super::context::Context, + #[serde(default, deserialize_with = "present")] + outputs: Option>, + #[serde(default, deserialize_with = "present")] + target: Option, + #[serde(default, deserialize_with = "present", rename = "type")] + field_type: Option, + #[serde(default, deserialize_with = "present")] + null: Option, +} + +impl TryFrom for FieldSpec { + type Error = Reason; + + fn try_from(wire: FieldSpecWire) -> Result { + let what = match (wire.outputs, wire.target) { + (Some(outputs), None) => What::Outputs(outputs.into_iter().map(Output::from).collect()), + (None, Some(TargetWire::Name(target))) => What::Target(target, None), + (None, Some(TargetWire::Configured(ConfiguredTarget { name, options }))) => { + What::Target(name, options.map(|options| TargetOptions::Json(options.0))) + } + (Some(_), Some(_)) => return Err(Reason::OutputsWithTarget), + (None, None) => return Err(Reason::MissingOutputs), + }; + Ok(FieldSpec { + context: wire.context, + what, + field_type: wire.field_type, + null: wire.null, + }) + } +} + +/// A field's `"target"`: the target's name, which runs it under its +/// defaults, or an object of its name and its options, which are the +/// options of the index the target carries (the JSON index's options +/// object, as an output spells it). +/// +/// The options are read in the JSON index's grammar whatever the target, +/// since that is the only grammar any target takes, and the target is +/// resolved after: options that are not that grammar (`{"x": 1}`) make +/// the target unreadable ([`Reason::InvalidTarget`]), and well-formed +/// options on a target that takes none (`{}` on `TextEq`) are +/// [`Reason::TargetOptions`]. Both refuse the plan before anything is +/// sealed. +#[derive(Deserialize)] +#[serde(untagged)] +enum TargetWire { + Name(String), + Configured(ConfiguredTarget), +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ConfiguredTarget { + name: String, + #[serde(default, deserialize_with = "present")] + options: Option, +} + +/// Absent is `None`. Present, a value must be of its kind: a null is +/// refused, as any other value of the wrong kind is. +fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + T::deserialize(d).map(Some) +} + +/// One entry of a field's `"outputs"`: `"c"`, `"passthrough"`, or an index +/// in its wire form ([`IndexSpec`'s docs](IndexSpec#wire-form)). +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum OutputWire { + #[serde(rename = "c")] + Ciphertext, + Passthrough, + Eq, + Match(Option), + Ore, + Ope, + #[serde(rename = "ore_block")] + OreBlock, + Json(Option), +} + +impl From for Output { + fn from(output: OutputWire) -> Self { + let index = match output { + OutputWire::Ciphertext => return Output::Ciphertext, + OutputWire::Passthrough => return Output::Passthrough, + OutputWire::Eq => IndexWire::Eq, + OutputWire::Match(options) => IndexWire::Match(options), + OutputWire::Ore => IndexWire::Ore, + OutputWire::Ope => IndexWire::Ope, + OutputWire::OreBlock => IndexWire::OreBlock, + OutputWire::Json(options) => IndexWire::Json(options), + }; + Output::Term(index.into()) + } +} + +/// A `"type"`: the name of a [`ValueKind`]. +#[derive(Deserialize)] +#[serde(try_from = "&str")] +struct KindName(ValueKind); + +impl TryFrom<&str> for KindName { + type Error = Reason; + + fn try_from(name: &str) -> Result { + name.parse().map(KindName).map_err(|_| Reason::UnknownType) + } +} + +/// A `"null"`: the name of a [`NullMode`]. +#[derive(Deserialize)] +#[serde(try_from = "&str")] +struct NullName(NullMode); + +impl TryFrom<&str> for NullName { + type Error = Reason; + + fn try_from(name: &str) -> Result { + match name { + "sealed" => Ok(NullName(NullMode::Sealed)), + "sql" => Ok(NullName(NullMode::Sql)), + _ => Err(Reason::UnknownNull), + } + } +} + +/// The parser's refusal of a plan the frame reader refused: the field from +/// the error's path, and the reason from where in the field it happened, +/// or from the reason a field's own rule gave. +fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { + use recipher_frame::serde::PathSegment::{Entry, Key}; + + let path = error.path(); + // A plan's keys are the host's, so the adapter places an error under one + // by its position, never its text; the field is read back from the + // frame that was refused. + let field = match path.first() { + Some(Entry(position)) => entry_key(frame, *position), + _ => None, + }; + let Some(field) = field else { + // The error is at the root of the plan. Either the bytes are not + // one frame, or the frame is not an object. + return match Frame::parse(frame) { + Err(_) => Error::bad_plan(Reason::NotAFrame), + Ok(root) => Error::Plan { + field: None, + reason: Reason::NotAnObject, + found: Some(Found::of_frame(root)), + }, + }; + }; + let field = &field; + if field == CONTEXT_FIELD { + return Error::bad_plan(Reason::ContextField); + } + if field == BIND { + return Error::bad_plan(Reason::Bind); + } + let reason = match path.get(1) { + Some(Key(key)) if key == "context" => { + return Error::bad_context(Reason::ContextKind).in_field(field) + } + Some(Key(key)) if key == "outputs" && path.len() == 2 => Reason::OutputsNotList, + Some(Key(key)) if key == "outputs" => Reason::UnknownOutput, + Some(Key(key)) if key == "target" => Reason::InvalidTarget, + Some(Key(key)) if key == "null" => Reason::UnknownNull, + // `"type"`: the one other key a spec reads, and so the only other + // key an error inside a spec's value is placed under (an unknown + // key is never on the path). + Some(_) => Reason::UnknownType, + // The error is at the field spec itself. There are three possible + // causes: the spec is not an object, the spec has a key that a spec + // does not take, or the spec has no context. The code decides + // between them from the kind of the spec and from its keys. The + // code does not read the text of the error, so a change to that + // text cannot change the reason. + // + // An object with only known keys must lack its context, because + // nothing else fails at this level: + // - An error in the value under a key is reported under that key. + // - A frame never contains a repeated key. + // - The rule that a spec has outputs or a target is checked after + // parsing. + None => match Frame::parse(frame) + .ok() + .and_then(|root| Found::of_entry(root, field)) + { + Some((Found::Kind(ValueKind::Object), keys)) => { + if keys.iter().any(|key| !SPEC_KEYS.contains(&key.as_str())) { + Reason::UnknownKey + } else { + Reason::MissingContext + } + } + found => { + return Error::Plan { + field: Some(field.clone()), + reason: Reason::NotAnObject, + found: found.map(|(found, _)| found), + } + } + }, + }; + Error::bad_plan(reason).in_field(field) +} diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index b16d7da37..f50b4c4a4 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -145,18 +145,13 @@ //! that a round-trip invariant rather than data loss. use std::collections::BTreeSet; -use std::fmt; - -use serde::de::{Deserializer, MapAccess, Visitor}; -use serde::Deserialize; use self::source::check_field; #[cfg(test)] use self::source::SourceRecordError; pub(super) use self::source::{into_source_records, SourceRecord}; use super::one_or_many::OneOrMany; -use super::term::{IndexWire, JsonWire, MatchWire}; -use super::{TargetOptions, ValueKind}; +use super::ValueKind; #[cfg(test)] use vitaminc_aead::frame::FrameWriteError; use vitaminc_aead::frame::{Frame, FrameWriter, OwnedFrame}; @@ -164,1495 +159,23 @@ use vitaminc_aead::plaintext::{Logical, MapSink, Physical, SeqSink, Sink}; use vitaminc_aead::Encrypt; use vitaminc_protected::{Controlled, Protected}; -use super::planned::{check_stored, check_values, compose, opening_base, Planned}; -use super::{ - not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes, -}; +use super::planned::{check_stored, check_values, opening_base, Planned}; +use super::{Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes}; use crate::plan::FieldValues; -use crate::target::{CallerContext, DeclaredContext, Encrypted, IndexSpec}; +#[cfg(test)] +use crate::target::{CallerContext, DeclaredContext}; +use crate::target::{Encrypted, IndexSpec}; use crate::{ - CipherRef, CipherText, ContextPiece, KeysetCipher, Label, NonEmpty, PassthroughFrame, Pending, - StackCipherText, + CipherRef, CipherText, KeysetCipher, Label, PassthroughFrame, Pending, StackCipherText, }; -use vitaminc_aead::IntoContext as _; +#[cfg(test)] +use crate::{ContextPiece, NonEmpty}; mod source; -/// 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)). -pub const EQL_KEY: &str = "eql"; - -/// What a plan field asks for. -/// -/// The keys are wire format twice over: they are how a binding spells an -/// output, *and* the keys of the per-field output map in the stored result. -/// That is why this enum is exhaustive — see the [module docs](super#stability). -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub enum Output { - /// `"c"` — the field's [`StackCipherText`]. - Ciphertext, - /// An index term, keyed `"eq"`, `"match"`, `"ore"` or `"ope"`: the - /// index, with its options, that derives it. - Term(IndexSpec), - /// `"passthrough"` — the field carried as it is, **unsealed and - /// unauthenticated**, so the record is whole. A field's only output - /// when it has it. - Passthrough, -} - -impl Output { - /// The output a bare key names, or `None` for a key that is not one. A - /// `"match"` key names the match index under default options; a plan - /// spells other options in the object form (see [`plan`]). - pub fn parse(s: &str) -> Option { - match s { - "c" => Some(Output::Ciphertext), - "passthrough" => Some(Output::Passthrough), - _ => IndexSpec::parse(s).map(Output::Term), - } - } - - /// The map key this output rides under. - pub fn key(&self) -> &'static str { - match self { - Output::Ciphertext => "c", - Output::Term(kind) => kind.key(), - Output::Passthrough => "passthrough", - } - } -} - -/// The verb a field's outputs lower to: one of the four combinators, or a -/// target, which the resolver runs beside the lowered fields. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(super) enum Verb { - Encrypt, - EncryptIndex, - Index, - Passthrough, - Target, -} - -/// How a field stores a value that is not there: what a plan's `"null"` -/// says. A field with no `"null"` needs every row to have it, and -/// refuses a null where it declares a type. -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum NullMode { - /// `"sealed"`: a null is sealed like a value, under the field's label, - /// as a typed null as long as a value of the field's type (vitaminc - /// 0.8), so the stored record does not say which rows are absent. It - /// opens as a null. An equality index stores a null's term beside it, - /// the one term every null of the field shares, so an `eq` query of a - /// null finds the absent rows; no other index has a term for a null. - /// A field can use this mode only when it declares a type of fixed - /// width. Those types are a boolean, a number, a date, a timestamp, a - /// decimal, and a UUID. Equality must also be the only index of the - /// field. For a target field, equality must be the only index of its - /// EQL type. - Sealed, - /// `"sql"`: a null, or a row with no entry for the field, produces - /// nothing: the stored record has no entry for the field, so the host - /// stores SQL `NULL` in its columns, which shows that the value is - /// absent. A stored record with no entry for the field opens it as a - /// null. Any field but a passthrough takes it. - Sql, -} - -impl NullMode { - /// How a plan spells the mode: `"sealed"` or `"sql"`. Frozen wire - /// format. - pub const fn name(self) -> &'static str { - match self { - NullMode::Sealed => "sealed", - NullMode::Sql => "sql", - } - } -} - -/// One field of a record plan: what to call it, what label to seal it -/// under, what to produce for it, and, optionally, what type its values are. -/// -/// A field may declare the type of its values (a [`ValueKind`]), and must -/// when it has a term output: [`Plan::new_with`] refuses the plan otherwise -/// ([`Error::UntypedIndex`]). A typed field admits only the indexes that -/// kind is defined for ([`admits`](super::admits), checked when the plan is built), seals -/// only values of that kind and opens only to one (checked per value), so -/// the engine verifies what a binding hands it rather than trusting the -/// binding's tagging. A field that only seals, or only carries its value -/// through, may leave the type out; see the -/// [module docs](self#what-a-fields-type-decides-and-what-it-does-not). -#[derive(Clone, Debug)] -pub struct FieldPlan { - name: String, - context: NonEmpty>, - label: Label, - extension: Vec>, - outputs: Vec, - target: Option, - target_options: Option, - field_type: Option, - null: Option, -} - -impl FieldPlan { - /// A field plan. - /// - /// `context` is the field's whole context as a binding spells it: its - /// label, a list of plain segments, extended by zero or more scalar - /// parts nested to the left (see the - /// [module docs](self#what-a-fields-context-must-be)). Build one from a - /// value with [`super::context`](super::context()). How many segments - /// the label needs is the plan's rule, not the field's: two or more - /// under a plan with a context of its own ([`Plan::new`]), exactly one - /// under a plan that takes its context from a field - /// ([`Plan::with_context_field`]). - /// - /// # Errors - /// - /// [`Error::Plan`] if `outputs` is empty, names an output twice (two - /// outputs with the same [key](Output::key) are the same output — two - /// match indexes under different options would both ride under - /// `"match"`), or names [`Output::Passthrough`] beside another output; - /// or if `context` is not a label, optionally extended. - pub fn new( - name: impl Into, - context: NonEmpty>, - outputs: Vec, - ) -> Result { - let name = name.into(); - let refuse = |reason| Error::bad_plan(reason).in_field(&name); - if outputs.is_empty() { - return Err(refuse(Reason::NoOutputs)); - } - for (at, output) in outputs.iter().enumerate() { - if outputs[..at] - .iter() - .any(|prior| prior.key() == output.key()) - { - return Err(refuse(Reason::DuplicateOutput)); - } - } - if outputs.contains(&Output::Passthrough) && outputs.len() > 1 { - return Err(refuse(Reason::PassthroughWithOutputs)); - } - // At most one index per operator, as the typed plan refuses - // (`PlanError::IndexOverlap`): `ore` beside `ope` would store a - // term no query uses. - let indexes: Vec = outputs - .iter() - .filter_map(|output| match output { - Output::Term(index) => Some(index.clone()), - _ => None, - }) - .collect(); - if crate::target::index::overlapping(&indexes).is_some() { - return Err(refuse(Reason::OverlappingOutputs)); - } - let (label, extension) = field_context(&name, context.get())?; - Ok(Self { - name, - context, - label, - extension, - outputs, - target: None, - target_options: None, - field_type: None, - null: None, - }) - } - - /// A field plan that names an EQL type as its target instead of - /// outputs: the type's own plan decides what is sealed and which terms - /// sit beside it. Whether the name is one this build can run is decided - /// when the plan is built ([`Plan::new_with`]), against the resolver. - /// - /// # Errors - /// - /// [`Error::Plan`] if `target` is empty, or if `context` is not a label, - /// optionally extended. How many segments the label needs is the plan's - /// rule ([`Plan::new_with`]), as it is for [`new`](Self::new). - pub fn with_target( - name: impl Into, - context: NonEmpty>, - target: impl Into, - ) -> Result { - let name = name.into(); - let target = target.into(); - if target.is_empty() { - return Err(Error::bad_plan(Reason::InvalidTarget).in_field(&name)); - } - let (label, extension) = field_context(&name, context.get())?; - Ok(Self { - name, - context, - label, - extension, - outputs: Vec::new(), - target: Some(target), - target_options: None, - field_type: None, - null: None, - }) - } - - /// Give the field's target its options: the options of the index the - /// target carries, such as a JSON document's sealed root and ordered - /// paths. Whether the target takes them is decided when the plan is - /// built ([`Plan::new_with`]), against the resolver; a target that - /// carries the JSON index and is given none takes the index's - /// defaults. Options on a field with no target are refused there too. - #[must_use] - pub fn with_target_options(mut self, options: TargetOptions) -> Self { - self.target_options = Some(options); - self - } - - /// The options the field's target runs under: the ones given, or for a - /// target that carries the JSON index and was given none, the index's - /// defaults, once the plan is built. `None` for a target that takes - /// none, and for a field with no target. - pub fn target_options(&self) -> Option<&TargetOptions> { - self.target_options.as_ref() - } - - /// Declare the type of this field's values. - /// - /// # Errors - /// - /// [`Error::Plan`] if the field asks for an index the kind is not - /// defined for ([`admits`](super::admits)), with the reason [`not_admitted`] gives: - /// [`Reason::IndexNotAdmitted`] for match on an integer, equality or an - /// order index on a boolean, an order index on an 8-bit integer or on - /// bytes, any index on a composite. - pub fn with_type(mut self, field_type: ValueKind) -> Result { - for output in &self.outputs { - if let Output::Term(index) = output { - if let Some(reason) = not_admitted(field_type, index) { - return Err(Error::bad_plan(reason).in_field(&self.name)); - } - } - } - self.field_type = Some(field_type); - Ok(self) - } - - /// Say how the field stores a value that is not there ([`NullMode`]). - /// Whether the field can is decided when the plan is built - /// ([`Plan::new_with`]), once its type is known. - pub fn with_null(mut self, null: NullMode) -> Self { - self.null = Some(null); - self - } - - /// How the field stores a value that is not there, if the plan says. - pub fn null(&self) -> Option { - self.null - } - - /// The field's name — its key in the source and in the result. - pub fn name(&self) -> &str { - &self.name - } - - /// The field's whole context as it was declared: its label, extended - /// by the call's parts if any. What a probe for the field takes. - pub fn context(&self) -> &NonEmpty> { - &self.context - } - - /// The label the field is sealed and indexed under before any - /// extension: the plan's context, then the field's identity — or the - /// identity alone, under a plan that takes its context from a field. - pub fn label(&self) -> &Label { - &self.label - } - - /// The label segment the field's data is keyed under: the last segment - /// of its label. - pub fn identity(&self) -> &str { - // A label has at least one segment by construction (`new`), so - // this never falls back. - self.label.segments().last().unwrap_or("") - } - - /// What the field produces. Empty for a field that names a target: its - /// outputs are the EQL type's own. - pub fn outputs(&self) -> &[Output] { - &self.outputs - } - - /// The EQL type this field names as its target, if it does. - pub fn target(&self) -> Option<&str> { - self.target.as_deref() - } - - /// The declared type of the field's values, if the plan declares one. - /// A host with no types of its own reads this to know what a decrypted - /// value is. - pub fn field_type(&self) -> Option { - self.field_type - } - - /// Whether the field has a ciphertext to seal and open. - pub fn has_ciphertext(&self) -> bool { - self.outputs.contains(&Output::Ciphertext) - } - - /// Whether the field comes back from [`decrypt`]: sealed and passthrough - /// fields do, index-only fields do not. - pub(super) fn opens(&self) -> bool { - self.verb() != Verb::Index - } - - pub(super) fn verb(&self) -> Verb { - if self.target.is_some() { - Verb::Target - } else if self.outputs.contains(&Output::Passthrough) { - Verb::Passthrough - } else if self.has_ciphertext() { - if self.indexes().is_empty() { - Verb::Encrypt - } else { - Verb::EncryptIndex - } - } else { - Verb::Index - } - } - - /// The indexes the field declares, in output order. - pub(super) fn indexes(&self) -> Vec { - self.outputs - .iter() - .filter_map(|output| match output { - Output::Term(index) => Some(index.clone()), - Output::Ciphertext | Output::Passthrough => None, - }) - .collect() - } - - /// The plan context the field's label sits under: every segment but - /// the last. - fn prefix(&self) -> Result { - let segments: Vec<&str> = self.label.segments().collect(); - let Some((_, prefix)) = segments.split_last() else { - return Err(Error::Internal); - }; - Label::new(prefix) - .map_err(|_| Error::bad_plan(Reason::ContextNotLabel).in_field(&self.name)) - } - - /// What the output adapters need of the field: no context, which is the - /// engine's by then. - fn shape(&self) -> FieldShape { - FieldShape { - name: self.name.clone(), - verb: self.verb(), - keys: self.indexes().iter().map(IndexSpec::key).collect(), - kind: self.field_type, - null: self.null, - } - } - - /// Why the field cannot store a null as its [`NullMode`] says, if it - /// cannot: a passthrough carries a null as it is; a sealed null needs - /// a type of fixed width and no term. A target field's terms are its - /// type's, which [`Plan::new_with`] checks. - fn null_refusal(&self) -> Option { - let null = self.null?; - if self.verb() == Verb::Passthrough { - return Some(Reason::NullPassthrough); - } - if null == NullMode::Sql { - return None; - } - if self - .indexes() - .iter() - .any(|index| !matches!(index, IndexSpec::Equality)) - { - return Some(Reason::SealedNullIndex); - } - match self.field_type.and_then(ValueKind::sealed_null) { - Some(_) => None, - None => Some(Reason::SealedNullType), - } - } - - /// Whether the field is run by the resolver rather than the lowered plan. - pub(super) fn is_target(&self) -> bool { - self.target.is_some() - } - - /// Extend the field's context by `part`, nested to the left as a - /// binding spells it (`[[..label], part]`), and record it in the - /// extension: what [`Plan::with_scopes`] does to every field. - fn extend(&mut self, part: ContextPiece<'static>) { - let own = self.context.get().clone(); - let nested = ContextPiece::List(vec![own, part.clone()]); - self.context = NonEmpty::new(nested) - .unwrap_or_else(|_| unreachable!("a list of two parts is not empty")); - self.extension.push(part); - } -} - -/// The text of a text part. -fn text_of<'a>(piece: &'a ContextPiece<'_>) -> Option<&'a str> { - match piece { - ContextPiece::Text(text) => Some(text.as_ref()), - _ => None, - } -} - -/// A field's declared context, taken apart into its label and the -/// extension parts around it. -/// -/// A non-empty list of plain text segments is the label. A two-element list -/// whose second element is a scalar is a context extended by that part, -/// nested to the left, so the first element is taken apart in turn. -/// Anything else — a bare part, an empty list, a list mixing segments and -/// other parts, a part that is itself a list — is not a context a fields -/// plan can give a field. A one-segment label is a label here; whether the -/// plan admits one is [`Plan::new`]'s and [`Plan::with_context_field`]'s -/// rule. -fn split_context(piece: &ContextPiece<'_>) -> Option<(Label, Vec>)> { - let ContextPiece::List(parts) = piece else { - return None; - }; - if let Some(segments) = parts.iter().map(text_of).collect::>>() { - if !segments.is_empty() { - let label = Label::new(segments).ok()?; - return Some((label, Vec::new())); - } - } - match parts.as_slice() { - [inner, part] if !matches!(part, ContextPiece::List(_)) => { - let (label, mut extension) = split_context(inner)?; - extension.push(part.clone().into_owned()); - Some((label, extension)) - } - _ => None, - } -} - -/// [`split_context`] for the field `name`, refusing a context that is not -/// a label, optionally extended, as that field's. -fn field_context( - name: &str, - piece: &ContextPiece<'_>, -) -> Result<(Label, Vec>), Error> { - split_context(piece).ok_or_else(|| Error::bad_plan(Reason::ContextNotLabel).in_field(name)) -} - -/// A refusal of the lowering or the engine's own check, as the field it -/// names and the nearest [`Reason`]. Matched exhaustively, so a new -/// [`PlanError`](crate::PlanError) says here which reason it reads as; an -/// engine failure that is not a plan refusal is [`Reason::Refused`]. -fn refusal(error: crate::Error) -> (Option, Reason) { - use crate::PlanError as P; - let crate::Error::Plan(error) = error else { - return (None, Reason::Refused); - }; - match error { - P::ContextLabel(_) => (None, Reason::ContextNotLabel), - P::FieldLabel { field, .. } => (Some(field), Reason::ContextNotLabel), - P::DuplicateField { field } => (Some(field), Reason::DuplicateField), - P::SharedIdentity { second, .. } => (Some(second), Reason::SharedIdentity), - P::DuplicateIndex { at, .. } => (Some(at), Reason::DuplicateOutput), - P::IndexOverlap { at, .. } => (Some(at), Reason::OverlappingOutputs), - P::EmptyIndexes => (None, Reason::NoOutputs), - P::NotInPlan { field } => (Some(field), Reason::UnknownField), - P::NotInValue { field } => (Some(field), Reason::FieldMissing), - P::FieldType { field, .. } => (Some(field), Reason::FieldType), - P::NoSuchField { field } => (Some(field), Reason::NoSuchField), - P::BindInQuery => (None, Reason::BindInQuery), - P::EmptyPart => (None, Reason::EmptyBinding), - P::TwoContextSources { .. } | P::ContextNotStorable { .. } => (None, Reason::Refused), - } -} - -/// A record plan: the fields a record has, each with what to call it, what -/// label to seal it under, and what to produce for it. -/// -/// Opaque, because the operations over a plan rely on properties of the -/// whole that no single [`FieldPlan`] can carry: there is at least one -/// field, no two fields share a name, every field's label sits under the -/// one plan context (or, under a context field, is its identity alone) and -/// carries the one extension, and no two keyed fields share an identity, -/// so the whole composes. Both the parser ([`plan`]) and the -/// manual constructors ([`Plan::new`], [`Plan::with_context_field`]) go -/// through the one check, so a plan in hand is a plan that holds them, -/// whichever way it was built. -#[derive(Clone, Debug)] -pub struct Plan { - context: Context, - extension: Vec>, - /// The caller's bindings, in order: in the stored context of every - /// field, after the scopes, and in no query context. The plan-level - /// `"bind"` key. - bindings: Vec>, - fields: Vec, -} - -/// Where a data plan takes its context from: the plan, or a field of each -/// record. A binding names the context in the declaration it sends. -#[derive(Clone, Debug)] -pub(super) enum Context { - /// The plan's own label, which every field's label extends. - Label(Label), - /// The named field of each record, whose value is the context. - Field(String), -} - -impl Plan { - /// A plan over `fields`, in the order given — which is the order of the - /// fields in every result — under the context every field's label - /// shares, for a build without EQL types: [`new_with`](Self::new_with) - /// under [`NoTargets`], so a field that names a target is refused. - /// - /// # Errors - /// - /// As [`new_with`](Self::new_with). - pub fn new(fields: Vec) -> Result { - Self::new_with(fields, &NoTargets) - } - - /// A plan over `fields`, in the order given — which is the order of the - /// fields in every result — under the context every field's label - /// shares, resolving each target field's name through `resolver`. - /// - /// # Errors - /// - /// [`Error::Plan`] if `fields` is empty, names a field twice, has a - /// field whose label has fewer than two segments, has fields whose - /// labels sit under different contexts or carry different extensions, - /// or does not build as a fields plan: two sealed or indexed fields - /// keyed under one identity, for instance, whose terms would be - /// interchangeable. [`Error::UntypedIndex`], naming the field, if a field - /// with a term output declares no type: every constructor shares that - /// rule, so a parsed and a hand-built plan are refused alike. - /// [`Error::Target`] if a target field names a type the - /// resolver does not know or cannot produce, declares a `"type"` other - /// than the kind that type is produced from, or has a label that is not - /// a column. - pub fn new_with( - mut fields: Vec, - resolver: &(impl TargetResolver + ?Sized), - ) -> Result { - let Some(first) = fields.first() else { - return Err(Error::bad_plan(Reason::NoFields)); - }; - let context = first.prefix()?; - for field in &fields { - // `prefix` refuses a one-segment label, which has nothing to - // sit under; a longer one must sit under the first field's. - if field.prefix()? != context { - return Err(Error::bad_plan(Reason::MixedContexts).in_field(&field.name)); - } - } - for field in fields.iter_mut().filter(|field| field.is_target()) { - let name = field.target.clone().unwrap_or_default(); - let descriptor = resolver.resolve(&name)?; - // An EQL value is stored under a table and a column, so the - // label is exactly two segments. Decided here, where the plan is - // built and se_plan_check reports it, not at the first value: a - // generator that asks the engine must be told before it writes - // the code. The resolver re-checks, since it is public API. - if field.label.segments().len() != 2 { - return Err(TargetError::Column { - name: field.name.clone(), - label: field.label.to_string(), - reason: "an EQL column is a two-segment label: table and column".to_owned(), - } - .into()); - } - match (field.field_type, descriptor.plaintext) { - (Some(declared), expected) if expected != Some(declared) => { - return Err(TargetError::Kind { - name: field.name.clone(), - target: name, - expected, - declared, - } - .into()); - } - (None, Some(kind)) => field.field_type = Some(kind), - _ => {} - } - // A target takes the options of the index it carries, the JSON - // index's alone today. Defaults are filled in here, once, so - // every write, query and read of the field runs under one - // resolved definition. - let carries_json = descriptor - .indexes - .iter() - .any(|index| index == IndexSpec::Json(Default::default()).key()); - field.target_options = match (field.target_options.take(), carries_json) { - (None, false) => None, - (None, true) => Some(TargetOptions::Json(Default::default())), - (Some(TargetOptions::Json(options)), true) => { - options.check().map_err(|_| { - Error::bad_plan(Reason::InvalidTarget).in_field(&field.name) - })?; - Some(TargetOptions::Json(options)) - } - (Some(_), false) => { - return Err(Error::bad_plan(Reason::TargetOptions).in_field(&field.name)) - } - }; - // A null has an equality term and no other, so a sealed null - // needs a type whose terms are equality's alone. - if field.null == Some(NullMode::Sealed) - && descriptor - .indexes - .iter() - .any(|index| index != IndexSpec::Equality.key()) - { - return Err(Error::bad_plan(Reason::SealedNullIndex).in_field(&field.name)); - } - } - Self::build(Context::Label(context), fields) - } - - /// A plan over `fields` that takes its context from the field named - /// `context_field`. That - /// field's value in each record is the context every other field is - /// sealed under, and the field is carried as a passthrough of type - /// string. Each field's label is its identity alone, a one-segment - /// label, optionally extended; see the - /// [module docs](self#a-plan-whose-context-is-a-field-of-the-record). - /// - /// # Errors - /// - /// [`Error::Plan`] as [`new`](Self::new) refuses, and if no field is - /// named `context_field`, that field asks for anything but - /// [`Output::Passthrough`] (a context is not sealed, and indexing it - /// would derive a term from a value that is not secret), declares a - /// type other than [`ValueKind::String`], or any field's label has - /// more than one segment. [`Error::UntypedIndex`], naming the field, as - /// [`new_with`](Self::new_with) refuses. [`Error::Target`] - /// ([`TargetError::ContextField`]) if a field names an EQL type as its - /// target: an EQL value is stored under a table the declaration fixes, - /// and a plan with a context field has none. - pub fn with_context_field( - context_field: impl Into, - fields: Vec, - ) -> Result { - let context_field = context_field.into(); - let refuse = |reason| Error::bad_plan(reason).in_field(&context_field); - let Some(field) = fields.iter().find(|field| field.name == context_field) else { - return Err(refuse(Reason::NoSuchField)); - }; - if field.outputs != [Output::Passthrough] - || field - .field_type - .is_some_and(|kind| kind != ValueKind::String) - { - return Err(refuse(Reason::ContextField)); - } - if let Some(field) = fields - .iter() - .find(|field| field.label.segments().count() != 1) - { - return Err(Error::bad_plan(Reason::ContextNotLabel).in_field(&field.name)); - } - // A target field's label must be a column, `
/`, - // which a context field's one-segment identity is not: the table - // is each record's own, and an EQL value stores one fixed by the - // declaration. - if let Some(target) = fields.iter().find(|field| field.is_target()) { - return Err(TargetError::ContextField { - name: target.name.clone(), - context_field, - } - .into()); - } - let fields = fields - .into_iter() - .map(|mut field| { - if field.name == context_field { - // A string whether or not the declaration says so: the - // value is read as a label, and the opener checks the - // stored one is text before any key is requested. - field.field_type = Some(ValueKind::String); - } - field - }) - .collect(); - Self::build(Context::Field(context_field), fields) - } - - /// The rules both constructors share: fields named once, one extension, - /// every field with a term output typed, no two keyed fields under one - /// identity. - fn build(context: Context, fields: Vec) -> Result { - let Some(first) = fields.first() else { - return Err(Error::bad_plan(Reason::NoFields)); - }; - let extension = first.extension.clone(); - for (at, field) in fields.iter().enumerate() { - let refuse = |reason| Error::bad_plan(reason).in_field(&field.name); - if fields[..at].iter().any(|prior| prior.name == field.name) { - return Err(refuse(Reason::DuplicateField)); - } - if field.extension != extension { - return Err(refuse(Reason::MixedContexts)); - } - if let Some(reason) = field.null_refusal() { - return Err(refuse(reason)); - } - // A JSON document is stored through a target that stores one; - // a target's options belong to a target. - if !field.is_target() && field.field_type == Some(ValueKind::Json) { - return Err(refuse(Reason::JsonNeedsTarget)); - } - if !field.is_target() && field.target_options.is_some() { - return Err(refuse(Reason::TargetOptions)); - } - // An indexed field declares its type: every value's term derives - // from the one declared kind, never from whatever tag each value - // arrived with. A target field's kind is the type's own. - if !field.is_target() && !field.indexes().is_empty() && field.field_type.is_none() { - return Err(Error::UntypedIndex { - field: field.name.clone(), - }); - } - // Two fields that key something, sealed or indexed or a target, - // cannot share one identity: their data would share one - // descriptor. A passthrough keys nothing (the context field is - // one), so two may share a label, and one may share a sealed - // field's. A target shares with nothing. - let keys = |f: &FieldPlan| f.verb() != Verb::Passthrough; - if fields[..at].iter().any(|prior| { - prior.identity() == field.identity() - && (prior.is_target() || field.is_target() || (keys(prior) && keys(field))) - }) { - return Err(refuse(Reason::SharedIdentity)); - } - } - let plan = Self { - context, - extension, - bindings: Vec::new(), - fields, - }; - Ok(plan) - } - - /// The plan's fields, in result order. Never empty, and no two share a - /// name. Under a context field, that field is among them. - pub fn fields(&self) -> &[FieldPlan] { - &self.fields - } - - /// The plan's one context: the label every field's label extends. - /// `None` for a plan that takes its context from a field - /// ([`context_field`](Self::context_field)). - pub fn label(&self) -> Option<&Label> { - match &self.context { - Context::Label(label) => Some(label), - Context::Field(_) => None, - } - } - - /// The field the plan takes its context from, if it has one. - pub fn context_field(&self) -> Option<&str> { - match &self.context { - Context::Field(name) => Some(name), - Context::Label(_) => None, - } - } - - /// The parts every field's label is extended by, in order; empty when - /// the declaration carries none. - pub fn extension(&self) -> &[ContextPiece<'static>] { - &self.extension - } - - /// The contexts this plan's fields are sealed and indexed under, with - /// the plan's extension applied and a placeholder for a context read - /// from a field of each record. No key is requested. The same view as - /// a derived record's `contexts()`, so a binding can show a record's - /// contexts, and a test in that language can pin them. - /// - /// # Errors - /// - /// Unreachable for a plan from [`plan`], [`Plan::new`] or - /// [`Plan::with_context_field`]: a parsed plan always composes. - pub fn contexts(&self) -> Result { - let shapes = self.placed(compose::<()>(self, &Absent::new())?.shapes()); - Ok(crate::contexts::resolve( - crate::contexts::under_declared(shapes, &self.declared_context()), - crate::contexts::CallerShape::none(), - )) - } - - /// The shape of every field's context, in plan order: the `lowered` - /// fields' shapes, and each target field under its label, then the - /// context it is handed. The resolver runs an EQL type under its label - /// and the plan's parts, as the lowering runs a field with outputs, so - /// the two kinds of field show the same parts. - fn placed(&self, lowered: crate::contexts::Shapes) -> crate::contexts::Shapes { - let mut lowered = lowered.into_iter().peekable(); - let mut shapes = crate::contexts::Shapes::with_capacity(self.fields.len()); - for field in &self.fields { - if field.is_target() { - shapes.push(crate::contexts::leaf_under( - &field.name, - field.label.clone().into_context(), - )); - continue; - } - while lowered - .peek() - .is_some_and(|leaf| leaf.name() == Some(field.name.as_str())) - { - shapes.extend(lowered.next()); - } - } - shapes.extend(lowered); - shapes - } - - /// Where this plan takes its context from. - pub(super) fn context_source(&self) -> &Context { - &self.context - } - - /// This plan with the caller's bindings `parts`, each in the stored - /// context of every field after the scopes, and in no query context. - /// What a binding's `"bind"` key carries. - /// - /// # Errors - /// - /// [`Error::Plan`] with [`Reason::EmptyBinding`] for an empty part: a - /// row ID not yet assigned would bind every row to one context, and - /// the typed path refuses the same. - pub fn with_bindings(mut self, parts: Vec>) -> Result { - if parts.iter().any(crate::MaybeEmpty::is_empty) { - return Err(Error::bad_plan(Reason::EmptyBinding)); - } - self.bindings = parts; - Ok(self) - } - - /// The caller's bindings, in order. Empty for a plan with none. - pub fn bindings(&self) -> &[ContextPiece<'static>] { - &self.bindings - } - - /// Add a caller's scopes to this plan. Each scope becomes one more part - /// at the end of every field's context, after the parts the plan - /// already has, in the order given. A scoped call runs the plan this - /// returns. So a field is sealed and indexed under its label, then the - /// plan's own extension, then the scopes. A call with no scope borrows - /// the plan instead, and copies nothing. - /// - /// A field that names an EQL type is scoped as any other field is. Its - /// EQL value stores its table and column, and not the scope. - /// - /// The scope shows in the context of the call. Here a record under a - /// one-field plan is encrypted under the scope `42u64`: - /// - /// ``` - /// use stack_encrypt::dynamic::{record, Planned, frame::OwnedFrame}; - /// use stack_encrypt::target::Scope; - /// use stack_encrypt::{AsProtectedRef, EncryptInto, Pending, StackCipher, StackCipherText}; - /// use recipher_frame::serde::to_vec; - /// - /// # 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 = to_vec(&serde_json::json!({ - /// "email": { "context": ["users", "email"], "outputs": ["c"], "type": "string" }, - /// }))?; - /// let plan = record::plan(declaration.as_protected_ref())?; - /// let values = OwnedFrame::from_buffer(to_vec(&serde_json::json!({"email": "ada@example.com"}))?)?; - /// let call: Pending<'_, StackCipherText, _> = - /// Planned::new(&plan, values).encrypt_into_with_context(&keyset, Scope::new(42u64)); - /// // The field's context is its label, then the scope. - /// # #[cfg(feature = "testing")] - /// stack_encrypt::assert_context!(call.context(), [["users", "email"], 42u64]); - /// let _row = call.await?; - /// # Ok::<(), Box>(()) - /// # }).unwrap(); - /// ``` - /// - /// # Errors - /// - /// [`Error::Plan`] with [`Reason::EmptyContext`] for an empty part. - pub(super) fn with_scopes( - mut self, - parts: impl IntoIterator>, - ) -> Result { - let parts: Vec<_> = parts.into_iter().collect(); - if parts.iter().any(crate::MaybeEmpty::is_empty) { - return Err(Error::bad_plan(Reason::EmptyContext)); - } - for field in &mut self.fields { - for part in &parts { - field.extend(part.clone()); - } - } - self.extension.extend(parts); - Ok(self) - } - - /// The shapes of every field's leaf, run under this plan's context and - /// then the context the caller hands a [`Planned`] - /// record. - pub(super) fn caller_shapes(&self) -> Result { - Ok(crate::contexts::under_declared_then_caller( - self.placed(compose::<()>(self, &Absent::new())?.shapes()), - &self.declared_context(), - )) - } - - /// The scopes every field's label is run under: the extension. A - /// query runs under these alone. - fn scopes(&self) -> DeclaredContext { - self.extension - .iter() - .cloned() - .fold(DeclaredContext::default(), |context, part| { - context.with(CallerContext::from_piece(part)) - }) - } - - /// The context every field's label is run under: the scopes, then the - /// bindings. - pub(super) fn declared_context(&self) -> DeclaredContext { - self.bindings - .iter() - .cloned() - .fold(self.scopes(), |context, part| { - context.with(CallerContext::bind_piece(part)) - }) - } - - pub(super) fn shape(&self) -> Vec { - self.fields.iter().map(FieldPlan::shape).collect() - } - - /// The fields that name a target, in plan order: the resolver's. - pub(super) fn target_fields(&self) -> impl Iterator + '_ { - self.fields.iter().filter(|field| field.is_target()) - } -} - -/// Read a record plan from its frame, for a build without EQL types: -/// [`plan_with`] under [`NoTargets`], so a field that names a `"target"` is -/// refused ([`TargetError::NoTargets`]). -/// -/// # Errors -/// -/// As [`plan_with`]. -pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result { - plan_with(frame, &NoTargets) -} - -/// Read a record plan from its frame, resolving each target field's name -/// through `resolver`. -/// -/// The plan is a frame object, read by serde -/// (`recipher_frame::serde`): -/// -/// ```text -/// { : { "context": , "outputs": [ "c" | "passthrough" | , ... ], "type": }, ... } -/// ``` -/// -/// with one optional key beside the field specs, `"context_field": -/// ""`, which makes the plan take its context from that field -/// of each record ([`Plan::with_context_field`]; the -/// [module docs](self#a-plan-whose-context-is-a-field-of-the-record) give -/// the shape), and one more, `"bind": [, ...]`, the caller's -/// bindings ([`Plan::with_bindings`]). Both keys are reserved: a top-level -/// `"context_field"` whose value is not a string, or a `"bind"` whose -/// value is not a list of context parts, is refused rather than read as a -/// field of that name ([`Reason::ContextField`], [`Reason::Bind`]). -/// -/// A field may name an EQL type as its target instead of outputs: -/// -/// ```text -/// { : { "context": , "target": "", "type": }, ... } -/// ``` -/// -/// A field has `"outputs"` or `"target"`, never both. `"target"` is the -/// type's name as the resolver lists it (`"TextEq"`), resolved when the plan -/// is built so a name the build cannot run fails here and not at the first -/// value; its `"type"`, when given, must be the kind the type is produced -/// from. See the [module docs](self#a-field-that-names-an-eql-type). A -/// target field needs a column for its label, so it is refused under a -/// context field ([`TargetError::ContextField`]). -/// -/// `"target"` may instead be an object of the name and the options of the -/// index the type carries: a type that stores a JSON document -/// (`JsonSearch`) takes the JSON index's options object, as the -/// `{"json": ...}` output spells it, and no other type takes any. -/// -/// ```text -/// "target": { "name": "JsonSearch", -/// "options": { "sealed_root": , "ordered": [, ...] } } -/// ``` -/// -/// Such a field declares the `"json"` type (or leaves it to the target), -/// hands each document over as UTF-8 JSON text, and stores a null as SQL -/// `NULL` (`"null": "sql"`): a document has no length to pad. -/// -/// `` is an index in its wire form, which is its key — `"eq"`, -/// `"match"`, `"ore"` or `"ope"` — save for a match index with options other -/// than the defaults, which is a one-entry object mapping `"match"` to them: -/// -/// ```text -/// { "match": { "tokenizer": "standard" | { "ngram": }, -/// "downcase": , "short_words": , -/// "k": , "m": } } -/// ``` -/// -/// A bare `"match"` is the default options ([`MatchOptions::default`]: -/// 3-grams, downcased, no short-word tokens, `k = 3`, `m = 256`), so a plan -/// written before options had a wire form means what it always meant. In -/// the object form each option is optional and defaults the same way; an -/// unknown or repeated option, or a set the match scheme refuses (`k` -/// outside `3..=16`, `m` not a power of two in `32..=65536`, a zero n-gram -/// length, `short_words` beside the standard tokenizer or an n-gram length -/// under 3), is refused. The -/// other three indexes have no options and no object form. A field names -/// each output key at most once, so it carries at most one match index. -/// [`IndexSpec`] serializes to this form and [`IndexSpec::from_frame`] -/// reads it. `"passthrough"` is a field's only output when it has it. -/// -/// [`MatchOptions::default`]: crate::sem::MatchOptions::default -/// -/// `"type"` names a [`ValueKind`] (`"int64"`, `"string"`, …; see -/// [`ValueKind::name`]): vitaminc's vocabulary, not one of this crate's. It -/// is **required on every field with a term output** (`"eq"`, `"match"`, -/// `"ore"`, `"ope"`): the field's terms derive from that one kind, and every -/// value is checked against it on the way in and on the way out, so a -/// binding is never trusted to have tagged each value alike (a `34` sent once -/// as a `Float64` and once as an `Int64` would store two terms under one -/// field). A field with term outputs and no `"type"` is refused when the plan -/// is built ([`Error::UntypedIndex`], naming the field). It is optional on a -/// field whose only output is `"c"` or -/// `"passthrough"`, and on a target field, whose kind is the EQL type's own. -/// Declared, it is checked against the field's outputs here ([`admits`](super::admits)) and -/// decides nothing about the bytes (see the -/// [module docs](self#what-a-fields-type-decides-and-what-it-does-not)). -/// -/// `"null"`, when given, is `"sealed"` or `"sql"`: how the field stores a -/// value that is not there ([`NullMode`]). Without it a row must -/// have the field, and a typed field refuses a null. `"sealed"` seals a -/// null as a typed null as long as a value, so the stored record does not -/// show it, and beside an equality index stores a null's equality term, the -/// one every null of the field shares, which an `eq` query of a null finds. -/// The field must declare a type of fixed width: a bool, a number, a date, a -/// timestamp, a decimal, or a UUID. Equality must be the only index of the -/// field, or of a target field's EQL type. `"sql"` stores nothing for a null -/// or a missing field, so the host's columns hold SQL `NULL`; any field but -/// a passthrough takes it. -/// -/// `` is read by [`super::context`](super::context()) and must be -/// the field's label, optionally extended; the -/// [module docs](self#what-a-fields-context-must-be) give the shape. -/// -/// # Examples -/// -/// ``` -/// use stack_encrypt::dynamic::{record, NoTargets, Output}; -/// use stack_encrypt::target::IndexSpec; -/// use stack_encrypt::AsProtectedRef; -/// -/// // As a binding sends it: seal `age` under the label users/age and index -/// // it for equality. -/// let frame = recipher_frame::serde::to_vec(&serde_json::json!({ -/// "age": { -/// "context": ["users", "age"], -/// "outputs": ["c", "eq"], -/// "type": "uint32", -/// }, -/// }))?; -/// let plan = record::plan_with(frame.as_protected_ref(), &NoTargets)?; -/// -/// assert_eq!(plan.fields().len(), 1); -/// assert_eq!(plan.fields()[0].name(), "age"); -/// assert_eq!(plan.label().map(ToString::to_string).as_deref(), Some("users")); -/// assert_eq!( -/// plan.fields()[0].outputs(), -/// [Output::Ciphertext, Output::Term(IndexSpec::Equality)] -/// ); -/// # Ok::<(), Box>(()) -/// ``` -/// -/// # Errors -/// -/// [`Error::Plan`] for a plan that is not an object of field specs -/// (including bytes that are not one frame, which is how a field or key -/// given twice is refused: the frame refuses it), an empty plan, a spec with -/// a key other than `"context"`, `"outputs"`, `"target"`, `"type"` and -/// `"null"`, a `"null"` other than `"sealed"` or `"sql"`, a field that cannot -/// store a null as its `"null"` says ([`NullMode`]), -/// missing `"context"`, having neither `"outputs"` nor `"target"` or having -/// both, an output list that is not a list of outputs (above), is empty, -/// names an output key twice or names `"passthrough"` beside another -/// output, a `"target"` that is not a non-empty string, a `"type"` that is -/// not a string naming a [`ValueKind`], a type that does not admit one of -/// the field's index outputs, a context that is not a label of at least two -/// segments (optionally extended), fields under different contexts or -/// extensions, or a plan [`Plan::new`] refuses; with -/// `"context_field"`, a value that is not a string, naming no field of the -/// plan, or a plan [`Plan::with_context_field`] refuses. -/// [`Error::UntypedIndex`], naming the field, for a field with a term output -/// and no `"type"`. [`Error::Context`] for a `"context"` that is present but -/// is not a context at all, or renders empty. [`Error::Target`] for a -/// target the resolver refuses ([`Plan::new_with`]). -pub fn plan_with( - frame: vitaminc_protected::ProtectedRef<'_, [u8]>, - resolver: &(impl TargetResolver + ?Sized), -) -> Result { - let frame = frame.risky_ref(); - let wire: PlanWire = - recipher_frame::serde::from_slice(frame).map_err(|e| plan_refusal(&e, frame))?; - let mut fields: Vec = Vec::with_capacity(wire.fields.len()); - for (name, spec) in wire.fields { - let spec = - FieldSpec::try_from(spec).map_err(|reason| Error::bad_plan(reason).in_field(&name))?; - let context = super::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; - let field = match spec.what { - What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, - What::Target(target, options) => { - let field = FieldPlan::with_target(name, context, target)?; - match options { - Some(options) => field.with_target_options(options), - None => field, - } - } - }; - let field = match spec.field_type { - Some(KindName(field_type)) => field.with_type(field_type)?, - None => field, - }; - fields.push(match spec.null { - Some(NullName(null)) => field.with_null(null), - None => field, - }); - } - // The whole-plan rules are the constructors', so a parsed plan and a - // hand-built one are refused alike. - let plan = match wire.context_field { - Some(name) => Plan::with_context_field(name, fields), - None => Plan::new_with(fields, resolver), - }?; - // The grammar's `bind` is a nonempty list of scalar parts: an explicit - // empty list is not an absent key, and a grouped part is not a part Go - // can supply through `Bind`. - match wire.bindings { - None => Ok(plan), - Some(parts) if parts.is_empty() => Err(Error::bad_plan(Reason::EmptyBinding)), - Some(parts) - if parts - .iter() - .any(|part| matches!(part, ContextPiece::List(_))) => - { - Err(Error::bad_plan(Reason::Bind)) - } - Some(parts) => plan.with_bindings(parts), - } -} - -/// A plan as a binding writes it: an object of field specs, in order, with -/// two reserved keys beside them, `"context_field"` and `"bind"`. A visitor -/// only to tell those keys from a field's name; every value below it is -/// derived. -struct PlanWire { - context_field: Option, - /// `None` when the plan has no `"bind"` key: an explicit empty list is - /// kept apart from an absent key, and refused. - bindings: Option>>, - fields: Vec<(String, FieldSpecWire)>, -} - -impl<'de> Deserialize<'de> for PlanWire { - fn deserialize>(d: D) -> Result { - struct V; - impl<'de> Visitor<'de> for V { - type Value = PlanWire; - fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("a plan: an object of field specs") - } - fn visit_map>(self, mut map: A) -> Result { - let mut plan = PlanWire { - context_field: None, - bindings: None, - fields: Vec::with_capacity(super::context::reserved(map.size_hint())), - }; - while let Some(name) = map.next_key::<&'de str>()? { - if name == CONTEXT_FIELD { - plan.context_field = Some(map.next_value()?); - } else if name == BIND { - let parts: Vec = map.next_value()?; - plan.bindings = Some(parts.into_iter().map(|part| part.0).collect()); - } else { - plan.fields.push((name.to_owned(), map.next_value()?)); - } - } - Ok(plan) - } - } - d.deserialize_map(V) - } -} - -/// The key of the `position`th entry of the object `frame` holds, or `None` -/// when it is not an object of that many entries. -fn entry_key(frame: &[u8], position: usize) -> Option { - let root = Frame::parse(frame).ok()?; - super::found::object_keys(root)?.into_iter().nth(position) -} - -/// The keys a field's spec reads ([`FieldSpecWire`]). -const SPEC_KEYS: [&str; 5] = ["context", "outputs", "target", "type", "null"]; - -/// The plan-level key naming the field a plan takes its context from. -const CONTEXT_FIELD: &str = "context_field"; -/// The plan-level key listing the caller's bindings: a list of parts, each -/// a context as [`context`](super::context()) reads one. -const BIND: &str = "bind"; - -/// One field's spec: a context, and exactly one of `"outputs"` and -/// `"target"` (checked in `TryFrom`, once the field's name is known, so the -/// refusal names it), and optionally a `"type"`. A key that is present must -/// hold its kind of value: a null is refused. -struct FieldSpec { - context: super::context::Context, - what: What, - field_type: Option, - null: Option, -} - -enum What { - Outputs(Vec), - Target(String, Option), -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct FieldSpecWire { - context: super::context::Context, - #[serde(default, deserialize_with = "present")] - outputs: Option>, - #[serde(default, deserialize_with = "present")] - target: Option, - #[serde(default, deserialize_with = "present", rename = "type")] - field_type: Option, - #[serde(default, deserialize_with = "present")] - null: Option, -} - -impl TryFrom for FieldSpec { - type Error = Reason; - - fn try_from(wire: FieldSpecWire) -> Result { - let what = match (wire.outputs, wire.target) { - (Some(outputs), None) => What::Outputs(outputs.into_iter().map(Output::from).collect()), - (None, Some(TargetWire::Name(target))) => What::Target(target, None), - (None, Some(TargetWire::Configured(ConfiguredTarget { name, options }))) => { - What::Target(name, options.map(|options| TargetOptions::Json(options.0))) - } - (Some(_), Some(_)) => return Err(Reason::OutputsWithTarget), - (None, None) => return Err(Reason::MissingOutputs), - }; - Ok(FieldSpec { - context: wire.context, - what, - field_type: wire.field_type, - null: wire.null, - }) - } -} - -/// A field's `"target"`: the target's name, which runs it under its -/// defaults, or an object of its name and its options, which are the -/// options of the index the target carries (the JSON index's options -/// object, as an output spells it). -/// -/// The options are read in the JSON index's grammar whatever the target, -/// since that is the only grammar any target takes, and the target is -/// resolved after: options that are not that grammar (`{"x": 1}`) make -/// the target unreadable ([`Reason::InvalidTarget`]), and well-formed -/// options on a target that takes none (`{}` on `TextEq`) are -/// [`Reason::TargetOptions`]. Both refuse the plan before anything is -/// sealed. -#[derive(Deserialize)] -#[serde(untagged)] -enum TargetWire { - Name(String), - Configured(ConfiguredTarget), -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct ConfiguredTarget { - name: String, - #[serde(default, deserialize_with = "present")] - options: Option, -} - -/// Absent is `None`. Present, a value must be of its kind: a null is -/// refused, as any other value of the wrong kind is. -fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { - T::deserialize(d).map(Some) -} - -/// One entry of a field's `"outputs"`: `"c"`, `"passthrough"`, or an index -/// in its wire form ([`IndexSpec`'s docs](IndexSpec#wire-form)). -#[derive(Deserialize)] -#[serde(rename_all = "lowercase")] -enum OutputWire { - #[serde(rename = "c")] - Ciphertext, - Passthrough, - Eq, - Match(Option), - Ore, - Ope, - #[serde(rename = "ore_block")] - OreBlock, - Json(Option), -} - -impl From for Output { - fn from(output: OutputWire) -> Self { - let index = match output { - OutputWire::Ciphertext => return Output::Ciphertext, - OutputWire::Passthrough => return Output::Passthrough, - OutputWire::Eq => IndexWire::Eq, - OutputWire::Match(options) => IndexWire::Match(options), - OutputWire::Ore => IndexWire::Ore, - OutputWire::Ope => IndexWire::Ope, - OutputWire::OreBlock => IndexWire::OreBlock, - OutputWire::Json(options) => IndexWire::Json(options), - }; - Output::Term(index.into()) - } -} - -/// A `"type"`: the name of a [`ValueKind`]. -#[derive(Deserialize)] -#[serde(try_from = "&str")] -struct KindName(ValueKind); - -impl TryFrom<&str> for KindName { - type Error = Reason; - - fn try_from(name: &str) -> Result { - name.parse().map(KindName).map_err(|_| Reason::UnknownType) - } -} - -/// A `"null"`: the name of a [`NullMode`]. -#[derive(Deserialize)] -#[serde(try_from = "&str")] -struct NullName(NullMode); - -impl TryFrom<&str> for NullName { - type Error = Reason; - - fn try_from(name: &str) -> Result { - match name { - "sealed" => Ok(NullName(NullMode::Sealed)), - "sql" => Ok(NullName(NullMode::Sql)), - _ => Err(Reason::UnknownNull), - } - } -} - -/// The parser's refusal of a plan the frame reader refused: the field from -/// the error's path, and the reason from where in the field it happened, -/// or from the reason a field's own rule gave. -fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { - use recipher_frame::serde::PathSegment::{Entry, Key}; - - let path = error.path(); - // A plan's keys are the host's, so the adapter places an error under one - // by its position, never its text; the field is read back from the - // frame that was refused. - let field = match path.first() { - Some(Entry(position)) => entry_key(frame, *position), - _ => None, - }; - let Some(field) = field else { - // The error is at the root of the plan. Either the bytes are not - // one frame, or the frame is not an object. - return match Frame::parse(frame) { - Err(_) => Error::bad_plan(Reason::NotAFrame), - Ok(root) => Error::Plan { - field: None, - reason: Reason::NotAnObject, - found: Some(Found::of_frame(root)), - }, - }; - }; - let field = &field; - if field == CONTEXT_FIELD { - return Error::bad_plan(Reason::ContextField); - } - if field == BIND { - return Error::bad_plan(Reason::Bind); - } - let reason = match path.get(1) { - Some(Key(key)) if key == "context" => { - return Error::bad_context(Reason::ContextKind).in_field(field) - } - Some(Key(key)) if key == "outputs" && path.len() == 2 => Reason::OutputsNotList, - Some(Key(key)) if key == "outputs" => Reason::UnknownOutput, - Some(Key(key)) if key == "target" => Reason::InvalidTarget, - Some(Key(key)) if key == "null" => Reason::UnknownNull, - // `"type"`: the one other key a spec reads, and so the only other - // key an error inside a spec's value is placed under (an unknown - // key is never on the path). - Some(_) => Reason::UnknownType, - // The error is at the field spec itself. There are three possible - // causes: the spec is not an object, the spec has a key that a spec - // does not take, or the spec has no context. The code decides - // between them from the kind of the spec and from its keys. The - // code does not read the text of the error, so a change to that - // text cannot change the reason. - // - // An object with only known keys must lack its context, because - // nothing else fails at this level: - // - An error in the value under a key is reported under that key. - // - A frame never contains a repeated key. - // - The rule that a spec has outputs or a target is checked after - // parsing. - None => match Frame::parse(frame) - .ok() - .and_then(|root| Found::of_entry(root, field)) - { - Some((Found::Kind(ValueKind::Object), keys)) => { - if keys.iter().any(|key| !SPEC_KEYS.contains(&key.as_str())) { - Reason::UnknownKey - } else { - Reason::MissingContext - } - } - found => { - return Error::Plan { - field: Some(field.clone()), - reason: Reason::NotAnObject, - found: found.map(|(found, _)| found), - } - } - }, - }; - Error::bad_plan(reason).in_field(field) -} +use super::plan::refusal; +pub use super::plan::{plan, plan_with, FieldPlan, NullMode, Output, Plan, EQL_KEY}; +pub(super) use super::plan::{Context, Verb}; /// Encrypt a record — or a batch of records — per a plan. /// @@ -1787,20 +310,20 @@ pub fn query<'a, K: 'static>( resolver: &(impl TargetResolver + ?Sized), ) -> Result, K>, Error> { let field = plan - .fields + .fields() .iter() - .find(|candidate| candidate.name == field) + .find(|candidate| candidate.name() == field) .ok_or_else(|| Error::bad_plan(Reason::NoSuchField).in_field(field))?; let name = field .target() - .ok_or_else(|| Error::bad_plan(Reason::NotATarget).in_field(&field.name))?; + .ok_or_else(|| Error::bad_plan(Reason::NotATarget).in_field(field.name()))?; let value = OwnedFrame::of(value) - .map_err(|_| Error::bad_source(Reason::FieldType).in_field(&field.name))?; + .map_err(|_| Error::bad_source(Reason::FieldType).in_field(field.name()))?; // A null is queried by the term a field that seals its nulls stores // beside each (#1298), through the type's equality index alone. let value = if value.frame().is_null() { - if field.null != Some(NullMode::Sealed) || *index != IndexSpec::Equality { - return Err(Error::bad_source(Reason::NullQuery).in_field(&field.name)); + if field.null() != Some(NullMode::Sealed) || *index != IndexSpec::Equality { + return Err(Error::bad_source(Reason::NullQuery).in_field(field.name())); } value } else { @@ -1815,7 +338,7 @@ pub fn query<'a, K: 'static>( &plan.scopes(), value.frame(), ) - .map_err(|error| Error::Target(name_target(error, &field.name))) + .map_err(|error| Error::Target(name_target(error, field.name()))) } /// A resolver's refusal, with the field named where the resolver could not @@ -2163,11 +686,11 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { /// What the adapters know of a field once the engine has run. #[derive(Clone, Debug)] pub(super) struct FieldShape { - name: String, - verb: Verb, - keys: Vec<&'static str>, - kind: Option, - null: Option, + pub(super) name: String, + pub(super) verb: Verb, + pub(super) keys: Vec<&'static str>, + pub(super) kind: Option, + pub(super) null: Option, } /// A slot of the record the engine built from the plan, at the type the @@ -2425,19 +948,19 @@ fn record_row( let mut values = FieldValues::new(); let mut targets = Vec::new(); let mut absent = Absent::new(); - for field in plan.fields.iter().filter(|field| field.opens()) { - let misfit = |reason| StackCipherText::misfit(&field.name, reason); - let Some((_, node)) = take(&mut row, &field.name) else { + for field in plan.fields().iter().filter(|field| field.opens()) { + let misfit = |reason| StackCipherText::misfit(field.name(), reason); + let Some((_, node)) = take(&mut row, field.name()) else { let reason = absence( &row, - &field.name, + field.name(), Reason::FieldMissing, Reason::FieldRepeated, ); // A `"null": "sql"` field left out of the record was null when // it was stored: it opens as a null. - if reason == Reason::FieldMissing && field.null == Some(NullMode::Sql) { - let _ = absent.insert(field.name.clone()); + if reason == Reason::FieldMissing && field.null() == Some(NullMode::Sql) { + let _ = absent.insert(field.name().to_owned()); continue; } return Err(misfit(reason)); @@ -2471,17 +994,17 @@ fn record_row( let value = passthrough_value(&payload).ok_or_else(|| misfit(Reason::NotPassthrough))?; if field - .field_type + .field_type() .is_some_and(|kind| !kind.holds(value.frame().kind())) { return Err(misfit(Reason::FieldType)); } - let _ = values.insert(&field.name, value); + let _ = values.insert(field.name(), value); } Verb::Encrypt | Verb::EncryptIndex | Verb::Index => { let ciphertext = node("c", Reason::NoCiphertextNode)?; - check_tree(&ciphertext, &field.name)?; - let _ = values.insert(&field.name, ciphertext); + check_tree(&ciphertext, field.name())?; + let _ = values.insert(field.name(), ciphertext); } } } diff --git a/packages/stack-encrypt/src/dynamic/record/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs index 5f219a73f..8b6e855ea 100644 --- a/packages/stack-encrypt/src/dynamic/record/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -151,23 +151,23 @@ fn source_record(mut row: RawFields, plan: &Plan) -> Result let mut values = FieldValues::new(); let mut targets = Vec::new(); let mut absent = Absent::new(); - for field in &plan.fields { - let Some((_, value)) = take(&mut row, &field.name) else { + for field in plan.fields() { + let Some((_, value)) = take(&mut row, field.name()) else { let reason = absence( &row, - &field.name, + field.name(), Reason::FieldMissing, Reason::FieldRepeated, ); - if reason == Reason::FieldMissing && field.null == Some(NullMode::Sql) { - let _ = absent.insert(field.name.clone()); + if reason == Reason::FieldMissing && field.null() == Some(NullMode::Sql) { + let _ = absent.insert(field.name().to_owned()); continue; } - return Err(misfit(&field.name, reason)); + return Err(misfit(field.name(), reason)); }; - let value = match field.null { + let value = match field.null() { Some(NullMode::Sql) if value.frame().is_null() => { - let _ = absent.insert(field.name.clone()); + let _ = absent.insert(field.name().to_owned()); continue; } // A null the field seals: as a typed null of its type, as long @@ -176,7 +176,7 @@ fn source_record(mut row: RawFields, plan: &Plan) -> Result // null on any other type, and on a field with a term other than // equality's, which a null has. Some(NullMode::Sealed) if value.frame().is_null() => { - match field.field_type.and_then(ValueKind::sealed_null) { + match field.field_type().and_then(ValueKind::sealed_null) { Some(SealedNull::Typed(ty)) => OwnedFrame::typed_null(ty), _ => value, } @@ -186,7 +186,7 @@ fn source_record(mut row: RawFields, plan: &Plan) -> Result if field.is_target() { targets.push(value); } else { - let _ = values.insert(&field.name, value); + let _ = values.insert(field.name(), value); } } // Every plan field is taken; anything left is a field the plan does not @@ -215,10 +215,10 @@ fn source_record(mut row: RawFields, plan: &Plan) -> Result /// too. What comes back is what is sealed: a value already of the type, /// as it came, or the converted one, with the value it came as wiped. pub(super) fn check_field(value: OwnedFrame, field: &FieldPlan) -> Result { - let misfit = |reason| Error::bad_source(reason).in_field(&field.name); - let value = match field.field_type { + let misfit = |reason| Error::bad_source(reason).in_field(field.name()); + let value = match field.field_type() { Some(declared) => convert(declared, value.frame()) - .map_err(|error| error.in_field(&field.name))? + .map_err(|error| error.in_field(field.name()))? .unwrap_or(value), None => value, }; @@ -231,10 +231,10 @@ pub(super) fn check_field(value: OwnedFrame, field: &FieldPlan) -> Result Result Date: Mon, 30 Nov 2026 23:23:20 +1100 Subject: [PATCH 14/23] refactor(stack-encrypt): FieldValues and IntoLabel move into dynamic Only the dynamic module uses them, so they move out of the top-level plan module, which now holds PlanError alone. IntoLabel's public path is now stack_encrypt::dynamic::IntoLabel. --- packages/stack-encrypt/src/dynamic/context.rs | 2 +- .../src/{plan => dynamic}/label.rs | 18 +++++++----------- packages/stack-encrypt/src/dynamic/mod.rs | 3 +++ packages/stack-encrypt/src/dynamic/planned.rs | 3 ++- packages/stack-encrypt/src/dynamic/record.rs | 4 ++-- .../stack-encrypt/src/dynamic/record/source.rs | 2 +- .../src/{plan => dynamic}/values.rs | 2 +- packages/stack-encrypt/src/plan/mod.rs | 17 ++++------------- packages/stack-encrypt/tests/plan_grammar.rs | 2 +- .../stack-encrypt/tests/record_lowering.rs | 2 +- 10 files changed, 23 insertions(+), 32 deletions(-) rename packages/stack-encrypt/src/{plan => dynamic}/label.rs (75%) rename packages/stack-encrypt/src/{plan => dynamic}/values.rs (99%) diff --git a/packages/stack-encrypt/src/dynamic/context.rs b/packages/stack-encrypt/src/dynamic/context.rs index 0a2ccff61..189a85edb 100644 --- a/packages/stack-encrypt/src/dynamic/context.rs +++ b/packages/stack-encrypt/src/dynamic/context.rs @@ -9,9 +9,9 @@ use serde::Deserialize; use vitaminc_aead::frame::{Frame, OwnedFrame}; use vitaminc_aead::plaintext::{Encrypt, Logical, Physical}; +use super::label::IntoLabel; use super::term::OneScalar; use super::{Error, Reason}; -use crate::plan::IntoLabel; use crate::{ContextPiece, Label, LabelError, NonEmpty}; /// A context arrives from a binding as a frame and becomes a diff --git a/packages/stack-encrypt/src/plan/label.rs b/packages/stack-encrypt/src/dynamic/label.rs similarity index 75% rename from packages/stack-encrypt/src/plan/label.rs rename to packages/stack-encrypt/src/dynamic/label.rs index 51a3be637..2cccf136d 100644 --- a/packages/stack-encrypt/src/plan/label.rs +++ b/packages/stack-encrypt/src/dynamic/label.rs @@ -8,7 +8,7 @@ use crate::{Label, LabelError}; /// `"users"`, or `"documents/v2/body"`, which is three segments and renders /// in the ZeroKMS log exactly as written. Text that is not a plain label is /// refused when the plan is parsed or run -/// ([`PlanError::ContextLabel`](super::PlanError::ContextLabel)). +/// ([`PlanError::ContextLabel`](crate::PlanError::ContextLabel)). pub trait IntoLabel { /// The label, or why the text is not one. fn into_label(self) -> Result; @@ -41,22 +41,18 @@ impl IntoLabel for &String { } /// Who supplied a context, for -/// [`PlanError::TwoContextSources`](super::PlanError::TwoContextSources). -#[cfg(feature = "dynamic")] -pub(crate) const FROM_PLAN: &str = "the plan"; -#[cfg(feature = "dynamic")] -pub(crate) const FROM_CALL: &str = "the call"; +/// [`PlanError::TwoContextSources`](crate::PlanError::TwoContextSources). +pub(super) const FROM_PLAN: &str = "the plan"; +pub(super) const FROM_CALL: &str = "the call"; /// The label a field is sealed under: the context, then its identity. -#[cfg(feature = "dynamic")] -pub(crate) fn join(context: &Label, identity: &str) -> Result { +pub(super) fn join(context: &Label, identity: &str) -> Result { Label::new(context.segments().chain([identity])) } /// The refusal of a field whose label is not plain. -#[cfg(feature = "dynamic")] -pub(crate) fn field_label(field: &str, source: LabelError) -> crate::Error { - super::PlanError::FieldLabel { +pub(super) fn field_label(field: &str, source: LabelError) -> crate::Error { + crate::PlanError::FieldLabel { field: field.to_owned(), source, } diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index f90590532..bbeaaa771 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -104,6 +104,7 @@ mod found; mod json; mod json_query; mod kind; +mod label; mod one_or_many; mod plan; pub mod planned; @@ -123,6 +124,7 @@ mod term; #[cfg(test)] mod test_frame; pub mod value; +mod values; /// The document a `json` field's value holds, as [`read_json`] returns it: /// [`crate::json::JsonPlaintext`], named here for a binding that reaches @@ -131,6 +133,7 @@ pub use crate::json::JsonPlaintext; pub use context::{borrowed, context}; pub use json::{json_frame, read_json, JsonValueError}; pub use kind::{admits, not_admitted, read}; +pub use label::IntoLabel; pub use planned::{DynamicQuery, FieldHandle, Planned, QueryPlan, QueryValue}; pub use query::{ check_json_open, check_query, field_operators, json_open, query_term, target_limit, verify, diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index a23eaaed3..b0464c26c 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -80,6 +80,7 @@ use std::sync::Arc; use zeroize::Zeroize; +use super::label::{field_label, join, IntoLabel, FROM_CALL, FROM_PLAN}; use super::one_or_many::OneOrMany; use super::query::{field_operators, find, query_term, QueryTerm}; use super::record::{ @@ -87,10 +88,10 @@ use super::record::{ Verb, }; use super::target::{NoTargets, TargetResolver}; +use super::values::{FieldValues, Slot}; use super::{Error, Op, Reason, TermBytes}; use crate::contexts::{self, CallerShape, Contexts, LeafContext, Placeholder}; use crate::kms::MaybeSend; -use crate::plan::{field_label, join, FieldValues, IntoLabel, Slot, FROM_CALL, FROM_PLAN}; use crate::target::{ ciphertext, indexed, inspect, open, AeadContext, Borrowed, CallerContext, DeclaredContext, DecryptSource, Decryption, EncryptTarget, Encrypted, Encryption, ExpectedContext, IndexSpec, diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index f50b4c4a4..23bd91329 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -160,8 +160,8 @@ use vitaminc_aead::Encrypt; use vitaminc_protected::{Controlled, Protected}; use super::planned::{check_stored, check_values, opening_base, Planned}; +use super::values::FieldValues; use super::{Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes}; -use crate::plan::FieldValues; #[cfg(test)] use crate::target::{CallerContext, DeclaredContext}; use crate::target::{Encrypted, IndexSpec}; @@ -1031,8 +1031,8 @@ mod tests { use vitaminc_aead::frame::MAX_DEPTH; use vitaminc_protected::Controlled; + use crate::dynamic::label::join; use crate::dynamic::term; - use crate::plan::join; use crate::sem::EqualityTerm; use crate::target::{ciphertext, indexed, AeadContext, Borrowed, DecryptSource, EncryptTarget}; use crate::{nonempty, DecryptFrom, EncryptInto, Equality, Indexes, PlanError, StackCipher}; diff --git a/packages/stack-encrypt/src/dynamic/record/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs index 8b6e855ea..ee711f7c6 100644 --- a/packages/stack-encrypt/src/dynamic/record/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -47,8 +47,8 @@ use vitaminc_protected::Buffer; use super::{absence, take, Absent, FieldPlan, NullMode, Output, Plan}; use crate::dynamic::kind::convert; use crate::dynamic::one_or_many::OneOrMany; +use crate::dynamic::values::FieldValues; use crate::dynamic::{Error, Reason, TargetError}; -use crate::plan::FieldValues; use crate::refusal::Found; use vitaminc_aead::plaintext::SealedNull; diff --git a/packages/stack-encrypt/src/plan/values.rs b/packages/stack-encrypt/src/dynamic/values.rs similarity index 99% rename from packages/stack-encrypt/src/plan/values.rs rename to packages/stack-encrypt/src/dynamic/values.rs index 5ef093483..55116d5a3 100644 --- a/packages/stack-encrypt/src/plan/values.rs +++ b/packages/stack-encrypt/src/dynamic/values.rs @@ -4,8 +4,8 @@ use std::any::{type_name, Any}; use std::fmt; use std::sync::Arc; -use super::PlanError; use crate::Error; +use crate::PlanError; /// One value in a [`FieldValues`]: the value, and its type's name so the /// record can say what it holds without showing it. diff --git a/packages/stack-encrypt/src/plan/mod.rs b/packages/stack-encrypt/src/plan/mod.rs index c8d718a99..475d913ad 100644 --- a/packages/stack-encrypt/src/plan/mod.rs +++ b/packages/stack-encrypt/src/plan/mod.rs @@ -1,21 +1,12 @@ -//! What a plan that is data shares with the rest of the crate: the errors a -//! plan is refused with ([`PlanError`]), and the label a plan's context is -//! written as ([`IntoLabel`]). +//! The errors a declaration is refused with ([`PlanError`]): a record with +//! static types and a plan that is data are refused with the same ones. //! //! A program does not build a plan in Rust. A record with static types //! derives `EncryptTarget` and `DecryptSource`, and queries a field through //! its field reference ([`FieldReference`](crate::FieldReference)). A program whose declaration is -//! data parses a plan with the `dynamic` feature -//! (`dynamic::record::plan`) and runs it as a `dynamic::Planned` value. +//! data parses a plan with the `dynamic` feature and runs it as a +//! `dynamic::Planned` value. mod error; -mod label; -#[cfg(feature = "dynamic")] -mod values; pub(crate) use error::article; pub use error::PlanError; -pub use label::IntoLabel; -#[cfg(feature = "dynamic")] -pub(crate) use label::{field_label, join, FROM_CALL, FROM_PLAN}; -#[cfg(feature = "dynamic")] -pub(crate) use values::{FieldValues, Slot}; diff --git a/packages/stack-encrypt/tests/plan_grammar.rs b/packages/stack-encrypt/tests/plan_grammar.rs index 43d6a4809..7a7398ddd 100644 --- a/packages/stack-encrypt/tests/plan_grammar.rs +++ b/packages/stack-encrypt/tests/plan_grammar.rs @@ -30,8 +30,8 @@ use std::sync::atomic::Ordering; use common::frames::{frame, object}; use common::{counting_cipher, recording_cipher}; +use stack_encrypt::dynamic::IntoLabel; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record, NoTargets, Op, Operand, Planned}; -use stack_encrypt::plan::IntoLabel; use stack_encrypt::target::Scope; use stack_encrypt::{ AsProtectedRef as _, CipherText, DecryptFrom, EncryptInto, Error, Label, PlanError, diff --git a/packages/stack-encrypt/tests/record_lowering.rs b/packages/stack-encrypt/tests/record_lowering.rs index fecd76036..5f1fbb85f 100644 --- a/packages/stack-encrypt/tests/record_lowering.rs +++ b/packages/stack-encrypt/tests/record_lowering.rs @@ -44,8 +44,8 @@ use common::{deterministic_cipher, DeterministicSource}; use recipher_frame::serde::from_slice; use serde_json::{json, Map, Value as Json}; use stack_encrypt::dynamic::record::{self, Plan as DataPlan}; +use stack_encrypt::dynamic::IntoLabel; use stack_encrypt::dynamic::{frame::OwnedFrame, TermBytes, ValueKind}; -use stack_encrypt::plan::IntoLabel; use stack_encrypt::sem::MatchOptions; use stack_encrypt::target::{ ciphertext, indexed, open, passthrough as carried, Borrowed, DeclaredContext, Encrypted, From b62b346f3597676ce0039e3eb1b9405fafa10064 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 23:34:17 +1100 Subject: [PATCH 15/23] refactor(stack-encrypt): plan, planned and values are submodules of record A plan describes a record, and Planned runs one, so both now live under dynamic/record with the source reader and FieldValues. record's helpers and the source module's items are visible to record and its submodules alone. The query module is the one user outside record. It reads a plan through record's public re-exports and two methods that stay visible to dynamic: FieldPlan::indexes and Plan::declared_context. dynamic::planned is now dynamic::record::planned. Its public types are still re-exported from dynamic. --- packages/stack-encrypt/src/dynamic/mod.rs | 5 +- packages/stack-encrypt/src/dynamic/record.rs | 56 ++++---- .../src/dynamic/{ => record}/plan.rs | 43 +++--- .../src/dynamic/{ => record}/planned.rs | 123 +++++++++--------- .../src/dynamic/record/source.rs | 12 +- .../src/dynamic/{ => record}/values.rs | 0 6 files changed, 119 insertions(+), 120 deletions(-) rename packages/stack-encrypt/src/dynamic/{ => record}/plan.rs (97%) rename packages/stack-encrypt/src/dynamic/{ => record}/planned.rs (96%) rename packages/stack-encrypt/src/dynamic/{ => record}/values.rs (100%) diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index bbeaaa771..973ccbc8b 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -106,8 +106,6 @@ mod json_query; mod kind; mod label; mod one_or_many; -mod plan; -pub mod planned; mod query; pub mod record; @@ -124,7 +122,6 @@ mod term; #[cfg(test)] mod test_frame; pub mod value; -mod values; /// The document a `json` field's value holds, as [`read_json`] returns it: /// [`crate::json::JsonPlaintext`], named here for a binding that reaches @@ -134,11 +131,11 @@ pub use context::{borrowed, context}; pub use json::{json_frame, read_json, JsonValueError}; pub use kind::{admits, not_admitted, read}; pub use label::IntoLabel; -pub use planned::{DynamicQuery, FieldHandle, Planned, QueryPlan, QueryValue}; pub use query::{ check_json_open, check_query, field_operators, json_open, query_term, target_limit, verify, Fidelity, Op, Operand, OperatorEntry, QueryTerm, }; +pub use record::planned::{DynamicQuery, FieldHandle, Planned, QueryPlan, QueryValue}; pub use record::{FieldPlan, NullMode, Output, Plan}; pub use target::{NoTargets, TargetDescriptor, TargetError, TargetOptions, TargetResolver}; pub use term::{term, TermBytes}; diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 23bd91329..0ec4d9d5b 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -3,7 +3,7 @@ //! //! A binding has no types to name, so it declares a record as data: per //! field, a context, what to produce and, optionally, what type the values -//! are. This module reads that declaration ([`plan`]) and *lowers* it to +//! are. This module reads that declaration ([`plan`](plan())) and *lowers* it to //! the combinators the derive's generated code is made of //! (`super::planned::compose`): `ciphertext`, `indexed`, the indexes' //! `operations` or `passthrough` per field, each under the field's label. @@ -66,7 +66,7 @@ //! own plan through the [`TargetResolver`] the host installed //! ([`plan_with`], [`encrypt_with`], [`decrypt_with`], [`query`]), zipping //! its [`Pending`] into the record's so the whole record is still one -//! ZeroKMS request. The bare entry points ([`plan`], [`encrypt`], +//! ZeroKMS request. The bare entry points ([`plan`](plan()), [`encrypt`], //! [`decrypt`]) run with [`NoTargets`], the resolver of a build without EQL //! types, which refuses every target name when the plan is built: a plan //! that parses there has no target field. @@ -149,7 +149,7 @@ use std::collections::BTreeSet; use self::source::check_field; #[cfg(test)] use self::source::SourceRecordError; -pub(super) use self::source::{into_source_records, SourceRecord}; +use self::source::{into_source_records, SourceRecord}; use super::one_or_many::OneOrMany; use super::ValueKind; #[cfg(test)] @@ -159,8 +159,8 @@ use vitaminc_aead::plaintext::{Logical, MapSink, Physical, SeqSink, Sink}; use vitaminc_aead::Encrypt; use vitaminc_protected::{Controlled, Protected}; -use super::planned::{check_stored, check_values, opening_base, Planned}; -use super::values::FieldValues; +use self::planned::{check_stored, check_values, opening_base, Planned}; +use self::values::FieldValues; use super::{Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes}; #[cfg(test)] use crate::target::{CallerContext, DeclaredContext}; @@ -171,11 +171,14 @@ use crate::{ #[cfg(test)] use crate::{ContextPiece, NonEmpty}; +mod plan; +pub mod planned; mod source; +mod values; -use super::plan::refusal; -pub use super::plan::{plan, plan_with, FieldPlan, NullMode, Output, Plan, EQL_KEY}; -pub(super) use super::plan::{Context, Verb}; +use self::plan::refusal; +use self::plan::Verb; +pub use self::plan::{plan, plan_with, FieldPlan, NullMode, Output, Plan, EQL_KEY}; /// Encrypt a record — or a batch of records — per a plan. /// @@ -344,7 +347,7 @@ pub fn query<'a, K: 'static>( /// A resolver's refusal, with the field named where the resolver could not /// name it: a resolver sees a type and a label, the lowering knows the /// field. -pub(super) fn name_target(error: TargetError, field: &str) -> TargetError { +fn name_target(error: TargetError, field: &str) -> TargetError { match error { TargetError::Column { label, reason, .. } => TargetError::Column { name: field.to_owned(), @@ -598,10 +601,10 @@ impl RecordTree for StackCipherText { /// - `targets` holds the stored bytes of each target field, in plan order, /// for the resolver. /// - `absent` names the fields that the record leaves out. -pub(super) struct EncryptedRecord { - pub(super) values: FieldValues, - pub(super) targets: Vec>, - pub(super) absent: Absent, +struct EncryptedRecord { + values: FieldValues, + targets: Vec>, + absent: Absent, } /// The `"null": "sql"` fields a row leaves out: null in a source, or with @@ -609,7 +612,7 @@ pub(super) struct EncryptedRecord { /// opened for them, so a row is run by the plan composed without them /// (`super::planned::compose`), with the other rows that leave out the same /// fields. -pub(super) type Absent = BTreeSet; +type Absent = BTreeSet; /// Take the one entry named `name` out of a row, whatever order the row had /// it in. `None` if the row has no such entry — or has it twice: the maps @@ -685,12 +688,12 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { /// What the adapters know of a field once the engine has run. #[derive(Clone, Debug)] -pub(super) struct FieldShape { - pub(super) name: String, - pub(super) verb: Verb, - pub(super) keys: Vec<&'static str>, - pub(super) kind: Option, - pub(super) null: Option, +struct FieldShape { + name: String, + verb: Verb, + keys: Vec<&'static str>, + kind: Option, + null: Option, } /// A slot of the record the engine built from the plan, at the type the @@ -747,7 +750,7 @@ fn passthrough_bytes(payload: &PassthroughFrame) -> Option> { /// The record the plan produced, in the stored shape: per field, in plan /// order, its output map. -pub(super) fn shape_record( +fn shape_record( mut values: FieldValues, eql: Vec>, shape: &[FieldShape], @@ -813,7 +816,7 @@ fn take_leaf(values: &mut FieldValues, name: &str) -> Result, shape: &[FieldShape], @@ -857,9 +860,7 @@ pub(super) fn open_record( /// straight into its entry of the record's [`FrameWriter`], and dropped, /// which wipes it; the result is the only copy of the record's plaintext /// left. -pub(super) fn write_record( - rows: OneOrMany>, -) -> Result { +fn write_record(rows: OneOrMany>) -> Result { fn row>( mut map: S, fields: Vec<(String, OwnedFrame)>, @@ -902,10 +903,7 @@ pub(super) fn write_record( /// each passthrough field is present exactly once with exactly one /// `"passthrough"` node carrying a value of the field's kind. Terms, and /// entries the plan does not open, are ignored: comparands, not ciphertext. -pub(super) fn record_rows( - tree: StackCipherText, - plan: &Plan, -) -> Result, Error> { +fn record_rows(tree: StackCipherText, plan: &Plan) -> Result, Error> { let not_an_object = |row, tree: &StackCipherText| Error::Record { field: None, row, diff --git a/packages/stack-encrypt/src/dynamic/plan.rs b/packages/stack-encrypt/src/dynamic/record/plan.rs similarity index 97% rename from packages/stack-encrypt/src/dynamic/plan.rs rename to packages/stack-encrypt/src/dynamic/record/plan.rs index f252a3c07..c91e0c32a 100644 --- a/packages/stack-encrypt/src/dynamic/plan.rs +++ b/packages/stack-encrypt/src/dynamic/record/plan.rs @@ -2,7 +2,7 @@ //! that reads a plan from a frame. //! //! The grammar of a plan and what each key decides are described in the -//! [`record`](super::record) module's documentation. +//! [`record`](super) module's documentation. use std::fmt; @@ -10,10 +10,10 @@ use serde::de::{Deserializer, MapAccess, Visitor}; use serde::Deserialize; use super::planned::compose; -use super::record::{Absent, FieldShape}; -use super::term::{IndexWire, JsonWire, MatchWire}; -use super::{not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver}; -use super::{TargetOptions, ValueKind}; +use super::{Absent, FieldShape}; +use crate::dynamic::term::{IndexWire, JsonWire, MatchWire}; +use crate::dynamic::{not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver}; +use crate::dynamic::{TargetOptions, ValueKind}; use crate::target::{CallerContext, DeclaredContext, IndexSpec}; use crate::{ContextPiece, Label, NonEmpty}; use vitaminc_aead::frame::Frame; @@ -117,7 +117,7 @@ impl NullMode { /// A field may declare the type of its values (a [`ValueKind`]), and must /// when it has a term output: [`Plan::new_with`] refuses the plan otherwise /// ([`Error::UntypedIndex`]). A typed field admits only the indexes that -/// kind is defined for ([`admits`](super::admits), checked when the plan is built), seals +/// kind is defined for ([`admits`](crate::dynamic::admits), checked when the plan is built), seals /// only values of that kind and opens only to one (checked per value), so /// the engine verifies what a binding hands it rather than trusting the /// binding's tagging. A field that only seals, or only carries its value @@ -143,7 +143,7 @@ impl FieldPlan { /// label, a list of plain segments, extended by zero or more scalar /// parts nested to the left (see the /// [module docs](crate::dynamic::record#what-a-fields-context-must-be)). Build one from a - /// value with [`super::context`](super::context()). How many segments + /// value with [`crate::dynamic::context`](crate::dynamic::context()). How many segments /// the label needs is the plan's rule, not the field's: two or more /// under a plan with a context of its own ([`Plan::new`]), exactly one /// under a plan that takes its context from a field @@ -263,7 +263,7 @@ impl FieldPlan { /// # Errors /// /// [`Error::Plan`] if the field asks for an index the kind is not - /// defined for ([`admits`](super::admits)), with the reason [`not_admitted`] gives: + /// defined for ([`admits`](crate::dynamic::admits)), with the reason [`not_admitted`] gives: /// [`Reason::IndexNotAdmitted`] for match on an integer, equality or an /// order index on a boolean, an order index on an 8-bit integer or on /// bytes, any index on a composite. @@ -364,7 +364,7 @@ impl FieldPlan { } /// The indexes the field declares, in output order. - pub(super) fn indexes(&self) -> Vec { + pub(in crate::dynamic) fn indexes(&self) -> Vec { self.outputs .iter() .filter_map(|output| match output { @@ -969,7 +969,7 @@ impl Plan { /// The context every field's label is run under: the scopes, then the /// bindings. - pub(super) fn declared_context(&self) -> DeclaredContext { + pub(in crate::dynamic) fn declared_context(&self) -> DeclaredContext { self.bindings .iter() .cloned() @@ -1083,7 +1083,7 @@ pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result) -> Result` is read by [`super::context`](super::context()) and must be +/// `` is read by [`crate::dynamic::context`](crate::dynamic::context()) and must be /// the field's label, optionally extended; the /// [module docs](crate::dynamic::record#what-a-fields-context-must-be) give the shape. /// @@ -1164,7 +1164,8 @@ pub fn plan_with( for (name, spec) in wire.fields { let spec = FieldSpec::try_from(spec).map_err(|reason| Error::bad_plan(reason).in_field(&name))?; - let context = super::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; + let context = + crate::dynamic::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; let field = match spec.what { What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, What::Target(target, options) => { @@ -1231,13 +1232,13 @@ impl<'de> Deserialize<'de> for PlanWire { let mut plan = PlanWire { context_field: None, bindings: None, - fields: Vec::with_capacity(super::context::reserved(map.size_hint())), + fields: Vec::with_capacity(crate::dynamic::context::reserved(map.size_hint())), }; while let Some(name) = map.next_key::<&'de str>()? { if name == CONTEXT_FIELD { plan.context_field = Some(map.next_value()?); } else if name == BIND { - let parts: Vec = map.next_value()?; + let parts: Vec = map.next_value()?; plan.bindings = Some(parts.into_iter().map(|part| part.0).collect()); } else { plan.fields.push((name.to_owned(), map.next_value()?)); @@ -1254,7 +1255,9 @@ impl<'de> Deserialize<'de> for PlanWire { /// when it is not an object of that many entries. fn entry_key(frame: &[u8], position: usize) -> Option { let root = Frame::parse(frame).ok()?; - super::found::object_keys(root)?.into_iter().nth(position) + crate::dynamic::found::object_keys(root)? + .into_iter() + .nth(position) } /// The keys a field's spec reads ([`FieldSpecWire`]). @@ -1263,7 +1266,7 @@ const SPEC_KEYS: [&str; 5] = ["context", "outputs", "target", "type", "null"]; /// The plan-level key naming the field a plan takes its context from. const CONTEXT_FIELD: &str = "context_field"; /// The plan-level key listing the caller's bindings: a list of parts, each -/// a context as [`context`](super::context()) reads one. +/// a context as [`context`](crate::dynamic::context()) reads one. const BIND: &str = "bind"; /// One field's spec: a context, and exactly one of `"outputs"` and @@ -1271,7 +1274,7 @@ const BIND: &str = "bind"; /// refusal names it), and optionally a `"type"`. A key that is present must /// hold its kind of value: a null is refused. struct FieldSpec { - context: super::context::Context, + context: crate::dynamic::context::Context, what: What, field_type: Option, null: Option, @@ -1285,7 +1288,7 @@ enum What { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct FieldSpecWire { - context: super::context::Context, + context: crate::dynamic::context::Context, #[serde(default, deserialize_with = "present")] outputs: Option>, #[serde(default, deserialize_with = "present")] @@ -1342,7 +1345,7 @@ enum TargetWire { struct ConfiguredTarget { name: String, #[serde(default, deserialize_with = "present")] - options: Option, + options: Option, } /// Absent is `None`. Present, a value must be of its kind: a null is diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/record/planned.rs similarity index 96% rename from packages/stack-encrypt/src/dynamic/planned.rs rename to packages/stack-encrypt/src/dynamic/record/planned.rs index b0464c26c..7c006e79a 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/record/planned.rs @@ -80,17 +80,18 @@ use std::sync::Arc; use zeroize::Zeroize; -use super::label::{field_label, join, IntoLabel, FROM_CALL, FROM_PLAN}; -use super::one_or_many::OneOrMany; -use super::query::{field_operators, find, query_term, QueryTerm}; -use super::record::{ - self, name_target, open_record, shape_record, write_record, Absent, Context, FieldPlan, Plan, - Verb, -}; -use super::target::{NoTargets, TargetResolver}; +use super::plan::{Context, Verb}; use super::values::{FieldValues, Slot}; -use super::{Error, Op, Reason, TermBytes}; +use super::{ + into_source_records, name_target, open_record, record_rows, shape_record, write_record, Absent, + EncryptedRecord, FieldPlan, Plan, SourceRecord, +}; use crate::contexts::{self, CallerShape, Contexts, LeafContext, Placeholder}; +use crate::dynamic::label::{field_label, join, IntoLabel, FROM_CALL, FROM_PLAN}; +use crate::dynamic::one_or_many::OneOrMany; +use crate::dynamic::query::{field_operators, find, query_term, QueryTerm}; +use crate::dynamic::target::{NoTargets, TargetResolver}; +use crate::dynamic::{Error, Op, Reason, TermBytes}; use crate::kms::MaybeSend; use crate::target::{ ciphertext, indexed, inspect, open, AeadContext, Borrowed, CallerContext, DeclaredContext, @@ -468,7 +469,7 @@ where /// /// # Errors /// - /// As [`record::encrypt_with`]. + /// As [`encrypt_with`](super::encrypt_with). pub(super) fn run_encrypt<'a, K: 'static>( self, cipher: &'a KeysetCipher<'_, K>, @@ -478,7 +479,7 @@ where value, resolver, } = self; - let rows = record::into_source_records(value, plan)?; + let rows = into_source_records(value, plan)?; let extend = plan.declared_context(); let shape = plan.shape(); // Every target field of every row, in row-major order, run by the @@ -486,30 +487,29 @@ where // below. A row runs the target fields it does not leave out, so each // row's count is its own. let mut pendings = Vec::new(); - let mut targets = - |row: record::SourceRecord| -> Result<(Absent, FieldValues, usize), Error> { - let fields = plan - .target_fields() - .filter(|field| !row.absent.contains(field.name())); - let mut count = 0; - for (field, value) in fields.zip(row.targets) { - let name = field.target().unwrap_or_default(); - pendings.push( - resolver - .encrypt( - name, - field.target_options(), - cipher, - field.label(), - &extend, - value.frame(), - ) - .map_err(|error| Error::Target(name_target(error, field.name())))?, - ); - count += 1; - } - Ok((row.absent, row.values, count)) - }; + let mut targets = |row: SourceRecord| -> Result<(Absent, FieldValues, usize), Error> { + let fields = plan + .target_fields() + .filter(|field| !row.absent.contains(field.name())); + let mut count = 0; + for (field, value) in fields.zip(row.targets) { + let name = field.target().unwrap_or_default(); + pendings.push( + resolver + .encrypt( + name, + field.target_options(), + cipher, + field.label(), + &extend, + value.frame(), + ) + .map_err(|error| Error::Target(name_target(error, field.name())))?, + ); + count += 1; + } + Ok((row.absent, row.values, count)) + }; Ok(match rows { OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; @@ -604,7 +604,7 @@ where /// /// # Errors /// - /// As [`record::decrypt_with`]. + /// As [`decrypt_with`](super::decrypt_with). pub(super) fn run_decrypt<'a, K: 'static>( self, cipher_ref: impl Into>, @@ -616,32 +616,31 @@ where resolver, } = self; let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); - let rows = record::record_rows(value, plan)?; + let rows = record_rows(value, plan)?; let extend = plan.declared_context(); let shape = plan.shape(); let cipher = cipher_ref.cipher(); let mut pendings = Vec::new(); - let mut targets = - |row: record::EncryptedRecord| -> Result<(Absent, FieldValues, usize), Error> { - let fields = plan - .target_fields() - .filter(|field| !row.absent.contains(field.name())); - let mut count = 0; - for (field, stored) in fields.zip(row.targets) { - let name = field.target().unwrap_or_default(); - // Confined to the caller's keyset, as the lowered plan's - // leaves are: a target value sealed under another keyset is - // refused before any key is retrieved. - pendings.push(confine( - resolver - .decrypt(name, cipher, field.label(), &extend, &stored) - .map_err(|error| Error::Target(name_target(error, field.name())))?, - &cipher_ref, - )); - count += 1; - } - Ok((row.absent, row.values, count)) - }; + let mut targets = |row: EncryptedRecord| -> Result<(Absent, FieldValues, usize), Error> { + let fields = plan + .target_fields() + .filter(|field| !row.absent.contains(field.name())); + let mut count = 0; + for (field, stored) in fields.zip(row.targets) { + let name = field.target().unwrap_or_default(); + // Confined to the caller's keyset, as the lowered plan's + // leaves are: a target value sealed under another keyset is + // refused before any key is retrieved. + pendings.push(confine( + resolver + .decrypt(name, cipher, field.label(), &extend, &stored) + .map_err(|error| Error::Target(name_target(error, field.name())))?, + &cipher_ref, + )); + count += 1; + } + Ok((row.absent, row.values, count)) + }; Ok(match rows { OneOrMany::One(row) => { let (absent, values, _) = targets(row)?; @@ -1436,7 +1435,7 @@ where /// The values' fields against the plan's, both ways, and each at the type /// the plan reads: what running the plan checks before any key is -/// requested, and what [`check_source`](super::record::check_source) asks +/// requested, and what [`check_source`](super::check_source) asks /// without a cipher. pub(super) fn check_values( plan: &Plan, @@ -1614,7 +1613,8 @@ mod tests { field("age", &["c", "eq"], "uint32"), field("id", &["passthrough"], "uint64"), ]); - record::plan(frame_of(&value).as_protected_ref().as_deref()).expect("parses") + crate::dynamic::record::plan(frame_of(&value).as_protected_ref().as_deref()) + .expect("parses") } /// Two sealed fields, so a row that leaves out neither asks for two /// data keys. @@ -1623,7 +1623,8 @@ mod tests { field("age", &["c", "eq"], "uint32"), field("id", &["c"], "uint64"), ]); - record::plan(frame_of(&value).as_protected_ref().as_deref()).expect("parses") + crate::dynamic::record::plan(frame_of(&value).as_protected_ref().as_deref()) + .expect("parses") } async fn cipher() -> StackCipher { StackCipher::builder() diff --git a/packages/stack-encrypt/src/dynamic/record/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs index ee711f7c6..efdd370ee 100644 --- a/packages/stack-encrypt/src/dynamic/record/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -44,10 +44,10 @@ use vitaminc_aead::plaintext::{ }; use vitaminc_protected::Buffer; +use super::values::FieldValues; use super::{absence, take, Absent, FieldPlan, NullMode, Output, Plan}; use crate::dynamic::kind::convert; use crate::dynamic::one_or_many::OneOrMany; -use crate::dynamic::values::FieldValues; use crate::dynamic::{Error, Reason, TargetError}; use crate::refusal::Found; use vitaminc_aead::plaintext::SealedNull; @@ -62,10 +62,10 @@ use vitaminc_aead::plaintext::SealedNull; /// - `targets` holds the value of each target field, in plan order, for /// the resolver. /// - `absent` names the fields that the record leaves out. -pub(in crate::dynamic) struct SourceRecord { - pub(in crate::dynamic) values: FieldValues, - pub(in crate::dynamic) targets: Vec, - pub(in crate::dynamic) absent: Absent, +pub(super) struct SourceRecord { + pub(super) values: FieldValues, + pub(super) targets: Vec, + pub(super) absent: Absent, } /// The rows of a record source, each as the [`FieldValues`] the lowered @@ -78,7 +78,7 @@ pub(in crate::dynamic) struct SourceRecord { /// into an [`OwnedFrame`] of its own as the walk reaches it, and nothing else /// is copied. A value the frame cannot carry, or that holds a repeated key, /// is refused naming its field. -pub(in crate::dynamic) fn into_source_records( +pub(super) fn into_source_records( source: impl Encrypt, plan: &Plan, ) -> Result, Error> { diff --git a/packages/stack-encrypt/src/dynamic/values.rs b/packages/stack-encrypt/src/dynamic/record/values.rs similarity index 100% rename from packages/stack-encrypt/src/dynamic/values.rs rename to packages/stack-encrypt/src/dynamic/record/values.rs From 46e99ab9de4e4bdf73946fbc805ba56804d438eb Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 1 Dec 2026 00:00:35 +1100 Subject: [PATCH 16/23] refactor(stack-encrypt)!: a plan is read with Plan::from_frame The parser was a function named plan in a module that now has a submodule named plan. It is now an associated function: record::plan(frame) Plan::from_frame(frame) record::plan_with(frame, resolver) Plan::from_frame_with(frame, resolver) The _with form follows the crate's other pairs: Plan::new and Plan::new_with, encrypt and encrypt_with. Callers are updated in stack-encrypt, its fuzz target, eql-bindings, the EQL encryption tests, the Go guest and the current docs. The changelog entry also records the two paths that moved in earlier commits on this branch: plan::IntoLabel and dynamic::planned. --- .../stack-encrypt/declaration-grammar.md | 4 +- languages/golang/encrypt/guest/src/ops.rs | 6 +- languages/golang/encrypt/guest/src/options.rs | 2 +- .../eql-bindings/src/encryption/resolver.rs | 8 +- .../eql/tests/encryption/tests/json_tree.rs | 2 +- .../encryption/tests/json_tree/elements.rs | 4 +- .../encryption/tests/json_tree/predicate.rs | 2 +- .../encryption/tests/json_tree_data_plan.rs | 8 +- .../tests/json_tree_field_references.rs | 2 +- .../encryption/tests/opaque_json_bytes.rs | 2 +- .../tests/encryption/tests/record_fields.rs | 4 +- packages/stack-encrypt/CHANGELOG.md | 14 + .../docs/language-integration.md | 10 +- .../fuzz/fuzz_targets/check_record.rs | 6 +- packages/stack-encrypt/src/dynamic/query.rs | 20 +- packages/stack-encrypt/src/dynamic/record.rs | 25 +- .../stack-encrypt/src/dynamic/record/plan.rs | 436 +++++++++--------- .../src/dynamic/record/planned.rs | 6 +- packages/stack-encrypt/src/dynamic/target.rs | 6 +- packages/stack-encrypt/tests/audit.rs | 2 +- .../tests/binding_conformance.rs | 4 +- packages/stack-encrypt/tests/conformance.rs | 2 +- .../tests/context_conformance.rs | 8 +- packages/stack-encrypt/tests/contexts.rs | 2 +- packages/stack-encrypt/tests/declarations.rs | 5 +- .../tests/exchange_conformance.rs | 2 +- .../stack-encrypt/tests/fixtures/README.md | 2 +- packages/stack-encrypt/tests/heap_hygiene.rs | 16 +- .../tests/json_field_references.rs | 2 +- packages/stack-encrypt/tests/json_index.rs | 2 +- .../stack-encrypt/tests/json_leakage/real.rs | 2 +- .../stack-encrypt/tests/json_operators.rs | 10 +- .../tests/json_predicate_macro.rs | 2 +- .../tests/lifecycle_conformance.rs | 2 +- .../stack-encrypt/tests/owned_equivalence.rs | 2 +- packages/stack-encrypt/tests/plan_grammar.rs | 2 +- packages/stack-encrypt/tests/planned.rs | 4 +- .../stack-encrypt/tests/query_operators.rs | 4 +- .../tests/query_refusal_conformance.rs | 2 +- .../tests/raw_frame_conformance.rs | 2 +- .../stack-encrypt/tests/read_conformance.rs | 2 +- .../stack-encrypt/tests/record_lowering.rs | 11 +- .../tests/runtime_conformance.rs | 2 +- .../tests/scopes_and_bindings.rs | 2 +- packages/stack-encrypt/tests/stored_rows.rs | 3 +- packages/stack-encrypt/tests/value_bytes.rs | 4 +- .../stack-encrypt/tests/value_conformance.rs | 2 +- packages/stack-encrypt/tests/value_kinds.rs | 3 +- 48 files changed, 350 insertions(+), 325 deletions(-) diff --git a/conformance/stack-encrypt/declaration-grammar.md b/conformance/stack-encrypt/declaration-grammar.md index 6ae67da0e..5f29065e1 100644 --- a/conformance/stack-encrypt/declaration-grammar.md +++ b/conformance/stack-encrypt/declaration-grammar.md @@ -26,8 +26,8 @@ SDK syntax. It is an experimental conformance profile, not a new production wire version. The input is a Vitamin C **typed transport frame**. JSON below is a readable projection; it cannot distinguish every integer width or carry bytes. -The executable authority is `stack_encrypt::dynamic::record::plan_with`, with the -selected target resolver. Native `record::plan` and the Go guest without EQL use +The executable authority is `stack_encrypt::dynamic::record::Plan::from_frame_with`, with the +selected target resolver. Native `record::Plan::from_frame` and the Go guest without EQL use `NoTargets`. The corpus fixes that resolver explicitly as `none`. It checks target syntax and unavailable-target refusals; it does not certify EQL targets. diff --git a/languages/golang/encrypt/guest/src/ops.rs b/languages/golang/encrypt/guest/src/ops.rs index 2374f4ac4..f80a6b69a 100644 --- a/languages/golang/encrypt/guest/src/ops.rs +++ b/languages/golang/encrypt/guest/src/ops.rs @@ -165,7 +165,7 @@ fn parse_term(value: Frame<'_>, kind: u32) -> Result { /// Encrypt a record — or a batch of records — per a plan. /// /// Both arguments are codec-encoded: the plan is the object -/// [`dynamic::record::plan`] parses, the source an object of +/// [`dynamic::record::Plan::from_frame`] parses, the source an object of /// `{ field: value }` (one record) or an array of them (a batch). The /// result is a codec-encoded ciphertext tree — per record a map of /// `field → { output-key → node }`. @@ -442,7 +442,7 @@ fn parse_query<'f>( /// input's are, before the plan's own grammar. fn parse_plan(plan: &Bytes) -> Result { let _ = parse_frame(plan)?; - dynamic::record::plan_with(lend(plan), &resolver()).map_err(|e| fail_dynamic(&e)) + dynamic::record::Plan::from_frame_with(lend(plan), &resolver()).map_err(|e| fail_dynamic(&e)) } // ============================================================================= @@ -450,7 +450,7 @@ fn parse_plan(plan: &Bytes) -> Result { // ============================================================================= /// Check a codec-encoded plan without a cipher: everything -/// [`dynamic::record::plan`] refuses — a malformed object, an unknown output, +/// [`dynamic::record::Plan::from_frame`] refuses — a malformed object, an unknown output, /// a type that does not admit one of its indexes, a context that is not a /// label of two or more segments, two fields under one identity — is /// [`STATUS_ENCODING`]. The Go generator (`stashgen`) asks this for every diff --git a/languages/golang/encrypt/guest/src/options.rs b/languages/golang/encrypt/guest/src/options.rs index 677e59b91..ebdad1db9 100644 --- a/languages/golang/encrypt/guest/src/options.rs +++ b/languages/golang/encrypt/guest/src/options.rs @@ -27,7 +27,7 @@ //! //! `context` is the context the host expects a record's context field to //! hold, for a plan that takes its context from a field (the plan-level -//! `"context_field"` key of `dynamic::record::plan`): a string that parses +//! `"context_field"` key of `dynamic::record::Plan::from_frame`): a string that parses //! as a plain label, `"tenants/acme"`, which the engine checks against each //! record's stored context field before any key is retrieved and refuses //! with [`STATUS_CONTEXT_MISMATCH`](crate::status::STATUS_CONTEXT_MISMATCH). diff --git a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs index 16437aa50..bfe6a052f 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/resolver.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/resolver.rs @@ -31,7 +31,7 @@ use super::targets::{self, decrypt_under, encrypt_under, query_under, Target, Ta /// label's column alone. /// /// Pass `&EqlTargets` wherever the dynamic interface accepts a resolver, -/// such as `stack_encrypt::dynamic::record::plan_with`. +/// such as `stack_encrypt::dynamic::record::Plan::from_frame_with`. /// /// ``` /// use eql_bindings::encryption::EqlTargets; @@ -296,7 +296,8 @@ mod tests { } }); let frame = dynamic::frame::serde::to_vec(&wire).expect("plan frame"); - let plan = record::plan_with(frame.as_protected_ref(), &EqlTargets).expect("plan"); + let plan = + record::Plan::from_frame_with(frame.as_protected_ref(), &EqlTargets).expect("plan"); dynamic::field_operators(&plan, "profile", &EqlTargets) .expect("operators") .into_iter() @@ -397,7 +398,8 @@ mod tests { } }); let frame = dynamic::frame::serde::to_vec(&wire).expect("plan frame"); - let error = record::plan_with(frame.as_protected_ref(), &EqlTargets).unwrap_err(); + let error = + record::Plan::from_frame_with(frame.as_protected_ref(), &EqlTargets).unwrap_err(); assert_eq!( error.reason(), Some(dynamic::Reason::TargetOptions), diff --git a/packages/eql/tests/encryption/tests/json_tree.rs b/packages/eql/tests/encryption/tests/json_tree.rs index 90cf0944b..c8ce67cff 100644 --- a/packages/eql/tests/encryption/tests/json_tree.rs +++ b/packages/eql/tests/encryption/tests/json_tree.rs @@ -73,7 +73,7 @@ fn plan() -> record::Plan { "target": {"name": "JsonSearch", "options": {"ordered": ORDERED}} } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/eql/tests/encryption/tests/json_tree/elements.rs b/packages/eql/tests/encryption/tests/json_tree/elements.rs index 376d1f115..b8c160631 100644 --- a/packages/eql/tests/encryption/tests/json_tree/elements.rs +++ b/packages/eql/tests/encryption/tests/json_tree/elements.rs @@ -49,7 +49,7 @@ fn contact_plan() -> record::Plan { "target": {"name": "JsonSearch", "options": {"ordered": [RELATIONSHIP, CALLS]}} } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -122,7 +122,7 @@ fn layout_plan(sealed: bool) -> record::Plan { }} } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/eql/tests/encryption/tests/json_tree/predicate.rs b/packages/eql/tests/encryption/tests/json_tree/predicate.rs index 6402abe87..a9e1ef93f 100644 --- a/packages/eql/tests/encryption/tests/json_tree/predicate.rs +++ b/packages/eql/tests/encryption/tests/json_tree/predicate.rs @@ -36,7 +36,7 @@ fn people_plan() -> record::Plan { "target": {"name": "JsonSearch", "options": {"ordered": ORDERED}} } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), 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..8f7835db2 100644 --- a/packages/eql/tests/encryption/tests/json_tree_data_plan.rs +++ b/packages/eql/tests/encryption/tests/json_tree_data_plan.rs @@ -61,7 +61,7 @@ fn plan() -> record::Plan { } } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -340,7 +340,7 @@ async fn a_document_does_not_open_under_another_column() { .unwrap() .await .unwrap(); - let other = record::plan_with( + let other = record::Plan::from_frame_with( (dynamic::frame::serde::to_vec(&json!({ "profile": { "context": ["users", "other"], @@ -487,7 +487,7 @@ fn a_document_field_answers_the_json_operators() { ("match", "predicate"), ] ); - let unordered = record::plan_with( + let unordered = record::Plan::from_frame_with( (dynamic::frame::serde::to_vec(&json!({ "profile": {"context": ["users", "profile"], "target": "JsonSearch"} })) @@ -1130,7 +1130,7 @@ fn scoped_plan(tenant: u64, row: Option) -> record::Plan { if let Some(row) = row { wire["bind"] = json!([row]); } - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/eql/tests/encryption/tests/json_tree_field_references.rs b/packages/eql/tests/encryption/tests/json_tree_field_references.rs index 41acae2b6..6ac197860 100644 --- a/packages/eql/tests/encryption/tests/json_tree_field_references.rs +++ b/packages/eql/tests/encryption/tests/json_tree_field_references.rs @@ -76,7 +76,7 @@ fn plan() -> record::Plan { } } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/eql/tests/encryption/tests/opaque_json_bytes.rs b/packages/eql/tests/encryption/tests/opaque_json_bytes.rs index e26a3ac6e..073b0717b 100644 --- a/packages/eql/tests/encryption/tests/opaque_json_bytes.rs +++ b/packages/eql/tests/encryption/tests/opaque_json_bytes.rs @@ -207,7 +207,7 @@ fn plan(null: Option<&str>) -> record::Plan { if let Some(policy) = null { field["null"] = json!(policy); } - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&json!({ "profile": field })) .unwrap() .as_protected_ref(), diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index 1479c6d4f..5609d8b9a 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -213,7 +213,7 @@ fn contact_plan() -> record::Plan { "age": {"context": ["contacts", "age"], "target": "IntegerOrd"}, "profile": {"context": ["contacts", "profile"], "target": "JsonSearch"}, }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -553,7 +553,7 @@ fn lead_plan() -> record::Plan { "email": {"context": ["leads", "email"], "target": "TextEq"}, "profile": {"context": ["leads", "profile"], "target": "JsonSearch"}, }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7ab0bf090..24c4bf5ab 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -571,6 +571,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A plan is read with `Plan::from_frame`.** Three paths have moved too. + The code is the same. Only the names and the paths have changed. + - `dynamic::record::plan(frame)` is now `Plan::from_frame(frame)`. + `dynamic::record::plan_with(frame, resolver)` is now + `Plan::from_frame_with(frame, resolver)`. `Plan` is at + `dynamic::Plan` and `dynamic::record::Plan`, as before. + - `plan::IntoLabel` is now `dynamic::IntoLabel`. The trait needs the + `dynamic` feature, because only the dynamic interface uses it. The + `plan` module keeps `PlanError`. + - The module `dynamic::planned` is now `dynamic::record::planned`. + `Planned`, `QueryPlan`, `FieldHandle`, `DynamicQuery` and `QueryValue` + are still at `dynamic::`, so code that uses those paths needs no + change. + - **A `Ciphertext` decrypts only into a type that is built from one scalar** (#2009). `OpaqueDecode` was implemented for every `Decrypt` type that is `Zeroize`. So `keyset.decrypt::>(ciphertext)` compiled, diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 064f5c2b0..304a852a2 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -96,8 +96,8 @@ context argument. - A **plan**: the declaration of what each field is, as data. Section 4 has the grammar. Read it once, when the language SDK loads a declaration, and - keep it. [`crate::dynamic::record::plan`] reads one from its frame; - [`crate::dynamic::record::plan_with`] reads one that may name EQL types + keep it. [`crate::dynamic::record::Plan::from_frame`] reads one from its frame; + [`crate::dynamic::record::Plan::from_frame_with`] reads one that may name EQL types (see "EQL types" below). Both take the frame as a [`vitaminc_protected::ProtectedRef`]; call [`crate::AsProtectedRef::as_protected_ref`] on the bytes. @@ -283,7 +283,7 @@ EQL types; the crate that does, `eql-bindings`, depends on this one. So the binding that links the EQL types passes a [`crate::dynamic::TargetResolver`], which the engine calls once per target field to run the named type's own plan: to -[`crate::dynamic::record::plan_with`], to `Planned::with_resolver`, and to +[`crate::dynamic::record::Plan::from_frame_with`], to `Planned::with_resolver`, and to [`crate::dynamic::record::Plan::query_with`] and [`crate::dynamic::record::Plan::field_with`]. [`crate::dynamic::NoTargets`] is the resolver of a build without them; it @@ -324,7 +324,7 @@ boundary hands over the plan's bytes on every call: ## 4. The plan grammar A plan is a map from field name to field spec. The grammar is defined by -what [`crate::dynamic::record::plan_with`] accepts, in `src/dynamic/record.rs`; +what [`crate::dynamic::record::Plan::from_frame_with`] accepts, in `src/dynamic/record/plan.rs`; its docs and the module docs there are the full statement, and `conformance/stack-encrypt/declaration-grammar.md` states it as a contract with the cases every binding runs. The shape: @@ -831,7 +831,7 @@ let keyset = cipher.default_keyset(); let declaration = recipher_frame::serde::to_vec(&serde_json::json!({ "age": { "context": ["profiles", "age"], "outputs": ["c", "eq"], "type": "int32" }, }))?; -let plan = record::plan(declaration.as_protected_ref())?; +let plan = record::Plan::from_frame(declaration.as_protected_ref())?; let by_age = plan.query("age", Op::Eq)?; // A frame is moved into each call and wiped by it, so the row is written diff --git a/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs b/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs index cf9004999..bc39154b0 100644 --- a/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs +++ b/packages/stack-encrypt/fuzz/fuzz_targets/check_record.rs @@ -12,7 +12,7 @@ //! drawn from a small name alphabet so field names, output keys and map //! keys collide often, with passthroughs and duplicate keys anywhere. //! -//! Two invariants. Neither `plan_with` nor `check_record` may panic on any +//! Two invariants. Neither `Plan::from_frame_with` nor `check_record` may panic on any //! input. And for a plan that parses, `check_record` accepts the tree //! exactly when the model does — the rules from the record docs, written //! independently of the walk: one map, or a sequence of maps; every @@ -31,7 +31,7 @@ use std::sync::OnceLock; use arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; -use stack_encrypt::dynamic::record::{check_record, plan_with, Plan}; +use stack_encrypt::dynamic::record::{check_record, Plan}; use stack_encrypt::dynamic::{ frame::{Frame, OwnedFrame}, Output, TargetDescriptor, TargetError, TargetOptions, TargetResolver, ValueKind, @@ -433,7 +433,7 @@ fuzz_target!(|case: Case| { return; }; let frame = frame.into_buffer(); - let Ok(plan) = plan_with(frame.as_protected_ref(), &Fixed) else { + let Ok(plan) = Plan::from_frame_with(frame.as_protected_ref(), &Fixed) else { if trace { eprintln!("verdict: plan refused"); } diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 29cf6a0be..6f240339d 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -517,7 +517,7 @@ fn answers( /// let declaration = recipher_frame::serde::to_vec(&serde_json::json!({ /// "age": { "context": ["users", "age"], "outputs": ["c", "eq", "ore"], "type": "uint32" }, /// }))?; -/// let plan = record::plan(declaration.as_protected_ref())?; +/// let plan = record::Plan::from_frame(declaration.as_protected_ref())?; /// /// let operators = field_operators(&plan, "age", &NoTargets)?; /// assert_eq!(operators[0], (Op::Eq, IndexSpec::Equality)); @@ -779,7 +779,7 @@ fn query_tokens(value: &OwnedFrame, options: &MatchOptions) -> Result Plan { - record::plan_with( + record::Plan::from_frame_with( frame_of(&Tree::Object(vec![( "name".into(), Tree::Object(vec![ @@ -2848,7 +2848,7 @@ mod tests { async fn a_target_field_answers_with_its_types_query_and_domain() { let cipher = cipher().await; let keyset = cipher.default_keyset(); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( frame_of(&Tree::Object(vec![( "email".into(), Tree::Object(vec![ @@ -2956,7 +2956,7 @@ mod tests { /// A plan with one field, `email`, naming [`OrderedText`]'s type. fn ordered_text_plan(resolver: &OrderedText) -> Plan { - record::plan_with( + record::Plan::from_frame_with( frame_of(&Tree::Object(vec![( "email".into(), Tree::Object(vec![ diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 0ec4d9d5b..c754399ea 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -3,7 +3,7 @@ //! //! A binding has no types to name, so it declares a record as data: per //! field, a context, what to produce and, optionally, what type the values -//! are. This module reads that declaration ([`plan`](plan())) and *lowers* it to +//! are. This module reads that declaration ([`Plan::from_frame`]) and *lowers* it to //! the combinators the derive's generated code is made of //! (`super::planned::compose`): `ciphertext`, `indexed`, the indexes' //! `operations` or `passthrough` per field, each under the field's label. @@ -64,9 +64,9 @@ //! `{"context": [...], "target": "TextEq"}`. The two forms are exclusive — //! a field with both is refused — and the lowering runs the named type's //! own plan through the [`TargetResolver`] the host installed -//! ([`plan_with`], [`encrypt_with`], [`decrypt_with`], [`query`]), zipping +//! ([`Plan::from_frame_with`], [`encrypt_with`], [`decrypt_with`], [`query`]), zipping //! its [`Pending`] into the record's so the whole record is still one -//! ZeroKMS request. The bare entry points ([`plan`](plan()), [`encrypt`], +//! ZeroKMS request. The bare entry points ([`Plan::from_frame`], [`encrypt`], //! [`decrypt`]) run with [`NoTargets`], the resolver of a build without EQL //! types, which refuses every target name when the plan is built: a plan //! that parses there has no target field. @@ -178,7 +178,7 @@ mod values; use self::plan::refusal; use self::plan::Verb; -pub use self::plan::{plan, plan_with, FieldPlan, NullMode, Output, Plan, EQL_KEY}; +pub use self::plan::{FieldPlan, NullMode, Output, Plan, EQL_KEY}; /// Encrypt a record — or a batch of records — per a plan. /// @@ -223,7 +223,7 @@ pub use self::plan::{plan, plan_with, FieldPlan, NullMode, Output, Plan, EQL_KEY /// let declaration = recipher_frame::serde::to_vec(&serde_json::json!({ /// "age": { "context": ["users", "age"], "outputs": ["c", "eq"], "type": "uint32" }, /// }))?; -/// let plan = record::plan(declaration.as_protected_ref())?; +/// let plan = record::Plan::from_frame(declaration.as_protected_ref())?; /// /// // The row as a binding hands it over: one transport frame. Here a Rust /// // map writes it; a binding's codec writes the same bytes. @@ -1122,7 +1122,7 @@ mod tests { /// The plan `value` spells, read from its frame as a binding sends it. fn plan(value: Tree) -> Result { - super::plan( + Plan::from_frame( crate::dynamic::test_frame::frame_of(&value) .as_protected_ref() .as_deref(), @@ -1131,7 +1131,7 @@ mod tests { /// [`plan`], under `resolver`. fn plan_with(value: Tree, resolver: &(impl TargetResolver + ?Sized)) -> Result { - super::plan_with( + Plan::from_frame_with( crate::dynamic::test_frame::frame_of(&value) .as_protected_ref() .as_deref(), @@ -1381,7 +1381,7 @@ mod tests { fn a_plan_that_declares_more_fields_than_it_holds_is_refused() { let mut bytes = vec![vitaminc_aead::frame::OBJECT]; bytes.extend_from_slice(&u32::MAX.to_le_bytes()); - assert!(crate::dynamic::record::plan( + assert!(crate::dynamic::record::Plan::from_frame( Protected::new(bytes.to_vec()).as_protected_ref().as_deref() ) .is_err()); @@ -7233,7 +7233,7 @@ mod tests { } let json = br#"{"age": {"context": ["users", "age"], "outputs": ["c"]}}"#; for bytes in [&[][..], &[0xff, 1, 2], &json[..], &repeated] { - let error = super::super::plan( + let error = super::super::Plan::from_frame( Protected::new(bytes.to_vec()).as_protected_ref().as_deref(), ) .expect_err("refused"); @@ -7284,9 +7284,10 @@ mod tests { typed_null.extend_from_slice(&3u32.to_le_bytes()); typed_null.extend_from_slice(b"age"); vitaminc_aead::leaf::write_typed_null(ty, &mut typed_null); - let error = - super::super::plan(Protected::new(typed_null).as_protected_ref().as_deref()) - .expect_err("a typed null spec"); + let error = super::super::Plan::from_frame( + Protected::new(typed_null).as_protected_ref().as_deref(), + ) + .expect_err("a typed null spec"); expect_shape(&error, "Plan", Some("age"), None, Found::Null); // A field spec can be an object with a key that a spec does not // take. The reason is then the one for an unknown key, and not diff --git a/packages/stack-encrypt/src/dynamic/record/plan.rs b/packages/stack-encrypt/src/dynamic/record/plan.rs index c91e0c32a..833646c22 100644 --- a/packages/stack-encrypt/src/dynamic/record/plan.rs +++ b/packages/stack-encrypt/src/dynamic/record/plan.rs @@ -45,7 +45,7 @@ pub enum Output { impl Output { /// The output a bare key names, or `None` for a key that is not one. A /// `"match"` key names the match index under default options; a plan - /// spells other options in the object form (see [`plan`]). + /// spells other options in the object form (see [`Plan::from_frame`]). pub fn parse(s: &str) -> Option { match s { "c" => Some(Output::Ciphertext), @@ -522,7 +522,7 @@ pub(super) fn refusal(error: crate::Error) -> (Option, Reason) { /// field, no two fields share a name, every field's label sits under the /// one plan context (or, under a context field, is its identity alone) and /// carries the one extension, and no two keyed fields share an identity, -/// so the whole composes. Both the parser ([`plan`]) and the +/// so the whole composes. Both the parser ([`Plan::from_frame`]) and the /// manual constructors ([`Plan::new`], [`Plan::with_context_field`]) go /// through the one check, so a plan in hand is a plan that holds them, /// whichever way it was built. @@ -820,7 +820,7 @@ impl Plan { /// /// # Errors /// - /// Unreachable for a plan from [`plan`], [`Plan::new`] or + /// Unreachable for a plan from [`Plan::from_frame`], [`Plan::new`] or /// [`Plan::with_context_field`]: a parsed plan always composes. pub fn contexts(&self) -> Result { let shapes = self.placed(compose::<()>(self, &Absent::new())?.shapes()); @@ -914,7 +914,7 @@ impl Plan { /// let declaration = to_vec(&serde_json::json!({ /// "email": { "context": ["users", "email"], "outputs": ["c"], "type": "string" }, /// }))?; - /// let plan = record::plan(declaration.as_protected_ref())?; + /// let plan = record::Plan::from_frame(declaration.as_protected_ref())?; /// let values = OwnedFrame::from_buffer(to_vec(&serde_json::json!({"email": "ada@example.com"}))?)?; /// let call: Pending<'_, StackCipherText, _> = /// Planned::new(&plan, values).encrypt_into_with_context(&keyset, Scope::new(42u64)); @@ -988,223 +988,225 @@ impl Plan { } } -/// Read a record plan from its frame, for a build without EQL types: -/// [`plan_with`] under [`NoTargets`], so a field that names a `"target"` is -/// refused ([`TargetError::NoTargets`]). -/// -/// # Errors -/// -/// As [`plan_with`]. -pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result { - plan_with(frame, &NoTargets) -} +impl Plan { + /// Read a record plan from its frame, for a build without EQL types: + /// [`from_frame_with`](Self::from_frame_with) under [`NoTargets`], so a field that names a `"target"` is + /// refused ([`TargetError::NoTargets`]). + /// + /// # Errors + /// + /// As [`from_frame_with`](Self::from_frame_with). + pub fn from_frame(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result { + Self::from_frame_with(frame, &NoTargets) + } -/// Read a record plan from its frame, resolving each target field's name -/// through `resolver`. -/// -/// The plan is a frame object, read by serde -/// (`recipher_frame::serde`): -/// -/// ```text -/// { : { "context": , "outputs": [ "c" | "passthrough" | , ... ], "type": }, ... } -/// ``` -/// -/// with one optional key beside the field specs, `"context_field": -/// ""`, which makes the plan take its context from that field -/// of each record ([`Plan::with_context_field`]; the -/// [module docs](crate::dynamic::record#a-plan-whose-context-is-a-field-of-the-record) give -/// the shape), and one more, `"bind": [, ...]`, the caller's -/// bindings ([`Plan::with_bindings`]). Both keys are reserved: a top-level -/// `"context_field"` whose value is not a string, or a `"bind"` whose -/// value is not a list of context parts, is refused rather than read as a -/// field of that name ([`Reason::ContextField`], [`Reason::Bind`]). -/// -/// A field may name an EQL type as its target instead of outputs: -/// -/// ```text -/// { : { "context": , "target": "", "type": }, ... } -/// ``` -/// -/// A field has `"outputs"` or `"target"`, never both. `"target"` is the -/// type's name as the resolver lists it (`"TextEq"`), resolved when the plan -/// is built so a name the build cannot run fails here and not at the first -/// value; its `"type"`, when given, must be the kind the type is produced -/// from. See the [module docs](crate::dynamic::record#a-field-that-names-an-eql-type). A -/// target field needs a column for its label, so it is refused under a -/// context field ([`TargetError::ContextField`]). -/// -/// `"target"` may instead be an object of the name and the options of the -/// index the type carries: a type that stores a JSON document -/// (`JsonSearch`) takes the JSON index's options object, as the -/// `{"json": ...}` output spells it, and no other type takes any. -/// -/// ```text -/// "target": { "name": "JsonSearch", -/// "options": { "sealed_root": , "ordered": [, ...] } } -/// ``` -/// -/// Such a field declares the `"json"` type (or leaves it to the target), -/// hands each document over as UTF-8 JSON text, and stores a null as SQL -/// `NULL` (`"null": "sql"`): a document has no length to pad. -/// -/// `` is an index in its wire form, which is its key — `"eq"`, -/// `"match"`, `"ore"` or `"ope"` — save for a match index with options other -/// than the defaults, which is a one-entry object mapping `"match"` to them: -/// -/// ```text -/// { "match": { "tokenizer": "standard" | { "ngram": }, -/// "downcase": , "short_words": , -/// "k": , "m": } } -/// ``` -/// -/// A bare `"match"` is the default options ([`MatchOptions::default`]: -/// 3-grams, downcased, no short-word tokens, `k = 3`, `m = 256`), so a plan -/// written before options had a wire form means what it always meant. In -/// the object form each option is optional and defaults the same way; an -/// unknown or repeated option, or a set the match scheme refuses (`k` -/// outside `3..=16`, `m` not a power of two in `32..=65536`, a zero n-gram -/// length, `short_words` beside the standard tokenizer or an n-gram length -/// under 3), is refused. The -/// other three indexes have no options and no object form. A field names -/// each output key at most once, so it carries at most one match index. -/// [`IndexSpec`] serializes to this form and [`IndexSpec::from_frame`] -/// reads it. `"passthrough"` is a field's only output when it has it. -/// -/// [`MatchOptions::default`]: crate::sem::MatchOptions::default -/// -/// `"type"` names a [`ValueKind`] (`"int64"`, `"string"`, …; see -/// [`ValueKind::name`]): vitaminc's vocabulary, not one of this crate's. It -/// is **required on every field with a term output** (`"eq"`, `"match"`, -/// `"ore"`, `"ope"`): the field's terms derive from that one kind, and every -/// value is checked against it on the way in and on the way out, so a -/// binding is never trusted to have tagged each value alike (a `34` sent once -/// as a `Float64` and once as an `Int64` would store two terms under one -/// field). A field with term outputs and no `"type"` is refused when the plan -/// is built ([`Error::UntypedIndex`], naming the field). It is optional on a -/// field whose only output is `"c"` or -/// `"passthrough"`, and on a target field, whose kind is the EQL type's own. -/// Declared, it is checked against the field's outputs here ([`admits`](crate::dynamic::admits)) and -/// decides nothing about the bytes (see the -/// [module docs](crate::dynamic::record#what-a-fields-type-decides-and-what-it-does-not)). -/// -/// `"null"`, when given, is `"sealed"` or `"sql"`: how the field stores a -/// value that is not there ([`NullMode`]). Without it a row must -/// have the field, and a typed field refuses a null. `"sealed"` seals a -/// null as a typed null as long as a value, so the stored record does not -/// show it, and beside an equality index stores a null's equality term, the -/// one every null of the field shares, which an `eq` query of a null finds. -/// The field must declare a type of fixed width: a bool, a number, a date, a -/// timestamp, a decimal, or a UUID. Equality must be the only index of the -/// field, or of a target field's EQL type. `"sql"` stores nothing for a null -/// or a missing field, so the host's columns hold SQL `NULL`; any field but -/// a passthrough takes it. -/// -/// `` is read by [`crate::dynamic::context`](crate::dynamic::context()) and must be -/// the field's label, optionally extended; the -/// [module docs](crate::dynamic::record#what-a-fields-context-must-be) give the shape. -/// -/// # Examples -/// -/// ``` -/// use stack_encrypt::dynamic::{record, NoTargets, Output}; -/// use stack_encrypt::target::IndexSpec; -/// use stack_encrypt::AsProtectedRef; -/// -/// // As a binding sends it: seal `age` under the label users/age and index -/// // it for equality. -/// let frame = recipher_frame::serde::to_vec(&serde_json::json!({ -/// "age": { -/// "context": ["users", "age"], -/// "outputs": ["c", "eq"], -/// "type": "uint32", -/// }, -/// }))?; -/// let plan = record::plan_with(frame.as_protected_ref(), &NoTargets)?; -/// -/// assert_eq!(plan.fields().len(), 1); -/// assert_eq!(plan.fields()[0].name(), "age"); -/// assert_eq!(plan.label().map(ToString::to_string).as_deref(), Some("users")); -/// assert_eq!( -/// plan.fields()[0].outputs(), -/// [Output::Ciphertext, Output::Term(IndexSpec::Equality)] -/// ); -/// # Ok::<(), Box>(()) -/// ``` -/// -/// # Errors -/// -/// [`Error::Plan`] for a plan that is not an object of field specs -/// (including bytes that are not one frame, which is how a field or key -/// given twice is refused: the frame refuses it), an empty plan, a spec with -/// a key other than `"context"`, `"outputs"`, `"target"`, `"type"` and -/// `"null"`, a `"null"` other than `"sealed"` or `"sql"`, a field that cannot -/// store a null as its `"null"` says ([`NullMode`]), -/// missing `"context"`, having neither `"outputs"` nor `"target"` or having -/// both, an output list that is not a list of outputs (above), is empty, -/// names an output key twice or names `"passthrough"` beside another -/// output, a `"target"` that is not a non-empty string, a `"type"` that is -/// not a string naming a [`ValueKind`], a type that does not admit one of -/// the field's index outputs, a context that is not a label of at least two -/// segments (optionally extended), fields under different contexts or -/// extensions, or a plan [`Plan::new`] refuses; with -/// `"context_field"`, a value that is not a string, naming no field of the -/// plan, or a plan [`Plan::with_context_field`] refuses. -/// [`Error::UntypedIndex`], naming the field, for a field with a term output -/// and no `"type"`. [`Error::Context`] for a `"context"` that is present but -/// is not a context at all, or renders empty. [`Error::Target`] for a -/// target the resolver refuses ([`Plan::new_with`]). -pub fn plan_with( - frame: vitaminc_protected::ProtectedRef<'_, [u8]>, - resolver: &(impl TargetResolver + ?Sized), -) -> Result { - let frame = frame.risky_ref(); - let wire: PlanWire = - recipher_frame::serde::from_slice(frame).map_err(|e| plan_refusal(&e, frame))?; - let mut fields: Vec = Vec::with_capacity(wire.fields.len()); - for (name, spec) in wire.fields { - let spec = - FieldSpec::try_from(spec).map_err(|reason| Error::bad_plan(reason).in_field(&name))?; - let context = - crate::dynamic::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; - let field = match spec.what { - What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, - What::Target(target, options) => { - let field = FieldPlan::with_target(name, context, target)?; - match options { - Some(options) => field.with_target_options(options), - None => field, + /// Read a record plan from its frame, resolving each target field's name + /// through `resolver`. + /// + /// The plan is a frame object, read by serde + /// (`recipher_frame::serde`): + /// + /// ```text + /// { : { "context": , "outputs": [ "c" | "passthrough" | , ... ], "type": }, ... } + /// ``` + /// + /// with one optional key beside the field specs, `"context_field": + /// ""`, which makes the plan take its context from that field + /// of each record ([`Plan::with_context_field`]; the + /// [module docs](crate::dynamic::record#a-plan-whose-context-is-a-field-of-the-record) give + /// the shape), and one more, `"bind": [, ...]`, the caller's + /// bindings ([`Plan::with_bindings`]). Both keys are reserved: a top-level + /// `"context_field"` whose value is not a string, or a `"bind"` whose + /// value is not a list of context parts, is refused rather than read as a + /// field of that name ([`Reason::ContextField`], [`Reason::Bind`]). + /// + /// A field may name an EQL type as its target instead of outputs: + /// + /// ```text + /// { : { "context": , "target": "", "type": }, ... } + /// ``` + /// + /// A field has `"outputs"` or `"target"`, never both. `"target"` is the + /// type's name as the resolver lists it (`"TextEq"`), resolved when the plan + /// is built so a name the build cannot run fails here and not at the first + /// value; its `"type"`, when given, must be the kind the type is produced + /// from. See the [module docs](crate::dynamic::record#a-field-that-names-an-eql-type). A + /// target field needs a column for its label, so it is refused under a + /// context field ([`TargetError::ContextField`]). + /// + /// `"target"` may instead be an object of the name and the options of the + /// index the type carries: a type that stores a JSON document + /// (`JsonSearch`) takes the JSON index's options object, as the + /// `{"json": ...}` output spells it, and no other type takes any. + /// + /// ```text + /// "target": { "name": "JsonSearch", + /// "options": { "sealed_root": , "ordered": [, ...] } } + /// ``` + /// + /// Such a field declares the `"json"` type (or leaves it to the target), + /// hands each document over as UTF-8 JSON text, and stores a null as SQL + /// `NULL` (`"null": "sql"`): a document has no length to pad. + /// + /// `` is an index in its wire form, which is its key — `"eq"`, + /// `"match"`, `"ore"` or `"ope"` — save for a match index with options other + /// than the defaults, which is a one-entry object mapping `"match"` to them: + /// + /// ```text + /// { "match": { "tokenizer": "standard" | { "ngram": }, + /// "downcase": , "short_words": , + /// "k": , "m": } } + /// ``` + /// + /// A bare `"match"` is the default options ([`MatchOptions::default`]: + /// 3-grams, downcased, no short-word tokens, `k = 3`, `m = 256`), so a plan + /// written before options had a wire form means what it always meant. In + /// the object form each option is optional and defaults the same way; an + /// unknown or repeated option, or a set the match scheme refuses (`k` + /// outside `3..=16`, `m` not a power of two in `32..=65536`, a zero n-gram + /// length, `short_words` beside the standard tokenizer or an n-gram length + /// under 3), is refused. The + /// other three indexes have no options and no object form. A field names + /// each output key at most once, so it carries at most one match index. + /// [`IndexSpec`] serializes to this form and [`IndexSpec::from_frame`] + /// reads it. `"passthrough"` is a field's only output when it has it. + /// + /// [`MatchOptions::default`]: crate::sem::MatchOptions::default + /// + /// `"type"` names a [`ValueKind`] (`"int64"`, `"string"`, …; see + /// [`ValueKind::name`]): vitaminc's vocabulary, not one of this crate's. It + /// is **required on every field with a term output** (`"eq"`, `"match"`, + /// `"ore"`, `"ope"`): the field's terms derive from that one kind, and every + /// value is checked against it on the way in and on the way out, so a + /// binding is never trusted to have tagged each value alike (a `34` sent once + /// as a `Float64` and once as an `Int64` would store two terms under one + /// field). A field with term outputs and no `"type"` is refused when the plan + /// is built ([`Error::UntypedIndex`], naming the field). It is optional on a + /// field whose only output is `"c"` or + /// `"passthrough"`, and on a target field, whose kind is the EQL type's own. + /// Declared, it is checked against the field's outputs here ([`admits`](crate::dynamic::admits)) and + /// decides nothing about the bytes (see the + /// [module docs](crate::dynamic::record#what-a-fields-type-decides-and-what-it-does-not)). + /// + /// `"null"`, when given, is `"sealed"` or `"sql"`: how the field stores a + /// value that is not there ([`NullMode`]). Without it a row must + /// have the field, and a typed field refuses a null. `"sealed"` seals a + /// null as a typed null as long as a value, so the stored record does not + /// show it, and beside an equality index stores a null's equality term, the + /// one every null of the field shares, which an `eq` query of a null finds. + /// The field must declare a type of fixed width: a bool, a number, a date, a + /// timestamp, a decimal, or a UUID. Equality must be the only index of the + /// field, or of a target field's EQL type. `"sql"` stores nothing for a null + /// or a missing field, so the host's columns hold SQL `NULL`; any field but + /// a passthrough takes it. + /// + /// `` is read by [`crate::dynamic::context`](crate::dynamic::context()) and must be + /// the field's label, optionally extended; the + /// [module docs](crate::dynamic::record#what-a-fields-context-must-be) give the shape. + /// + /// # Examples + /// + /// ``` + /// use stack_encrypt::dynamic::{record, NoTargets, Output}; + /// use stack_encrypt::target::IndexSpec; + /// use stack_encrypt::AsProtectedRef; + /// + /// // As a binding sends it: seal `age` under the label users/age and index + /// // it for equality. + /// let frame = recipher_frame::serde::to_vec(&serde_json::json!({ + /// "age": { + /// "context": ["users", "age"], + /// "outputs": ["c", "eq"], + /// "type": "uint32", + /// }, + /// }))?; + /// let plan = record::Plan::from_frame_with(frame.as_protected_ref(), &NoTargets)?; + /// + /// assert_eq!(plan.fields().len(), 1); + /// assert_eq!(plan.fields()[0].name(), "age"); + /// assert_eq!(plan.label().map(ToString::to_string).as_deref(), Some("users")); + /// assert_eq!( + /// plan.fields()[0].outputs(), + /// [Output::Ciphertext, Output::Term(IndexSpec::Equality)] + /// ); + /// # Ok::<(), Box>(()) + /// ``` + /// + /// # Errors + /// + /// [`Error::Plan`] for a plan that is not an object of field specs + /// (including bytes that are not one frame, which is how a field or key + /// given twice is refused: the frame refuses it), an empty plan, a spec with + /// a key other than `"context"`, `"outputs"`, `"target"`, `"type"` and + /// `"null"`, a `"null"` other than `"sealed"` or `"sql"`, a field that cannot + /// store a null as its `"null"` says ([`NullMode`]), + /// missing `"context"`, having neither `"outputs"` nor `"target"` or having + /// both, an output list that is not a list of outputs (above), is empty, + /// names an output key twice or names `"passthrough"` beside another + /// output, a `"target"` that is not a non-empty string, a `"type"` that is + /// not a string naming a [`ValueKind`], a type that does not admit one of + /// the field's index outputs, a context that is not a label of at least two + /// segments (optionally extended), fields under different contexts or + /// extensions, or a plan [`Plan::new`] refuses; with + /// `"context_field"`, a value that is not a string, naming no field of the + /// plan, or a plan [`Plan::with_context_field`] refuses. + /// [`Error::UntypedIndex`], naming the field, for a field with a term output + /// and no `"type"`. [`Error::Context`] for a `"context"` that is present but + /// is not a context at all, or renders empty. [`Error::Target`] for a + /// target the resolver refuses ([`Plan::new_with`]). + pub fn from_frame_with( + frame: vitaminc_protected::ProtectedRef<'_, [u8]>, + resolver: &(impl TargetResolver + ?Sized), + ) -> Result { + let frame = frame.risky_ref(); + let wire: PlanWire = + recipher_frame::serde::from_slice(frame).map_err(|e| plan_refusal(&e, frame))?; + let mut fields: Vec = Vec::with_capacity(wire.fields.len()); + for (name, spec) in wire.fields { + let spec = FieldSpec::try_from(spec) + .map_err(|reason| Error::bad_plan(reason).in_field(&name))?; + let context = crate::dynamic::context::non_empty(spec.context.0) + .map_err(|e| e.in_field(&name))?; + let field = match spec.what { + What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, + What::Target(target, options) => { + let field = FieldPlan::with_target(name, context, target)?; + match options { + Some(options) => field.with_target_options(options), + None => field, + } } + }; + let field = match spec.field_type { + Some(KindName(field_type)) => field.with_type(field_type)?, + None => field, + }; + fields.push(match spec.null { + Some(NullName(null)) => field.with_null(null), + None => field, + }); + } + // The whole-plan rules are the constructors', so a parsed plan and a + // hand-built one are refused alike. + let plan = match wire.context_field { + Some(name) => Plan::with_context_field(name, fields), + None => Plan::new_with(fields, resolver), + }?; + // The grammar's `bind` is a nonempty list of scalar parts: an explicit + // empty list is not an absent key, and a grouped part is not a part Go + // can supply through `Bind`. + match wire.bindings { + None => Ok(plan), + Some(parts) if parts.is_empty() => Err(Error::bad_plan(Reason::EmptyBinding)), + Some(parts) + if parts + .iter() + .any(|part| matches!(part, ContextPiece::List(_))) => + { + Err(Error::bad_plan(Reason::Bind)) } - }; - let field = match spec.field_type { - Some(KindName(field_type)) => field.with_type(field_type)?, - None => field, - }; - fields.push(match spec.null { - Some(NullName(null)) => field.with_null(null), - None => field, - }); - } - // The whole-plan rules are the constructors', so a parsed plan and a - // hand-built one are refused alike. - let plan = match wire.context_field { - Some(name) => Plan::with_context_field(name, fields), - None => Plan::new_with(fields, resolver), - }?; - // The grammar's `bind` is a nonempty list of scalar parts: an explicit - // empty list is not an absent key, and a grouped part is not a part Go - // can supply through `Bind`. - match wire.bindings { - None => Ok(plan), - Some(parts) if parts.is_empty() => Err(Error::bad_plan(Reason::EmptyBinding)), - Some(parts) - if parts - .iter() - .any(|part| matches!(part, ContextPiece::List(_))) => - { - Err(Error::bad_plan(Reason::Bind)) + Some(parts) => plan.with_bindings(parts), } - Some(parts) => plan.with_bindings(parts), } } diff --git a/packages/stack-encrypt/src/dynamic/record/planned.rs b/packages/stack-encrypt/src/dynamic/record/planned.rs index 7c006e79a..691d5a90d 100644 --- a/packages/stack-encrypt/src/dynamic/record/planned.rs +++ b/packages/stack-encrypt/src/dynamic/record/planned.rs @@ -30,7 +30,7 @@ //! "email": { "context": ["users", "email"], "outputs": ["c", "eq"], "type": "string" }, //! "age": { "context": ["users", "age"], "outputs": ["c", "ore"], "type": "uint64" }, //! }))?; -//! let plan = record::plan(declaration.as_protected_ref())?; +//! let plan = record::Plan::from_frame(declaration.as_protected_ref())?; //! //! // Each value goes straight into a frame, which keeps its bytes under //! // `Protected` and wipes them when it is dropped. A row is a map of them. @@ -1613,7 +1613,7 @@ mod tests { field("age", &["c", "eq"], "uint32"), field("id", &["passthrough"], "uint64"), ]); - crate::dynamic::record::plan(frame_of(&value).as_protected_ref().as_deref()) + crate::dynamic::record::Plan::from_frame(frame_of(&value).as_protected_ref().as_deref()) .expect("parses") } /// Two sealed fields, so a row that leaves out neither asks for two @@ -1623,7 +1623,7 @@ mod tests { field("age", &["c", "eq"], "uint32"), field("id", &["c"], "uint64"), ]); - crate::dynamic::record::plan(frame_of(&value).as_protected_ref().as_deref()) + crate::dynamic::record::Plan::from_frame(frame_of(&value).as_protected_ref().as_deref()) .expect("parses") } async fn cipher() -> StackCipher { diff --git a/packages/stack-encrypt/src/dynamic/target.rs b/packages/stack-encrypt/src/dynamic/target.rs index 360ba50c9..a245ffab1 100644 --- a/packages/stack-encrypt/src/dynamic/target.rs +++ b/packages/stack-encrypt/src/dynamic/target.rs @@ -1,7 +1,7 @@ //! EQL types as plan field targets: what the host that holds them installs. //! //! A data plan field may name an EQL type instead of its outputs -//! (`{"target": "TextEq", "context": [...]}`; see [`record::plan`]). The +//! (`{"target": "TextEq", "context": [...]}`; see [`record::Plan::from_frame`]). The //! engine knows no EQL type: `eql-bindings` depends on this crate, so this //! crate cannot depend on it. A host that has the EQL types resolves the //! name, as the Go guest's EQL build does. This module is the seam: a @@ -23,7 +23,7 @@ //! crate that owns the data grammar, and `eql-bindings` is tested to spell //! its table the same way. //! -//! [`record::plan`]: super::record::plan() +//! [`record::Plan::from_frame`]: super::record::Plan::from_frame() use std::fmt; @@ -665,7 +665,7 @@ pub trait TargetResolver { /// The resolver of a build that holds no EQL types: every name is refused /// with [`TargetError::NoTargets`], so a plan naming a target fails when it -/// is built ([`record::plan`](super::record::plan())), before any value is +/// is built ([`record::Plan::from_frame`](super::record::Plan::from_frame())), before any value is /// read. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct NoTargets; diff --git a/packages/stack-encrypt/tests/audit.rs b/packages/stack-encrypt/tests/audit.rs index f2ce421de..0f19cefb8 100644 --- a/packages/stack-encrypt/tests/audit.rs +++ b/packages/stack-encrypt/tests/audit.rs @@ -531,7 +531,7 @@ mod dynamic_path { "notes": { "context": ["users", "notes"], "outputs": ["c"], "type": "string" }, })) .expect("the plan is a frame"); - let plan = record::plan(plan.as_protected_ref()).expect("the plan parses"); + let plan = record::Plan::from_frame(plan.as_protected_ref()).expect("the plan parses"); let user = recipher_frame::serde::to_vec(&json!({ "email": "bob@example.com", "notes": "likes cats", diff --git a/packages/stack-encrypt/tests/binding_conformance.rs b/packages/stack-encrypt/tests/binding_conformance.rs index 2a4f8ba6e..20378d22e 100644 --- a/packages/stack-encrypt/tests/binding_conformance.rs +++ b/packages/stack-encrypt/tests/binding_conformance.rs @@ -94,7 +94,7 @@ fn plan(case: &Case, with_bind: bool) -> record::Plan { ("type", frame("string")), ]), )); - record::plan(object(fields).into_buffer().as_protected_ref()).unwrap() + record::Plan::from_frame(object(fields).into_buffer().as_protected_ref()).unwrap() } /// The bytes a passthrough frame holds: a stored term. fn passthrough_bytes(payload: &stack_encrypt::PassthroughFrame) -> Vec { @@ -298,7 +298,7 @@ async fn binding_conformance() { ]), ), ]; - record::plan(object(tampered).into_buffer().as_protected_ref()).unwrap() + record::Plan::from_frame(object(tampered).into_buffer().as_protected_ref()).unwrap() }; assert!( record::decrypt(keyset.clone(), stored(expected), &other, None) diff --git a/packages/stack-encrypt/tests/conformance.rs b/packages/stack-encrypt/tests/conformance.rs index 6d4b9621b..f440b702c 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -76,7 +76,7 @@ fn plan(corpus: &Corpus, case: &Case) -> record::Plan { let declaration = json!({corpus.field.clone(): { "context": context, "outputs": ["c", "eq"], "type": case.kind, }}); - record::plan( + record::Plan::from_frame( recipher_frame::serde::to_vec(&declaration) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/context_conformance.rs b/packages/stack-encrypt/tests/context_conformance.rs index 24c2b495a..60fafa852 100644 --- a/packages/stack-encrypt/tests/context_conformance.rs +++ b/packages/stack-encrypt/tests/context_conformance.rs @@ -133,7 +133,7 @@ fn plan(case: &Case) -> record::Plan { ("type", frame("string")), ]), )); - record::plan(object(fields).into_buffer().as_protected_ref()).unwrap() + record::Plan::from_frame(object(fields).into_buffer().as_protected_ref()).unwrap() } fn source(case: &Case) -> OwnedFrame { let mut fields = vec![]; @@ -301,7 +301,7 @@ async fn shared_context_composition() { sent.lock().unwrap().generated(), std::slice::from_ref(&vector.descriptor) ); - let query_plan = record::plan( + let query_plan = record::Plan::from_frame( object(vec![( "text", object(vec![ @@ -638,7 +638,7 @@ async fn shared_context_boundaries() { .map(str::to_owned) .collect::>(); label.push("text".into()); - record::plan( + record::Plan::from_frame( object(vec![( "text", object(vec![ @@ -730,7 +730,7 @@ async fn a_grouped_extension_remains_one_part_when_appended() { ("outputs", frame(vec!["c"])), ]), )]); - assert!(record::plan(declaration.into_buffer().as_protected_ref()).is_err()); + assert!(record::Plan::from_frame(declaration.into_buffer().as_protected_ref()).is_err()); } /// A record the removed plan chain sealed when a second `.extend` replaced diff --git a/packages/stack-encrypt/tests/contexts.rs b/packages/stack-encrypt/tests/contexts.rs index 447a882d4..88cb48df9 100644 --- a/packages/stack-encrypt/tests/contexts.rs +++ b/packages/stack-encrypt/tests/contexts.rs @@ -287,7 +287,7 @@ mod a_data_plan { /// A data plan read from its JSON declaration. fn plan_of(declaration: serde_json::Value) -> DataPlan { - record::plan(to_vec(&declaration).unwrap().as_protected_ref()).unwrap() + record::Plan::from_frame(to_vec(&declaration).unwrap().as_protected_ref()).unwrap() } /// One record, as a binding sends it. diff --git a/packages/stack-encrypt/tests/declarations.rs b/packages/stack-encrypt/tests/declarations.rs index f321bb159..4445a0087 100644 --- a/packages/stack-encrypt/tests/declarations.rs +++ b/packages/stack-encrypt/tests/declarations.rs @@ -135,7 +135,10 @@ fn shared_declaration_grammar() { assert!(boundary.fields.is_empty()); } // No cipher/key source exists: declaration checking cannot do key I/O. - match (record::plan(frame.as_protected_ref()), case.expected_error) { + match ( + record::Plan::from_frame(frame.as_protected_ref()), + case.expected_error, + ) { (Ok(plan), None) => { if let Some(expected) = case.normalized { let actual = normalized(&plan); diff --git a/packages/stack-encrypt/tests/exchange_conformance.rs b/packages/stack-encrypt/tests/exchange_conformance.rs index 900218e27..cd0022a60 100644 --- a/packages/stack-encrypt/tests/exchange_conformance.rs +++ b/packages/stack-encrypt/tests/exchange_conformance.rs @@ -218,7 +218,7 @@ impl Serialize for Declaration<'_> { } fn plan_of(fields: &[(String, serde_json::Value)]) -> record::Plan { - record::plan( + record::Plan::from_frame( recipher_frame::serde::to_vec(&Declaration(fields)) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/fixtures/README.md b/packages/stack-encrypt/tests/fixtures/README.md index bdbc55b08..e6ca561ca 100644 --- a/packages/stack-encrypt/tests/fixtures/README.md +++ b/packages/stack-encrypt/tests/fixtures/README.md @@ -79,7 +79,7 @@ by hand. another field's label does not open, as it would not under ZeroKMS. The index key is `FakeDataKeySource`'s: `SHA-256("stack-kms::FakeDataKeySource::index-key::v1" ‖ keyset_id)`, the same every test in the repository derives terms under. -- **`plan`.** The declaration in the data grammar `dynamic::record::plan` +- **`plan`.** The declaration in the data grammar `dynamic::record::Plan::from_frame` parses: per field its label (a list of plain segments), its outputs (`"c"`, `"passthrough"`, or an index key `"eq"`, `"match"`, `"ore"`, `"ope"`) and its `"type"` (a vitaminc `ValueKind` name). The typed author writes the same diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index 73a978fbd..f83a550a5 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -388,7 +388,7 @@ fn spec<'a>(field: &'a str, outputs: &[&str], ty: Option<&str>) -> (&'a str, Own } fn plan() -> record::Plan { - record::plan( + record::Plan::from_frame( object(vec![ spec("email", &["c", "eq", "match", "ore"], Some("string")), spec("doc", &["c"], None), @@ -501,13 +501,13 @@ fn a_late_read_type_failure_leaves_no_plaintext_on_the_heap() { let rt = runtime(); let cipher = rt.block_on(common::stack_cipher()); let keyset = cipher.default_keyset(); - let writer = record::plan( + let writer = record::Plan::from_frame( object(vec![spec("value", &["c"], None)]) .into_buffer() .as_protected_ref(), ) .unwrap(); - let reader = record::plan( + let reader = record::Plan::from_frame( object(vec![spec("value", &["c"], Some("string"))]) .into_buffer() .as_protected_ref(), @@ -1053,7 +1053,7 @@ fn a_json_operators_input_leaves_no_plaintext_on_the_heap() { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.age"]}}} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( stack_encrypt::dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -1235,7 +1235,7 @@ fn an_escaped_literal_in_a_predicate_leaves_no_plaintext_on_the_heap() { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.age"]}}} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( stack_encrypt::dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -1280,7 +1280,7 @@ fn a_key_in_an_operators_input_leaves_no_plaintext_on_the_heap() { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.age"]}}} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( stack_encrypt::dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -2577,7 +2577,7 @@ mod json_index { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": "JsonSearch"} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( stack_encrypt::dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -2636,7 +2636,7 @@ mod json_index { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.age", "$.visits[*].at"]}}} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( stack_encrypt::dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/json_field_references.rs b/packages/stack-encrypt/tests/json_field_references.rs index b38b5e8a6..f3cc59f3b 100644 --- a/packages/stack-encrypt/tests/json_field_references.rs +++ b/packages/stack-encrypt/tests/json_field_references.rs @@ -1695,7 +1695,7 @@ mod as_the_data_plan_derives { } } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/json_index.rs b/packages/stack-encrypt/tests/json_index.rs index 34ec8303f..575131972 100644 --- a/packages/stack-encrypt/tests/json_index.rs +++ b/packages/stack-encrypt/tests/json_index.rs @@ -466,7 +466,7 @@ mod query { } } }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/json_leakage/real.rs b/packages/stack-encrypt/tests/json_leakage/real.rs index 47075bd32..42c458670 100644 --- a/packages/stack-encrypt/tests/json_leakage/real.rs +++ b/packages/stack-encrypt/tests/json_leakage/real.rs @@ -112,7 +112,7 @@ fn plan(column: &Column) -> record::Plan { } } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .expect("the plan is a frame") .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index b9c5b2b89..df0d78863 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -144,7 +144,7 @@ fn scoped_plan_of(target: Value, scope: u64, binding: Option) -> record::Pl } fn parsed(wire: &Value) -> record::Plan { - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(wire) .unwrap() .as_protected_ref(), @@ -1337,7 +1337,7 @@ async fn rows_that_are_not_the_reads_are_refused() { // An entry of another field of the plan, under another column: the // selector is derived under this field's column, so it is not the // one asked for. - let two = record::plan_with( + let two = record::Plan::from_frame_with( (dynamic::frame::serde::to_vec(&json!({ "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.age"]}}}, @@ -1554,7 +1554,7 @@ fn a_malformed_read_is_refused_before_any_key() { // A field that does not store a document has no reads. let wire = json!({"email": {"context": ["users", "email"], "type": "string", "outputs": ["c"]}}); - let scalar = record::plan_with( + let scalar = record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -2234,7 +2234,7 @@ mod element_match { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": {"name": "JsonSearch", "options": {"ordered": ["$.a[*].b"]}}} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), @@ -3315,7 +3315,7 @@ mod compiled_match { "profile": {"context": ["users", "profile"], "type": "json", "null": "sql", "target": "JsonSearch"} }); - let plan = record::plan_with( + let plan = record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/json_predicate_macro.rs b/packages/stack-encrypt/tests/json_predicate_macro.rs index c2dbf5d9b..8c7acf02b 100644 --- a/packages/stack-encrypt/tests/json_predicate_macro.rs +++ b/packages/stack-encrypt/tests/json_predicate_macro.rs @@ -465,7 +465,7 @@ mod as_the_data_plan_derives { } } }); - record::plan_with( + record::Plan::from_frame_with( dynamic::frame::serde::to_vec(&wire) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/lifecycle_conformance.rs b/packages/stack-encrypt/tests/lifecycle_conformance.rs index 19a8aa99a..b8b09dc6e 100644 --- a/packages/stack-encrypt/tests/lifecycle_conformance.rs +++ b/packages/stack-encrypt/tests/lifecycle_conformance.rs @@ -109,7 +109,7 @@ async fn cipher() -> (StackCipher, Arc) { } fn plan() -> record::Plan { - record::plan( + record::Plan::from_frame( (recipher_frame::serde::to_vec(&serde_json::json!({ "value": {"context": ["lifecycle", "value"], "outputs": ["c"], "type": "string"} })) diff --git a/packages/stack-encrypt/tests/owned_equivalence.rs b/packages/stack-encrypt/tests/owned_equivalence.rs index 4da27366f..23cb1333c 100644 --- a/packages/stack-encrypt/tests/owned_equivalence.rs +++ b/packages/stack-encrypt/tests/owned_equivalence.rs @@ -128,7 +128,7 @@ fn data_plan() -> DataPlan { "email": { "context": ["users", "email"], "outputs": ["c", "eq"], "type": "string" }, }); let declaration = recipher_frame::serde::to_vec(&json).expect("frames"); - record::plan(declaration.as_protected_ref()).expect("a plan") + record::Plan::from_frame(declaration.as_protected_ref()).expect("a plan") } fn dynamic_source(user: &User) -> OwnedFrame { object(vec![ diff --git a/packages/stack-encrypt/tests/plan_grammar.rs b/packages/stack-encrypt/tests/plan_grammar.rs index 7a7398ddd..4158ff10c 100644 --- a/packages/stack-encrypt/tests/plan_grammar.rs +++ b/packages/stack-encrypt/tests/plan_grammar.rs @@ -59,7 +59,7 @@ fn field(context: &[&str], outputs: &[&str], kind: &str) -> OwnedFrame { } fn plan_of(declaration: Vec<(&str, OwnedFrame)>) -> Result { - record::plan(object(declaration).into_buffer().as_protected_ref()) + record::Plan::from_frame(object(declaration).into_buffer().as_protected_ref()) } /// A plan whose context is in the declaration: `email` sealed and indexed diff --git a/packages/stack-encrypt/tests/planned.rs b/packages/stack-encrypt/tests/planned.rs index bf45fb389..4e430a265 100644 --- a/packages/stack-encrypt/tests/planned.rs +++ b/packages/stack-encrypt/tests/planned.rs @@ -59,7 +59,7 @@ async fn cipher() -> StackCipher { /// A data plan read from its JSON declaration, with no EQL types. fn plan_of(declaration: serde_json::Value) -> record::Plan { let declaration = recipher_frame::serde::to_vec(&declaration).unwrap(); - record::plan(declaration.as_protected_ref()).unwrap() + record::Plan::from_frame(declaration.as_protected_ref()).unwrap() } /// The data plan of a record with a searchable email and an ordered age, @@ -135,7 +135,7 @@ fn target_plan() -> record::Plan { "email": { "context": ["users", "email"], "target": "Some" }, })) .unwrap(); - record::plan_with(declaration.as_protected_ref(), &OneType).unwrap() + record::Plan::from_frame_with(declaration.as_protected_ref(), &OneType).unwrap() } fn ada() -> OwnedFrame { diff --git a/packages/stack-encrypt/tests/query_operators.rs b/packages/stack-encrypt/tests/query_operators.rs index 24b317de4..1d2f81f9d 100644 --- a/packages/stack-encrypt/tests/query_operators.rs +++ b/packages/stack-encrypt/tests/query_operators.rs @@ -266,8 +266,8 @@ async fn data_term( async fn derived() -> Json { let cipher = deterministic_cipher(SEED).await; let keyset = cipher.default_keyset(); - let plan = - record::plan(frame_of_json(&plan_json()).as_protected_ref()).expect("the plan parses"); + let plan = record::Plan::from_frame(frame_of_json(&plan_json()).as_protected_ref()) + .expect("the plan parses"); let mut terms = Vec::new(); for (field, operator, input) in queries() { diff --git a/packages/stack-encrypt/tests/query_refusal_conformance.rs b/packages/stack-encrypt/tests/query_refusal_conformance.rs index 61aeab18a..d6d6683da 100644 --- a/packages/stack-encrypt/tests/query_refusal_conformance.rs +++ b/packages/stack-encrypt/tests/query_refusal_conformance.rs @@ -290,7 +290,7 @@ async fn shared_query_refusal_profile() { } declaration.insert(name.clone(), field); } - let plan = record::plan( + let plan = record::Plan::from_frame( recipher_frame::serde::to_vec(&declaration) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/raw_frame_conformance.rs b/packages/stack-encrypt/tests/raw_frame_conformance.rs index 072a4795c..f76f65a99 100644 --- a/packages/stack-encrypt/tests/raw_frame_conformance.rs +++ b/packages/stack-encrypt/tests/raw_frame_conformance.rs @@ -189,7 +189,7 @@ fn plan(read: &Declaration) -> record::Plan { if !read.null.is_empty() { spec["null"] = json!(read.null); } - record::plan( + record::Plan::from_frame( recipher_frame::serde::to_vec(&json!({"value": spec})) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/read_conformance.rs b/packages/stack-encrypt/tests/read_conformance.rs index 396c383e8..cf2b974e6 100644 --- a/packages/stack-encrypt/tests/read_conformance.rs +++ b/packages/stack-encrypt/tests/read_conformance.rs @@ -118,7 +118,7 @@ fn plan(decl: &Declaration, context_field: bool, context_name: &str) -> record:: )); } fields.push(("value", framed(&spec))); - record::plan(object(fields).into_buffer().as_protected_ref()).unwrap() + record::Plan::from_frame(object(fields).into_buffer().as_protected_ref()).unwrap() } fn rows(input: &[Row], context_name: Option<&str>) -> OwnedFrame { frame( diff --git a/packages/stack-encrypt/tests/record_lowering.rs b/packages/stack-encrypt/tests/record_lowering.rs index 5f1fbb85f..fa5d04ff7 100644 --- a/packages/stack-encrypt/tests/record_lowering.rs +++ b/packages/stack-encrypt/tests/record_lowering.rs @@ -467,7 +467,7 @@ async fn open_lowered( #[tokio::test] async fn the_chain_and_the_lowering_are_one_engine_today() { let cipher = deterministic_cipher(SEED).await; - let plan = record::plan(frame_of_json(&data_plan_json()).as_protected_ref()) + let plan = record::Plan::from_frame(frame_of_json(&data_plan_json()).as_protected_ref()) .expect("the data plan parses"); let typed = json_of_record(seal_typed(&cipher).await); @@ -502,7 +502,7 @@ async fn the_chain_and_the_lowering_are_one_engine_today() { async fn the_committed_fixture_opens_both_ways() { let update = common::fixture_updates_requested_or_panic(); let cipher = deterministic_cipher(SEED).await; - let plan = record::plan(frame_of_json(&data_plan_json()).as_protected_ref()) + let plan = record::Plan::from_frame(frame_of_json(&data_plan_json()).as_protected_ref()) .expect("the data plan parses"); let path = fixture_path(); @@ -783,7 +783,7 @@ async fn open_note_lowered( #[tokio::test] async fn the_chain_and_the_lowering_agree_on_a_context_field_today() { let cipher = deterministic_cipher(SEED).await; - let plan = record::plan(frame_of_json(¬e_plan_json()).as_protected_ref()) + let plan = record::Plan::from_frame(frame_of_json(¬e_plan_json()).as_protected_ref()) .expect("the data plan parses"); assert_eq!(plan.context_field(), Some("tenant")); @@ -834,7 +834,7 @@ async fn the_chain_and_the_lowering_agree_on_a_context_field_today() { async fn the_committed_context_field_case_opens_both_ways() { let update = common::fixture_updates_requested_or_panic(); let cipher = deterministic_cipher(SEED).await; - let plan = record::plan(frame_of_json(¬e_plan_json()).as_protected_ref()) + let plan = record::Plan::from_frame(frame_of_json(¬e_plan_json()).as_protected_ref()) .expect("the data plan parses"); let path = fixture_path(); @@ -907,7 +907,8 @@ async fn the_committed_context_field_case_opens_both_ways() { #[tokio::test] async fn the_fixture_records_are_bound_to_their_labels() { let cipher = deterministic_cipher(SEED).await; - let plan = record::plan(frame_of_json(&data_plan_json()).as_protected_ref()).expect("plan"); + let plan = record::Plan::from_frame(frame_of_json(&data_plan_json()).as_protected_ref()) + .expect("plan"); let sealed = seal_lowered(&cipher, &plan).await; let CipherText::Map(mut fields) = sealed else { panic!("a map"); diff --git a/packages/stack-encrypt/tests/runtime_conformance.rs b/packages/stack-encrypt/tests/runtime_conformance.rs index 0432584cf..cbe75ea79 100644 --- a/packages/stack-encrypt/tests/runtime_conformance.rs +++ b/packages/stack-encrypt/tests/runtime_conformance.rs @@ -103,7 +103,7 @@ async fn shared_record_runtime_profile() { if !case.null.is_empty() { spec["null"] = json!(case.null); } - let plan = record::plan( + let plan = record::Plan::from_frame( recipher_frame::serde::to_vec(&json!({"value":spec})) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/scopes_and_bindings.rs b/packages/stack-encrypt/tests/scopes_and_bindings.rs index 586d9f636..db23067c5 100644 --- a/packages/stack-encrypt/tests/scopes_and_bindings.rs +++ b/packages/stack-encrypt/tests/scopes_and_bindings.rs @@ -641,7 +641,7 @@ mod a_binding_in_a_query { "email": { "context": ["users", "email"], "outputs": ["c", "eq"], "type": "string" }, })) .unwrap(); - record::plan(declaration.as_protected_ref()).unwrap() + record::Plan::from_frame(declaration.as_protected_ref()).unwrap() } #[tokio::test] diff --git a/packages/stack-encrypt/tests/stored_rows.rs b/packages/stack-encrypt/tests/stored_rows.rs index 37625fc41..a0d0612b4 100644 --- a/packages/stack-encrypt/tests/stored_rows.rs +++ b/packages/stack-encrypt/tests/stored_rows.rs @@ -317,7 +317,8 @@ fn frame_of_json(value: &Json) -> vitaminc_protected::Buffer { } fn plan_of(json: &Json) -> DataPlan { - record::plan(frame_of_json(json).as_protected_ref()).expect("the frozen plan parses") + record::Plan::from_frame(frame_of_json(json).as_protected_ref()) + .expect("the frozen plan parses") } // ---- sealing and opening ---------------------------------------------------- diff --git a/packages/stack-encrypt/tests/value_bytes.rs b/packages/stack-encrypt/tests/value_bytes.rs index 57967889e..5077041b3 100644 --- a/packages/stack-encrypt/tests/value_bytes.rs +++ b/packages/stack-encrypt/tests/value_bytes.rs @@ -210,7 +210,7 @@ async fn typed_section(cipher: &StackCipher, keys: &Kept) -> Json { fn plan(spec: &Json) -> Result { let mut spec = spec.clone(); spec["context"] = json!(CONTEXT); - record::plan( + record::Plan::from_frame( recipher_frame::serde::to_vec(&json!({ "value": spec })) .unwrap() .as_protected_ref(), @@ -747,7 +747,7 @@ async fn a_timestamp_in_any_unit_seals_to_the_nanosecond_leaf() { #[tokio::test] async fn a_passthrough_timestamp_keeps_the_hosts_bytes() { let (cipher, _) = cipher().await; - let plan = record::plan( + let plan = record::Plan::from_frame( recipher_frame::serde::to_vec(&json!({ "sealed": { "context": ["conformance", "sealed"], "outputs": ["c"], "type": "int32" }, "value": { "context": ["conformance", "value"], "outputs": ["passthrough"], "type": "timestamp" }, diff --git a/packages/stack-encrypt/tests/value_conformance.rs b/packages/stack-encrypt/tests/value_conformance.rs index efea2159d..35aa46c68 100644 --- a/packages/stack-encrypt/tests/value_conformance.rs +++ b/packages/stack-encrypt/tests/value_conformance.rs @@ -182,7 +182,7 @@ async fn shared_record_value_profile() { if !case.null.is_empty() { spec["null"] = json!(case.null); } - let plan = record::plan( + let plan = record::Plan::from_frame( recipher_frame::serde::to_vec(&json!({"value": spec})) .unwrap() .as_protected_ref(), diff --git a/packages/stack-encrypt/tests/value_kinds.rs b/packages/stack-encrypt/tests/value_kinds.rs index 6a5b118fb..35637a4e9 100644 --- a/packages/stack-encrypt/tests/value_kinds.rs +++ b/packages/stack-encrypt/tests/value_kinds.rs @@ -188,7 +188,8 @@ fn data_plan() -> DataPlan { ) }) .collect(); - record::plan(object(fields).into_buffer().as_protected_ref()).expect("the data plan parses") + record::Plan::from_frame(object(fields).into_buffer().as_protected_ref()) + .expect("the data plan parses") } /// The source as a binding hands it over: one frame, a map of the fields in From 3a9d31623eaabbbdf221f40b42cf19284b0fdee6 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 3 Dec 2026 22:57:38 +1100 Subject: [PATCH 17/23] test(stack-encrypt): the UI snapshot names planned.rs at its new path The module moved under dynamic/record, so the compiler's note points there. --- .../tests/ui/field_handle_value_is_a_frame.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/stack-encrypt/tests/ui/field_handle_value_is_a_frame.stderr b/packages/stack-encrypt/tests/ui/field_handle_value_is_a_frame.stderr index f74a4771b..fb90ba413 100644 --- a/packages/stack-encrypt/tests/ui/field_handle_value_is_a_frame.stderr +++ b/packages/stack-encrypt/tests/ui/field_handle_value_is_a_frame.stderr @@ -7,7 +7,7 @@ error[E0277]: the trait bound `std::string::String: stack_encrypt::dynamic::Quer | required by a bound introduced by this call | help: the following other types implement trait `stack_encrypt::dynamic::QueryValue` - --> src/dynamic/planned.rs + --> src/dynamic/record/planned.rs | | impl QueryValue for OwnedFrame {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `OwnedFrame` @@ -18,7 +18,7 @@ help: the following other types implement trait `stack_encrypt::dynamic::QueryVa | impl QueryValue for Frame<'_> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Frame<'_>` note: required by a bound in `FieldHandle::<'p, R>::eq` - --> src/dynamic/planned.rs + --> src/dynamic/record/planned.rs | | pub fn $method(self, value: V) -> Result, Error> { | ^^^^^^^^^^ required by this bound in `FieldHandle::<'p, R>::eq` From db03a5cf2889689fe843973848cfc18cb97a6b5e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 3 Dec 2026 23:37:00 +1100 Subject: [PATCH 18/23] docs(stack-encrypt): doc comments name planned at its new path The record module's docs, the Absent type and a comment in target::operations named dynamic::planned, which is now dynamic::record::planned. The language integration guide pointed at plan.rs for the grammar, which record.rs still describes, and the source reader's docs now say a value that is not a record is a NotARecord error. --- packages/stack-encrypt/docs/language-integration.md | 2 +- packages/stack-encrypt/src/dynamic/record.rs | 6 +++--- packages/stack-encrypt/src/dynamic/record/source.rs | 6 +++--- packages/stack-encrypt/src/target/operations.rs | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 304a852a2..c914b9ac7 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -325,7 +325,7 @@ boundary hands over the plan's bytes on every call: A plan is a map from field name to field spec. The grammar is defined by what [`crate::dynamic::record::Plan::from_frame_with`] accepts, in `src/dynamic/record/plan.rs`; -its docs and the module docs there are the full statement, and +its docs and the module docs of `src/dynamic/record.rs` are the full statement, and `conformance/stack-encrypt/declaration-grammar.md` states it as a contract with the cases every binding runs. The shape: diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index c754399ea..d67b6806e 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -5,11 +5,11 @@ //! field, a context, what to produce and, optionally, what type the values //! are. This module reads that declaration ([`Plan::from_frame`]) and *lowers* it to //! the combinators the derive's generated code is made of -//! (`super::planned::compose`): `ciphertext`, `indexed`, the indexes' +//! (`self::planned::compose`): `ciphertext`, `indexed`, the indexes' //! `operations` or `passthrough` per field, each under the field's label. //! Encrypting runs that description through //! [`KeysetCipher::run`](crate::KeysetCipher::run); decrypting runs its -//! opening (`super::planned::opening`). There is no second executor here: +//! opening (`self::planned::opening`). There is no second executor here: //! every field's context, every key request and the one batch they settle //! in are the engine's, so a record written from Go and one written from //! Rust under the same declaration are the same bytes because they ran the @@ -610,7 +610,7 @@ struct EncryptedRecord { /// The `"null": "sql"` fields a row leaves out: null in a source, or with /// no entry in a source or a stored record. Nothing is sealed, derived or /// opened for them, so a row is run by the plan composed without them -/// (`super::planned::compose`), with the other rows that leave out the same +/// (`self::planned::compose`), with the other rows that leave out the same /// fields. type Absent = BTreeSet; diff --git a/packages/stack-encrypt/src/dynamic/record/source.rs b/packages/stack-encrypt/src/dynamic/record/source.rs index efdd370ee..aef3e45d4 100644 --- a/packages/stack-encrypt/src/dynamic/record/source.rs +++ b/packages/stack-encrypt/src/dynamic/record/source.rs @@ -16,9 +16,9 @@ //! value lists them. A field name that appears twice is kept twice. //! * A sequence is a batch. Each element of the sequence is one record. //! * Anything else is not a record: a single value, a null, a passthrough -//! value, or a sequence inside a batch. The entry for that value is the -//! kind of the value, as a [`Found`]. Nothing inside the value is copied -//! or checked. +//! value, or a sequence inside a batch. The entry for that value is a +//! `NotARecord` error with the kind of the value, as a [`Found`]. +//! Nothing inside the value is copied or checked. //! //! The first step does not compare the fields with the plan. The second //! step does: [`into_source_records`] refuses a value that is not a diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 95810f036..ad2f5f998 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -736,7 +736,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { /// description yields that error without I/O. /// /// Crate-internal: the data plan's lowering - /// (`dynamic::planned::compose`) is its caller. + /// (`dynamic::record::planned::compose`) is its caller. /// /// `field` names the field of the source the label is read from, and /// `identity` the segment `own` joins to it, for From d92d4dcb604090d8f3700b6dc82b14d2a040fae0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 3 Dec 2026 23:54:56 +1100 Subject: [PATCH 19/23] docs(stack-encrypt): the last references to record::plan and the old paths The IndexSpec rustdoc, three unreleased changelog entries and the TypeScript SDK plan named record::plan, which is now Plan::from_frame, and the plan cited planned.rs at its old path. Output's link to the stability section resolved against the wrong module after the move. The source reader's docs say what "the split" is now that split_source is renamed, and a test's doc comment names the rule it refers to. --- docs/plans/2026-11-22-recipher-typescript-sdk.md | 10 +++++----- packages/stack-encrypt/CHANGELOG.md | 6 +++--- packages/stack-encrypt/src/dynamic/record/plan.rs | 2 +- packages/stack-encrypt/src/dynamic/record/source.rs | 8 +++++--- packages/stack-encrypt/src/target/index.rs | 2 +- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/plans/2026-11-22-recipher-typescript-sdk.md b/docs/plans/2026-11-22-recipher-typescript-sdk.md index 3338d379a..1ce7d36ed 100644 --- a/docs/plans/2026-11-22-recipher-typescript-sdk.md +++ b/docs/plans/2026-11-22-recipher-typescript-sdk.md @@ -451,7 +451,7 @@ const opened = await cipher.decrypt(stored, { record: UserRecord }).unwrap(); from, and the stored type is fixed before any row exists. So `encrypt(kinds.string)` names it, in Stack Encrypt's word for the kind. - **`record()` writes Stack Encrypt's plan.** The plan is the form that - `dynamic::record::plan` reads, and the form that Go sends. The + `Plan::from_frame` reads, and the form that Go sends. The declaration above holds this plan: ```ts @@ -474,7 +474,7 @@ const opened = await cipher.decrypt(stored, { record: UserRecord }).unwrap(); name for it. - **The binding reads the plan and calls Stack Encrypt.** The value bridge converts the plan object to a frame, as it converts any value, so - TypeScript writes no frame. `dynamic::record::plan` reads the frame. + TypeScript writes no frame. `Plan::from_frame` reads the frame. `dynamic::Planned` encrypts and decrypts the rows. The binding keeps each plan it has read, keyed by the plan's bytes, so each plan is read once. @@ -1148,7 +1148,7 @@ The core, with no EQL: UUID record field. 3. **Records.** `record`, `encrypt`, `passthrough`, nulls, the encrypted row's type, the type tests, and the declaration, runtime, and read - profiles. This step is the first to call `dynamic::record::plan` and + profiles. This step is the first to call `Plan::from_frame` and `Planned`. One field with `{ record, field }` comes later, when Stack Encrypt has a call for it (#2028). The pending result (#2026) follows the records, and changes every async call before search terms add more. @@ -1299,7 +1299,7 @@ Read on 2026-11-23, on `next` at `e62420d8e`: closed; the others named there are open. - A plan field declares its context as a list of names (`"context": ["users", "email"]`, in the module example of - `packages/stack-encrypt/src/dynamic/planned.rs`), and a `Planned` + `packages/stack-encrypt/src/dynamic/record/planned.rs`), and a `Planned` encrypts and decrypts with no context from the caller (`encrypt_into` and `decrypt_from` in the tests of `dynamic/record.rs`). An expected context is an `Option