From bdfd9feedb9575d773917272020cd129e4b8c332 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 30 Nov 2026 01:10:45 +1100 Subject: [PATCH 1/6] feat(stack-encrypt): encrypt and decrypt one field of a plan An application often changes one field of a row. A language binding had no call for that: a row that lacks a field of the plan is refused. So a binding had to build a second plan for each field, and wrap each value in a row of one field. Plan::one_field(name) returns a OneFieldPlan, the plan narrowed to that field. A value under it runs through Planned and the one executor of a whole row. The result is the field's node, as it sits in a whole row. Decrypting takes that node. A null of a "null": "sql" field has no node. The executor and the opener are split out of run_encrypt and run_decrypt, so a whole row and one field run through the same code. The new reasons are passthrough_field, context_from_record, and index_only. --- packages/stack-encrypt/CHANGELOG.md | 30 + .../docs/language-integration.md | 28 + packages/stack-encrypt/src/dynamic/mod.rs | 5 +- packages/stack-encrypt/src/dynamic/planned.rs | 682 +++++++++---- packages/stack-encrypt/src/dynamic/record.rs | 232 +++++ packages/stack-encrypt/src/refusal.rs | 16 + .../tests/one_field.proptest-regressions | 7 + packages/stack-encrypt/tests/one_field.rs | 911 ++++++++++++++++++ 8 files changed, 1723 insertions(+), 188 deletions(-) create mode 100644 packages/stack-encrypt/tests/one_field.proptest-regressions create mode 100644 packages/stack-encrypt/tests/one_field.rs diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7ab0bf090..10116f5d4 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Encrypt and decrypt one field of a record alone** (#2028). An + application often changes one field of a row, such as a user's email. + `Plan::one_field(name)` returns a `OneFieldPlan`: the record's plan + narrowed to that field. A value runs under it through `Planned`, as a + record does: + - `Planned::new(&one, value).encrypt_into(&keyset)` returns an + `Option`. It is the field's node, the map of its + outputs (`c` and its index terms), exactly as it sits in a whole row. + It is `None` for a null of a `"null": "sql"` field. Store SQL `NULL` + for it. + - `OwnedFrame::decrypt_from(Planned::new(&one, node), &keyset)` decrypts + a node, or an `Option` of one, to the field's value. + - A `Vec` of them is a batch, in one key request. + - The field keeps its context, type, conversions, indexes, and null + mode. It also keeps the plan's scopes and bindings. It runs through + the same code as a whole row. So a node encrypted alone decrypts inside + a whole row, and a whole row's node decrypts alone. + - A field that names an EQL type runs through the resolver given to + `Planned::with_resolver`, as it does in a whole row. + - `Plan::one_field` refuses: + - a name that the plan does not declare (`no_such_field`) + - a passthrough field (`passthrough_field`, a new reason) + - every field of a plan that takes its context from a field of each + record (`context_from_record`, a new reason) + - A field with index terms and no `c` has nothing to decrypt. Its + decrypt is refused before any key is requested (`index_only`, a new + reason). + - The conformance profile `record-fields-v1` has the shared cases. Its + Go runner is pending. + - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 064f5c2b0..dd0d8ee43 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -170,6 +170,34 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. +### Encrypt or decrypt one field + +An application often changes one field of a row, and an ORM can encrypt a +row one column at a time. A binding does not build a plan for each field, +or wrap a value in a row of one field. It asks the plan for the field: + +1. [`crate::dynamic::record::Plan::one_field`]`(name)` returns a + [`crate::dynamic::OneFieldPlan`]. Keep it beside the plan. The call + refuses a name that the plan does not declare, and a passthrough field. + It also refuses every field of a plan with a `"context_field"`, because + the field's context is in another field of the row. +2. `Planned::new(&one_field, value).encrypt_into(&keyset)` settles to an + `Option`: the field's **node**, the map of its outputs, + exactly as it sits under the field's name in a whole row. It is `None` + for a null of a `"null": "sql"` field. Store SQL `NULL` for it. +3. `OwnedFrame::decrypt_from(Planned::new(&one_field, node), cipher)` + settles to the field's value. The node is a `StackCipherText`, or an + `Option` of one, whose `None` opens as a null of a `"null": "sql"` + field. A field with index terms and no `c` has nothing to decrypt. + +The field runs through the same code as a whole row. It keeps its context, +type, conversions, indexes, and null mode. It also keeps the plan's scopes +and bindings. So a node encrypted alone decrypts inside a whole row, +and a whole row's node decrypts alone. + +The call takes a scope and a binding as a record does. A `Vec` of +`Planned` values is a batch, in one ZeroKMS call. + ### One value as one ciphertext A record is not the only stored form. Rust's `keyset.encrypt(value)` diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 23771176e..d61fbd981 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -45,6 +45,9 @@ //! language is the same bytes. The one step that stays dynamic is //! dispatching a value whose type is known only at run time to the typed //! term operation, which [`IndexSpec`](crate::target::IndexSpec)'s `Index` impls do. +//! * [`OneFieldPlan`] — a record's plan narrowed to one field +//! ([`Plan::one_field`]). One value of the field encrypts to the node +//! that the field has in a whole row. That node decrypts alone. //! * [`read_json`] and [`json_frame`] — a `json` field's document, from //! the JSON text a binding hands over and back to it. //! * [`TargetResolver`] — the EQL types a build holds, installed by the host @@ -130,7 +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 planned::{DynamicQuery, FieldHandle, Planned, QueryPlan, QueryValue}; +pub use planned::{DynamicQuery, FieldHandle, OneFieldPlan, 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, diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 8f38d5a04..edf8ced45 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -11,6 +11,11 @@ //! a query takes scopes only: a binding on a query is refused before any //! key is requested ([`PlanError::BindInQuery`]). //! +//! A [`OneFieldPlan`], from [`Plan::one_field`], is a plan narrowed to one +//! of its fields. One value of the field runs under it, through the same +//! lowering as a whole row. The value encrypts to the field's node: what +//! the field stores in a whole row. +//! //! ``` //! use stack_encrypt::dynamic::{record, Op, Planned, QueryTerm, frame::OwnedFrame}; //! use stack_encrypt::target::Scope; @@ -343,6 +348,31 @@ impl Plan { resolver, }) } + + /// This plan for the field `name` alone ([`OneFieldPlan`]). One value + /// of the field encrypts and decrypts under it. The field keeps its + /// label, type, indexes, and null mode. It also keeps the plan's scopes + /// and bindings. So the value is sealed as it is in a whole row, with + /// the same terms. + /// + /// A field that cannot be encrypted alone is refused here, before any + /// value exists. + /// + /// # Errors + /// + /// [`Error::Plan`], naming the field, with one of these reasons: + /// + /// - [`Reason::NoSuchField`] for a name that the plan does not declare. + /// - [`Reason::ContextFromRecord`] for a plan that takes its context + /// from a field of each record ([`Plan::with_context_field`]). The + /// field's context is in another field of the row. + /// - [`Reason::PassthroughField`] for a passthrough field. A passthrough + /// is stored as it is. + pub fn one_field(&self, name: &str) -> Result { + Ok(OneFieldPlan { + plan: self.narrowed(name)?, + }) + } } /// A record under a plan encrypts to the stored row: every field under its @@ -477,105 +507,123 @@ where resolver, } = self; let rows = record::source_rows(value, plan)?; - let extend = plan.declared_context(); - let shape = plan.shape(); - // Every target field of every row, in row-major order, run by the - // resolver; `all` merges their requests with the lowered plan's - // 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)) - }; - Ok(match rows { - Rows::One(row) => { - let (absent, values, _) = targets(row)?; - let description = compose::(plan, &absent).map_err(|_| Error::Internal)?; - let eql = Pending::all(cipher, pendings); - cipher - .run(description, values, extend) - .zip(eql) - .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) + seal_rows(cipher, plan, rows, resolver) + } +} + +/// Run the plan over its rows, as [`Planned::run_encrypt`] describes: the +/// one executor of a plan that is data. A whole record and one field alone +/// ([`OneFieldPlan`]) both run here. So a field is sealed and indexed the +/// same way in each. +/// +/// # Errors +/// +/// [`Error::Target`] for what the resolver refuses. +/// [`Error::Internal`] for a plan that does not lower. +fn seal_rows<'a, K: 'static>( + cipher: &'a KeysetCipher<'_, K>, + plan: &Plan, + rows: Rows, + resolver: &(impl TargetResolver + ?Sized), +) -> Result, Error> { + let extend = plan.declared_context(); + let shape = plan.shape(); + // Every target field of every row, in row-major order, run by the + // resolver; `all` merges their requests with the lowered plan's + // 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)) + }; + Ok(match rows { + Rows::One(row) => { + let (absent, values, _) = targets(row)?; + let description = compose::(plan, &absent).map_err(|_| Error::Internal)?; + let eql = Pending::all(cipher, pendings); + cipher + .run(description, values, extend) + .zip(eql) + .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) + } + Rows::Batch(rows) => { + let rows = rows + .into_iter() + .map(&mut targets) + .collect::, Error>>()?; + let len = rows.len(); + let mut per_row = Vec::with_capacity(len); + let groups = by_absent( + rows.into_iter() + .map(|(absent, values, count)| { + per_row.push((absent.clone(), count)); + (absent, values) + }) + .collect(), + ); + // One lowered plan per group of rows that leave out the same + // fields, every group's requests merged into the one call. + // Each row lowers its own when it is built. Lowering depends + // on the plan and the group alone, so a group whose plan + // does not lower is refused here, before the pending exists. + for (absent, _, _) in &groups { + let _ = compose::(plan, absent).map_err(|_| Error::Internal)?; } - Rows::Batch(rows) => { - let rows = rows + let (groups, positions) = BatchRows::new(groups); + let plan = plan.clone(); + let row = move |absent: &Absent, values: FieldValues| match compose::(&plan, absent) + { + Ok(description) => cipher.run(description, values, extend.clone()), + // Not reached: lowering depends on the plan and the + // group alone, and every group lowered above. Each + // row composes its own because a description runs + // once. + Err(_) => Pending::failed(cipher, wrap(Error::Internal)), + }; + let eql = Pending::all(cipher, pendings); + let finish = move |groups: Vec>>| { + let runs = groups .into_iter() - .map(&mut targets) - .collect::, Error>>()?; - let len = rows.len(); - let mut per_row = Vec::with_capacity(len); - let groups = by_absent( - rows.into_iter() - .map(|(absent, values, count)| { - per_row.push((absent.clone(), count)); - (absent, values) - }) - .collect(), - ); - // One lowered plan per group of rows that leave out the same - // fields, every group's requests merged into the one call. - // Each row lowers its own when it is built. Lowering depends - // on the plan and the group alone, so a group whose plan - // does not lower is refused here, before the pending exists. - for (absent, _, _) in &groups { - let _ = compose::(plan, absent).map_err(|_| Error::Internal)?; - } - let (groups, positions) = BatchRows::new(groups); - let plan = plan.clone(); - let row = - move |absent: &Absent, values: FieldValues| match compose::(&plan, absent) { - Ok(description) => cipher.run(description, values, extend.clone()), - // Not reached: lowering depends on the plan and the - // group alone, and every group lowered above. Each - // row composes its own because a description runs - // once. - Err(_) => Pending::failed(cipher, wrap(Error::Internal)), - }; - let eql = Pending::all(cipher, pendings); - let finish = move |groups: Vec>>| { - let runs = groups - .into_iter() - .map(|rows| Pending::all(cipher, rows)) - .collect(); - Pending::all(cipher, runs) - .zip(eql) - .try_map(move |(groups, eql)| { - let rows = in_row_order(len, positions.into_iter().zip(groups))?; - let mut eql = eql.into_iter(); - rows.into_iter() - .zip(per_row) - .map(|(values, (absent, count))| { - let own: Vec> = eql.by_ref().take(count).collect(); - shape_record(values, own, &shape, &absent) - }) - .collect::, _>>() - .map(CipherText::Sequence) - }) - }; - built_in_chunks(cipher, groups, row, finish) - } - }) - } + .map(|rows| Pending::all(cipher, rows)) + .collect(); + Pending::all(cipher, runs) + .zip(eql) + .try_map(move |(groups, eql)| { + let rows = in_row_order(len, positions.into_iter().zip(groups))?; + let mut eql = eql.into_iter(); + rows.into_iter() + .zip(per_row) + .map(|(values, (absent, count))| { + let own: Vec> = eql.by_ref().take(count).collect(); + shape_record(values, own, &shape, &absent) + }) + .collect::, _>>() + .map(CipherText::Sequence) + }) + }; + built_in_chunks(cipher, groups, row, finish) + } + }) } impl<'p, 'r, R> Planned<'p, Plan, StackCipherText, &'r R> @@ -612,100 +660,121 @@ where value, resolver, } = self; - let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); let rows = record::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::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)) - }; - Ok(match rows { - Rows::One(row) => { - let (absent, values, _) = targets(row)?; - let eql = Pending::all(cipher, pendings); - confine( - cipher.run_decryption(opening::(plan, values, expected, extend, &absent)), - &cipher_ref, - ) - .zip(eql) - .try_map(move |(values, eql)| { - write_record(Rows::One(open_record(values, eql, &shape, &absent)?)) - }) - } - Rows::Batch(rows) => { - let rows = rows - .into_iter() - .map(&mut targets) - .collect::, Error>>()?; - let len = rows.len(); - let mut per_row = Vec::with_capacity(len); - let groups = by_absent( - rows.into_iter() - .map(|(absent, values, count)| { - per_row.push((absent.clone(), count)); - (absent, values) - }) - .collect(), - ); - let (groups, positions) = BatchRows::new(groups); - let plan = plan.clone(); - let row = move |absent: &Absent, values: FieldValues| { - cipher.run_decryption(opening::( - &plan, - values, - expected.clone(), - extend.clone(), - absent, - )) - }; - let eql = Pending::all(cipher, pendings); - let caller = cipher_ref.clone(); - let finish = move |groups: Vec>>| { - let opens = groups - .into_iter() - .map(|rows| confine(Pending::collect(cipher, rows), &caller)) - .collect(); - Pending::all(cipher, opens) - .zip(eql) - .try_map(move |(groups, eql)| { - let rows = in_row_order(len, positions.into_iter().zip(groups))?; - let mut eql = eql.into_iter(); - let rows = rows - .into_iter() - .zip(per_row) - .map(|(values, (absent, count))| { - let own: Vec = eql.by_ref().take(count).collect(); - open_record(values, own, &shape, &absent) - }) - .collect::, _>>()?; - write_record(Rows::Batch(rows)) - }) - }; - built_in_chunks(cipher_ref, groups, row, finish) - } - }) + open_rows(cipher_ref, plan, rows, resolver, expected) + .map(|pending| pending.try_map(write_record)) } } +/// One opened row: each field that comes back, with its value, in plan +/// order. +type OpenedRow = Vec<(String, OwnedFrame)>; + +/// Open the stored rows through the plan, as [`Planned::run_decrypt`] +/// describes: the one opener of a plan that is data. A whole record and +/// one field alone ([`OneFieldPlan`]) both open here. The pending settles +/// to each row's fields, for the caller to write out. +/// +/// # Errors +/// +/// [`Error::Target`] for what the resolver refuses. +fn open_rows<'a, K: 'static>( + cipher_ref: impl Into>, + plan: &Plan, + rows: Rows, + resolver: &(impl TargetResolver + ?Sized), + expected: Option