From c6125822d7aece1d8c8f8e916eaa2ec4a246fd69 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 14:04:05 +1100 Subject: [PATCH 01/68] feat(normalize): add vitaminc-normalize with the Terms sink Index terms become a sink, and normalization becomes its own crate. The per-scalar equality encoders behind vitaminc-aead-value's canonical feature move here and become public, under the same frozen domain labels, plus a domain of its own for a uuid over its sixteen raw bytes. A date, a timestamp, a decimal and a uuid are separate from the physical value they are stored as, so a date's day count never matches the integer it equals; every other logical type has no term. Terms produces one term per scalar that has a domain, with the path to it, and runs beside encryption as Tee(EncryptSink, Terms), so a caller holds every term before any cipher is called and, with an async cipher, before the first await. A null, a boolean or an undefined produces no term and does not stop the walk, since those are ordinary things to find in a document; a logical type this crate does not know stops it, since encrypting a value from a newer client with no term and no error would leave an index silently incomplete. The crate has no cryptography in it and never imports PAE, though it builds on vitaminc-aead and inherits that crate's dependencies. It takes rust_decimal for the decimal term only, whose constant-time encoding it does not want a second copy of. SourceError::inner is now 'static so a caller can downcast the NormalizeError a terms walk reports. Refs cipherstash/vitaminc#410 Claude-Session: https://claude.ai/code/session_4caef6c7-64a1-4cf8-b491-2026ed98c2a9 --- packages/vitaminc-normalize/Cargo.toml | 50 ++ packages/vitaminc-normalize/README.md | 114 ++++ packages/vitaminc-normalize/src/lib.rs | 14 + packages/vitaminc-normalize/src/scalar.rs | 308 +++++++++++ .../vitaminc-normalize/src/scalar_tests.rs | 433 +++++++++++++++ packages/vitaminc-normalize/src/terms.rs | 267 ++++++++++ .../vitaminc-normalize/tests/known_answers.rs | 504 ++++++++++++++++++ 7 files changed, 1690 insertions(+) create mode 100644 packages/vitaminc-normalize/Cargo.toml create mode 100644 packages/vitaminc-normalize/README.md create mode 100644 packages/vitaminc-normalize/src/lib.rs create mode 100644 packages/vitaminc-normalize/src/scalar.rs create mode 100644 packages/vitaminc-normalize/src/scalar_tests.rs create mode 100644 packages/vitaminc-normalize/src/terms.rs create mode 100644 packages/vitaminc-normalize/tests/known_answers.rs diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml new file mode 100644 index 000000000..2167e104a --- /dev/null +++ b/packages/vitaminc-normalize/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "vitaminc-normalize" +description = "Normalized equality terms for the plaintext data model. Part of the Vitamin-C cryptographic suite." +documentation = "https://docs.rs/vitaminc-normalize" +version.workspace = true +repository.workspace = true +authors.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +keywords.workspace = true +categories.workspace = true +rust-version.workspace = true + +[dependencies] +vitaminc-aead = { version = "0.5.1", path = "../aead" } +vitaminc-protected = { version = "0.5.1", path = "../protected" } + +# Only for the decimal term. Its encoding is constant-time arithmetic over +# the mantissa and scale that this crate does not want a second copy of, so +# the (scale, mantissa) pair is turned back into a `Decimal` to encode it. +rust_decimal = { version = "1.41", default-features = false, features = ["std"] } + +# Temporary review pin: ore.rs #97; replace with its 0.2 release before publishing. +[dependencies.orderable-bytes] +git = "https://github.com/cipherstash/ore.rs" +rev = "b3b7800b9c0cd8f7c53c5382f8e018a4e8bcbbd5" +features = ["decimal"] + +# NFC is stable for assigned code points, and the Unicode 16 assignment check +# refuses everything else, so newer normalization releases are safe. +[dependencies.unicode-normalization] +version = "0.1.24" + +# Exact pin: this table defines which code points are assigned in Unicode 16, +# and a newer table would widen the accepted input of a frozen domain. +[dependencies.unicode-general-category] +version = "=1.1.0" + +[dev-dependencies] +# Path-only, so publish order does not matter: the known-answer tests check +# every term against today's `canonical` encoders, byte for byte, until +# those are removed. +vitaminc-aead-value = { path = "../aead-value", features = ["canonical", "chrono", "rust_decimal"] } +vitaminc-aead = { path = "../aead", features = ["chrono", "rust_decimal", "uuid"] } +chrono = { version = "0.4.44", default-features = false, features = ["std"] } +uuid = { version = "1", default-features = false } +quickcheck = "1.1.0" +quickcheck_macros = "1.2.0" +futures-executor = "0.3.31" diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md new file mode 100644 index 000000000..e189d64ff --- /dev/null +++ b/packages/vitaminc-normalize/README.md @@ -0,0 +1,114 @@ +# Vitamin C Normalize + +[![Crates.io](https://img.shields.io/crates/v/vitaminc-normalize.svg)](https://crates.io/crates/vitaminc-normalize) +[![Workflow Status](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml/badge.svg)](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml) + +Normalized equality terms for the plaintext data model of +[`vitaminc-aead`](https://docs.rs/vitaminc-aead). Part of the +[Vitamin C](https://github.com/cipherstash/vitaminc) framework. + +An equality index derives a key from a value. Two values that are equal +must derive the same key whichever width, scale or spelling wrote them, +and two values that merely look alike (a date and the integer it is stored +as, a uuid and the same sixteen bytes) must not. This crate decides both: +each scalar kind that can be indexed has a frozen **domain label** and a +**normalization** to bytes, and everything else has no term. + +There is no cryptography here and no PAE: the crate's own dependencies +are the Unicode tables, `orderable-bytes` and `rust_decimal`. (It builds +on `vitaminc-aead` for the data model, which brings that crate's +dependencies with it.) A PRF crate such as +[`vitaminc-prf`](https://docs.rs/vitaminc-prf) takes a [`Normalized`] +and derives under its domain. + +## One scalar + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::{Int, Logical, Physical}; +use vitaminc_protected::Controlled; + +// Every integer width is one term. +let a = normalize(None, Physical::Int(Int::I8(34)))?; +let b = normalize(None, Physical::Int(Int::U64(34)))?; +assert_eq!(a.domain, domain::INTEGER); +assert_eq!(a.bytes.risky_ref(), b.bytes.risky_ref()); + +// A date is not the integer it is stored as. +let day = normalize(Some(Logical::Date), Physical::Int(Int::I32(34)))?; +assert_eq!(day.domain, domain::DATE); +assert_ne!(day.bytes.risky_ref(), a.bytes.risky_ref()); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +Logical types opt in: a date, a timestamp, a decimal and a uuid have +domains of their own. A null, a boolean, an `undefined` and a logical type +this crate does not know have no term, and `normalize` refuses them with +[`NormalizeError::NoDomain`]. + +## A whole value, beside encryption + +[`Terms`] is a sink that collects one [`Term`] per indexable scalar, with +the path to it. Teed with the encrypting sink it sees the same walk, so +the terms are complete before any cipher call: + +```rust +use std::collections::BTreeMap; +use vitaminc_normalize::{domain, encrypt_with_terms, Step}; +# use vitaminc_aead::{seal::Cipher, Context}; +# use vitaminc_protected::{Controlled, Protected}; +# /// Keeps the plaintext in the clear, for the example. Any `Cipher` will do. +# struct Clear; +# impl Cipher for Clear { +# type Leaf = Vec; +# type Error = core::convert::Infallible; +# fn seal(&self, plaintext: Protected>, _: &Context<'_>) -> Result, Self::Error> { +# Ok(plaintext.risky_unwrap()) +# } +# fn open(&self, leaf: Vec, _: &Context<'_>) -> Result>, Self::Error> { +# Ok(Protected::new(leaf)) +# } +# } +# let cipher = Clear; + +let mut user = BTreeMap::new(); +user.insert("email", "ada@example.com"); +user.insert("name", "Ada"); + +let (ciphertext, terms) = encrypt_with_terms(user, &cipher, "users/v1")?; +assert_eq!(terms.len(), 2); +assert_eq!(terms[0].path, [Step::Key("email".into())]); +assert_eq!(terms[0].normalized.domain, domain::TEXT); +# Ok::<(), vitaminc_aead::EncryptError>(()) +``` + +`encrypt_with_terms_async` does the same through an async cipher and has +every term before its first await. `plan_with_terms` walks without +sealing at all. + +A scalar whose kind has no domain (a null, a boolean, an `undefined`) +produces no term and does not stop the walk; passthrough subtrees get none +either. A scalar whose *logical type* has no domain, one from a newer +client, stops the walk: encrypting it with no term and no error would leave +an index silently incomplete. That refusal, an unassigned code point and a +value invalid for its logical type all arrive as `EncryptError::Source` +carrying a `NormalizeError`. + +## Encodings + +These are protocol data. Changing any of them, or a domain label, means a +new label. + +| Kind | Domain | Bytes | +| --- | --- | --- | +| integer, any width | `vitaminc/prf/value/integer-orderable/v1` | sign byte (`0x00` negative, `0x01` otherwise), then the big-endian 128-bit two's-complement word | +| float, either width | `vitaminc/prf/value/float-orderable/v1` | the `f64` value's orderable bytes; `f32` widened exactly, zero signs and NaN payloads folded | +| date | `vitaminc/prf/value/date-orderable/v1` | orderable days from 0001-01-01 | +| timestamp, any unit | `vitaminc/prf/value/timestamp-micros-orderable/v1` | orderable seconds, then nanoseconds truncated to microseconds | +| decimal | `vitaminc/prf/value/decimal-orderable/v1` | `rust_decimal`'s orderable bytes, scale and signed zero normalized | +| text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | +| bytes | `vitaminc/prf/value/bytes/v1` | as they are | +| uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | + +Text normalization is variable-time. The integer and float paths use no +floating-point arithmetic. diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs new file mode 100644 index 000000000..7e42300a2 --- /dev/null +++ b/packages/vitaminc-normalize/src/lib.rs @@ -0,0 +1,14 @@ +#![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] +#![doc = include_str!("../README.md")] + +mod scalar; +mod terms; + +pub use scalar::{ + bytes, date, decimal, domain, domain_of, float, integer, normalize, text, timestamp, uuid, + NormalizeError, Normalized, +}; +pub use terms::{ + encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, Step, Term, Terms, TermsMap, + TermsSeq, WithTerms, +}; diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs new file mode 100644 index 000000000..6061067f7 --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -0,0 +1,308 @@ +//! One normalized equality term per scalar. +//! +//! [`normalize`] turns a physical value and its optional logical type into +//! the bytes an equality index derives under, and the frozen domain label +//! those bytes belong to. The encoders are public, one per kind, so an index +//! layer that already knows a value's kind can call them directly. +//! +//! Every integer width shares one 17-byte encoding and domain, and both +//! float widths share one 8-byte encoding and domain, so equal numbers +//! match whichever width wrote them. Text is Unicode 16 NFC. These bytes +//! and their [`domain`] labels are protocol data: changing either requires +//! a new domain. Text processing is variable-time; this module makes no +//! constant-time claim for Unicode normalization. +//! +//! Logical types opt in. A date, a timestamp, a decimal and a uuid each +//! have a domain of their own, separate from the physical value they are +//! stored as, so a date's day count never matches the integer it equals and +//! a uuid never matches the same sixteen bytes written as bytes. Every other +//! logical type, [`Logical::Unknown`] included, has no term and is refused +//! with [`NormalizeError::NoDomain`]. + +use core::fmt; + +use orderable_bytes::ToOrderableBytes; +use unicode_general_category::{get_general_category, GeneralCategory}; +use unicode_normalization::UnicodeNormalization; +use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; +use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; +use vitaminc_protected::{Controlled, Protected}; + +/// Frozen domain labels for equality terms, one per kind that has one. +pub mod domain { + /// Every integer width, `i8` through `u128`. + pub const INTEGER: &str = "vitaminc/prf/value/integer-orderable/v1"; + /// `f32` and `f64`, as `f64`. + pub const FLOAT: &str = "vitaminc/prf/value/float-orderable/v1"; + /// A date, over its day count. + pub const DATE: &str = "vitaminc/prf/value/date-orderable/v1"; + /// A timestamp, truncated to microseconds. + pub const TIMESTAMP: &str = "vitaminc/prf/value/timestamp-micros-orderable/v1"; + /// A decimal, with scale and signed zero normalized. + pub const DECIMAL: &str = "vitaminc/prf/value/decimal-orderable/v1"; + /// Text, as Unicode 16 NFC. + pub const TEXT: &str = "vitaminc/prf/value/text-nfc/unicode-16/v1"; + /// Bytes. + pub const BYTES: &str = "vitaminc/prf/value/bytes/v1"; + /// A uuid, over its sixteen raw bytes. + pub const UUID: &str = "vitaminc/prf/value/uuid/v1"; + /// Every domain, for a test or an index layer that enumerates them. + pub const ALL: [&str; 8] = [INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID]; +} + +/// The normalized bytes for one equality term and the domain they belong +/// to. +/// +/// The fields are public so an index layer can build a term of its own, +/// and whatever consumes a `Normalized` trusts them: a PRF derives under +/// the `domain` it is handed. The only way to get the frozen encodings is +/// through [`normalize`] or the per-kind encoders here. +#[derive(Debug)] +pub struct Normalized { + /// The frozen domain label, one of the [`domain`] constants. + pub domain: &'static str, + /// The normalized plaintext, protected. + pub bytes: Protected>, +} + +/// Why a scalar has no term. Never includes plaintext. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum NormalizeError { + /// The scalar has no equality domain: a null, an `undefined`, a + /// boolean, or a logical type outside the opt-in table. + NoDomain, + /// The value is not valid for its logical type. + Invalid, + /// Text contains a code point unassigned in Unicode 16. + UnassignedCodePoint, +} + +impl fmt::Display for NormalizeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoDomain => f.write_str("no equality domain for this kind of value"), + Self::Invalid => f.write_str("the value is not valid for its logical type"), + Self::UnassignedCodePoint => { + f.write_str("text contains a code point unassigned in Unicode 16") + } + } + } +} + +impl core::error::Error for NormalizeError {} + +/// The opt-in table: the domain for a scalar, or `None` for one that has +/// no term. A logical type decides on its own; a value without one goes by +/// its kind. Neither looks at the value: [`normalize`] checks that. +pub fn domain_of(ty: Option, v: &Physical<'_>) -> Option<&'static str> { + match (ty, v) { + (None, Physical::Int(_)) => Some(domain::INTEGER), + (None, Physical::Float(_)) => Some(domain::FLOAT), + (None, Physical::Text(_)) => Some(domain::TEXT), + (None, Physical::Bytes(_)) => Some(domain::BYTES), + (None, Physical::Null | Physical::Bool(_)) => None, + (Some(Logical::Date), _) => Some(domain::DATE), + (Some(Logical::Timestamp(_)), _) => Some(domain::TIMESTAMP), + (Some(Logical::Decimal { .. }), _) => Some(domain::DECIMAL), + (Some(Logical::Uuid), _) => Some(domain::UUID), + // `Logical` is non-exhaustive: a type this build does not know, and + // any added later, has no term until it is given a domain here. + (Some(_), _) => None, + } +} + +/// Encode one scalar for equality, with the domain its term belongs to. +/// +/// Integers of every width share [`domain::INTEGER`]: a sign byte (`0x00` +/// negative, `0x01` otherwise) then the value as a big-endian 128-bit +/// two's-complement word, which orders correctly across `i128::MIN` to +/// `u128::MAX`. Both float widths share [`domain::FLOAT`]: an `f32` widens +/// exactly to `f64`, so it matches an `f64` only when the numbers are equal +/// (`f32` 1.5 matches, `f32` 0.1 does not match `f64` 0.1). Float zero +/// signs and NaN payloads are folded. A timestamp in any unit is truncated +/// to microseconds. A decimal's scale is normalized, so `1.50` and `1.5` +/// are one term, as are `-0.00` and `0`. +pub fn normalize(ty: Option, v: Physical<'_>) -> Result { + // A value that does not fit its logical type is refused as invalid + // before the type is looked up, so `undefined` over an int is `Invalid` + // rather than "nothing to index". + if ty.is_some_and(|ty| !ty.admits(&v)) { + return Err(NormalizeError::Invalid); + } + let domain = domain_of(ty, &v).ok_or(NormalizeError::NoDomain)?; + let bytes = match (ty, v) { + (None, Physical::Int(i)) => Some(integer(i)), + (None, Physical::Float(f)) => Some(float(f)), + (None, Physical::Text(s)) => Some(text(s)?), + (None, Physical::Bytes(b)) => Some(bytes(b)), + (Some(Logical::Date), Physical::Int(days)) => date(days), + (Some(Logical::Timestamp(unit)), Physical::Int(count)) => timestamp(unit, count), + (Some(Logical::Decimal { scale }), Physical::Int(mantissa)) => decimal(scale, mantissa), + (Some(Logical::Uuid), Physical::Bytes(b)) => uuid(b), + // `admits` has already refused a logical type over the wrong kind, + // and `domain_of` everything without a term. Each encoder checks + // its own range as well, for a caller that goes to it directly. + _ => None, + } + .ok_or(NormalizeError::Invalid)?; + Ok(Normalized { domain, bytes }) +} + +/// An integer of any width: a sign byte, then the big-endian 128-bit word. +pub fn integer(value: Int) -> Protected> { + let (negative, word) = value.sign_and_word(); + let word = Protected::new(word.to_be_bytes()); + let mut bytes = Protected::new(Vec::with_capacity(17)); + bytes.risky_inner_mut().push(u8::from(!negative)); + bytes.risky_inner_mut().extend_from_slice(word.risky_ref()); + bytes +} + +/// A float of either width, as the orderable bytes of its `f64` value with +/// zero signs and NaN payloads folded. +pub fn float(value: Float) -> Protected> { + let value = match value { + Float::F32(f) => widen_f32(f), + Float::F64(f) => f, + }; + Protected::new(orderable_f64(canonical_f64(value)).to_vec()) +} + +/// A date's day count since 1970-01-01, as the orderable bytes of its +/// count of days from 0001-01-01 (the same bytes chrono's `NaiveDate` +/// orders by). `None` outside the date range. +pub fn date(days: Int) -> Option>> { + let days = i32::try_from(days.to_i128()?).ok()?; + if !(MIN_DATE_DAYS..=MAX_DATE_DAYS).contains(&days) { + return None; + } + let from_ce = days.checked_add(EPOCH_DAYS_FROM_CE)?; + Some(Protected::new( + ((from_ce as u32) ^ (1u32 << 31)).to_be_bytes().to_vec(), + )) +} + +/// A count of `unit`s since the Unix epoch, as orderable seconds then +/// big-endian nanoseconds truncated to microseconds (the same bytes +/// chrono's `DateTime` orders by, truncated). `None` outside the +/// timestamp range. +pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { + let nanos = timestamp_nanos(unit, count)?; + let seconds = i64::try_from(nanos.div_euclid(NANOS_PER_SECOND)).ok()?; + let sub = (nanos.rem_euclid(NANOS_PER_SECOND) as u32) / 1_000 * 1_000; + let mut bytes = Protected::new(Vec::with_capacity(12)); + bytes + .risky_inner_mut() + .extend_from_slice(&((seconds as u64) ^ (1u64 << 63)).to_be_bytes()); + bytes + .risky_inner_mut() + .extend_from_slice(&sub.to_be_bytes()); + Some(bytes) +} + +/// A decimal's mantissa and scale, as `rust_decimal`'s orderable bytes, +/// which normalize the scale and a signed zero. `None` if the mantissa does +/// not fit 96 bits or the scale is above 28. +pub fn decimal(scale: u8, mantissa: Int) -> Option>> { + let value = + rust_decimal::Decimal::try_from_i128_with_scale(mantissa.to_i128()?, u32::from(scale)) + .ok()?; + let bytes = Protected::new(value.to_orderable_bytes()); + Some(Protected::new(bytes.risky_ref().to_vec())) +} + +/// NFC in the pinned Unicode version, without case or accent folding. +/// +/// The result is written into one protected buffer sized exactly up front, +/// so it never reallocates and frees an unwiped partial copy. The +/// `unicode-normalization` iterator keeps its own small buffers of pending +/// code points (inline for four, spilling to the heap for longer combining +/// sequences); those are not wiped and are out of this crate's control. +pub fn text(text: &str) -> Result>, NormalizeError> { + if text + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned) + { + return Err(NormalizeError::UnassignedCodePoint); + } + // NFC can grow UTF-8 (U+0344 is two bytes, its NFC form four), so measure + // the output first rather than sizing from the input. + let len = text.nfc().map(char::len_utf8).sum(); + let mut result = Protected::new(Vec::with_capacity(len)); + for c in text.nfc() { + let mut encoded = Protected::new([0u8; 4]); + result + .risky_inner_mut() + .extend_from_slice(c.encode_utf8(encoded.risky_inner_mut()).as_bytes()); + } + Ok(result) +} + +/// Bytes, as they are. +pub fn bytes(value: &[u8]) -> Protected> { + Protected::new(value.to_vec()) +} + +/// A uuid's sixteen raw bytes. `None` for any other length. +pub fn uuid(value: &[u8]) -> Option>> { + (value.len() == 16).then(|| Protected::new(value.to_vec())) +} + +/// Days from 0001-01-01 (day 1, chrono's "days from CE") to 1970-01-01. +const EPOCH_DAYS_FROM_CE: i32 = 719_163; +const NANOS_PER_SECOND: i128 = 1_000_000_000; + +/// The orderable bytes of an `f64`: negatives flip every bit, positives +/// the sign bit, so the bytes sort as the numbers do. Expects a value +/// [`canonical_f64`] has already folded. +fn orderable_f64(value: f64) -> [u8; 8] { + let bits = value.to_bits(); + let sign_extension = ((bits as i64) >> 63) as u64; + (bits ^ (sign_extension | (1u64 << 63))).to_be_bytes() +} + +/// `f64::from(f32)` in integer operations only. A hardware conversion can +/// take a slow path on subnormal inputs, which would leak timing; this keeps +/// the float path free of floating-point arithmetic. +fn widen_f32(value: f32) -> f64 { + let bits = value.to_bits(); + let sign = u64::from(bits >> 31) << 63; + let exponent = (bits >> 23) & 0xff; + let mantissa = u64::from(bits & 0x7f_ffff); + let zero_exponent = 0u64.wrapping_sub((exponent == 0) as u64); + let max_exponent = 0u64.wrapping_sub((exponent == 0xff) as u64); + let nonzero = 0u64.wrapping_sub((mantissa != 0) as u64); + // Normal, infinite and NaN: rebias the exponent (127 to 1023, or all + // ones stays all ones) and left-align the mantissa. + let rebiased = ((u64::from(exponent) + 896) & !max_exponent) | (0x7ff & max_exponent); + let normal = (rebiased << 52) | (mantissa << 29); + // Subnormal: the highest set bit becomes the implicit leading one. + let top = highest_set_bit(mantissa); + let subnormal = ((top + 874) << 52) | ((mantissa << (52 - top)) & ((1 << 52) - 1)); + f64::from_bits(sign | (normal & !zero_exponent) | (subnormal & zero_exponent & nonzero)) +} + +/// Index of the highest set bit of a subnormal f32 mantissa. `| 1` keeps the +/// result in range for a zero mantissa, which `widen_f32` masks out. +/// +/// Kept out of `widen_f32` so the `.cargo/mutants.toml` exclusion of that +/// function's equivalent `|`-to-`^` mutants cannot reach this `|`, whose +/// operands overlap and whose mutant a test does catch. +fn highest_set_bit(mantissa: u64) -> u64 { + u64::from(63 - (mantissa | 1).leading_zeros()) +} + +/// Folds every NaN to one quiet NaN and `-0.0` to `0.0`, in integer +/// operations only. +fn canonical_f64(value: f64) -> f64 { + let bits = value.to_bits(); + let magnitude = bits & 0x7fff_ffff_ffff_ffff; + let nan = 0u64.wrapping_sub((magnitude > 0x7ff0_0000_0000_0000) as u64); + let nonzero = 0u64.wrapping_sub((magnitude != 0) as u64); + f64::from_bits((bits & !nan).wrapping_add(0x7ff8_0000_0000_0000 & nan) & nonzero) +} + +#[cfg(test)] +#[path = "scalar_tests.rs"] +mod tests; diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs new file mode 100644 index 000000000..144c258b8 --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -0,0 +1,433 @@ +use super::*; +use quickcheck_macros::quickcheck; +use vitaminc_aead::UnknownLogical; + +fn term(ty: Option, v: Physical<'_>) -> Vec { + normalize(ty, v) + .expect("valid test value") + .bytes + .risky_ref() + .clone() +} + +fn int(ty: Option, i: Int) -> Vec { + term(ty, Physical::Int(i)) +} + +fn integer_bytes(sign: u8, word: u128) -> Vec { + let mut expected = vec![sign]; + expected.extend_from_slice(&word.to_be_bytes()); + expected +} + +#[test] +fn integers_share_one_domain_whatever_their_width() { + let five = [ + Int::I8(5), + Int::U8(5), + Int::I16(5), + Int::U16(5), + Int::I32(5), + Int::U32(5), + Int::I64(5), + Int::U64(5), + Int::I128(5), + Int::U128(5), + ]; + for value in five { + let n = normalize(None, Physical::Int(value)).expect("int"); + assert_eq!(n.domain, domain::INTEGER); + assert_eq!(n.bytes.risky_ref(), &integer_bytes(1, 5)); + } + for value in [ + Int::I8(-7), + Int::I16(-7), + Int::I32(-7), + Int::I64(-7), + Int::I128(-7), + ] { + assert_eq!(int(None, value), integer_bytes(0, -7i128 as u128)); + } + assert_eq!(int(None, Int::I128(i128::MIN)), integer_bytes(0, 1 << 127)); + assert_eq!(int(None, Int::I128(-1)), integer_bytes(0, u128::MAX)); + assert_eq!(int(None, Int::I128(0)), integer_bytes(1, 0)); + assert_eq!(int(None, Int::U128(u128::MAX)), integer_bytes(1, u128::MAX)); + let ascending = [ + Int::I128(i128::MIN), + Int::I64(i64::MIN), + Int::I8(-1), + Int::U8(0), + Int::I8(i8::MAX), + Int::U64(u64::MAX), + Int::I128(i128::MAX), + Int::U128(u128::MAX), + ]; + for pair in ascending.windows(2) { + assert!(int(None, pair[0]) < int(None, pair[1])); + } +} + +#[quickcheck] +fn signed_and_unsigned_integers_agree_when_equal(value: u64) -> bool { + int(None, Int::U64(value)) == int(None, Int::I128(value.into())) + && int(None, Int::U128(value.into())) == int(None, Int::I128(value.into())) +} + +#[quickcheck] +fn integer_order_agrees_with_numeric_order(a: i64, b: u64) -> bool { + let (wide_a, wide_b) = (i128::from(a), i128::from(b)); + int(None, Int::I64(a)).cmp(&int(None, Int::U64(b))) == wide_a.cmp(&wide_b) + && int(None, Int::I128(wide_a * wide_b)).cmp(&int(None, Int::I64(a))) + == (wide_a * wide_b).cmp(&wide_a) +} + +#[test] +fn the_opt_in_table_names_every_domain_and_nothing_else() { + let one = Physical::Int(Int::I32(1)); + assert_eq!(domain_of(None, &one), Some(domain::INTEGER)); + assert_eq!( + domain_of(None, &Physical::Float(Float::F32(1.0))), + Some(domain::FLOAT) + ); + assert_eq!(domain_of(None, &Physical::Text("a")), Some(domain::TEXT)); + assert_eq!(domain_of(None, &Physical::Bytes(&[1])), Some(domain::BYTES)); + assert_eq!(domain_of(Some(Logical::Date), &one), Some(domain::DATE)); + assert_eq!( + domain_of(Some(Logical::Timestamp(TimeUnit::Millis)), &one), + Some(domain::TIMESTAMP) + ); + assert_eq!( + domain_of(Some(Logical::Decimal { scale: 2 }), &one), + Some(domain::DECIMAL) + ); + assert_eq!( + domain_of(Some(Logical::Uuid), &Physical::Bytes(&[0; 16])), + Some(domain::UUID) + ); + assert_eq!(domain_of(None, &Physical::Null), None); + assert_eq!(domain_of(None, &Physical::Bool(true)), None); + assert_eq!(domain_of(Some(Logical::Undefined), &Physical::Null), None); + let unknown = Logical::from_wire(200, 1).expect("unknown"); + assert!(matches!(unknown, Logical::Unknown(UnknownLogical { .. }))); + assert_eq!(domain_of(Some(unknown), &one), None); + assert_eq!(domain::ALL.len(), 8); + for label in domain::ALL { + assert!(label.starts_with("vitaminc/prf/value/"), "{label}"); + } +} + +#[test] +fn a_scalar_with_no_domain_is_refused_with_no_domain() { + let unknown = Logical::from_wire(200, 1).expect("unknown"); + for (ty, v) in [ + (None, Physical::Null), + (None, Physical::Bool(false)), + (Some(Logical::Undefined), Physical::Null), + (Some(unknown), Physical::Int(Int::I32(1))), + (Some(unknown), Physical::Text("x")), + ] { + assert_eq!( + normalize(ty, v).expect_err("no term"), + NormalizeError::NoDomain + ); + } + for error in [ + NormalizeError::NoDomain, + NormalizeError::Invalid, + NormalizeError::UnassignedCodePoint, + ] { + assert!(!error.to_string().is_empty()); + } +} + +#[test] +fn a_value_that_does_not_fit_its_logical_type_is_invalid() { + for (ty, v) in [ + (Logical::Date, Physical::Text("2024-01-01")), + (Logical::Date, Physical::Int(Int::I64(i64::MAX))), + ( + Logical::Timestamp(TimeUnit::Nanos), + Physical::Int(Int::I128(i128::MAX)), + ), + (Logical::Decimal { scale: 29 }, Physical::Int(Int::I32(1))), + ( + Logical::Decimal { scale: 1 }, + Physical::Int(Int::I128(1 << 100)), + ), + (Logical::Uuid, Physical::Bytes(&[0; 15])), + (Logical::Uuid, Physical::Int(Int::I32(1))), + ] { + assert_eq!( + normalize(Some(ty), v).expect_err("invalid"), + NormalizeError::Invalid + ); + } + // `undefined` over anything but a null is a value that does not fit + // its type, not one with nothing to index. + assert_eq!( + normalize(Some(Logical::Undefined), Physical::Int(Int::I32(1))).expect_err("invalid"), + NormalizeError::Invalid + ); + // The encoders say the same without going through `admits`, one day + // past chrono's range on either side included. + assert!(date(Int::I64(i64::MAX)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS + 1)).is_none()); + assert!(date(Int::I32(MIN_DATE_DAYS - 1)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS)).is_some()); + assert!(date(Int::I32(MIN_DATE_DAYS)).is_some()); + for days in [MAX_DATE_DAYS + 1, MIN_DATE_DAYS - 1] { + assert_eq!( + normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect_err("invalid"), + NormalizeError::Invalid + ); + } + assert!(timestamp(TimeUnit::Nanos, Int::I128(i128::MAX)).is_none()); + assert!(decimal(29, Int::I32(1)).is_none()); + assert!(decimal(1, Int::U128(u128::MAX)).is_none()); + assert!(uuid(&[0; 15]).is_none()); +} + +#[test] +fn a_logical_value_never_shares_a_term_with_its_physical_value() { + let days = Int::I32(19_000); + assert_ne!(int(Some(Logical::Date), days), int(None, days)); + let count = Int::I64(1_700_000_000_000); + assert_ne!( + int(Some(Logical::Timestamp(TimeUnit::Millis)), count), + int(None, count) + ); + let mantissa = Int::I128(150); + assert_ne!( + int(Some(Logical::Decimal { scale: 2 }), mantissa), + int(None, mantissa) + ); + // A uuid is its sixteen bytes, so the domain alone keeps it apart from + // the same bytes written as bytes. + let id = [5u8; 16]; + assert_eq!(uuid(&id).expect("uuid").risky_ref(), bytes(&id).risky_ref()); + assert_ne!( + normalize(Some(Logical::Uuid), Physical::Bytes(&id)) + .expect("uuid") + .domain, + normalize(None, Physical::Bytes(&id)).expect("bytes").domain + ); +} + +#[test] +fn dates_are_orderable_days_from_the_common_era() { + // 0001-01-01 is day 1 from CE; 1970-01-01 is day 719163. + assert_eq!( + int(Some(Logical::Date), Int::I32(1 - EPOCH_DAYS_FROM_CE)), + [0x80, 0x00, 0x00, 0x01] + ); + assert_eq!( + int(Some(Logical::Date), Int::I32(0)), + ((EPOCH_DAYS_FROM_CE as u32) ^ (1 << 31)).to_be_bytes() + ); + assert!(int(Some(Logical::Date), Int::I32(-1)) < int(Some(Logical::Date), Int::I32(0))); + assert!(int(Some(Logical::Date), Int::I32(0)) < int(Some(Logical::Date), Int::I32(1))); +} + +#[test] +fn timestamps_in_any_unit_truncate_to_microseconds() { + let nanos = Int::I128(1_700_000_000_123_456_789); + let micros = Int::I64(1_700_000_000_123_456); + let millis = Int::I64(1_700_000_000_123); + let seconds = Int::I64(1_700_000_000); + let by = |unit, count| int(Some(Logical::Timestamp(unit)), count); + assert_eq!(by(TimeUnit::Nanos, nanos), by(TimeUnit::Micros, micros)); + assert_eq!( + by(TimeUnit::Millis, millis), + by(TimeUnit::Micros, Int::I64(1_700_000_000_123_000)) + ); + assert_eq!( + by(TimeUnit::Seconds, seconds), + by(TimeUnit::Nanos, Int::I128(1_700_000_000_000_000_000)) + ); + let mut expected = ((1_700_000_000u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(by(TimeUnit::Nanos, nanos), expected); + // Before the epoch the seconds floor and the fraction stays positive. + let before = by(TimeUnit::Nanos, Int::I128(-1_000_000_000 + 123_456_789)); + let mut expected = ((-1i64 as u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(before, expected); + assert!(before < by(TimeUnit::Seconds, Int::I64(0))); +} + +#[test] +fn decimals_normalize_scale_and_signed_zero() { + let by = |scale, mantissa| int(Some(Logical::Decimal { scale }), Int::I128(mantissa)); + assert_eq!(by(0, 1), by(1, 10)); + assert_eq!(by(0, 1), by(2, 100)); + assert_eq!(by(2, 150), by(1, 15)); + assert_eq!(by(2, 0), by(0, 0)); + assert_eq!(by(0, -0), by(0, 0)); + assert!(by(0, -1) < by(0, 0)); + assert!(by(0, 0) < by(0, 1)); + assert!(by(2, 150) < by(0, 2)); +} + +#[test] +fn nfc_expansion_fills_an_exactly_sized_buffer() { + // U+0344 is two UTF-8 bytes; its NFC form U+0308 U+0301 is four. + let normalized = text("\u{344}").expect("valid test value"); + assert_eq!(normalized.risky_ref(), "\u{308}\u{301}".as_bytes()); + assert_eq!(normalized.risky_ref().capacity(), 4); +} + +#[test] +fn unicode_version_and_equivalence_are_frozen() { + // Normalization stability makes newer NFC tables safe for text that is + // assigned in Unicode 16; the assignment table is the exact pin. + assert!(unicode_normalization::UNICODE_VERSION >= (16, 0, 0)); + assert_eq!(unicode_general_category::UNICODE_VERSION, (16, 0, 0)); + assert_eq!(term(None, Physical::Text("e\u{301}")), "é".as_bytes()); + assert_ne!( + term(None, Physical::Text("É")), + term(None, Physical::Text("é")) + ); + assert_ne!( + term(None, Physical::Text("e")), + term(None, Physical::Text("é")) + ); + for s in ["\u{378}", "\u{10ffff}", "\u{1faea}"] { + assert_eq!( + normalize(None, Physical::Text(s)).expect_err("unsupported input"), + NormalizeError::UnassignedCodePoint + ); + } + assert_eq!(text("a\0").expect("valid test value").risky_ref(), b"a\0"); +} + +#[quickcheck] +fn nfc_is_idempotent(s: String) -> bool { + match text(&s) { + Ok(first) => { + let first = String::from_utf8(first.risky_ref().clone()).expect("utf-8"); + text(&first).expect("valid test value").risky_ref() == first.as_bytes() + } + Err(_) => s + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned), + } +} + +fn f32_term(v: f32) -> Vec { + term(None, Physical::Float(Float::F32(v))) +} + +fn f64_term(v: f64) -> Vec { + term(None, Physical::Float(Float::F64(v))) +} + +#[test] +fn floats_have_postgres_zero_and_nan_ordering() { + assert_eq!(f64_term(-0.0), f64_term(0.0)); + assert_eq!(f32_term(-0.0), f64_term(0.0)); + for bits in [0x7fc0_0000, 0xff80_0001, 0xffff_ffff, 0x7f80_0001] { + assert_eq!( + f32_term(f32::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + for bits in [0x7ff8_0000_0000_0000, 0xfff0_0000_0000_0001, u64::MAX] { + assert_eq!( + f64_term(f64::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + assert_eq!(f32_term(1.5), [0xbf, 0xf8, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(-1.5), + [0x40, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + assert_eq!(f32_term(f32::INFINITY), [0xff, 0xf0, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(f32::NEG_INFINITY), + [0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + let ascending = [f64::NEG_INFINITY, -1.0, 0.0, 1.0, f64::INFINITY, f64::NAN]; + for pair in ascending.windows(2) { + assert!(f64_term(pair[0]) < f64_term(pair[1])); + } +} + +#[quickcheck] +fn f64_order_agrees_with_numeric_order(a: f64, b: f64) -> bool { + a.is_nan() + || b.is_nan() + || f64_term(a).cmp(&f64_term(b)) == a.partial_cmp(&b).expect("valid test value") +} + +#[test] +fn float_widths_share_one_domain_for_equal_numbers() { + for value in [ + 0.0f32, + 1.5, + -0.25, + 16_777_216.0, + f32::MAX, + f32::MIN_POSITIVE, + ] { + assert_eq!(f32_term(value), f64_term(value.into())); + } + // 0.1 is a different number in each width, so the terms differ. + assert_ne!(f32_term(0.1), f64_term(0.1)); +} + +fn widen_matches_hardware(bits: u32) -> bool { + let value = f32::from_bits(bits); + let (ours, hardware) = (widen_f32(value), f64::from(value)); + // NaN payload bits are folded later; only NaN-ness must agree for them. + if value.is_nan() { + ours.is_nan() && ours.is_sign_negative() == hardware.is_sign_negative() + } else { + ours.to_bits() == hardware.to_bits() + } +} + +#[test] +fn widening_matches_hardware_at_every_exponent_and_subnormal_bit() { + for sign in [0, 1u32 << 31] { + for exponent in 0..=0xffu32 { + for mantissa in [0, 1, 0x40_0000, 0x7f_ffff, 0x2a_aaaa] { + let bits = sign | (exponent << 23) | mantissa; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + } + } + for shift in 0..23 { + let bits = sign | 1 << shift; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + assert!( + widen_matches_hardware(bits | ((1 << shift) - 1)), + "{bits:#010x}" + ); + } + } +} + +#[quickcheck] +fn widening_matches_hardware_conversion(bits: u32) -> bool { + widen_matches_hardware(bits) +} + +/// Every f32 bit pattern; slow in debug builds, so run on demand with +/// `cargo test --release -p vitaminc-normalize -- --ignored`. +#[test] +#[ignore] +fn widening_matches_hardware_for_every_f32() { + assert!((0..=u32::MAX).all(widen_matches_hardware)); +} + +#[quickcheck] +fn f64_canonicalisation_is_idempotent(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + canonical_f64(value).to_bits() == value.to_bits() +} + +#[quickcheck] +fn orderable_f64_agrees_with_orderable_bytes(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + orderable_f64(value) == value.to_orderable_bytes() +} diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs new file mode 100644 index 000000000..11f099d12 --- /dev/null +++ b/packages/vitaminc-normalize/src/terms.rs @@ -0,0 +1,267 @@ +//! Equality terms as a sink, and encryption that produces them in the +//! same walk. +//! +//! [`Terms`] is a [`Sink`] that produces one [`Term`] per scalar that has +//! an equality domain. It runs beside encryption as `Tee(EncryptSink, +//! Terms)`, so a caller holds every term before any cipher is called and, +//! with an async cipher, before the first await. + +use core::future::Future; +use core::marker::PhantomData; + +use vitaminc_aead::plaintext::Error; +use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; +use vitaminc_aead::{ + EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, Plaintext, + SeqSink, Sink, SourceError, Tee, +}; + +use crate::scalar::{normalize, NormalizeError, Normalized}; + +/// One step of the path from the root of a value to a scalar. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Step { + /// The element at this index of a sequence. + Index(usize), + /// The entry under this key of a map. + Key(String), +} + +/// One equality term: where the scalar sits in the value, and its +/// normalized bytes with their domain. +#[derive(Debug)] +pub struct Term { + /// The path from the root, empty for a scalar at the root. + pub path: Vec, + /// The term itself: the frozen domain label and the normalized bytes. + pub normalized: Normalized, +} + +/// A sink that collects one [`Term`] per scalar with an equality domain, +/// in walk order. +/// +/// Generic over its error type so it adopts its [`Tee`] partner's. +/// +/// A scalar whose *kind* has no domain (a null, a boolean, an `undefined`) +/// produces no term and does not stop the walk: an absent or unindexable +/// value is an ordinary thing to find in a document, and the caller has +/// the paths to see which fields were indexed. A scalar whose *logical +/// type* has no domain ([`Logical::Unknown`], or a type this crate does +/// not know) stops the walk instead: it came from a newer client and +/// means something, and encrypting it with no term and no error would +/// leave an index silently incomplete. +/// +/// Passthrough subtrees travel in the clear and get no terms. +/// +/// # Errors +/// +/// The walk stops with `E::source(SourceError::new(error))`, carrying the +/// [`NormalizeError`], when a scalar's logical type has no domain +/// (`NoDomain`), when text holds a code point unassigned in Unicode 16 +/// (`UnassignedCodePoint`), or when a value is not valid for its logical +/// type (`Invalid`). Beside [`EncryptSink`] that arrives as +/// [`EncryptError::Source`], and `source.inner().downcast_ref::()` +/// recovers which it was. +pub struct Terms<'t, E> { + out: &'t mut Vec, + /// The path of the container this sink is a child of, borrowed from + /// that container's sink, and the step from it to this value. Owned + /// only when a term is pushed, so a child that produces none costs no + /// allocation. + parent: &'t [Step], + step: Option, + _error: PhantomData, +} + +impl<'t, E> Terms<'t, E> { + /// A sink that appends to `out`. + pub fn new(out: &'t mut Vec) -> Self { + Self { + out, + parent: &[], + step: None, + _error: PhantomData, + } + } + + fn path(&self) -> Vec { + let mut path = Vec::with_capacity(self.parent.len() + usize::from(self.step.is_some())); + path.extend_from_slice(self.parent); + path.extend(self.step.iter().cloned()); + path + } +} + +impl<'t, E: Error> Sink for Terms<'t, E> { + type Ok = (); + type Error = E; + type Seq = TermsSeq<'t, E>; + type Map = TermsMap<'t, E>; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { + match normalize(ty, value) { + Ok(normalized) => { + let path = self.path(); + self.out.push(Term { path, normalized }); + Ok(()) + } + // No domain for the kind: nothing to index, carry on. No domain + // for a logical type: refuse, see the type's docs. + Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => { + Ok(()) + } + Err(error) => Err(E::source(SourceError::new(error))), + } + } + + fn seq(self, _: Option) -> Result { + Ok(TermsSeq { + path: self.path(), + out: self.out, + next: 0, + _error: PhantomData, + }) + } + + fn map(self, _: Option) -> Result { + Ok(TermsMap { + path: self.path(), + out: self.out, + _error: PhantomData, + }) + } + + fn passthrough(self, _: P) -> Result<(), E> { + Ok(()) + } +} + +/// The sequence side of [`Terms`]: each element's path is the sequence's +/// plus its index. +pub struct TermsSeq<'t, E> { + out: &'t mut Vec, + path: Vec, + next: usize, + _error: PhantomData, +} + +impl SeqSink for TermsSeq<'_, E> { + type Ok = (); + type Error = E; + type Element<'s> + = Terms<'s, E> + where + Self: 's; + + fn element(&mut self) -> Result, E> { + let step = Step::Index(self.next); + self.next += 1; + Ok(Terms { + out: self.out, + parent: &self.path, + step: Some(step), + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + Ok(()) + } +} + +/// The map side of [`Terms`]: each entry's path is the map's plus its +/// key. +pub struct TermsMap<'t, E> { + out: &'t mut Vec, + path: Vec, + _error: PhantomData, +} + +impl MapSink for TermsMap<'_, E> { + type Ok = (); + type Error = E; + type Entry<'s> + = Terms<'s, E> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result, E> { + Ok(Terms { + out: self.out, + parent: &self.path, + step: Some(Step::Key(key.to_owned())), + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + Ok(()) + } +} + +/// A ciphertext tree and the terms of the value it was sealed from, in +/// walk order. +pub type WithTerms = (Node, Vec); + +/// Walk `value` into the encrypting sink and the terms sink at once, +/// without sealing: the planned tree of pending leaves, and every term. +/// +/// # Errors +/// +/// Everything [`EncryptSink`] refuses, plus what [`Terms`] refuses, which +/// arrives as [`EncryptError::Source`] carrying a [`NormalizeError`]. +pub fn plan_with_terms<'a, P, E, A>(value: P, aad: A) -> Result, EncryptError> +where + P: Plaintext, + A: IntoAad<'a>, +{ + let mut terms = Vec::new(); + let (planned, ()) = value.visit(Tee(EncryptSink::root(aad), Terms::new(&mut terms)))?; + Ok((planned, terms)) +} + +/// Encrypt `value` and produce its equality terms in the same walk. +/// +/// # Errors +/// +/// As [`plan_with_terms`], then [`EncryptError::Cipher`] if the cipher +/// refuses a leaf. +pub fn encrypt_with_terms<'a, P, C, A>( + value: P, + cipher: &C, + aad: A, +) -> Result, EncryptError> +where + P: Plaintext, + C: Cipher, + A: IntoAad<'a>, +{ + let (planned, terms) = plan_with_terms(value, aad)?; + Ok((seal_all(cipher, planned)?, terms)) +} + +/// Encrypt `value` through an async cipher and produce its equality terms +/// in the same walk. The walk, and so every term, is complete before the +/// future is returned, so the future holds only the planned leaves and is +/// `Send` even when the source is not. +/// +/// # Errors +/// +/// As [`encrypt_with_terms`]. A refusal during the walk is held in the +/// future and returned on its first poll. +pub fn encrypt_with_terms_async<'a, 'c, P, C, A>( + value: P, + cipher: &'c C, + aad: A, +) -> impl Future, EncryptError>> + Send + 'c +where + P: Plaintext, + C: AsyncCipher, + A: IntoAad<'a>, +{ + let planned = plan_with_terms(value, aad); + async move { + let (planned, terms) = planned?; + Ok((seal_all_async(cipher, planned).await?, terms)) + } +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs new file mode 100644 index 000000000..395a48f3a --- /dev/null +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -0,0 +1,504 @@ +//! Every term this crate produces, checked against today's `canonical` +//! encoders in `vitaminc-aead-value` byte for byte, and the terms sink +//! beside encryption. + +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::collections::BTreeMap; + +use chrono::{DateTime, NaiveDate, Utc}; +use futures_executor::block_on; +use vitaminc_aead::plaintext::kinds::chrono as conv; +use vitaminc_aead::seal::{AsyncCipher, Cipher}; +use vitaminc_aead::{ + Context, EncryptError, Float, Int, Logical, Physical, Plaintext, Sink, TimeUnit, +}; +use vitaminc_aead_value::canonical::equality_input; +use vitaminc_aead_value::Value; +use vitaminc_normalize::{ + domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, + NormalizeError, Step, Term, +}; +use vitaminc_protected::{Controlled, Protected}; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The new term for a scalar must be the old term for the equivalent +/// `Value`, domain and bytes. +#[track_caller] +fn same(ty: Option, v: Physical<'_>, value: Value) { + let new = normalize(ty, v).expect("normalizes"); + let old = equality_input(&value).expect("has a term"); + assert_eq!(new.domain, old.domain); + assert_eq!( + hex(new.bytes.risky_ref()), + hex(old.bytes.risky_ref()), + "{}", + old.domain + ); +} + +#[test] +fn every_integer_width_matches_todays_term() { + for n in [0i128, 1, 5, -7, 127, -128, 255, 65_535, -32_768] { + if let Ok(v) = i8::try_from(n) { + same(None, Physical::Int(Int::I8(v)), Value::Int8(v)); + } + if let Ok(v) = u8::try_from(n) { + same(None, Physical::Int(Int::U8(v)), Value::UInt8(v)); + } + if let Ok(v) = i16::try_from(n) { + same(None, Physical::Int(Int::I16(v)), Value::Int16(v)); + } + if let Ok(v) = u16::try_from(n) { + same(None, Physical::Int(Int::U16(v)), Value::UInt16(v)); + } + if let Ok(v) = i32::try_from(n) { + same(None, Physical::Int(Int::I32(v)), Value::Int32(v)); + } + if let Ok(v) = u32::try_from(n) { + same(None, Physical::Int(Int::U32(v)), Value::UInt32(v)); + } + if let Ok(v) = i64::try_from(n) { + same(None, Physical::Int(Int::I64(v)), Value::Int64(v)); + } + if let Ok(v) = u64::try_from(n) { + same(None, Physical::Int(Int::U64(v)), Value::UInt64(v)); + } + same(None, Physical::Int(Int::I128(n)), Value::Int128(n)); + if let Ok(v) = u128::try_from(n) { + same(None, Physical::Int(Int::U128(v)), Value::UInt128(v)); + } + } + for v in [i128::MIN, i128::MAX] { + same(None, Physical::Int(Int::I128(v)), Value::Int128(v)); + } + for v in [i8::MIN, i8::MAX] { + same(None, Physical::Int(Int::I8(v)), Value::Int8(v)); + } + for v in [i16::MIN, i16::MAX] { + same(None, Physical::Int(Int::I16(v)), Value::Int16(v)); + } + for v in [i32::MIN, i32::MAX] { + same(None, Physical::Int(Int::I32(v)), Value::Int32(v)); + } + for v in [i64::MIN, i64::MAX] { + same(None, Physical::Int(Int::I64(v)), Value::Int64(v)); + } + same(None, Physical::Int(Int::U8(u8::MAX)), Value::UInt8(u8::MAX)); + same( + None, + Physical::Int(Int::U16(u16::MAX)), + Value::UInt16(u16::MAX), + ); + same( + None, + Physical::Int(Int::U32(u32::MAX)), + Value::UInt32(u32::MAX), + ); + same( + None, + Physical::Int(Int::U64(u64::MAX)), + Value::UInt64(u64::MAX), + ); + same( + None, + Physical::Int(Int::U128(u128::MAX)), + Value::UInt128(u128::MAX), + ); +} + +#[test] +fn both_float_widths_match_todays_term() { + for v in [ + 0.0f32, + -0.0, + 1.5, + -1.5, + 0.1, + f32::MAX, + f32::MIN_POSITIVE, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + f32::from_bits(0xff80_0001), + f32::from_bits(1), + ] { + same(None, Physical::Float(Float::F32(v)), Value::Float32(v)); + } + for v in [ + 0.0f64, + -0.0, + 1.5, + 0.1, + f64::MAX, + f64::MIN_POSITIVE, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + f64::from_bits(0xfff0_0000_0000_0001), + ] { + same(None, Physical::Float(Float::F64(v)), Value::Float64(v)); + } +} + +#[test] +fn text_and_bytes_match_todays_term() { + for s in ["", "Ada", "e\u{301}", "\u{344}", "a\0b", "日本語"] { + same(None, Physical::Text(s), Value::String(s.into())); + } + for b in [&[][..], &[0], &[1, 2, 3], &[0xff; 40]] { + same( + None, + Physical::Bytes(b), + Value::Bytes(Protected::new(b.to_vec())), + ); + } + assert_eq!( + normalize(None, Physical::Text("\u{378}")).expect_err("unassigned"), + NormalizeError::UnassignedCodePoint + ); +} + +#[test] +fn dates_match_todays_term() { + for date in [ + NaiveDate::MIN, + NaiveDate::from_ymd_opt(1, 1, 1).expect("date"), + NaiveDate::from_ymd_opt(1969, 12, 31).expect("date"), + NaiveDate::from_ymd_opt(1970, 1, 1).expect("date"), + NaiveDate::from_ymd_opt(2024, 2, 29).expect("date"), + NaiveDate::MAX, + ] { + same( + Some(Logical::Date), + Physical::Int(Int::I32(conv::date_days(date))), + Value::Date(date), + ); + } +} + +#[test] +fn timestamps_in_every_unit_match_todays_term() { + for (seconds, nanos) in [ + (0, 0), + (-1, 123_456_789), + (59, 999_999_999), + (1_700_000_000, 123_456_789), + (-62_000_000_000, 5_000), + ] { + let ts = DateTime::::from_timestamp(seconds, nanos).expect("timestamp"); + let nanos = conv::timestamp_nanos(ts).expect("not a leap second"); + same( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(nanos)), + Value::Timestamp(ts), + ); + // Coarser units truncate the same way, so they match the old term + // of the instant at that precision. + for (unit, per) in [ + (TimeUnit::Micros, 1_000i128), + (TimeUnit::Millis, 1_000_000), + (TimeUnit::Seconds, 1_000_000_000), + ] { + let count = nanos.div_euclid(per); + let truncated = DateTime::::from_timestamp( + (count * per).div_euclid(1_000_000_000) as i64, + ((count * per).rem_euclid(1_000_000_000)) as u32, + ) + .expect("timestamp"); + same( + Some(Logical::Timestamp(unit)), + Physical::Int(Int::I64(i64::try_from(count).expect("fits"))), + Value::Timestamp(truncated), + ); + } + } + for ts in [DateTime::::MIN_UTC, DateTime::::MAX_UTC] { + let nanos = conv::timestamp_nanos(ts).expect("not a leap second"); + same( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(nanos)), + Value::Timestamp(ts), + ); + } +} + +#[test] +fn decimals_match_todays_term() { + for s in [ + "0", + "0.0", + "-0.00", + "1", + "1.0", + "1.50", + "1.5", + "-1.5", + "0.001", + "123456789.987654321", + "79228162514264337593543950335", + "-79228162514264337593543950335", + "0.0000000000000000000000000001", + ] { + let d: rust_decimal::Decimal = s.parse().expect("decimal"); + same( + Some(Logical::Decimal { + scale: d.scale() as u8, + }), + Physical::Int(Int::I128(d.mantissa())), + Value::Decimal(d), + ); + } +} + +#[test] +fn a_uuid_has_a_domain_of_its_own() { + let id = uuid::Uuid::from_bytes([ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, + 0xf0, + ]); + let n = normalize(Some(Logical::Uuid), Physical::Bytes(id.as_bytes())).expect("uuid"); + assert_eq!(n.domain, "vitaminc/prf/value/uuid/v1"); + assert_eq!(hex(n.bytes.risky_ref()), "123456789abcdef0123456789abcdef0"); + let plain = normalize(None, Physical::Bytes(id.as_bytes())).expect("bytes"); + assert_eq!(hex(plain.bytes.risky_ref()), hex(n.bytes.risky_ref())); + assert_ne!(plain.domain, n.domain); + // The uuid source carries its logical type, so the two never meet. + let mut terms = Vec::new(); + let (_, ()) = id + .visit(vitaminc_aead::Tee( + vitaminc_aead::EncryptSink::<()>::root(()), + vitaminc_normalize::Terms::new(&mut terms), + )) + .expect("walks"); + assert_eq!(terms[0].normalized.domain, domain::UUID); +} + +#[test] +fn a_date_never_matches_its_day_count_and_widths_agree() { + let date = NaiveDate::from_ymd_opt(2024, 2, 29).expect("date"); + let days = conv::date_days(date); + let as_date = normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect("date"); + let as_int = normalize(None, Physical::Int(Int::I32(days))).expect("int"); + assert_ne!(as_date.domain, as_int.domain); + assert_ne!(as_date.bytes.risky_ref(), as_int.bytes.risky_ref()); + let narrow = normalize(None, Physical::Int(Int::I8(34))).expect("i8"); + let wide = normalize(None, Physical::Int(Int::U64(34))).expect("u64"); + assert_eq!(narrow.domain, wide.domain); + assert_eq!(narrow.bytes.risky_ref(), wide.bytes.risky_ref()); +} + +// The terms sink beside encryption. + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Leaf { + aad: Vec, + plaintext: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Refused; + +/// Seals in the clear and counts calls, so a test can see when the cipher +/// first runs. +#[derive(Default)] +struct Counting { + calls: AtomicUsize, +} + +impl Cipher for Counting { + type Leaf = Leaf; + type Error = Refused; + + fn seal(&self, plaintext: Protected>, aad: &Context<'_>) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(Leaf { + aad: aad.as_bytes().to_vec(), + plaintext: plaintext.risky_unwrap(), + }) + } + + fn open(&self, leaf: Leaf, aad: &Context<'_>) -> Result>, Refused> { + if leaf.aad != aad.as_bytes() { + return Err(Refused); + } + Ok(Protected::new(leaf.plaintext)) + } +} + +fn user() -> BTreeMap<&'static str, Vec>> { + let mut m = BTreeMap::new(); + m.insert("ages", vec![Some(36), None, Some(41)]); + m.insert("empty", vec![]); + m +} + +fn paths(terms: &[Term]) -> Vec> { + terms.iter().map(|t| t.path.clone()).collect() +} + +#[test] +fn plan_with_terms_has_every_term_without_a_cipher() { + let (planned, terms) = plan_with_terms::<_, Refused, _>(user(), "ctx").expect("plans"); + assert_eq!( + paths(&terms), + [ + vec![Step::Key("ages".into()), Step::Index(0)], + vec![Step::Key("ages".into()), Step::Index(2)], + ] + ); + assert_eq!(terms[0].normalized.domain, domain::INTEGER); + assert_eq!( + terms[1].normalized.bytes.risky_ref(), + normalize(None, Physical::Int(Int::U32(41))) + .expect("int") + .bytes + .risky_ref() + ); + // The plan is the same one `encrypt` would seal. + let sealed = vitaminc_aead::seal::seal_all(&Counting::default(), planned).expect("seals"); + assert!(matches!(sealed, vitaminc_aead::CipherText::Map(_))); +} + +#[test] +fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { + let cipher = Counting::default(); + let (sealed, terms) = encrypt_with_terms(user(), &cipher, "ctx").expect("encrypts"); + assert_eq!(terms.len(), 2); + // Three elements, one empty marker. + assert_eq!(cipher.calls.load(Ordering::SeqCst), 4); + let back: BTreeMap>> = + vitaminc_aead::decrypt(&cipher, sealed, "ctx").expect("decrypts"); + assert_eq!(back["ages"], [Some(36), None, Some(41)]); +} + +#[test] +fn scalars_without_a_domain_and_passthroughs_get_no_term() { + struct Doc; + impl Plaintext for Doc { + fn visit(self, sink: S) -> Result { + use vitaminc_aead::MapSink; + let mut map = sink.map(Some(5))?; + true.visit(map.entry("active")?)?; + None::.visit(map.entry("missing")?)?; + map.entry("tenant")?.passthrough("acme")?; + vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Null) + .visit(map.entry("undefined")?)?; + "Ada".visit(map.entry("name")?)?; + map.end() + } + } + let (_, terms) = plan_with_terms::<_, Refused, _>(Doc, "ctx").expect("plans"); + assert_eq!(paths(&terms), [vec![Step::Key("name".into())]]); + assert_eq!(terms[0].normalized.domain, domain::TEXT); +} + +/// A logical type this build does not know means something to the client +/// that sent it, so it is refused rather than encrypted with no term. +#[test] +fn an_unknown_logical_type_stops_the_walk() { + let newer = vitaminc_aead::Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Int(Int::I32(1)), + ); + let err = plan_with_terms::<_, Refused, _>(vec![newer], "ctx") + .err() + .expect("refused"); + match err { + EncryptError::Source(source) => assert_eq!( + source.inner().downcast_ref::().copied(), + Some(NormalizeError::NoDomain) + ), + other => panic!("{other:?}"), + } +} + +/// Nested paths are the container's path plus the step, at every depth. +#[test] +fn paths_follow_the_nesting() { + let mut inner = BTreeMap::new(); + inner.insert("k", vec![vec![1u8, 2]]); + let mut outer = BTreeMap::new(); + outer.insert("m", vec![inner]); + let (_, terms) = plan_with_terms::<_, Refused, _>(outer, "ctx").expect("plans"); + assert_eq!( + paths(&terms), + [vec![ + Step::Key("m".into()), + Step::Index(0), + Step::Key("k".into()), + Step::Index(0), + ]] + ); + assert_eq!(terms[0].normalized.domain, domain::BYTES); +} + +#[test] +fn an_unassigned_code_point_stops_the_walk_with_the_normalize_error() { + let err = plan_with_terms::<_, Refused, _>("\u{378}", "ctx") + .err() + .expect("refused"); + match err { + EncryptError::Source(source) => { + assert_eq!( + source.inner().downcast_ref::().copied(), + Some(NormalizeError::UnassignedCodePoint) + ); + } + other => panic!("{other:?}"), + } +} + +/// Seals through an await, and checks that the source's walk had finished +/// before the first one. +struct Remote { + walked: &'static AtomicBool, +} + +impl AsyncCipher for Remote { + type Leaf = Leaf; + type Error = Refused; + + async fn seal( + &self, + plaintext: Protected>, + aad: Context<'static>, + ) -> Result { + assert!( + self.walked.load(Ordering::SeqCst), + "sealed before the walk ended" + ); + Counting::default().seal(plaintext, &aad) + } + + async fn open(&self, leaf: Leaf, aad: Context<'static>) -> Result>, Refused> { + Counting::default().open(leaf, &aad) + } +} + +#[test] +fn encrypt_with_terms_async_has_every_term_before_its_first_await() { + static WALKED: AtomicBool = AtomicBool::new(false); + struct Source; + impl Plaintext for Source { + fn visit(self, sink: S) -> Result { + let out = vec![1u32, 2].visit(sink); + WALKED.store(true, Ordering::SeqCst); + out + } + } + let remote = Remote { walked: &WALKED }; + let future = encrypt_with_terms_async(Source, &remote, "ctx"); + // The walk ran, and the terms exist, before the future is polled. + assert!(WALKED.load(Ordering::SeqCst)); + fn assert_send(t: T) -> T { + t + } + let (sealed, terms) = block_on(assert_send(future)).expect("encrypts"); + assert_eq!(paths(&terms), [vec![Step::Index(0)], vec![Step::Index(1)]]); + let back: Vec = + block_on(vitaminc_aead::decrypt_async(&remote, sealed, "ctx")).expect("decrypts"); + assert_eq!(back, [1, 2]); +} From 87b7984f1ca8a5b899aecbad9f3a222ae3401659 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 16:38:03 +1100 Subject: [PATCH 02/68] fix(normalize): redact Normalized and Term through OpaqueDebug `Normalized` and `Term` derived std `Debug`, so the only thing keeping normalized plaintext out of a `{:?}` was that the bytes happen to sit in a `Protected`; the fields are public and a later change to them would have printed the bytes with no test failing. Both now derive `OpaqueDebug`, showing the domain label and the path, which are structure, and masking the term, and a test checks the output never holds the plaintext. `NormalizeError` derives its `Display` and `Error` impls with `thiserror`, as the workspace's other error types do, with the same messages. `domain::ALL` becomes a slice, so a domain added later does not change the type of a public constant. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/Cargo.toml | 1 + packages/vitaminc-normalize/src/scalar.rs | 33 +++++++------------ .../vitaminc-normalize/src/scalar_tests.rs | 10 ++++++ packages/vitaminc-normalize/src/terms.rs | 8 ++++- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 2167e104a..6543766b8 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -15,6 +15,7 @@ rust-version.workspace = true [dependencies] vitaminc-aead = { version = "0.5.1", path = "../aead" } vitaminc-protected = { version = "0.5.1", path = "../protected" } +thiserror = { workspace = true } # Only for the decimal term. Its encoding is constant-time arithmetic over # the mantissa and scale that this crate does not want a second copy of, so diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 6061067f7..34d7e5c13 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -19,14 +19,12 @@ //! logical type, [`Logical::Unknown`] included, has no term and is refused //! with [`NormalizeError::NoDomain`]. -use core::fmt; - use orderable_bytes::ToOrderableBytes; use unicode_general_category::{get_general_category, GeneralCategory}; use unicode_normalization::UnicodeNormalization; use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; -use vitaminc_protected::{Controlled, Protected}; +use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; /// Frozen domain labels for equality terms, one per kind that has one. pub mod domain { @@ -46,8 +44,9 @@ pub mod domain { pub const BYTES: &str = "vitaminc/prf/value/bytes/v1"; /// A uuid, over its sixteen raw bytes. pub const UUID: &str = "vitaminc/prf/value/uuid/v1"; - /// Every domain, for a test or an index layer that enumerates them. - pub const ALL: [&str; 8] = [INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID]; + /// Every domain, for a test or an index layer that enumerates them. A + /// slice, so a domain added later does not change its type. + pub const ALL: &[&str] = &[INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID]; } /// The normalized bytes for one equality term and the domain they belong @@ -57,41 +56,33 @@ pub mod domain { /// and whatever consumes a `Normalized` trusts them: a PRF derives under /// the `domain` it is handed. The only way to get the frozen encodings is /// through [`normalize`] or the per-kind encoders here. -#[derive(Debug)] +/// +/// `Debug` shows the domain and masks the bytes. +#[derive(OpaqueDebug)] pub struct Normalized { /// The frozen domain label, one of the [`domain`] constants. + #[non_sensitive] pub domain: &'static str, /// The normalized plaintext, protected. pub bytes: Protected>, } /// Why a scalar has no term. Never includes plaintext. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum NormalizeError { /// The scalar has no equality domain: a null, an `undefined`, a /// boolean, or a logical type outside the opt-in table. + #[error("no equality domain for this kind of value")] NoDomain, /// The value is not valid for its logical type. + #[error("the value is not valid for its logical type")] Invalid, /// Text contains a code point unassigned in Unicode 16. + #[error("text contains a code point unassigned in Unicode 16")] UnassignedCodePoint, } -impl fmt::Display for NormalizeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoDomain => f.write_str("no equality domain for this kind of value"), - Self::Invalid => f.write_str("the value is not valid for its logical type"), - Self::UnassignedCodePoint => { - f.write_str("text contains a code point unassigned in Unicode 16") - } - } - } -} - -impl core::error::Error for NormalizeError {} - /// The opt-in table: the domain for a scalar, or `None` for one that has /// no term. A logical type decides on its own; a value without one goes by /// its kind. Neither looks at the value: [`normalize`] checks that. diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index 144c258b8..c0b0cdf9b 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -431,3 +431,13 @@ fn orderable_f64_agrees_with_orderable_bytes(bits: u64) -> bool { let value = canonical_f64(f64::from_bits(bits)); orderable_f64(value) == value.to_orderable_bytes() } + +#[test] +fn debug_output_does_not_show_the_normalized_bytes() { + let n = normalize(None, Physical::Text("secret")).expect("text"); + let v = format!("{n:?}"); + assert!(v.contains(domain::TEXT), "{v}"); + assert!(v.contains("***"), "{v}"); + // "secret" as a `Vec` would print as [115, 101, 99, ...]. + assert!(!v.contains("secret") && !v.contains("115, 101, 99"), "{v}"); +} diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 11f099d12..fc3adf40b 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -16,6 +16,8 @@ use vitaminc_aead::{ SeqSink, Sink, SourceError, Tee, }; +use vitaminc_protected::OpaqueDebug; + use crate::scalar::{normalize, NormalizeError, Normalized}; /// One step of the path from the root of a value to a scalar. @@ -29,9 +31,13 @@ pub enum Step { /// One equality term: where the scalar sits in the value, and its /// normalized bytes with their domain. -#[derive(Debug)] +/// +/// `Debug` shows the path, which is structure (indexes and map keys, which +/// the ciphertext carries in the clear too), and masks the term. +#[derive(OpaqueDebug)] pub struct Term { /// The path from the root, empty for a scalar at the root. + #[non_sensitive] pub path: Vec, /// The term itself: the frozen domain label and the normalized bytes. pub normalized: Normalized, From 93b0261de50bcf395f4ef9a3821af8f1f0cf5522 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 16:38:04 +1100 Subject: [PATCH 03/68] test(normalize): pin the refusals, ranges and buffer sizes the docs promise Several documented guarantees had no test that fails when they change. A value `Terms` refuses must reach no cipher through `encrypt_with_terms`, and the async future must return the refusal on its first poll. `Terms` used alone, without `EncryptSink` in front, must itself refuse a value invalid for its logical type, and a root scalar has an empty path. With both sinks, `EncryptSink` runs first, so such a value is a shape error. The timestamp encoder must refuse one nanosecond past either end of chrono's range, the integer and timestamp encoders must never grow their buffer (a grown `Vec` frees an unwiped copy), and a date, timestamp or decimal term must be the same at every integer width. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- .../vitaminc-normalize/src/scalar_tests.rs | 73 ++++++++++++++++++ .../vitaminc-normalize/tests/known_answers.rs | 74 +++++++++++++++++++ 2 files changed, 147 insertions(+) diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index c0b0cdf9b..6bc89e369 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -432,6 +432,37 @@ fn orderable_f64_agrees_with_orderable_bytes(bits: u64) -> bool { orderable_f64(value) == value.to_orderable_bytes() } +#[test] +fn timestamps_one_past_chronos_range_are_invalid() { + use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; + let ns = Logical::Timestamp(TimeUnit::Nanos); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MAX_TIMESTAMP_NANOS)).is_some()); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MIN_TIMESTAMP_NANOS)).is_some()); + for nanos in [MAX_TIMESTAMP_NANOS + 1, MIN_TIMESTAMP_NANOS - 1] { + assert!(timestamp(TimeUnit::Nanos, Int::I128(nanos)).is_none()); + assert_eq!( + normalize(Some(ns), Physical::Int(Int::I128(nanos))).expect_err("invalid"), + NormalizeError::Invalid + ); + } +} + +/// A `Vec` that grows frees its old buffer without wiping it, so the +/// encoders that append in steps must start at their final size. +#[test] +fn incremental_encoders_never_outgrow_their_buffer() { + for value in [Int::I8(-1), Int::U128(u128::MAX), Int::I128(i128::MIN)] { + let bytes = integer(value); + assert_eq!(bytes.risky_ref().len(), 17); + assert_eq!(bytes.risky_ref().capacity(), 17); + } + for count in [Int::I64(-1), Int::I64(1_700_000_000_123)] { + let bytes = timestamp(TimeUnit::Millis, count).expect("in range"); + assert_eq!(bytes.risky_ref().len(), 12); + assert_eq!(bytes.risky_ref().capacity(), 12); + } +} + #[test] fn debug_output_does_not_show_the_normalized_bytes() { let n = normalize(None, Physical::Text("secret")).expect("text"); @@ -441,3 +472,45 @@ fn debug_output_does_not_show_the_normalized_bytes() { // "secret" as a `Vec` would print as [115, 101, 99, ...]. assert!(!v.contains("secret") && !v.contains("115, 101, 99"), "{v}"); } + +/// The widths an `i16` fits, each holding `n`. +fn every_width(n: i16) -> Vec { + let mut widths = vec![ + Int::I16(n), + Int::I32(n.into()), + Int::I64(n.into()), + Int::I128(n.into()), + ]; + if let Ok(v) = i8::try_from(n) { + widths.push(Int::I8(v)); + } + if let Ok(v) = u16::try_from(n) { + widths.extend([ + Int::U16(v), + Int::U32(v.into()), + Int::U64(v.into()), + Int::U128(v.into()), + ]); + } + if let Ok(v) = u8::try_from(n) { + widths.push(Int::U8(v)); + } + widths +} + +/// A logical term is over the number, not the width that carried it, as +/// the plain integer term is. +#[quickcheck] +fn a_logical_term_is_the_same_at_every_integer_width(n: i16) -> bool { + [ + Logical::Date, + Logical::Timestamp(TimeUnit::Seconds), + Logical::Decimal { scale: 2 }, + ] + .into_iter() + .all(|ty| { + let widths = every_width(n); + let first = int(Some(ty), widths[0]); + widths.iter().all(|&w| int(Some(ty), w) == first) + }) +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 395a48f3a..174fbf741 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -502,3 +502,77 @@ fn encrypt_with_terms_async_has_every_term_before_its_first_await() { block_on(vitaminc_aead::decrypt_async(&remote, sealed, "ctx")).expect("decrypts"); assert_eq!(back, [1, 2]); } + +/// A cipher that must never be reached. +struct Never; + +impl AsyncCipher for Never { + type Leaf = Leaf; + type Error = Refused; + + async fn seal(&self, _: Protected>, _: Context<'static>) -> Result { + panic!("sealed after the walk was refused") + } + + async fn open(&self, _: Leaf, _: Context<'static>) -> Result>, Refused> { + Err(Refused) + } +} + +fn is_unassigned(err: &EncryptError) -> bool { + matches!(err, EncryptError::Source(s) + if s.inner().downcast_ref::() == Some(&NormalizeError::UnassignedCodePoint)) +} + +/// The walk ends before any leaf is sealed, so a value `Terms` refuses +/// reaches no cipher, even when its first element was fine; the async +/// future holds the refusal and returns it on its first poll. +#[test] +fn a_refused_walk_never_reaches_the_cipher() { + let doc = || vec!["ok", "\u{378}"]; + let cipher = Counting::default(); + let err = encrypt_with_terms(doc(), &cipher, "ctx").expect_err("refused"); + assert!(is_unassigned(&err), "{err:?}"); + assert_eq!(cipher.calls.load(Ordering::SeqCst), 0); + let err = block_on(encrypt_with_terms_async(doc(), &Never, "ctx")).expect_err("refused"); + assert!(is_unassigned(&err), "{err:?}"); +} + +/// `Terms` is public and works without `EncryptSink` in front of it, and is +/// then the sink that refuses a value invalid for its logical type. +#[test] +fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { + use vitaminc_aead::Raw; + use vitaminc_normalize::Terms; + + // A scalar at the root has an empty path. + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError> = Terms::new(&mut out); + "Ada".visit(sink).expect("walks"); + assert_eq!(paths(&out), [Vec::::new()]); + + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError> = Terms::new(&mut out); + let err = Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))) + .visit(sink) + .expect_err("refused"); + match err { + EncryptError::Source(source) => assert_eq!( + source.inner().downcast_ref::().copied(), + Some(NormalizeError::Invalid) + ), + other => panic!("{other:?}"), + } + assert!(out.is_empty()); +} + +/// `EncryptSink` runs first in the `Tee`, so a value invalid for its +/// logical type is a shape error from encryption, not a normalize error. +#[test] +fn an_invalid_logical_value_is_refused_by_the_encrypt_sink_first() { + let invalid = vitaminc_aead::Raw(Some(Logical::Date), Physical::Text("2024-01-01")); + let err = plan_with_terms::<_, Refused, _>(invalid, "ctx") + .err() + .expect("refused"); + assert!(matches!(err, EncryptError::Shape(_)), "{err:?}"); +} From 6d69b4a37784c46b102d2a59f4fb8fff04dc0f65 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 20:30:34 +1100 Subject: [PATCH 04/68] feat(normalize): say which field Terms refused A refusal from Terms used to carry only a NormalizeError, so a caller could not tell which field of a document had no equality term. It now carries a TermError: the NormalizeError and the Path to the scalar. The downcast target for a refusal beside encryption is TermError. Step and Path come from vitaminc_aead::plaintext, so a Term's path and both crates' refusals use one type. Term::path is now a Path. As in vitaminc-aead, Display shows only the reason and Debug masks map keys, because they can be user data. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/README.md | 7 +- packages/vitaminc-normalize/src/lib.rs | 5 +- packages/vitaminc-normalize/src/terms.rs | 68 ++++++---- .../vitaminc-normalize/tests/known_answers.rs | 124 +++++++++++------- 4 files changed, 131 insertions(+), 73 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index e189d64ff..7033a130c 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -77,7 +77,7 @@ user.insert("name", "Ada"); let (ciphertext, terms) = encrypt_with_terms(user, &cipher, "users/v1")?; assert_eq!(terms.len(), 2); -assert_eq!(terms[0].path, [Step::Key("email".into())]); +assert!(matches!(terms[0].path.steps(), [Step::Key(k)] if k == "email")); assert_eq!(terms[0].normalized.domain, domain::TEXT); # Ok::<(), vitaminc_aead::EncryptError>(()) ``` @@ -92,7 +92,10 @@ either. A scalar whose *logical type* has no domain, one from a newer client, stops the walk: encrypting it with no term and no error would leave an index silently incomplete. That refusal, an unassigned code point and a value invalid for its logical type all arrive as `EncryptError::Source` -carrying a `NormalizeError`. +carrying a `TermError`, which holds the +`NormalizeError` and the path to the refused field. Its message names +neither the field nor the value, because map keys can be user data; read +the path with `TermError::path`. ## Encodings diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index 7e42300a2..238cf254f 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -9,6 +9,7 @@ pub use scalar::{ NormalizeError, Normalized, }; pub use terms::{ - encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, Step, Term, Terms, TermsMap, - TermsSeq, WithTerms, + encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, Term, TermError, Terms, + TermsMap, TermsSeq, WithTerms, }; +pub use vitaminc_aead::plaintext::{Path, Step}; diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index fc3adf40b..fe5f778ed 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -9,7 +9,7 @@ use core::future::Future; use core::marker::PhantomData; -use vitaminc_aead::plaintext::Error; +use vitaminc_aead::plaintext::{Error, Path, Step}; use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; use vitaminc_aead::{ EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, Plaintext, @@ -20,29 +20,47 @@ use vitaminc_protected::OpaqueDebug; use crate::scalar::{normalize, NormalizeError, Normalized}; -/// One step of the path from the root of a value to a scalar. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Step { - /// The element at this index of a sequence. - Index(usize), - /// The entry under this key of a map. - Key(String), -} - /// One equality term: where the scalar sits in the value, and its /// normalized bytes with their domain. /// -/// `Debug` shows the path, which is structure (indexes and map keys, which -/// the ciphertext carries in the clear too), and masks the term. +/// `Debug` shows the path's shape, with its map keys masked as [`Step`] +/// masks them, and masks the term. #[derive(OpaqueDebug)] pub struct Term { /// The path from the root, empty for a scalar at the root. #[non_sensitive] - pub path: Vec, + pub path: Path, /// The term itself: the frozen domain label and the normalized bytes. pub normalized: Normalized, } +/// A scalar [`Terms`] refused: why, and where in the value. +/// +/// `Display` shows only the reason, because the path can hold map keys and +/// map keys can be user data. `Debug` shows the reason and the path's +/// shape, with every key masked. Read the path with +/// [`path`](TermError::path). +#[derive(Clone, OpaqueDebug, thiserror::Error)] +#[error("no equality term: {error}")] +pub struct TermError { + #[non_sensitive] + path: Path, + #[non_sensitive] + error: NormalizeError, +} + +impl TermError { + /// Where the refused scalar sits, from the root. + pub fn path(&self) -> &Path { + &self.path + } + + /// Why the scalar has no term. + pub fn error(&self) -> NormalizeError { + self.error + } +} + /// A sink that collects one [`Term`] per scalar with an equality domain, /// in walk order. /// @@ -61,13 +79,14 @@ pub struct Term { /// /// # Errors /// -/// The walk stops with `E::source(SourceError::new(error))`, carrying the -/// [`NormalizeError`], when a scalar's logical type has no domain -/// (`NoDomain`), when text holds a code point unassigned in Unicode 16 -/// (`UnassignedCodePoint`), or when a value is not valid for its logical -/// type (`Invalid`). Beside [`EncryptSink`] that arrives as -/// [`EncryptError::Source`], and `source.inner().downcast_ref::()` -/// recovers which it was. +/// The walk stops with `E::source(SourceError::new(error))`, where `error` +/// is a [`TermError`] holding the scalar's path and the +/// [`NormalizeError`]: the scalar's logical type has no domain +/// (`NoDomain`), its text holds a code point unassigned in Unicode 16 +/// (`UnassignedCodePoint`), or it is not valid for its logical type +/// (`Invalid`). Beside [`EncryptSink`] that arrives as +/// [`EncryptError::Source`], and `source.inner().downcast_ref::()` +/// recovers it. pub struct Terms<'t, E> { out: &'t mut Vec, /// The path of the container this sink is a child of, borrowed from @@ -107,7 +126,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { match normalize(ty, value) { Ok(normalized) => { - let path = self.path(); + let path = Path::new(self.path()); self.out.push(Term { path, normalized }); Ok(()) } @@ -116,7 +135,10 @@ impl<'t, E: Error> Sink for Terms<'t, E> { Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => { Ok(()) } - Err(error) => Err(E::source(SourceError::new(error))), + Err(error) => Err(E::source(SourceError::new(TermError { + path: Path::new(self.path()), + error, + }))), } } @@ -215,7 +237,7 @@ pub type WithTerms = (Node, Vec); /// # Errors /// /// Everything [`EncryptSink`] refuses, plus what [`Terms`] refuses, which -/// arrives as [`EncryptError::Source`] carrying a [`NormalizeError`]. +/// arrives as [`EncryptError::Source`] carrying a [`TermError`]. pub fn plan_with_terms<'a, P, E, A>(value: P, aad: A) -> Result, EncryptError> where P: Plaintext, diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 174fbf741..1730835a1 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -16,7 +16,7 @@ use vitaminc_aead_value::canonical::equality_input; use vitaminc_aead_value::Value; use vitaminc_normalize::{ domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, - NormalizeError, Step, Term, + NormalizeError, Path, Step, Term, TermError, }; use vitaminc_protected::{Controlled, Protected}; @@ -335,20 +335,41 @@ fn user() -> BTreeMap<&'static str, Vec>> { m } -fn paths(terms: &[Term]) -> Vec> { - terms.iter().map(|t| t.path.clone()).collect() +/// A path written out for an assertion: `.key` for an entry and `[i]` for +/// an element. +fn render(path: &Path) -> String { + path.steps() + .iter() + .map(|step| match step { + Step::Index(i) => format!("[{i}]"), + Step::Key(k) => format!(".{k}"), + }) + .collect() +} + +fn paths(terms: &[Term]) -> Vec { + terms.iter().map(|t| render(&t.path)).collect() +} + +/// What `Terms` refused inside an encryption error, and where. +fn term_error(err: &EncryptError) -> Option<(NormalizeError, String)> { + match err { + EncryptError::Source(source) => source + .inner() + .downcast_ref::() + .map(|t| (t.error(), render(t.path()))), + _ => None, + } +} + +fn refused(error: NormalizeError, at: &str) -> Option<(NormalizeError, String)> { + Some((error, at.to_owned())) } #[test] fn plan_with_terms_has_every_term_without_a_cipher() { let (planned, terms) = plan_with_terms::<_, Refused, _>(user(), "ctx").expect("plans"); - assert_eq!( - paths(&terms), - [ - vec![Step::Key("ages".into()), Step::Index(0)], - vec![Step::Key("ages".into()), Step::Index(2)], - ] - ); + assert_eq!(paths(&terms), [".ages[0]", ".ages[2]"]); assert_eq!(terms[0].normalized.domain, domain::INTEGER); assert_eq!( terms[1].normalized.bytes.risky_ref(), @@ -391,7 +412,7 @@ fn scalars_without_a_domain_and_passthroughs_get_no_term() { } } let (_, terms) = plan_with_terms::<_, Refused, _>(Doc, "ctx").expect("plans"); - assert_eq!(paths(&terms), [vec![Step::Key("name".into())]]); + assert_eq!(paths(&terms), [".name"]); assert_eq!(terms[0].normalized.domain, domain::TEXT); } @@ -406,13 +427,7 @@ fn an_unknown_logical_type_stops_the_walk() { let err = plan_with_terms::<_, Refused, _>(vec![newer], "ctx") .err() .expect("refused"); - match err { - EncryptError::Source(source) => assert_eq!( - source.inner().downcast_ref::().copied(), - Some(NormalizeError::NoDomain) - ), - other => panic!("{other:?}"), - } + assert_eq!(term_error(&err), refused(NormalizeError::NoDomain, "[0]")); } /// Nested paths are the container's path plus the step, at every depth. @@ -423,15 +438,7 @@ fn paths_follow_the_nesting() { let mut outer = BTreeMap::new(); outer.insert("m", vec![inner]); let (_, terms) = plan_with_terms::<_, Refused, _>(outer, "ctx").expect("plans"); - assert_eq!( - paths(&terms), - [vec![ - Step::Key("m".into()), - Step::Index(0), - Step::Key("k".into()), - Step::Index(0), - ]] - ); + assert_eq!(paths(&terms), [".m[0].k[0]"]); assert_eq!(terms[0].normalized.domain, domain::BYTES); } @@ -440,14 +447,46 @@ fn an_unassigned_code_point_stops_the_walk_with_the_normalize_error() { let err = plan_with_terms::<_, Refused, _>("\u{378}", "ctx") .err() .expect("refused"); - match err { - EncryptError::Source(source) => { - assert_eq!( - source.inner().downcast_ref::().copied(), - Some(NormalizeError::UnassignedCodePoint) - ); - } - other => panic!("{other:?}"), + assert_eq!( + term_error(&err), + refused(NormalizeError::UnassignedCodePoint, "") + ); +} + +/// The refusal names the field, nested at any depth, through an accessor +/// only: neither the message nor `Debug` shows a key. +#[test] +fn a_refusal_names_the_field_only_on_request() { + let mut inner = BTreeMap::new(); + inner.insert("ada@example.com", vec!["ok", "\u{378}"]); + let mut outer = BTreeMap::new(); + outer.insert("emails", vec![inner]); + let err = plan_with_terms::<_, Refused, _>(outer, "ctx") + .err() + .expect("refused"); + assert_eq!( + term_error(&err), + refused( + NormalizeError::UnassignedCodePoint, + ".emails[0].ada@example.com[1]" + ) + ); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let term = source + .inner() + .downcast_ref::() + .expect("a term error"); + assert_eq!( + term.to_string(), + "no equality term: text contains a code point unassigned in Unicode 16" + ); + for shown in [format!("{term:?}"), format!("{err:?}")] { + assert!(!shown.contains("ada"), "{shown}"); + assert!(!shown.contains("emails"), "{shown}"); + assert!(shown.contains("UnassignedCodePoint"), "{shown}"); + assert!(shown.contains("Index(1)"), "{shown}"); } } @@ -497,7 +536,7 @@ fn encrypt_with_terms_async_has_every_term_before_its_first_await() { t } let (sealed, terms) = block_on(assert_send(future)).expect("encrypts"); - assert_eq!(paths(&terms), [vec![Step::Index(0)], vec![Step::Index(1)]]); + assert_eq!(paths(&terms), ["[0]", "[1]"]); let back: Vec = block_on(vitaminc_aead::decrypt_async(&remote, sealed, "ctx")).expect("decrypts"); assert_eq!(back, [1, 2]); @@ -520,8 +559,7 @@ impl AsyncCipher for Never { } fn is_unassigned(err: &EncryptError) -> bool { - matches!(err, EncryptError::Source(s) - if s.inner().downcast_ref::() == Some(&NormalizeError::UnassignedCodePoint)) + term_error(err) == refused(NormalizeError::UnassignedCodePoint, "[1]") } /// The walk ends before any leaf is sealed, so a value `Terms` refuses @@ -549,20 +587,14 @@ fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { let mut out = Vec::new(); let sink: Terms<'_, EncryptError> = Terms::new(&mut out); "Ada".visit(sink).expect("walks"); - assert_eq!(paths(&out), [Vec::::new()]); + assert_eq!(paths(&out), [""]); let mut out = Vec::new(); let sink: Terms<'_, EncryptError> = Terms::new(&mut out); let err = Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))) .visit(sink) .expect_err("refused"); - match err { - EncryptError::Source(source) => assert_eq!( - source.inner().downcast_ref::().copied(), - Some(NormalizeError::Invalid) - ), - other => panic!("{other:?}"), - } + assert_eq!(term_error(&err), refused(NormalizeError::Invalid, "")); assert!(out.is_empty()); } From f37ec07e56b5a5b6dde49c7d5c126dc868ba0a01 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 20:30:35 +1100 Subject: [PATCH 05/68] feat(normalize): collect equality terms without encrypting Running Terms alone did not infer an error type (E0282), so a caller that wanted terms without ciphertext had to name an unrelated error such as EncryptError<()>, or call plan_with_terms and build a pending leaf per scalar as well. terms(value) runs Terms on its own and fails with TermsError, a thin wrapper over the SourceError a source reports through. TermsError::term recovers the TermError when Terms refused a scalar, and returns None when the source failed on its own. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/README.md | 5 +- packages/vitaminc-normalize/src/lib.rs | 4 +- packages/vitaminc-normalize/src/terms.rs | 70 ++++++++++++++++++- .../vitaminc-normalize/tests/known_answers.rs | 50 ++++++++++++- 4 files changed, 120 insertions(+), 9 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 7033a130c..e20fae1a4 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -84,7 +84,8 @@ assert_eq!(terms[0].normalized.domain, domain::TEXT); `encrypt_with_terms_async` does the same through an async cipher and has every term before its first await. `plan_with_terms` walks without -sealing at all. +sealing at all, and `terms` collects the terms with no encryption in the +walk. A scalar whose kind has no domain (a null, a boolean, an `undefined`) produces no term and does not stop the walk; passthrough subtrees get none @@ -92,7 +93,7 @@ either. A scalar whose *logical type* has no domain, one from a newer client, stops the walk: encrypting it with no term and no error would leave an index silently incomplete. That refusal, an unassigned code point and a value invalid for its logical type all arrive as `EncryptError::Source` -carrying a `TermError`, which holds the +carrying a `TermError` (from `terms`, as a `TermsError`), which holds the `NormalizeError` and the path to the refused field. Its message names neither the field nor the value, because map keys can be user data; read the path with `TermError::path`. diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index 238cf254f..f98173601 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -9,7 +9,7 @@ pub use scalar::{ NormalizeError, Normalized, }; pub use terms::{ - encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, Term, TermError, Terms, - TermsMap, TermsSeq, WithTerms, + encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, terms, Term, TermError, Terms, + TermsError, TermsMap, TermsSeq, WithTerms, }; pub use vitaminc_aead::plaintext::{Path, Step}; diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index fe5f778ed..56ecc0f25 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -4,7 +4,7 @@ //! [`Terms`] is a [`Sink`] that produces one [`Term`] per scalar that has //! an equality domain. It runs beside encryption as `Tee(EncryptSink, //! Terms)`, so a caller holds every term before any cipher is called and, -//! with an async cipher, before the first await. +//! with an async cipher, before the first await. [`terms`] runs it alone. use core::future::Future; use core::marker::PhantomData; @@ -61,10 +61,37 @@ impl TermError { } } +/// What [`terms`] fails with: what [`Terms`] refuses, or the source's own +/// failure. +/// +/// A source reports through [`Error::source`] whichever sink it feeds, so +/// both arrive as a [`SourceError`]. [`term`](TermsError::term) recovers a +/// [`TermError`] from it, the same downcast a caller makes on +/// [`EncryptError::Source`] when `Terms` runs beside encryption. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct TermsError(pub SourceError); + +impl TermsError { + /// The scalar [`Terms`] refused, or `None` if the source failed on its + /// own. + pub fn term(&self) -> Option<&TermError> { + self.0.inner().downcast_ref() + } +} + +impl Error for TermsError { + fn source(error: SourceError) -> Self { + Self(error) + } +} + /// A sink that collects one [`Term`] per scalar with an equality domain, /// in walk order. /// -/// Generic over its error type so it adopts its [`Tee`] partner's. +/// Generic over its error type so it adopts its [`Tee`] partner's. To +/// collect terms without encrypting, call [`terms`], whose error type is +/// [`TermsError`]. /// /// A scalar whose *kind* has no domain (a null, a boolean, an `undefined`) /// produces no term and does not stop the walk: an absent or unindexable @@ -86,7 +113,7 @@ impl TermError { /// (`UnassignedCodePoint`), or it is not valid for its logical type /// (`Invalid`). Beside [`EncryptSink`] that arrives as /// [`EncryptError::Source`], and `source.inner().downcast_ref::()` -/// recovers it. +/// recovers it. Alone, through [`terms`], it is [`TermsError::term`]. pub struct Terms<'t, E> { out: &'t mut Vec, /// The path of the container this sink is a child of, borrowed from @@ -227,6 +254,43 @@ impl MapSink for TermsMap<'_, E> { } } +/// Every equality term of `value`, in walk order, without encrypting it. +/// +/// # Examples +/// +/// ``` +/// use std::collections::BTreeMap; +/// use vitaminc_normalize::{domain, terms, NormalizeError, Step}; +/// +/// let mut user = BTreeMap::new(); +/// user.insert("name", "Ada"); +/// let found = terms(&user)?; +/// assert!(matches!(found[0].path.steps(), [Step::Key(k)] if k == "name")); +/// assert_eq!(found[0].normalized.domain, domain::TEXT); +/// +/// // U+0378 is unassigned in Unicode 16, so the name has no term. +/// user.insert("name", "\u{378}"); +/// let refused = terms(&user).unwrap_err(); +/// let term = refused.term().expect("refused by Terms"); +/// assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); +/// assert!(matches!(term.path().steps(), [Step::Key(k)] if k == "name")); +/// // The message names neither the field nor its value. +/// assert_eq!( +/// refused.to_string(), +/// "no equality term: text contains a code point unassigned in Unicode 16" +/// ); +/// # Ok::<(), vitaminc_normalize::TermsError>(()) +/// ``` +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, or the source's own failure. +pub fn terms(value: P) -> Result, TermsError> { + let mut out = Vec::new(); + value.visit(Terms::new(&mut out))?; + Ok(out) +} + /// A ciphertext tree and the terms of the value it was sealed from, in /// walk order. pub type WithTerms = (Node, Vec); diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 1730835a1..21efe0fb7 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -10,12 +10,13 @@ use futures_executor::block_on; use vitaminc_aead::plaintext::kinds::chrono as conv; use vitaminc_aead::seal::{AsyncCipher, Cipher}; use vitaminc_aead::{ - Context, EncryptError, Float, Int, Logical, Physical, Plaintext, Sink, TimeUnit, + Context, EncryptError, Float, Int, Logical, Physical, Plaintext, SeqSink, Sink, SourceError, + TimeUnit, }; use vitaminc_aead_value::canonical::equality_input; use vitaminc_aead_value::Value; use vitaminc_normalize::{ - domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, + domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, terms, NormalizeError, Path, Step, Term, TermError, }; use vitaminc_protected::{Controlled, Protected}; @@ -490,6 +491,51 @@ fn a_refusal_names_the_field_only_on_request() { } } +#[test] +fn terms_collects_every_term_without_encrypting() { + let found = terms(user()).expect("walks"); + assert_eq!(paths(&found), [".ages[0]", ".ages[2]"]); + assert_eq!(found[1].normalized.domain, domain::INTEGER); + // A borrowed value walks too, and a scalar at the root has no steps. + let name = String::from("Ada"); + let found = terms(&name).expect("walks"); + assert_eq!(paths(&found), [""]); + assert!(terms(Vec::::new()).expect("walks").is_empty()); +} + +#[test] +fn terms_says_which_field_it_refused() { + let invalid = vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))); + let mut doc = BTreeMap::new(); + doc.insert("x", invalid); + let err = terms(doc).expect_err("refused"); + let term = err.term().expect("refused by Terms"); + assert_eq!(term.error(), NormalizeError::Invalid); + assert_eq!(render(term.path()), ".x"); + assert_eq!( + err.to_string(), + "no equality term: the value is not valid for its logical type" + ); +} + +#[test] +fn terms_passes_a_source_failure_through() { + struct Throws; + impl Plaintext for Throws { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(None)?; + 1u32.visit(seq.element()?)?; + Err(::source( + SourceError::msg("getter threw"), + )) + } + } + let err = terms(Throws).expect_err("refused"); + assert!(err.term().is_none()); + assert_eq!(err.to_string(), "getter threw"); + assert_eq!(err.0.to_string(), "getter threw"); +} + /// Seals through an await, and checks that the source's walk had finished /// before the first one. struct Remote { From 3c57cd41fc594f27ad558c59ea2903319ace41b7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 21:55:43 +1100 Subject: [PATCH 06/68] feat(aead): compare paths and steps by value Tests and callers had to match on a path's steps with guards to check where a value was refused or where a term sits. A map key in a path is not secret from the ciphertext, which carries it in the clear, so Step and Path now derive PartialEq and Eq. Debug still masks every key, so an assertion that fails does not print one into a log. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/README.md | 2 +- packages/vitaminc-normalize/src/terms.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index e20fae1a4..e144f1e09 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -77,7 +77,7 @@ user.insert("name", "Ada"); let (ciphertext, terms) = encrypt_with_terms(user, &cipher, "users/v1")?; assert_eq!(terms.len(), 2); -assert!(matches!(terms[0].path.steps(), [Step::Key(k)] if k == "email")); +assert_eq!(terms[0].path.steps(), [Step::Key("email".into())]); assert_eq!(terms[0].normalized.domain, domain::TEXT); # Ok::<(), vitaminc_aead::EncryptError>(()) ``` diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 56ecc0f25..7604b2d22 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -265,7 +265,7 @@ impl MapSink for TermsMap<'_, E> { /// let mut user = BTreeMap::new(); /// user.insert("name", "Ada"); /// let found = terms(&user)?; -/// assert!(matches!(found[0].path.steps(), [Step::Key(k)] if k == "name")); +/// assert_eq!(found[0].path.steps(), [Step::Key("name".into())]); /// assert_eq!(found[0].normalized.domain, domain::TEXT); /// /// // U+0378 is unassigned in Unicode 16, so the name has no term. @@ -273,7 +273,7 @@ impl MapSink for TermsMap<'_, E> { /// let refused = terms(&user).unwrap_err(); /// let term = refused.term().expect("refused by Terms"); /// assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); -/// assert!(matches!(term.path().steps(), [Step::Key(k)] if k == "name")); +/// assert_eq!(term.path().steps(), [Step::Key("name".into())]); /// // The message names neither the field nor its value. /// assert_eq!( /// refused.to_string(), From 5e1bd6a7ffaa4f318522a4a33ed128a3f8659ef0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 21:56:14 +1100 Subject: [PATCH 07/68] test(aead,normalize): share one copy of the path notation The normalize tests carried a second copy of render, because the aead copy was cfg(test) and so unreachable from another crate. The copy in vitaminc-aead is now also built under a test-support feature, hidden from the docs, and the normalize tests turn it on through their path-only dev-dependency. That is the smallest surface that shares it: no published build has the feature, and nothing public shows a key. A Display adapter on Path was the other option, but it would offer an unmasked rendering to every caller, which is what the masking is there to avoid. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/Cargo.toml | 4 +++- .../vitaminc-normalize/tests/known_answers.rs | 15 ++------------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 6543766b8..67139352d 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -43,7 +43,9 @@ version = "=1.1.0" # every term against today's `canonical` encoders, byte for byte, until # those are removed. vitaminc-aead-value = { path = "../aead-value", features = ["canonical", "chrono", "rust_decimal"] } -vitaminc-aead = { path = "../aead", features = ["chrono", "rust_decimal", "uuid"] } +# `test-support` for `plaintext::render`, the path notation the tests +# assert against, so there is one copy of it. +vitaminc-aead = { path = "../aead", features = ["chrono", "rust_decimal", "uuid", "test-support"] } chrono = { version = "0.4.44", default-features = false, features = ["std"] } uuid = { version = "1", default-features = false } quickcheck = "1.1.0" diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 21efe0fb7..eb7e7d3e4 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use chrono::{DateTime, NaiveDate, Utc}; use futures_executor::block_on; use vitaminc_aead::plaintext::kinds::chrono as conv; +use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::{AsyncCipher, Cipher}; use vitaminc_aead::{ Context, EncryptError, Float, Int, Logical, Physical, Plaintext, SeqSink, Sink, SourceError, @@ -17,7 +18,7 @@ use vitaminc_aead_value::canonical::equality_input; use vitaminc_aead_value::Value; use vitaminc_normalize::{ domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, terms, - NormalizeError, Path, Step, Term, TermError, + NormalizeError, Term, TermError, }; use vitaminc_protected::{Controlled, Protected}; @@ -336,18 +337,6 @@ fn user() -> BTreeMap<&'static str, Vec>> { m } -/// A path written out for an assertion: `.key` for an entry and `[i]` for -/// an element. -fn render(path: &Path) -> String { - path.steps() - .iter() - .map(|step| match step { - Step::Index(i) => format!("[{i}]"), - Step::Key(k) => format!(".{k}"), - }) - .collect() -} - fn paths(terms: &[Term]) -> Vec { terms.iter().map(|t| render(&t.path)).collect() } From ab980cb55dec26a937939f8e64a17417b8c4ed11 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 21:57:05 +1100 Subject: [PATCH 08/68] fix(normalize): put the NormalizeError on TermError's source chain TermError held its NormalizeError without naming it as its source, so a reporter that walks source() never reached the reason, and code written against the earlier docs, which downcast the chain to NormalizeError, silently found nothing. The reason is now TermError's source(). TermError stays the documented downcast target, and the docs say the NormalizeError is reachable through the chain. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/README.md | 8 ++-- packages/vitaminc-normalize/src/terms.rs | 6 +++ .../vitaminc-normalize/tests/known_answers.rs | 41 +++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index e144f1e09..acbb67971 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -94,9 +94,11 @@ client, stops the walk: encrypting it with no term and no error would leave an index silently incomplete. That refusal, an unassigned code point and a value invalid for its logical type all arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as a `TermsError`), which holds the -`NormalizeError` and the path to the refused field. Its message names -neither the field nor the value, because map keys can be user data; read -the path with `TermError::path`. +`NormalizeError` and the path to the refused field. Downcast to +`TermError`; the `NormalizeError` is also its `source()`, so a reporter +that walks the error chain reaches it. The message names neither the +field nor the value, because map keys can be user data; read the path +with `TermError::path`. ## Encodings diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 7604b2d22..50115df25 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -36,6 +36,10 @@ pub struct Term { /// A scalar [`Terms`] refused: why, and where in the value. /// +/// This is the type to downcast a refusal to. Its +/// [`source`](core::error::Error::source) is the [`NormalizeError`], so a +/// reporter that walks the error chain reaches the reason too. +/// /// `Display` shows only the reason, because the path can hold map keys and /// map keys can be user data. `Debug` shows the reason and the path's /// shape, with every key masked. Read the path with @@ -46,6 +50,7 @@ pub struct TermError { #[non_sensitive] path: Path, #[non_sensitive] + #[source] error: NormalizeError, } @@ -114,6 +119,7 @@ impl Error for TermsError { /// (`Invalid`). Beside [`EncryptSink`] that arrives as /// [`EncryptError::Source`], and `source.inner().downcast_ref::()` /// recovers it. Alone, through [`terms`], it is [`TermsError::term`]. +/// Either way the [`NormalizeError`] is on the `source()` chain. pub struct Terms<'t, E> { out: &'t mut Vec, /// The path of the container this sink is a child of, borrowed from diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index eb7e7d3e4..c28e409b3 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -480,6 +480,47 @@ fn a_refusal_names_the_field_only_on_request() { } } +/// Every error in a chain, from `err` down through each `source()`. +fn chain<'e>( + err: &'e (dyn core::error::Error + 'static), +) -> Vec<&'e (dyn core::error::Error + 'static)> { + core::iter::successors(Some(err), |e| e.source()).collect() +} + +/// A reporter that walks `source()` reaches the `NormalizeError` behind a +/// refusal, whether it arrived through encryption or through `terms`. +#[test] +fn the_normalize_error_is_on_the_source_chain() { + let reason = |err: &(dyn core::error::Error + 'static)| { + chain(err) + .into_iter() + .find_map(|e| e.downcast_ref::().copied()) + }; + let encrypting = plan_with_terms::<_, &str, _>(vec!["\u{378}"], "ctx") + .err() + .expect("refused"); + assert_eq!( + reason(&encrypting), + Some(NormalizeError::UnassignedCodePoint) + ); + let alone = terms(vec!["\u{378}"]).expect_err("refused"); + assert_eq!(reason(&alone), Some(NormalizeError::UnassignedCodePoint)); + // The chain ends at the reason, which says why and nothing more. + let last = chain(&alone).pop().expect("a chain"); + assert!(last.source().is_none()); + assert_eq!( + last.to_string(), + "text contains a code point unassigned in Unicode 16" + ); + // `TermError` itself names its reason as its source. + let term = alone.term().expect("refused by Terms"); + let source = core::error::Error::source(term).expect("a source"); + assert_eq!( + source.downcast_ref::(), + Some(&NormalizeError::UnassignedCodePoint) + ); +} + #[test] fn terms_collects_every_term_without_encrypting() { let found = terms(user()).expect("walks"); From 4343a6230901cff49bfba2400b2ae0117d4fb53d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 21:57:22 +1100 Subject: [PATCH 09/68] refactor(normalize): keep TermsError's field private A public tuple field fixed TermsError's shape: it could not become an enum, or carry anything else, without breaking every caller that read .0. The field is private now and source_error() returns it, beside term() as before. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/src/terms.rs | 9 ++++++++- packages/vitaminc-normalize/tests/known_answers.rs | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 50115df25..06a66446d 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -73,9 +73,10 @@ impl TermError { /// both arrive as a [`SourceError`]. [`term`](TermsError::term) recovers a /// [`TermError`] from it, the same downcast a caller makes on /// [`EncryptError::Source`] when `Terms` runs beside encryption. +/// [`source_error`](TermsError::source_error) is the error as it arrived. #[derive(Debug, thiserror::Error)] #[error(transparent)] -pub struct TermsError(pub SourceError); +pub struct TermsError(SourceError); impl TermsError { /// The scalar [`Terms`] refused, or `None` if the source failed on its @@ -83,6 +84,12 @@ impl TermsError { pub fn term(&self) -> Option<&TermError> { self.0.inner().downcast_ref() } + + /// The failure as the walk reported it: what [`Terms`] refused, or the + /// source's own error. + pub fn source_error(&self) -> &SourceError { + &self.0 + } } impl Error for TermsError { diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index c28e409b3..7132933a5 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -563,7 +563,7 @@ fn terms_passes_a_source_failure_through() { let err = terms(Throws).expect_err("refused"); assert!(err.term().is_none()); assert_eq!(err.to_string(), "getter threw"); - assert_eq!(err.0.to_string(), "getter threw"); + assert_eq!(err.source_error().to_string(), "getter threw"); } /// Seals through an await, and checks that the source's walk had finished From 19853becf8a8ec4fd27371f0b638619e09eeaa33 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 22:04:24 +1100 Subject: [PATCH 10/68] perf(normalize): build a term's path only when it is pushed Terms kept an owned Vec per container, cloned from its parent's, and copied every map key as the walk entered it, so a document paid for paths whether or not any field had a term. Its docs said a child that produced no term cost nothing, which was not true. Terms now uses parent links, as EncryptSink does: each child sink holds a link to its container's place and its own index, or the position of its key in one buffer of the keys on the path being walked. The walk shares that buffer and each container truncates it to where its own keys begin, so it holds only the current path's keys. A path is built from the links only when a term is pushed or a refusal is built. Beside encryption, a walk with no terms now allocates that one buffer and nothing else; a test with a counting allocator pins it (one allocation for the document it walks, where there were 116). Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/src/terms.rs | 142 +++++++++++++++--- .../vitaminc-normalize/tests/allocations.rs | 67 +++++++++ .../vitaminc-normalize/tests/known_answers.rs | 34 +++++ 3 files changed, 219 insertions(+), 24 deletions(-) create mode 100644 packages/vitaminc-normalize/tests/allocations.rs diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 06a66446d..fb06207f9 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -127,33 +127,103 @@ impl Error for TermsError { /// [`EncryptError::Source`], and `source.inner().downcast_ref::()` /// recovers it. Alone, through [`terms`], it is [`TermsError::term`]. /// Either way the [`NormalizeError`] is on the `source()` chain. +/// +/// # Cost +/// +/// A path costs nothing until a term is pushed or a refusal is built. Each +/// child sink holds a link to its container's place and its own index, or +/// the position of its key in one buffer of the keys on the path being +/// walked, which the whole walk shares and reuses. So the walk allocates +/// that buffer, as long as the keys on the longest path, and otherwise +/// only what each pushed term needs. pub struct Terms<'t, E> { out: &'t mut Vec, - /// The path of the container this sink is a child of, borrowed from - /// that container's sink, and the step from it to this value. Owned - /// only when a term is pushed, so a child that produces none costs no - /// allocation. - parent: &'t [Step], - step: Option, + keys: Keys<'t>, + at: Place<'t>, _error: PhantomData, } +/// The map keys on the path being walked, end to end. The root owns the +/// buffer and every sink below it borrows it. A container truncates it +/// back to where its own keys begin before each child, so it holds only +/// the keys of the current path. +enum Keys<'t> { + Own(String), + Lent(&'t mut String), +} + +impl Keys<'_> { + fn get(&mut self) -> &mut String { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } + + fn as_str(&self) -> &str { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } +} + +/// Where a node sits: a link to its container's place and its own step. +/// A key is named by its position in [`Keys`]. +#[derive(Clone, Copy)] +enum Place<'t> { + Root, + Element { + parent: &'t Place<'t>, + index: usize, + }, + Entry { + parent: &'t Place<'t>, + key: (usize, usize), + }, +} + +impl Place<'_> { + /// Append the steps from the root to this node, reading keys from + /// `keys`. + fn locate(&self, keys: &str, steps: &mut Vec) { + match *self { + Place::Root => {} + Place::Element { parent, index } => { + parent.locate(keys, steps); + steps.push(Step::Index(index)); + } + Place::Entry { + parent, + key: (start, end), + } => { + parent.locate(keys, steps); + steps.extend(keys.get(start..end).map(|key| Step::Key(key.to_owned()))); + } + } + } + + /// The path from the root to this node. + fn path(&self, keys: &str) -> Path { + let mut steps = Vec::new(); + self.locate(keys, &mut steps); + Path::new(steps) + } +} + impl<'t, E> Terms<'t, E> { /// A sink that appends to `out`. pub fn new(out: &'t mut Vec) -> Self { Self { out, - parent: &[], - step: None, + keys: Keys::Own(String::new()), + at: Place::Root, _error: PhantomData, } } - fn path(&self) -> Vec { - let mut path = Vec::with_capacity(self.parent.len() + usize::from(self.step.is_some())); - path.extend_from_slice(self.parent); - path.extend(self.step.iter().cloned()); - path + fn path(&self) -> Path { + self.at.path(self.keys.as_str()) } } @@ -166,7 +236,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { match normalize(ty, value) { Ok(normalized) => { - let path = Path::new(self.path()); + let path = self.path(); self.out.push(Term { path, normalized }); Ok(()) } @@ -176,7 +246,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { Ok(()) } Err(error) => Err(E::source(SourceError::new(TermError { - path: Path::new(self.path()), + path: self.path(), error, }))), } @@ -184,8 +254,10 @@ impl<'t, E: Error> Sink for Terms<'t, E> { fn seq(self, _: Option) -> Result { Ok(TermsSeq { - path: self.path(), + mark: self.keys.as_str().len(), out: self.out, + keys: self.keys, + at: self.at, next: 0, _error: PhantomData, }) @@ -193,8 +265,10 @@ impl<'t, E: Error> Sink for Terms<'t, E> { fn map(self, _: Option) -> Result { Ok(TermsMap { - path: self.path(), + mark: self.keys.as_str().len(), out: self.out, + keys: self.keys, + at: self.at, _error: PhantomData, }) } @@ -208,7 +282,11 @@ impl<'t, E: Error> Sink for Terms<'t, E> { /// plus its index. pub struct TermsSeq<'t, E> { out: &'t mut Vec, - path: Vec, + keys: Keys<'t>, + /// Where this sequence's own keys would begin: the length of `keys` + /// at its start. + mark: usize, + at: Place<'t>, next: usize, _error: PhantomData, } @@ -222,12 +300,17 @@ impl SeqSink for TermsSeq<'_, E> { Self: 's; fn element(&mut self) -> Result, E> { - let step = Step::Index(self.next); + let keys = self.keys.get(); + keys.truncate(self.mark); + let index = self.next; self.next += 1; Ok(Terms { out: self.out, - parent: &self.path, - step: Some(step), + keys: Keys::Lent(keys), + at: Place::Element { + parent: &self.at, + index, + }, _error: PhantomData, }) } @@ -241,7 +324,11 @@ impl SeqSink for TermsSeq<'_, E> { /// key. pub struct TermsMap<'t, E> { out: &'t mut Vec, - path: Vec, + keys: Keys<'t>, + /// Where this map's keys begin in `keys`: its length at the map's + /// start. Each entry's key replaces the last one there. + mark: usize, + at: Place<'t>, _error: PhantomData, } @@ -254,10 +341,17 @@ impl MapSink for TermsMap<'_, E> { Self: 's; fn entry(&mut self, key: &str) -> Result, E> { + let keys = self.keys.get(); + keys.truncate(self.mark); + keys.push_str(key); + let key = (self.mark, keys.len()); Ok(Terms { out: self.out, - parent: &self.path, - step: Some(Step::Key(key.to_owned())), + keys: Keys::Lent(keys), + at: Place::Entry { + parent: &self.at, + key, + }, _error: PhantomData, }) } diff --git a/packages/vitaminc-normalize/tests/allocations.rs b/packages/vitaminc-normalize/tests/allocations.rs new file mode 100644 index 000000000..7092d442d --- /dev/null +++ b/packages/vitaminc-normalize/tests/allocations.rs @@ -0,0 +1,67 @@ +//! What collecting terms beside encryption allocates, counted by a global +//! allocator. In its own test binary, so no other test allocates while one +//! is counting. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use vitaminc_aead::plan; +use vitaminc_normalize::plan_with_terms; + +struct Counting; + +static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0); + +// SAFETY: every call forwards to `System` unchanged; the counter is the +// only addition. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: the caller's contract is `System`'s. + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +fn allocations(f: impl FnOnce()) -> usize { + let before = ALLOCATIONS.load(Ordering::SeqCst); + f(); + ALLOCATIONS.load(Ordering::SeqCst) - before +} + +/// Beside encryption, a walk that pushes no term allocates one buffer for +/// the keys on its path and nothing for any container or entry, however +/// many there are. +#[test] +fn a_walk_with_no_terms_allocates_only_the_key_buffer() { + let mut inner = BTreeMap::new(); + for key in ["a", "b", "c", "d"] { + inner.insert(key, vec![None::, None]); + } + let mut doc = BTreeMap::new(); + for key in ["p", "q", "r"] { + doc.insert(key, vec![inner.clone(), inner.clone()]); + } + let encrypting = allocations(|| { + plan::<_, (), _>(doc.clone(), "ctx").expect("plans"); + }); + let with_terms = allocations(|| { + let (_, terms) = plan_with_terms::<_, (), _>(doc.clone(), "ctx").expect("plans"); + assert!(terms.is_empty()); + }); + assert_eq!(with_terms, encrypting + 1); +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 7132933a5..09b6cd0d5 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -432,6 +432,40 @@ fn paths_follow_the_nesting() { assert_eq!(terms[0].normalized.domain, domain::BYTES); } +/// Every container on a path shares one buffer of keys, and each starts +/// over where its own keys begin, so a path names only its own keys +/// however many siblings went before it. +#[test] +fn sibling_paths_name_only_their_own_keys() { + let mut first = BTreeMap::new(); + first.insert("x", vec!["1", "2"]); + first.insert("yy", vec!["3"]); + let mut second = BTreeMap::new(); + second.insert("zzz", vec!["4"]); + let mut doc = BTreeMap::new(); + doc.insert("a", vec![first.clone(), second]); + doc.insert("bb", vec![first]); + for found in [ + plan_with_terms::<_, Refused, _>(doc.clone(), "ctx") + .expect("plans") + .1, + terms(doc).expect("walks"), + ] { + assert_eq!( + paths(&found), + [ + ".a[0].x[0]", + ".a[0].x[1]", + ".a[0].yy[0]", + ".a[1].zzz[0]", + ".bb[0].x[0]", + ".bb[0].x[1]", + ".bb[0].yy[0]", + ] + ); + } +} + #[test] fn an_unassigned_code_point_stops_the_walk_with_the_normalize_error() { let err = plan_with_terms::<_, Refused, _>("\u{378}", "ctx") From 5af76c43a9259a0639e10f860734e4607f8f2e72 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 22:09:05 +1100 Subject: [PATCH 11/68] fix(normalize): refuse in terms what encryption refuses terms ran Terms without EncryptSink, so it skipped every shape rule encryption keeps and returned terms for values encryption refuses: a map that gave k twice produced two .k terms, while encrypt_with_terms failed with a duplicate key. An index fed from terms could then hold entries for a value that can never be stored. Terms now keeps the shape rules itself, through vitaminc-aead's shape module, the code EncryptSink keeps them with: depth, a valid logical value, a framable passthrough, no repeated key, no child sink dropped without a value, and something sealed in every container with children. That last rule is about sealing, and a terms-only walk seals nothing, but a value that breaks it cannot be encrypted, so terms refuses it too: the rule is that terms accepts a value exactly when encrypt_with_terms does, and refuses it for the same reason at the same path. A passthrough is framed, as encryption frames it, to check that it can be. A shape refusal is the same Refusal EncryptSink builds, from the same kind of parent-link chain, and TermsError::refusal recovers it. A scalar invalid for its logical type is now such a refusal, InvalidValue, rather than NormalizeError::Invalid, as it already was beside encryption. plan_with_terms and the functions built on it tee EncryptSink with a Terms that leaves the rules to it, so they are kept, and paid for, once. A test runs every rule both ways and checks that the two agree. Claude-Session: https://claude.ai/code/session_012zHhtTEo968WazExKxA5oT --- packages/vitaminc-normalize/README.md | 24 +- packages/vitaminc-normalize/src/terms.rs | 317 ++++++++++++--- .../vitaminc-normalize/tests/agreement.rs | 374 ++++++++++++++++++ .../vitaminc-normalize/tests/known_answers.rs | 43 +- 4 files changed, 695 insertions(+), 63 deletions(-) create mode 100644 packages/vitaminc-normalize/tests/agreement.rs diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index acbb67971..f61458a03 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -87,18 +87,26 @@ every term before its first await. `plan_with_terms` walks without sealing at all, and `terms` collects the terms with no encryption in the walk. +`terms` refuses every value encryption refuses, for the same reason and +at the same path, so an index never holds terms for a value that cannot +be stored. It keeps the same shape rules, through the same code: no +duplicate key, no value nested too deep, every scalar valid for its +logical type, every passthrough framable, and something sealed in every +container with children, even though it seals nothing itself. Read such a +refusal with `TermsError::refusal`; encryption reports the same one as +`EncryptError::Shape`. + A scalar whose kind has no domain (a null, a boolean, an `undefined`) produces no term and does not stop the walk; passthrough subtrees get none either. A scalar whose *logical type* has no domain, one from a newer client, stops the walk: encrypting it with no term and no error would leave -an index silently incomplete. That refusal, an unassigned code point and a -value invalid for its logical type all arrive as `EncryptError::Source` -carrying a `TermError` (from `terms`, as a `TermsError`), which holds the -`NormalizeError` and the path to the refused field. Downcast to -`TermError`; the `NormalizeError` is also its `source()`, so a reporter -that walks the error chain reaches it. The message names neither the -field nor the value, because map keys can be user data; read the path -with `TermError::path`. +an index silently incomplete. That refusal and an unassigned code point +arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as +`TermsError::term`), which holds the `NormalizeError` and the path to the +refused field. Downcast to `TermError`; the `NormalizeError` is also its +`source()`, so a reporter that walks the error chain reaches it. The +message names neither the field nor the value, because map keys can be +user data; read the path with `TermError::path`. ## Encodings diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index fb06207f9..3dca945be 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -4,16 +4,18 @@ //! [`Terms`] is a [`Sink`] that produces one [`Term`] per scalar that has //! an equality domain. It runs beside encryption as `Tee(EncryptSink, //! Terms)`, so a caller holds every term before any cipher is called and, -//! with an async cipher, before the first await. [`terms`] runs it alone. +//! with an async cipher, before the first await. [`terms`] runs it alone, +//! and then it refuses what encryption would refuse. use core::future::Future; use core::marker::PhantomData; use vitaminc_aead::plaintext::{Error, Path, Step}; use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; +use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; use vitaminc_aead::{ EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, Plaintext, - SeqSink, Sink, SourceError, Tee, + Refusal, SeqSink, Sink, SourceError, Tee, }; use vitaminc_protected::OpaqueDebug; @@ -70,9 +72,11 @@ impl TermError { /// failure. /// /// A source reports through [`Error::source`] whichever sink it feeds, so -/// both arrive as a [`SourceError`]. [`term`](TermsError::term) recovers a -/// [`TermError`] from it, the same downcast a caller makes on -/// [`EncryptError::Source`] when `Terms` runs beside encryption. +/// every failure arrives as a [`SourceError`]. [`term`](TermsError::term) +/// recovers a [`TermError`] from it, the same downcast a caller makes on +/// [`EncryptError::Source`] when `Terms` runs beside encryption, and +/// [`refusal`](TermsError::refusal) a value refused for its shape, which +/// encryption reports as [`EncryptError::Shape`]. /// [`source_error`](TermsError::source_error) is the error as it arrived. #[derive(Debug, thiserror::Error)] #[error(transparent)] @@ -80,11 +84,17 @@ pub struct TermsError(SourceError); impl TermsError { /// The scalar [`Terms`] refused, or `None` if the source failed on its - /// own. + /// own or the value was refused for its shape. pub fn term(&self) -> Option<&TermError> { self.0.inner().downcast_ref() } + /// The value refused for its shape, as encryption would refuse it, or + /// `None` if it was refused for another reason. + pub fn refusal(&self) -> Option<&Refusal> { + self.0.inner().downcast_ref() + } + /// The failure as the walk reported it: what [`Terms`] refused, or the /// source's own error. pub fn source_error(&self) -> &SourceError { @@ -116,17 +126,45 @@ impl Error for TermsError { /// /// Passthrough subtrees travel in the clear and get no terms. /// +/// # Only what can be encrypted +/// +/// A `Terms` refuses every value [`EncryptSink`] refuses, for the same +/// [`Unencryptable`](vitaminc_aead::Unencryptable) reason and at the same path, so an index never holds +/// terms for a value that cannot be stored. It keeps the +/// [`shape`](vitaminc_aead::shape) rules through the code `EncryptSink` +/// keeps them with: nothing deeper than the transport's depth limit, every +/// scalar valid for its logical type, every passthrough subtree framable, +/// no map key given twice, no child sink dropped without a value, and +/// something sealed in every container with children. The last rule is +/// about sealing, and this walk seals nothing, but a value that breaks it +/// cannot be encrypted, so it is refused here too. A passthrough is framed +/// as encryption frames it, to check that it can be, and the frame is +/// dropped. +/// +/// So [`terms`] accepts a value exactly when [`encrypt_with_terms`] does +/// with a cipher that does not fail, and refuses it for the same reason at +/// the same path. [`plan_with_terms`], and the encrypting functions built +/// on it, pair `EncryptSink` with a `Terms` that leaves the shape rules to +/// it, so they are kept once. +/// /// # Errors /// /// The walk stops with `E::source(SourceError::new(error))`, where `error` -/// is a [`TermError`] holding the scalar's path and the -/// [`NormalizeError`]: the scalar's logical type has no domain -/// (`NoDomain`), its text holds a code point unassigned in Unicode 16 -/// (`UnassignedCodePoint`), or it is not valid for its logical type -/// (`Invalid`). Beside [`EncryptSink`] that arrives as -/// [`EncryptError::Source`], and `source.inner().downcast_ref::()` -/// recovers it. Alone, through [`terms`], it is [`TermsError::term`]. -/// Either way the [`NormalizeError`] is on the `source()` chain. +/// is one of: +/// +/// - a [`Refusal`]: the value breaks a shape rule, as above. A scalar not +/// valid for its logical type is refused this way, as +/// [`Unencryptable::InvalidValue`](vitaminc_aead::Unencryptable::InvalidValue), before it is normalized. Through +/// [`terms`] it is [`TermsError::refusal`]. Beside `EncryptSink`, which +/// refuses it first, it is [`EncryptError::Shape`]. +/// - a [`TermError`] holding the scalar's path and the +/// [`NormalizeError`]: the scalar's logical type has no domain +/// (`NoDomain`), or its text holds a code point unassigned in Unicode 16 +/// (`UnassignedCodePoint`). Beside [`EncryptSink`] that arrives as +/// [`EncryptError::Source`], and +/// `source.inner().downcast_ref::()` recovers it. Alone, +/// through [`terms`], it is [`TermsError::term`]. Either way the +/// [`NormalizeError`] is on the `source()` chain. /// /// # Cost /// @@ -136,13 +174,44 @@ impl Error for TermsError { /// walked, which the whole walk shares and reuses. So the walk allocates /// that buffer, as long as the keys on the longest path, and otherwise /// only what each pushed term needs. +/// +/// The shape rules cost what they cost encryption: a map keeps one copy +/// of each of its keys until it ends, which is what checking for a repeat +/// exactly takes, and a passthrough is framed. Beside `EncryptSink`, +/// through [`plan_with_terms`], none of that is paid twice. A caller that +/// tees `Terms::new` beside `EncryptSink` itself has both keep the rules. pub struct Terms<'t, E> { out: &'t mut Vec, keys: Keys<'t>, at: Place<'t>, + /// `None` beside an [`EncryptSink`] that keeps the rules itself. + rules: Option>, _error: PhantomData, } +/// The shape rules one node keeps: how deep it sits, and its hold on its +/// container's rules, which it settles when it ends. The root has no +/// container. +struct NodeRules<'t> { + depth: usize, + settle: Option>, +} + +impl NodeRules<'_> { + /// The node put a sealed node: a scalar, or a container. + fn sealed(self) { + if let Some(settle) = self.settle { + settle.sealed(); + } + } +} + +/// A container's shape rules, `R`, with the rules of the node it is. +struct Held<'t, R> { + node: NodeRules<'t>, + rules: R, +} + /// The map keys on the path being walked, end to end. The root owns the /// buffer and every sink below it borrows it. A container truncates it /// back to where its own keys begin before each child, so it holds only @@ -211,19 +280,54 @@ impl Place<'_> { } } +/// A place with the keys it names: what the shape rules locate a refusal +/// with. +struct At<'a> { + place: &'a Place<'a>, + keys: &'a str, +} + +impl Locate for At<'_> { + fn locate(&self, steps: &mut Vec) { + self.place.locate(self.keys, steps); + } +} + +/// A shape refusal, reported the only way a sink generic over its error +/// can report anything. +fn refused(refusal: Refusal) -> E { + E::source(SourceError::new(refusal)) +} + impl<'t, E> Terms<'t, E> { - /// A sink that appends to `out`. + /// A sink that appends to `out` and keeps the shape rules itself. pub fn new(out: &'t mut Vec) -> Self { Self { out, keys: Keys::Own(String::new()), at: Place::Root, + rules: Some(NodeRules { + depth: 0, + settle: None, + }), _error: PhantomData, } } - fn path(&self) -> Path { - self.at.path(self.keys.as_str()) + /// A sink that appends to `out` and leaves the shape rules to the + /// [`EncryptSink`] it is teed beside, which refuses first. + fn beside_encryption(out: &'t mut Vec) -> Self { + Self { + rules: None, + ..Self::new(out) + } + } + + fn at(&self) -> At<'_> { + At { + place: &self.at, + keys: self.keys.as_str(), + } } } @@ -234,46 +338,100 @@ impl<'t, E: Error> Sink for Terms<'t, E> { type Map = TermsMap<'t, E>; fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { + if let Some(rules) = &self.rules { + shape::scalar(rules.depth, ty, &value, &self.at()).map_err(refused)?; + } match normalize(ty, value) { Ok(normalized) => { - let path = self.path(); + let path = self.at.path(self.keys.as_str()); self.out.push(Term { path, normalized }); - Ok(()) } // No domain for the kind: nothing to index, carry on. No domain // for a logical type: refuse, see the type's docs. - Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => { - Ok(()) + Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => {} + Err(error) => { + return Err(E::source(SourceError::new(TermError { + path: self.at.path(self.keys.as_str()), + error, + }))) } - Err(error) => Err(E::source(SourceError::new(TermError { - path: self.path(), - error, - }))), } + if let Some(rules) = self.rules { + rules.sealed(); + } + Ok(()) } fn seq(self, _: Option) -> Result { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: SeqRules::new(), + }) + } + None => None, + }; Ok(TermsSeq { mark: self.keys.as_str().len(), out: self.out, keys: self.keys, at: self.at, next: 0, + rules, _error: PhantomData, }) } fn map(self, _: Option) -> Result { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: MapRules::new(), + }) + } + None => None, + }; Ok(TermsMap { mark: self.keys.as_str().len(), out: self.out, keys: self.keys, at: self.at, + rules, _error: PhantomData, }) } - fn passthrough(self, _: P) -> Result<(), E> { + /// No terms. Keeping the shape rules, the subtree is framed, as + /// encryption frames it, and the frame dropped. + fn passthrough(self, value: P) -> Result<(), E> { + if let Some(rules) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + shape::frame_passthrough(value, rules.depth, &at, refused)?; + if let Some(settle) = rules.settle { + settle.passthrough(); + } + } Ok(()) } } @@ -288,6 +446,7 @@ pub struct TermsSeq<'t, E> { mark: usize, at: Place<'t>, next: usize, + rules: Option>, _error: PhantomData, } @@ -300,22 +459,48 @@ impl SeqSink for TermsSeq<'_, E> { Self: 's; fn element(&mut self) -> Result, E> { - let keys = self.keys.get(); - keys.truncate(self.mark); - let index = self.next; - self.next += 1; + let TermsSeq { + out, + keys, + mark, + at, + next, + rules, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .element(&At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); + let index = *next; + *next += 1; Ok(Terms { - out: self.out, + out, keys: Keys::Lent(keys), - at: Place::Element { - parent: &self.at, - index, - }, + at: Place::Element { parent: at, index }, + rules, _error: PhantomData, }) } fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } Ok(()) } } @@ -329,6 +514,7 @@ pub struct TermsMap<'t, E> { /// start. Each entry's key replaces the last one there. mark: usize, at: Place<'t>, + rules: Option>, _error: PhantomData, } @@ -341,28 +527,57 @@ impl MapSink for TermsMap<'_, E> { Self: 's; fn entry(&mut self, key: &str) -> Result, E> { - let keys = self.keys.get(); - keys.truncate(self.mark); + let TermsMap { + out, + keys, + mark, + at, + rules, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .entry(key, &At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); keys.push_str(key); - let key = (self.mark, keys.len()); + let key = (*mark, keys.len()); Ok(Terms { - out: self.out, + out, keys: Keys::Lent(keys), - at: Place::Entry { - parent: &self.at, - key, - }, + at: Place::Entry { parent: at, key }, + rules, _error: PhantomData, }) } fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } Ok(()) } } /// Every equality term of `value`, in walk order, without encrypting it. /// +/// It refuses every value encryption refuses, for the same reason at the +/// same path (see [`Terms`]), so it never returns terms for a value that +/// cannot be stored. +/// /// # Examples /// /// ``` @@ -386,12 +601,21 @@ impl MapSink for TermsMap<'_, E> { /// refused.to_string(), /// "no equality term: text contains a code point unassigned in Unicode 16" /// ); +/// +/// // A uuid of three bytes cannot be encrypted, so it has no term either: +/// // `terms` refuses it as encryption does. +/// use vitaminc_aead::{Logical, Physical, Raw, Unencryptable}; +/// let id = Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); +/// let refused = terms(id).unwrap_err(); +/// let refusal = refused.refusal().expect("refused for its shape"); +/// assert_eq!(refusal.reason(), Unencryptable::InvalidValue); /// # Ok::<(), vitaminc_normalize::TermsError>(()) /// ``` /// /// # Errors /// -/// [`TermsError`]: what [`Terms`] refuses, or the source's own failure. +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. pub fn terms(value: P) -> Result, TermsError> { let mut out = Vec::new(); value.visit(Terms::new(&mut out))?; @@ -415,7 +639,10 @@ where A: IntoAad<'a>, { let mut terms = Vec::new(); - let (planned, ()) = value.visit(Tee(EncryptSink::root(aad), Terms::new(&mut terms)))?; + let (planned, ()) = value.visit(Tee( + EncryptSink::root(aad), + Terms::beside_encryption(&mut terms), + ))?; Ok((planned, terms)) } diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs new file mode 100644 index 000000000..1fe77fd42 --- /dev/null +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -0,0 +1,374 @@ +//! `terms` and `encrypt_with_terms` agree on every value: each accepts +//! what the other accepts, with the same terms, and refuses what the other +//! refuses, for the same reason at the same path. One case per rule +//! encryption keeps, and per refusal of `Terms`'s own. + +use std::collections::BTreeMap; + +use vitaminc_aead::frame::MAX_DEPTH; +use vitaminc_aead::plaintext::render; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{ + Context, EncryptError, Logical, MapSink, Physical, Plaintext, Raw, SeqSink, Sink, SourceError, + Unencryptable, +}; +use vitaminc_normalize::{encrypt_with_terms, terms, NormalizeError, Term, TermError}; +use vitaminc_protected::{Controlled, Protected}; + +/// Seals in the clear: these tests are about the walk, not the cipher. +struct Clear; + +impl Cipher for Clear { + type Leaf = Vec; + type Error = &'static str; + + fn seal( + &self, + plaintext: Protected>, + _: &Context<'_>, + ) -> Result, &'static str> { + Ok(plaintext.risky_unwrap()) + } + + fn open(&self, leaf: Vec, _: &Context<'_>) -> Result>, &'static str> { + Ok(Protected::new(leaf)) + } +} + +/// How a walk ended, with every path written out. +#[derive(Debug, PartialEq)] +enum Outcome { + Terms(Vec), + Shape(Unencryptable, String), + Term(NormalizeError, String), + Source(String), +} + +use Outcome::{Shape, Source, Term as NoTerm, Terms}; + +fn paths(found: &[Term]) -> Outcome { + Terms(found.iter().map(|t| render(&t.path)).collect()) +} + +fn sourced(source: &SourceError) -> Outcome { + match source.inner().downcast_ref::() { + Some(term) => NoTerm(term.error(), render(term.path())), + None => Source(source.to_string()), + } +} + +fn alone(value: P) -> Outcome { + match terms(value) { + Ok(found) => paths(&found), + Err(err) => match err.refusal() { + Some(refusal) => Shape(refusal.reason(), render(refusal.path())), + None => sourced(err.source_error()), + }, + } +} + +fn encrypting(value: P) -> Outcome { + match encrypt_with_terms(value, &Clear, "ctx") { + Ok((_, found)) => paths(&found), + Err(EncryptError::Shape(refusal)) => Shape(refusal.reason(), render(refusal.path())), + Err(EncryptError::Source(source)) => sourced(&source), + Err(other) => panic!("{other:?}"), + } +} + +/// `value()` ends the same way both walks, and that way is `expected`. +#[track_caller] +fn agree(value: impl Fn() -> P, expected: Outcome) { + assert_eq!(encrypting(value()), expected, "encrypt_with_terms"); + assert_eq!(alone(value()), expected, "terms"); +} + +fn shape(reason: Unencryptable, at: &str) -> Outcome { + Shape(reason, at.to_owned()) +} + +/// A document whose `users` entry is a sequence of two values, the second +/// of them `bad`, beside a well-formed `id`, so every refusal below the +/// root has a path with a key and an index in it. +#[derive(Clone)] +struct Users

(P); + +impl Plaintext for Users

{ + fn visit(self, sink: S) -> Result { + let mut map = sink.map(Some(2))?; + 1u32.visit(map.entry("id")?)?; + let mut users = map.entry("users")?.seq(Some(2))?; + "ada".visit(users.element()?)?; + self.0.visit(users.element()?)?; + users.end()?; + map.end() + } +} + +/// A map that gives `k` twice. +#[derive(Clone)] +struct Dup; + +impl Plaintext for Dup { + fn visit(self, sink: S) -> Result { + let mut map = sink.map(None)?; + "one".visit(map.entry("k")?)?; + "two".visit(map.entry("k")?)?; + map.end() + } +} + +/// A container with one passthrough in it and nothing sealed. +#[derive(Clone)] +struct OnlyPass { + map: bool, +} + +impl Plaintext for OnlyPass { + fn visit(self, sink: S) -> Result { + if self.map { + let mut map = sink.map(Some(1))?; + map.entry("note")?.passthrough("public")?; + map.end() + } else { + let mut seq = sink.seq(Some(1))?; + seq.element()?.passthrough("public")?; + seq.end() + } + } +} + +/// A container whose source takes a child sink and drops it unused. +#[derive(Clone)] +struct DropsAChild { + map: bool, +} + +impl Plaintext for DropsAChild { + fn visit(self, sink: S) -> Result { + if self.map { + let mut map = sink.map(None)?; + let _ = map.entry("a")?; + "b".visit(map.entry("b")?)?; + map.end() + } else { + let mut seq = sink.seq(None)?; + "a".visit(seq.element()?)?; + let _ = seq.element()?; + seq.end() + } + } +} + +/// A passthrough that opens a container and never ends it. +#[derive(Clone)] +struct Unclosed; + +impl Plaintext for Unclosed { + fn visit(self, sink: S) -> Result { + let mut outer = sink.seq(None)?; + let mut inner = outer.element()?.seq(None)?; + 1u32.visit(inner.element()?)?; + drop(inner); + outer.end() + } +} + +/// `inner` as a passthrough, beside a sealed sibling. +#[derive(Clone)] +struct Passes

(P); + +impl Plaintext for Passes

{ + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(2))?; + "sealed".visit(seq.element()?)?; + seq.element()?.passthrough(self.0)?; + seq.end() + } +} + +/// A source whose getter throws. +#[derive(Clone)] +struct Throws; + +impl Plaintext for Throws { + fn visit(self, _: S) -> Result { + Err(::source( + SourceError::msg("getter threw"), + )) + } +} + +#[derive(Clone, Copy)] +enum Kind { + Seq, + Map, + Pass, + Scalar, +} + +/// `n` levels of one kind of nesting around an innermost value at depth +/// `n`: an empty sequence, or for `Scalar`, a string inside sequences. +#[derive(Clone, Copy)] +struct Nest(Kind, usize); + +impl Plaintext for Nest { + fn visit(self, sink: S) -> Result { + let Nest(kind, n) = self; + if n == 0 { + return match kind { + Kind::Scalar => "deep".visit(sink), + _ => sink.seq(Some(0))?.end(), + }; + } + let inner = Nest(kind, n - 1); + match kind { + Kind::Seq | Kind::Scalar => { + let mut seq = sink.seq(Some(1))?; + inner.visit(seq.element()?)?; + seq.end() + } + Kind::Map => { + let mut map = sink.map(Some(1))?; + inner.visit(map.entry("k")?)?; + map.end() + } + Kind::Pass => sink.passthrough(inner), + } + } +} + +#[test] +fn both_accept_a_well_formed_value_with_the_same_terms() { + let doc = || { + let mut doc = BTreeMap::new(); + doc.insert("ages", vec![Some(36u32), None]); + doc.insert("empty", vec![]); + doc + }; + agree(doc, Terms(vec![".ages[0]".into()])); + // A passthrough beside a sealed sibling, and nesting right up to the + // limit, are fine. + agree(|| Passes("public"), Terms(vec!["[0]".into()])); + agree( + || Nest(Kind::Scalar, MAX_DEPTH), + Terms(vec!["[0]".repeat(MAX_DEPTH)]), + ); + agree(|| Nest(Kind::Map, MAX_DEPTH), Terms(Vec::new())); +} + +#[test] +fn both_refuse_a_duplicate_key_at_the_repeated_entry() { + agree( + || Users(Dup), + shape(Unencryptable::DuplicateKey, ".users[1].k"), + ); + agree(|| Dup, shape(Unencryptable::DuplicateKey, ".k")); +} + +#[test] +fn both_refuse_a_container_with_nothing_sealed() { + agree( + || Users(OnlyPass { map: false }), + shape(Unencryptable::SequenceHasNothingSealed, ".users[1]"), + ); + agree( + || Users(OnlyPass { map: true }), + shape(Unencryptable::MapHasNothingSealed, ".users[1]"), + ); + agree( + || OnlyPass { map: false }, + shape(Unencryptable::SequenceHasNothingSealed, ""), + ); +} + +#[test] +fn both_refuse_a_dropped_child_sink() { + for map in [false, true] { + agree( + || Users(DropsAChild { map }), + shape(Unencryptable::DroppedChild, ".users[1]"), + ); + } +} + +#[test] +fn both_refuse_a_value_invalid_for_its_logical_type() { + let invalid = || Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); + agree( + || Users(invalid()), + shape(Unencryptable::InvalidValue, ".users[1]"), + ); + // `undefined` over an int has no term either, but is refused all the + // same: it cannot be encrypted. + agree( + || { + Raw( + Some(Logical::Undefined), + Physical::Int(vitaminc_aead::Int::I8(1)), + ) + }, + shape(Unencryptable::InvalidValue, ""), + ); +} + +#[test] +fn both_refuse_a_passthrough_that_does_not_frame_at_the_passthrough() { + agree( + || Passes(Unclosed), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + agree( + || Passes(Dup), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + // A source error inside the passthrough is the source's, both ways. + agree(|| Passes(Throws), Source("getter threw".into())); +} + +#[test] +fn both_refuse_a_value_nested_too_deep_at_the_same_node() { + for (kind, step) in [(Kind::Seq, "[0]"), (Kind::Map, ".k"), (Kind::Scalar, "[0]")] { + agree( + || Nest(kind, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, &step.repeat(MAX_DEPTH + 1)), + ); + } + // A passthrough too deep, or with too much inside it, is refused as a + // whole at its own place. + agree( + || Nest(Kind::Pass, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, ""), + ); + agree( + || Passes(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape(Unencryptable::TooDeep, "[1]"), + ); + agree( + || Users(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape( + Unencryptable::TooDeep, + &format!(".users[1]{}", "[0]".repeat(MAX_DEPTH - 1)), + ), + ); +} + +#[test] +fn both_refuse_what_terms_refuses_with_the_same_term_error() { + agree( + || Users("\u{378}"), + NoTerm(NormalizeError::UnassignedCodePoint, ".users[1]".into()), + ); + let newer = || { + Users(Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Bytes(b"x"), + )) + }; + agree(newer, NoTerm(NormalizeError::NoDomain, ".users[1]".into())); +} + +#[test] +fn both_pass_a_source_failure_through() { + agree(|| Users(Throws), Source("getter threw".into())); +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 09b6cd0d5..b6eaeea65 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -11,14 +11,14 @@ use vitaminc_aead::plaintext::kinds::chrono as conv; use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::{AsyncCipher, Cipher}; use vitaminc_aead::{ - Context, EncryptError, Float, Int, Logical, Physical, Plaintext, SeqSink, Sink, SourceError, - TimeUnit, + Context, EncryptError, Float, Int, Logical, Physical, Plaintext, Refusal, SeqSink, Sink, + SourceError, TimeUnit, Unencryptable, }; use vitaminc_aead_value::canonical::equality_input; use vitaminc_aead_value::Value; use vitaminc_normalize::{ domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, terms, - NormalizeError, Term, TermError, + NormalizeError, Path, Term, TermError, }; use vitaminc_protected::{Controlled, Protected}; @@ -569,17 +569,30 @@ fn terms_collects_every_term_without_encrypting() { #[test] fn terms_says_which_field_it_refused() { - let invalid = vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))); let mut doc = BTreeMap::new(); - doc.insert("x", invalid); + doc.insert("x", "\u{378}"); let err = terms(doc).expect_err("refused"); let term = err.term().expect("refused by Terms"); - assert_eq!(term.error(), NormalizeError::Invalid); + assert!(err.refusal().is_none()); + assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); assert_eq!(render(term.path()), ".x"); assert_eq!( err.to_string(), - "no equality term: the value is not valid for its logical type" + "no equality term: text contains a code point unassigned in Unicode 16" ); + + // A value invalid for its logical type cannot be encrypted, so it is + // refused for its shape, as encryption refuses it, before it is + // normalized. + let invalid = vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))); + let mut doc = BTreeMap::new(); + doc.insert("x", invalid); + let err = terms(doc).expect_err("refused"); + assert!(err.term().is_none()); + let refusal = err.refusal().expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(render(refusal.path()), ".x"); + assert_eq!(err.to_string(), "value is not valid for its logical type"); } #[test] @@ -686,8 +699,10 @@ fn a_refused_walk_never_reaches_the_cipher() { assert!(is_unassigned(&err), "{err:?}"); } -/// `Terms` is public and works without `EncryptSink` in front of it, and is -/// then the sink that refuses a value invalid for its logical type. +/// `Terms` is public and works without `EncryptSink` in front of it, and +/// then refuses a value invalid for its logical type itself, as +/// encryption would. The refusal arrives through its partner's error type +/// as a source error. #[test] fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { use vitaminc_aead::Raw; @@ -704,7 +719,15 @@ fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { let err = Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))) .visit(sink) .expect_err("refused"); - assert_eq!(term_error(&err), refused(NormalizeError::Invalid, "")); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let refusal = source + .inner() + .downcast_ref::() + .expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(refusal.path(), &Path::default()); assert!(out.is_empty()); } From 3df473747eadb323c0ae98423709bf5ff5595c47 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 15 Oct 2026 16:56:14 +1100 Subject: [PATCH 12/68] feat(aead-frame)!: rename aead-value to aead-frame and reduce it to the transport `vitaminc-aead-value` becomes `vitaminc-aead-frame` and holds only the transport (ADR 0001 section 8): the ciphertext codec, carrying a `CipherText` as bytes and back, and re-exports of the frame types that live in `vitaminc-aead` next to the leaf codec. The codec never writes the retired `CT_NONE` marker and refuses it when read, since a `None` is a null leaf now. `Value`, `ValueKind`, the `tagged` module, `encode_value`/`decode_value`, the `canonical` feature and the `FfiValue` alias are deleted: hosts implement `Plaintext` and `Sink` instead of converting to a parallel value type, and the equality encoders live in `vitaminc-normalize`. Two tests change hands rather than disappear. The normalize known-answer test compared every term with the `canonical` encoders; its vectors are now pinned as literals captured from those encoders, so a change to a frozen domain is a visible diff. The `Value`-path interop test is replaced by `legacy_fixture.rs`, which opens the Go binding's pre-ADR cross-language fixture through the ciphertext codec and the new decryption path and gets the frame it was sealed from, byte for byte, pinning the leaf format, the AAD derivations and the container rules against what shipped. The conformance test runs the shared corpus against the frame, from its own walk and from an independently built scalar. The Go guest depends on the renamed crate and its wasm is rebuilt; the Go tests that fail by design since cipherstash/vitaminc#413 are unchanged. Closes cipherstash/vitaminc#409. Closes cipherstash/vitaminc#348, superseded: `Value` no longer exists. Claude-Session: https://claude.ai/code/session_4caef6c7-64a1-4cf8-b491-2026ed98c2a9 --- packages/vitaminc-normalize/Cargo.toml | 9 +- .../vitaminc-normalize/tests/known_answers.rs | 1151 ++++++++++++++--- 2 files changed, 952 insertions(+), 208 deletions(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 67139352d..3ce6f7730 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -39,12 +39,9 @@ version = "0.1.24" version = "=1.1.0" [dev-dependencies] -# Path-only, so publish order does not matter: the known-answer tests check -# every term against today's `canonical` encoders, byte for byte, until -# those are removed. -vitaminc-aead-value = { path = "../aead-value", features = ["canonical", "chrono", "rust_decimal"] } -# `test-support` for `plaintext::render`, the path notation the tests -# assert against, so there is one copy of it. +# Path-only, so publish order does not matter. `test-support` for +# `plaintext::render`, the path notation the tests assert against, so there +# is one copy of it. vitaminc-aead = { path = "../aead", features = ["chrono", "rust_decimal", "uuid", "test-support"] } chrono = { version = "0.4.44", default-features = false, features = ["std"] } uuid = { version = "1", default-features = false } diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index b6eaeea65..52473a5e2 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -1,11 +1,15 @@ -//! Every term this crate produces, checked against today's `canonical` -//! encoders in `vitaminc-aead-value` byte for byte, and the terms sink -//! beside encryption. +//! Known answers for every term: the bytes and the domain label each scalar +//! normalizes to, pinned as literals. These are the terms the `canonical` +//! encoders of `vitaminc-aead-value` produced before ADR 0001, captured +//! from them when that crate held them, so an index written then still +//! matches one written now. A change here is a change to a frozen domain. +//! +//! The second half is the terms sink beside encryption. use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::collections::BTreeMap; -use chrono::{DateTime, NaiveDate, Utc}; +use chrono::NaiveDate; use futures_executor::block_on; use vitaminc_aead::plaintext::kinds::chrono as conv; use vitaminc_aead::plaintext::render; @@ -14,8 +18,6 @@ use vitaminc_aead::{ Context, EncryptError, Float, Int, Logical, Physical, Plaintext, Refusal, SeqSink, Sink, SourceError, TimeUnit, Unencryptable, }; -use vitaminc_aead_value::canonical::equality_input; -use vitaminc_aead_value::Value; use vitaminc_normalize::{ domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, terms, NormalizeError, Path, Term, TermError, @@ -26,137 +28,699 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } -/// The new term for a scalar must be the old term for the equivalent -/// `Value`, domain and bytes. #[track_caller] -fn same(ty: Option, v: Physical<'_>, value: Value) { - let new = normalize(ty, v).expect("normalizes"); - let old = equality_input(&value).expect("has a term"); - assert_eq!(new.domain, old.domain); - assert_eq!( - hex(new.bytes.risky_ref()), - hex(old.bytes.risky_ref()), - "{}", - old.domain - ); +fn pin(ty: Option, v: Physical<'_>, domain: &str, bytes: &str) { + let term = normalize(ty, v).expect("normalizes"); + assert_eq!(term.domain, domain, "{ty:?} {v:?}"); + assert_eq!(hex(term.bytes.risky_ref()), bytes, "{ty:?} {v:?}"); } #[test] -fn every_integer_width_matches_todays_term() { - for n in [0i128, 1, 5, -7, 127, -128, 255, 65_535, -32_768] { - if let Ok(v) = i8::try_from(n) { - same(None, Physical::Int(Int::I8(v)), Value::Int8(v)); - } - if let Ok(v) = u8::try_from(n) { - same(None, Physical::Int(Int::U8(v)), Value::UInt8(v)); - } - if let Ok(v) = i16::try_from(n) { - same(None, Physical::Int(Int::I16(v)), Value::Int16(v)); - } - if let Ok(v) = u16::try_from(n) { - same(None, Physical::Int(Int::U16(v)), Value::UInt16(v)); - } - if let Ok(v) = i32::try_from(n) { - same(None, Physical::Int(Int::I32(v)), Value::Int32(v)); - } - if let Ok(v) = u32::try_from(n) { - same(None, Physical::Int(Int::U32(v)), Value::UInt32(v)); - } - if let Ok(v) = i64::try_from(n) { - same(None, Physical::Int(Int::I64(v)), Value::Int64(v)); - } - if let Ok(v) = u64::try_from(n) { - same(None, Physical::Int(Int::U64(v)), Value::UInt64(v)); - } - same(None, Physical::Int(Int::I128(n)), Value::Int128(n)); - if let Ok(v) = u128::try_from(n) { - same(None, Physical::Int(Int::U128(v)), Value::UInt128(v)); - } - } - for v in [i128::MIN, i128::MAX] { - same(None, Physical::Int(Int::I128(v)), Value::Int128(v)); - } - for v in [i8::MIN, i8::MAX] { - same(None, Physical::Int(Int::I8(v)), Value::Int8(v)); - } - for v in [i16::MIN, i16::MAX] { - same(None, Physical::Int(Int::I16(v)), Value::Int16(v)); - } - for v in [i32::MIN, i32::MAX] { - same(None, Physical::Int(Int::I32(v)), Value::Int32(v)); - } - for v in [i64::MIN, i64::MAX] { - same(None, Physical::Int(Int::I64(v)), Value::Int64(v)); - } - same(None, Physical::Int(Int::U8(u8::MAX)), Value::UInt8(u8::MAX)); - same( +fn every_integer_width_normalizes_to_its_pinned_term() { + pin( + None, + Physical::Int(Int::I8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I8(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I16(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I32(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I64(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I128(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I8(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I16(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I32(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I64(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I128(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::U8(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I16(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I32(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I64(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-170141183460469231731687303715884105728)), + "vitaminc/prf/value/integer-orderable/v1", + "0080000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(170141183460469231731687303715884105727)), + "vitaminc/prf/value/integer-orderable/v1", + "017fffffffffffffffffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::I16(32767)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000007fff", + ); + pin( + None, + Physical::Int(Int::I32(-2147483648)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffff80000000", + ); + pin( None, - Physical::Int(Int::U16(u16::MAX)), - Value::UInt16(u16::MAX), + Physical::Int(Int::I32(2147483647)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000007fffffff", ); - same( + pin( None, - Physical::Int(Int::U32(u32::MAX)), - Value::UInt32(u32::MAX), + Physical::Int(Int::I64(-9223372036854775808)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffff8000000000000000", ); - same( + pin( None, - Physical::Int(Int::U64(u64::MAX)), - Value::UInt64(u64::MAX), + Physical::Int(Int::I64(9223372036854775807)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000007fffffffffffffff", ); - same( + pin( None, - Physical::Int(Int::U128(u128::MAX)), - Value::UInt128(u128::MAX), + Physical::Int(Int::U32(4294967295)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000ffffffff", + ); + pin( + None, + Physical::Int(Int::U64(18446744073709551615)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000ffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::U128(340282366920938463463374607431768211455)), + "vitaminc/prf/value/integer-orderable/v1", + "01ffffffffffffffffffffffffffffffff", ); } #[test] -fn both_float_widths_match_todays_term() { - for v in [ - 0.0f32, - -0.0, - 1.5, - -1.5, - 0.1, - f32::MAX, - f32::MIN_POSITIVE, - f32::INFINITY, - f32::NEG_INFINITY, - f32::NAN, - f32::from_bits(0xff80_0001), - f32::from_bits(1), - ] { - same(None, Physical::Float(Float::F32(v)), Value::Float32(v)); - } - for v in [ - 0.0f64, - -0.0, - 1.5, - 0.1, - f64::MAX, - f64::MIN_POSITIVE, - f64::INFINITY, - f64::NEG_INFINITY, - f64::NAN, - f64::from_bits(0xfff0_0000_0000_0001), - ] { - same(None, Physical::Float(Float::F64(v)), Value::Float64(v)); - } +fn both_float_widths_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x80000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xbfc00000))), + "vitaminc/prf/value/float-orderable/v1", + "4007ffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3dcccccd))), + "vitaminc/prf/value/float-orderable/v1", + "bfb99999a0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f7fffff))), + "vitaminc/prf/value/float-orderable/v1", + "c7efffffe0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x800000))), + "vitaminc/prf/value/float-orderable/v1", + "b810000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f800000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x1))), + "vitaminc/prf/value/float-orderable/v1", + "b6a0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x8000000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3fb999999999999a))), + "vitaminc/prf/value/float-orderable/v1", + "bfb999999999999a", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7fefffffffffffff))), + "vitaminc/prf/value/float-orderable/v1", + "ffefffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x10000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8010000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); } #[test] -fn text_and_bytes_match_todays_term() { - for s in ["", "Ada", "e\u{301}", "\u{344}", "a\0b", "日本語"] { - same(None, Physical::Text(s), Value::String(s.into())); - } - for b in [&[][..], &[0], &[1, 2, 3], &[0xff; 40]] { - same( - None, - Physical::Bytes(b), - Value::Bytes(Protected::new(b.to_vec())), - ); - } +fn text_and_bytes_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Text(""), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "", + ); + pin( + None, + Physical::Text("Ada"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "416461", + ); + pin( + None, + Physical::Text("e\u{301}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "c3a9", + ); + pin( + None, + Physical::Text("\u{344}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "cc88cc81", + ); + pin( + None, + Physical::Text("a\0b"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "610062", + ); + pin( + None, + Physical::Text("日本語"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "e697a5e69cace8aa9e", + ); + pin( + None, + Physical::Bytes(&[]), + "vitaminc/prf/value/bytes/v1", + "", + ); + pin( + None, + Physical::Bytes(&[0x00]), + "vitaminc/prf/value/bytes/v1", + "00", + ); + pin( + None, + Physical::Bytes(&[0x01, 0x02, 0x03]), + "vitaminc/prf/value/bytes/v1", + "010203", + ); + pin( + None, + Physical::Bytes(&[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + ]), + "vitaminc/prf/value/bytes/v1", + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); assert_eq!( normalize(None, Physical::Text("\u{378}")).expect_err("unassigned"), NormalizeError::UnassignedCodePoint @@ -164,95 +728,278 @@ fn text_and_bytes_match_todays_term() { } #[test] -fn dates_match_todays_term() { - for date in [ - NaiveDate::MIN, - NaiveDate::from_ymd_opt(1, 1, 1).expect("date"), - NaiveDate::from_ymd_opt(1969, 12, 31).expect("date"), - NaiveDate::from_ymd_opt(1970, 1, 1).expect("date"), - NaiveDate::from_ymd_opt(2024, 2, 29).expect("date"), - NaiveDate::MAX, - ] { - same( - Some(Logical::Date), - Physical::Int(Int::I32(conv::date_days(date))), - Value::Date(date), - ); - } +fn dates_normalize_to_their_pinned_terms() { + // NaiveDate::MIN, 0001-01-01, 1969-12-31, 1970-01-01, 2024-02-29, NaiveDate::MAX. + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-96465292)), + "vitaminc/prf/value/date-orderable/v1", + "7a4b07af", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-719162)), + "vitaminc/prf/value/date-orderable/v1", + "80000001", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-1)), + "vitaminc/prf/value/date-orderable/v1", + "800af93a", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/date-orderable/v1", + "800af93b", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(19782)), + "vitaminc/prf/value/date-orderable/v1", + "800b4681", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(95026236)), + "vitaminc/prf/value/date-orderable/v1", + "85b4f577", + ); } #[test] -fn timestamps_in_every_unit_match_todays_term() { - for (seconds, nanos) in [ - (0, 0), - (-1, 123_456_789), - (59, 999_999_999), - (1_700_000_000, 123_456_789), - (-62_000_000_000, 5_000), - ] { - let ts = DateTime::::from_timestamp(seconds, nanos).expect("timestamp"); - let nanos = conv::timestamp_nanos(ts).expect("not a leap second"); - same( - Some(Logical::Timestamp(TimeUnit::Nanos)), - Physical::Int(Int::I128(nanos)), - Value::Timestamp(ts), - ); - // Coarser units truncate the same way, so they match the old term - // of the instant at that precision. - for (unit, per) in [ - (TimeUnit::Micros, 1_000i128), - (TimeUnit::Millis, 1_000_000), - (TimeUnit::Seconds, 1_000_000_000), - ] { - let count = nanos.div_euclid(per); - let truncated = DateTime::::from_timestamp( - (count * per).div_euclid(1_000_000_000) as i64, - ((count * per).rem_euclid(1_000_000_000)) as u32, - ) - .expect("timestamp"); - same( - Some(Logical::Timestamp(unit)), - Physical::Int(Int::I64(i64::try_from(count).expect("fits"))), - Value::Timestamp(truncated), - ); - } - } - for ts in [DateTime::::MIN_UTC, DateTime::::MAX_UTC] { - let nanos = conv::timestamp_nanos(ts).expect("not a leap second"); - same( - Some(Logical::Timestamp(TimeUnit::Nanos)), - Physical::Int(Int::I128(nanos)), - Value::Timestamp(ts), - ); - } +fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { + // Five instants as nanoseconds, each then truncated to micros, millis + // and seconds (a coarser unit matches the term of the instant at that + // precision), then chrono's MIN_UTC and MAX_UTC. + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-876543211)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-876544)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-877)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff0754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-1)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(59999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(59999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(59999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b8b87c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(59)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(1700000000123456789)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(1700000000123456)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(1700000000123)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f1000754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(1700000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f10000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-61999999999999995000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-61999999999999995)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-62000000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-62000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-8334601228800000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffff86b730dee0000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(8210266876799999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800007779a0a6b7f3b9ac618", + ); } #[test] -fn decimals_match_todays_term() { - for s in [ - "0", - "0.0", - "-0.00", - "1", - "1.0", - "1.50", - "1.5", - "-1.5", - "0.001", - "123456789.987654321", - "79228162514264337593543950335", - "-79228162514264337593543950335", - "0.0000000000000000000000000001", - ] { - let d: rust_decimal::Decimal = s.parse().expect("decimal"); - same( - Some(Logical::Decimal { - scale: d.scale() as u8, - }), - Physical::Int(Int::I128(d.mantissa())), - Value::Decimal(d), - ); - } +fn decimals_normalize_to_their_pinned_terms() { + // 0 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 0.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // -0.00 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 1 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(10)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.50 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(150)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // 1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(15)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // -1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(-15)), + "vitaminc/prf/value/decimal-orderable/v1", + "3fffcf884a72a2c87c6e67ffffff", + ); + // 0.001 + pin( + Some(Logical::Decimal { scale: 3 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "bd00204fce5e3e25026110000000", + ); + // 123456789.987654321 + pin( + Some(Logical::Decimal { scale: 9 }), + Physical::Int(Int::I128(123456789987654321)), + "vitaminc/prf/value/decimal-orderable/v1", + "c80027e41b37904205f388c66800", + ); + // 79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "dc00ffffffffffffffffffffffff", + ); + // -79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(-79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "23ff000000000000000000000000", + ); + // 0.0000000000000000000000000001 + pin( + Some(Logical::Decimal { scale: 28 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "a400204fce5e3e25026110000000", + ); } #[test] From e8ad8c8a316ed1f1867c4bb829eb2839d9e38c3e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 13:35:18 +1100 Subject: [PATCH 13/68] feat(aead)!: name the source trait Encrypt so it pairs with Decrypt The Plaintext/Sink stack named the source trait for what a value is and the target trait for the operation. The pair now reads Encrypt and Decrypt: the traits say how a type is encrypted and decrypted, while the cipher does the cryptography. The same walk still feeds sinks that are not ciphers (equality terms, the transport frame); that is accepted. BREAKING CHANGE: `vitaminc_aead::Plaintext` and `#[derive(Plaintext)]` are renamed to `Encrypt` and `#[derive(Encrypt)]`. The `Encrypt` name now means the sink-based source trait (`fn visit(self, sink: S)`), not 0.5's visitor-based `Encrypt` that drove a cipher directly. The `vitaminc_aead::plaintext` module keeps its name. Refs cipherstash/vitaminc#449 --- packages/vitaminc-normalize/src/terms.rs | 12 +++++----- .../vitaminc-normalize/tests/agreement.rs | 24 +++++++++---------- .../vitaminc-normalize/tests/known_answers.rs | 8 +++---- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 3dca945be..52e0d28b4 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -14,7 +14,7 @@ use vitaminc_aead::plaintext::{Error, Path, Step}; use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; use vitaminc_aead::{ - EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, Plaintext, + Encrypt, EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, Refusal, SeqSink, Sink, SourceError, Tee, }; @@ -421,7 +421,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { /// No terms. Keeping the shape rules, the subtree is framed, as /// encryption frames it, and the frame dropped. - fn passthrough(self, value: P) -> Result<(), E> { + fn passthrough(self, value: P) -> Result<(), E> { if let Some(rules) = self.rules { let at = At { place: &self.at, @@ -616,7 +616,7 @@ impl MapSink for TermsMap<'_, E> { /// /// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse /// included, or the source's own failure. -pub fn terms(value: P) -> Result, TermsError> { +pub fn terms(value: P) -> Result, TermsError> { let mut out = Vec::new(); value.visit(Terms::new(&mut out))?; Ok(out) @@ -635,7 +635,7 @@ pub type WithTerms = (Node, Vec); /// arrives as [`EncryptError::Source`] carrying a [`TermError`]. pub fn plan_with_terms<'a, P, E, A>(value: P, aad: A) -> Result, EncryptError> where - P: Plaintext, + P: Encrypt, A: IntoAad<'a>, { let mut terms = Vec::new(); @@ -658,7 +658,7 @@ pub fn encrypt_with_terms<'a, P, C, A>( aad: A, ) -> Result, EncryptError> where - P: Plaintext, + P: Encrypt, C: Cipher, A: IntoAad<'a>, { @@ -681,7 +681,7 @@ pub fn encrypt_with_terms_async<'a, 'c, P, C, A>( aad: A, ) -> impl Future, EncryptError>> + Send + 'c where - P: Plaintext, + P: Encrypt, C: AsyncCipher, A: IntoAad<'a>, { diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs index 1fe77fd42..3327b8dc6 100644 --- a/packages/vitaminc-normalize/tests/agreement.rs +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -9,7 +9,7 @@ use vitaminc_aead::frame::MAX_DEPTH; use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::Cipher; use vitaminc_aead::{ - Context, EncryptError, Logical, MapSink, Physical, Plaintext, Raw, SeqSink, Sink, SourceError, + Context, Encrypt, EncryptError, Logical, MapSink, Physical, Raw, SeqSink, Sink, SourceError, Unencryptable, }; use vitaminc_normalize::{encrypt_with_terms, terms, NormalizeError, Term, TermError}; @@ -57,7 +57,7 @@ fn sourced(source: &SourceError) -> Outcome { } } -fn alone(value: P) -> Outcome { +fn alone(value: P) -> Outcome { match terms(value) { Ok(found) => paths(&found), Err(err) => match err.refusal() { @@ -67,7 +67,7 @@ fn alone(value: P) -> Outcome { } } -fn encrypting(value: P) -> Outcome { +fn encrypting(value: P) -> Outcome { match encrypt_with_terms(value, &Clear, "ctx") { Ok((_, found)) => paths(&found), Err(EncryptError::Shape(refusal)) => Shape(refusal.reason(), render(refusal.path())), @@ -78,7 +78,7 @@ fn encrypting(value: P) -> Outcome { /// `value()` ends the same way both walks, and that way is `expected`. #[track_caller] -fn agree(value: impl Fn() -> P, expected: Outcome) { +fn agree(value: impl Fn() -> P, expected: Outcome) { assert_eq!(encrypting(value()), expected, "encrypt_with_terms"); assert_eq!(alone(value()), expected, "terms"); } @@ -93,7 +93,7 @@ fn shape(reason: Unencryptable, at: &str) -> Outcome { #[derive(Clone)] struct Users

(P); -impl Plaintext for Users

{ +impl Encrypt for Users

{ fn visit(self, sink: S) -> Result { let mut map = sink.map(Some(2))?; 1u32.visit(map.entry("id")?)?; @@ -109,7 +109,7 @@ impl Plaintext for Users

{ #[derive(Clone)] struct Dup; -impl Plaintext for Dup { +impl Encrypt for Dup { fn visit(self, sink: S) -> Result { let mut map = sink.map(None)?; "one".visit(map.entry("k")?)?; @@ -124,7 +124,7 @@ struct OnlyPass { map: bool, } -impl Plaintext for OnlyPass { +impl Encrypt for OnlyPass { fn visit(self, sink: S) -> Result { if self.map { let mut map = sink.map(Some(1))?; @@ -144,7 +144,7 @@ struct DropsAChild { map: bool, } -impl Plaintext for DropsAChild { +impl Encrypt for DropsAChild { fn visit(self, sink: S) -> Result { if self.map { let mut map = sink.map(None)?; @@ -164,7 +164,7 @@ impl Plaintext for DropsAChild { #[derive(Clone)] struct Unclosed; -impl Plaintext for Unclosed { +impl Encrypt for Unclosed { fn visit(self, sink: S) -> Result { let mut outer = sink.seq(None)?; let mut inner = outer.element()?.seq(None)?; @@ -178,7 +178,7 @@ impl Plaintext for Unclosed { #[derive(Clone)] struct Passes

(P); -impl Plaintext for Passes

{ +impl Encrypt for Passes

{ fn visit(self, sink: S) -> Result { let mut seq = sink.seq(Some(2))?; "sealed".visit(seq.element()?)?; @@ -191,7 +191,7 @@ impl Plaintext for Passes

{ #[derive(Clone)] struct Throws; -impl Plaintext for Throws { +impl Encrypt for Throws { fn visit(self, _: S) -> Result { Err(::source( SourceError::msg("getter threw"), @@ -212,7 +212,7 @@ enum Kind { #[derive(Clone, Copy)] struct Nest(Kind, usize); -impl Plaintext for Nest { +impl Encrypt for Nest { fn visit(self, sink: S) -> Result { let Nest(kind, n) = self; if n == 0 { diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 52473a5e2..e05a4fa9e 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -15,7 +15,7 @@ use vitaminc_aead::plaintext::kinds::chrono as conv; use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::{AsyncCipher, Cipher}; use vitaminc_aead::{ - Context, EncryptError, Float, Int, Logical, Physical, Plaintext, Refusal, SeqSink, Sink, + Context, Encrypt, EncryptError, Float, Int, Logical, Physical, Refusal, SeqSink, Sink, SourceError, TimeUnit, Unencryptable, }; use vitaminc_normalize::{ @@ -1135,7 +1135,7 @@ fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { #[test] fn scalars_without_a_domain_and_passthroughs_get_no_term() { struct Doc; - impl Plaintext for Doc { + impl Encrypt for Doc { fn visit(self, sink: S) -> Result { use vitaminc_aead::MapSink; let mut map = sink.map(Some(5))?; @@ -1345,7 +1345,7 @@ fn terms_says_which_field_it_refused() { #[test] fn terms_passes_a_source_failure_through() { struct Throws; - impl Plaintext for Throws { + impl Encrypt for Throws { fn visit(self, sink: S) -> Result { let mut seq = sink.seq(None)?; 1u32.visit(seq.element()?)?; @@ -1391,7 +1391,7 @@ impl AsyncCipher for Remote { fn encrypt_with_terms_async_has_every_term_before_its_first_await() { static WALKED: AtomicBool = AtomicBool::new(false); struct Source; - impl Plaintext for Source { + impl Encrypt for Source { fn visit(self, sink: S) -> Result { let out = vec![1u32, 2].visit(sink); WALKED.store(true, Ordering::SeqCst); From 0d788d22edbc2d3bea9475f7fcad0d83234ddc71 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 13:42:12 +1100 Subject: [PATCH 14/68] refactor(normalize): own the decimal encoding instead of pinning orderable-bytes vitaminc-normalize was the one crate reaching into the ore.rs workspace, through a git pin on orderable-bytes for the 14-byte decimal encoding. ADR 0002 puts vitaminc at the bottom of the stack: ore-rs and cllw-ore will depend on vitaminc-ore, so nothing in vitaminc can depend on their workspace, and orderable-bytes is frozen for cipherstash-client's stored terms rather than being part of the target design. The encoding is ported as it is, constant-time arithmetic included, and the frozen 0.2.0 release becomes a dev-dependency so the tests check every value against it byte for byte; the pinned known answers for the decimal domain are unchanged. rust_decimal leaves the dependencies too, since the encoder works from the mantissa and scale a leaf carries. The workspace lockfile no longer has a git source. --- packages/vitaminc-normalize/Cargo.toml | 18 +- packages/vitaminc-normalize/README.md | 9 +- packages/vitaminc-normalize/src/decimal.rs | 353 ++++++++++++++++++ packages/vitaminc-normalize/src/lib.rs | 1 + packages/vitaminc-normalize/src/scalar.rs | 22 +- .../vitaminc-normalize/src/scalar_tests.rs | 1 + 6 files changed, 380 insertions(+), 24 deletions(-) create mode 100644 packages/vitaminc-normalize/src/decimal.rs diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 3ce6f7730..9517658f9 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -17,17 +17,6 @@ vitaminc-aead = { version = "0.5.1", path = "../aead" } vitaminc-protected = { version = "0.5.1", path = "../protected" } thiserror = { workspace = true } -# Only for the decimal term. Its encoding is constant-time arithmetic over -# the mantissa and scale that this crate does not want a second copy of, so -# the (scale, mantissa) pair is turned back into a `Decimal` to encode it. -rust_decimal = { version = "1.41", default-features = false, features = ["std"] } - -# Temporary review pin: ore.rs #97; replace with its 0.2 release before publishing. -[dependencies.orderable-bytes] -git = "https://github.com/cipherstash/ore.rs" -rev = "b3b7800b9c0cd8f7c53c5382f8e018a4e8bcbbd5" -features = ["decimal"] - # NFC is stable for assigned code points, and the Unicode 16 assignment check # refuses everything else, so newer normalization releases are safe. [dependencies.unicode-normalization] @@ -48,3 +37,10 @@ uuid = { version = "1", default-features = false } quickcheck = "1.1.0" quickcheck_macros = "1.2.0" futures-executor = "0.3.31" + +# The frozen release the decimal and float encodings were ported from, so +# the tests can check them byte for byte. It is not a dependency of the +# crate: ADR 0002 keeps `orderable-bytes` for cipherstash-client's stored +# terms and has vitaminc own its encodings. +orderable-bytes = { version = "=0.2.0", features = ["decimal"] } +rust_decimal = { version = "1.41", default-features = false, features = ["std"] } diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index f61458a03..6cbaa1ded 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -15,9 +15,10 @@ each scalar kind that can be indexed has a frozen **domain label** and a **normalization** to bytes, and everything else has no term. There is no cryptography here and no PAE: the crate's own dependencies -are the Unicode tables, `orderable-bytes` and `rust_decimal`. (It builds -on `vitaminc-aead` for the data model, which brings that crate's -dependencies with it.) A PRF crate such as +are the Unicode tables. (It builds on `vitaminc-aead` for the data model, +which brings that crate's dependencies with it.) The encodings are its +own, including the decimal one, which is ported from the frozen +`orderable-bytes` release and checked against it byte for byte. A PRF crate such as [`vitaminc-prf`](https://docs.rs/vitaminc-prf) takes a [`Normalized`] and derives under its domain. @@ -119,7 +120,7 @@ new label. | float, either width | `vitaminc/prf/value/float-orderable/v1` | the `f64` value's orderable bytes; `f32` widened exactly, zero signs and NaN payloads folded | | date | `vitaminc/prf/value/date-orderable/v1` | orderable days from 0001-01-01 | | timestamp, any unit | `vitaminc/prf/value/timestamp-micros-orderable/v1` | orderable seconds, then nanoseconds truncated to microseconds | -| decimal | `vitaminc/prf/value/decimal-orderable/v1` | `rust_decimal`'s orderable bytes, scale and signed zero normalized | +| decimal | `vitaminc/prf/value/decimal-orderable/v1` | the 14-byte orderable encoding of the value (see the `decimal` module), scale and signed zero normalized | | text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | | bytes | `vitaminc/prf/value/bytes/v1` | as they are | | uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs new file mode 100644 index 000000000..37e86a2f3 --- /dev/null +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -0,0 +1,353 @@ +//! The canonical, order-preserving 14-byte encoding of a decimal. +//! +//! Ported from `orderable-bytes` 0.2.0, whose encoding is frozen: an +//! equality index stores terms under [`domain::DECIMAL`](crate::domain::DECIMAL) +//! made from these bytes, so they can never change, and this crate owns +//! them rather than reaching into a crate that is kept only for +//! cipherstash-client's stored terms. The tests check every value against +//! that release byte for byte. +//! +//! The input is the mantissa and scale a [`Logical::Decimal`](vitaminc_aead::Logical::Decimal) +//! leaf carries: `value = mantissa × 10^(-scale)`, with the mantissa in +//! `(-2^96, 2^96)` and the scale at most 28, which is `rust_decimal`'s +//! range. The caller checks that; the encoder assumes it. +//! +//! ## Encoding (scientific form, base 10) +//! +//! Each non-zero value is re-expressed in signed scientific form: +//! +//! ```text +//! value = ±significand × 10^(leading_exp − digits(significand) + 1) +//! ``` +//! +//! where `significand` is the mantissa with trailing zeros stripped and +//! `leading_exp` is the decimal exponent of the leading significant digit, +//! in `[-28, 28]`. The 14 bytes are: +//! +//! ```text +//! byte 0 : [sign:1][biased_exp:7] +//! bytes 1..=13 : padded_significand (104 bits, big-endian) +//! ``` +//! +//! - The sign bit is `1` for positive and zero, `0` for negative, so every +//! negative sorts below zero and zero below every positive. +//! - The biased exponent is `leading_exp + 64`, in `[36, 92]` for a +//! non-zero value. Zero uses `0`, which no non-zero value reaches. +//! - The padded significand is the significand left-justified to 29 +//! digits by appending zeros, so values at one exponent compare +//! byte-wise however many digits they have. A 96-bit mantissa has at +//! most 29 digits, so the padded value fits 104 bits. +//! +//! For a negative, the exponent bits and the significand are inverted, so +//! a larger magnitude sorts lower. `1`, `1.0` and `1.00` reduce to the +//! same significand and exponent, and `+0` and `-0` to the same zero, so +//! equal values are equal bytes, as `rust_decimal` compares them. +//! +//! ## Constant time +//! +//! [`orderable`] is straight-line code with fixed-iteration loops and +//! branchless mask arithmetic: no branch on the sign, the zero-ness, the +//! digit count, the trailing-zero count or the scale, and no hardware +//! division, whose latency is data-dependent on some targets. + +/// Width of the padded-significand field in bytes (104 bits). +const MANTISSA_BYTES: usize = 13; + +/// Bias applied to `leading_exp` so it fits unsigned in the 7-bit field. +const EXP_BIAS: i32 = 64; + +/// The digit count the significand is padded to: the most a 96-bit +/// mantissa has. +const PADDED_DIGITS: u32 = 29; + +/// Top bit of byte 0: set for positives and zero, clear for negatives. +const SIGN_BIT: u8 = 0x80; + +/// The 7-bit exponent field of byte 0. +const EXP_MASK: u8 = 0x7F; + +/// The length of the encoding. +pub(crate) const ENCODED_LEN: usize = 14; + +/// `5⁻¹ mod 2¹²⁸`, so that dividing by ten (when exact) is a shift and a +/// multiply rather than a hardware division. +const INV5: u128 = 0xCCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCD; + +/// The largest `u128` divisible by 5. Multiplication by [`INV5`] is a +/// bijection that maps the multiples of 5 onto `[0, MAX_DIV_5]`, so +/// `x.wrapping_mul(INV5) <= MAX_DIV_5` exactly when `5 | x`. +const MAX_DIV_5: u128 = u128::MAX / 5; + +/// The encoding of `mantissa × 10^(-scale)`. Two equal values give the +/// same bytes, and the bytes sort as the values do. +pub(crate) fn orderable(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + let mut out = [0u8; ENCODED_LEN]; + + // The pipeline runs unconditionally: zero goes through the same steps + // as every other value (the helpers give it significand 0, digits 0, + // trailing 0) and its byte 0 is fixed up by a mask at the end, rather + // than a short-circuit that would tell zero apart by timing. + // + // Branchless absolute value: `(x ^ s) - s` where `s` is the sign bit + // arithmetically shifted across the word. + let sign_extension = mantissa >> 127; + let abs_mantissa = ((mantissa ^ sign_extension).wrapping_sub(sign_extension)) as u128; + let (significand, trailing) = strip_trailing_zeros(abs_mantissa); + let digits = digit_count(significand); + + // value = ±significand × 10^trailing × 10^(-scale); the leading digit's + // exponent is in [-28, 28] for a non-zero value. For zero the formula + // gives -1 - scale, in [-29, -1]: a valid-looking positive byte that is + // overwritten below. + let leading_exp = digits as i32 - 1 + trailing - scale as i32; + debug_assert!( + (-29..=28).contains(&leading_exp), + "leading_exp {leading_exp} out of bounds: mantissa or scale out of range" + ); + let biased_exp = (leading_exp + EXP_BIAS) as u8; + debug_assert!(biased_exp <= EXP_MASK, "biased_exp overflowed 7 bits"); + + // Pad the significand to 29 digits. Not `pow`, whose work depends on + // its exponent: a fixed loop that multiplies by ten under a mask that + // is set while padding remains. The product is computed every + // iteration and never overflows: while the mask is set the value is + // below 10^28, and once clear the unstored product is below 10^30. + let mut padded_mantissa = significand; + for i in 0..PADDED_DIGITS { + let do_step = ((digits + i) < PADDED_DIGITS) as u128; + let mask = 0u128.wrapping_sub(do_step); + let stepped = padded_mantissa.wrapping_mul(10); + padded_mantissa = (padded_mantissa & !mask) | (stepped & mask); + } + let mant_be = padded_mantissa.to_be_bytes(); + debug_assert!( + mant_be[..16 - MANTISSA_BYTES].iter().all(|&b| b == 0), + "padded mantissa overflowed 104 bits" + ); + let mant_field = &mant_be[16 - MANTISSA_BYTES..]; + + // One mask handles the sign: 0xFF for a negative, 0x00 otherwise. Byte + // 0 keeps the sign bit only when positive and XORs the exponent bits + // with the mask; each significand byte is XORed with it too. + let neg_mask = (mantissa >> 127) as u8; + out[0] = (SIGN_BIT & !neg_mask) | (biased_exp ^ (neg_mask & EXP_MASK)); + for (i, &b) in mant_field.iter().enumerate() { + out[1 + i] = b ^ neg_mask; + } + + // The zero plaintext, applied branchlessly: the tail is already all + // zero, so only byte 0 is replaced, by the bare sign bit, when the + // mantissa is zero. + let mant_nonzero_bit = ((abs_mantissa | abs_mantissa.wrapping_neg()) >> 127) as u8; + let zero_mask = 0u8.wrapping_sub(mant_nonzero_bit ^ 1); + out[0] = (out[0] & !zero_mask) | (SIGN_BIT & zero_mask); + out +} + +/// Divide by ten while the trailing digit is zero: the stripped value and +/// how many zeros were removed. Zero strips to `(0, 0)`. +/// +/// A fixed `PADDED_DIGITS` iterations, each selecting by mask. Division by +/// ten, valid only when exact, is a halving and a multiply by [`INV5`]; +/// divisibility by ten is divisibility by two (the low bit) and by five +/// (the [`MAX_DIV_5`] test), with the comparison done by `overflowing_sub` +/// so it lowers to a borrow rather than a branch. +fn strip_trailing_zeros(mut mantissa: u128) -> (u128, i32) { + let mut exponent: i32 = 0; + for _ in 0..PADDED_DIGITS { + let div = (mantissa >> 1).wrapping_mul(INV5); + let q5 = mantissa.wrapping_mul(INV5); + let (_, borrow) = MAX_DIV_5.overflowing_sub(q5); + let div_by_5 = (borrow as u128) ^ 1; + let div_by_2 = (mantissa & 1) ^ 1; + let div_by_10 = div_by_5 & div_by_2; + let mantissa_nz = (mantissa | mantissa.wrapping_neg()) >> 127; + let do_strip = mantissa_nz & div_by_10; + let mask = 0u128.wrapping_sub(do_strip); + mantissa = (div & mask) | (mantissa & !mask); + exponent = exponent.wrapping_add(do_strip as i32); + } + (mantissa, exponent) +} + +/// The number of decimal digits in `m`, `0` for zero: how many powers of +/// ten below `10^PADDED_DIGITS` it is at least, each test a borrow. +fn digit_count(m: u128) -> u32 { + let mut n: u32 = 0; + let mut pow: u128 = 1; + for _ in 0..PADDED_DIGITS { + let (_, borrow) = m.overflowing_sub(pow); + n = n.wrapping_add((borrow as u32) ^ 1); + pow = pow.wrapping_mul(10); + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use orderable_bytes::OrderableBytes; + use quickcheck_macros::quickcheck; + use rust_decimal::Decimal; + + const U96_MAX: u128 = (1u128 << 96) - 1; + + /// The frozen encoding this one was ported from. + fn oracle(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + Decimal::try_from_i128_with_scale(mantissa, scale) + .expect("in range") + .to_orderable_bytes() + } + + #[test] + fn zero_in_any_scale_or_sign_is_the_bare_sign_bit() { + let mut expected = [0u8; ENCODED_LEN]; + expected[0] = SIGN_BIT; + for scale in [0, 1, 3, 28] { + assert_eq!(orderable(0, scale), expected, "scale {scale}"); + } + assert_eq!(orderable(-0, 0), expected); + } + + #[test] + fn equivalent_forms_encode_identically() { + let one = orderable(1, 0); + assert_eq!(orderable(10, 1), one); + assert_eq!(orderable(100, 2), one); + assert_eq!(orderable(1_000, 3), one); + // 100 strips to significand 1 at exponent 2: the same significand + // bytes as 1, and an exponent two higher. + let hundred = orderable(100, 0); + assert_eq!(&one[1..], &hundred[1..]); + assert_eq!(one[0], SIGN_BIT | EXP_BIAS as u8); + assert_eq!(hundred[0], SIGN_BIT | (2 + EXP_BIAS) as u8); + } + + #[test] + fn worked_examples() { + assert_eq!(orderable(5, 1)[0], SIGN_BIT | (-1 + EXP_BIAS) as u8); + assert_eq!(orderable(10, 0)[0], SIGN_BIT | (1 + EXP_BIAS) as u8); + let (neg_one, pos_one) = (orderable(-1, 0), orderable(1, 0)); + assert_eq!(neg_one[0] & SIGN_BIT, 0); + assert_eq!(neg_one[0] & EXP_MASK, !(EXP_BIAS as u8) & EXP_MASK); + for i in 1..ENCODED_LEN { + assert_eq!(neg_one[i], !pos_one[i]); + } + } + + #[test] + fn byte_order_is_value_order() { + let values: [(i128, u32); 13] = [ + (-(U96_MAX as i128), 0), + (-1_000_000_000, 0), + (-15, 1), + (-105, 2), + (-1, 0), + (-1, 3), + (0, 0), + (1, 3), + (1, 0), + (105, 2), + (15, 1), + (1_000_000_000, 0), + (U96_MAX as i128, 0), + ]; + for pair in values.windows(2) { + let (a, b) = (pair[0], pair[1]); + assert!( + orderable(a.0, a.1) < orderable(b.0, b.1), + "{a:?} < {b:?} failed" + ); + } + } + + #[test] + fn strip_trailing_zeros_edge_cases() { + assert_eq!(strip_trailing_zeros(0), (0, 0)); + for d in 1u128..=9 { + assert_eq!(strip_trailing_zeros(d), (d, 0), "input {d}"); + } + for k in 0..=28u32 { + assert_eq!(strip_trailing_zeros(10u128.pow(k)), (1, k as i32), "10^{k}"); + } + assert_eq!(strip_trailing_zeros(U96_MAX), (U96_MAX, 0)); + assert_eq!(strip_trailing_zeros(12_340_000), (1234, 4)); + assert_eq!(strip_trailing_zeros(50), (5, 1)); + assert_eq!(strip_trailing_zeros(100_500), (1005, 2)); + } + + #[test] + fn digit_count_counts_digits() { + assert_eq!(digit_count(0), 0); + assert_eq!(digit_count(1), 1); + assert_eq!(digit_count(9), 1); + assert_eq!(digit_count(10), 2); + assert_eq!(digit_count(U96_MAX), 29); + } + + fn u96(m: u128) -> u128 { + m & U96_MAX + } + + #[quickcheck] + fn strip_reconstructs_and_is_canonical(m: u128) -> bool { + let m = u96(m); + let (s, c) = strip_trailing_zeros(m); + (0..=28).contains(&c) + && s.wrapping_mul(10u128.pow(c as u32)) == m + && (s == 0 || s % 10 != 0) + && (m == 0) == (s == 0) + && strip_trailing_zeros(s) == (s, 0) + } + + #[quickcheck] + fn strip_distributes_over_powers_of_ten(m: u128, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u96(m)); + let k = u32::from(k) % 29; + match s.checked_mul(10u128.pow(k)) { + Some(extended) if s != 0 && extended <= U96_MAX => { + strip_trailing_zeros(extended) == (s, k as i32) + } + _ => true, + } + } + + /// Every value encodes exactly as the frozen `orderable-bytes` release + /// encodes it. + #[quickcheck] + fn matches_orderable_bytes_byte_for_byte(m: u128, negative: bool, scale: u8) -> bool { + let magnitude = u96(m) as i128; + let mantissa = if negative { -magnitude } else { magnitude }; + let scale = u32::from(scale) % 29; + orderable(mantissa, scale) == oracle(mantissa, scale) + } + + #[test] + fn the_extremes_match_orderable_bytes() { + for (mantissa, scale) in [ + (U96_MAX as i128, 0), + (-(U96_MAX as i128), 0), + (U96_MAX as i128, 28), + (-(U96_MAX as i128), 28), + (1, 28), + (-1, 28), + (0, 28), + ] { + assert_eq!(orderable(mantissa, scale), oracle(mantissa, scale)); + } + } + + #[quickcheck] + fn byte_order_matches_decimal_order(a: u64, b: u64, sa: u8, sb: u8, neg: (bool, bool)) -> bool { + let (sa, sb) = (u32::from(sa) % 29, u32::from(sb) % 29); + let (a, b) = ( + if neg.0 { -(a as i128) } else { a as i128 }, + if neg.1 { -(b as i128) } else { b as i128 }, + ); + let (x, y) = ( + Decimal::try_from_i128_with_scale(a, sa).expect("in range"), + Decimal::try_from_i128_with_scale(b, sb).expect("in range"), + ); + orderable(a, sa).cmp(&orderable(b, sb)) == x.cmp(&y) + } +} diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index f98173601..b0a0005f7 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -1,6 +1,7 @@ #![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] #![doc = include_str!("../README.md")] +mod decimal; mod scalar; mod terms; diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 34d7e5c13..cbeabf344 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -19,10 +19,11 @@ //! logical type, [`Logical::Unknown`] included, has no term and is refused //! with [`NormalizeError::NoDomain`]. -use orderable_bytes::ToOrderableBytes; use unicode_general_category::{get_general_category, GeneralCategory}; use unicode_normalization::UnicodeNormalization; -use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; +use vitaminc_aead::plaintext::kinds::{ + timestamp_nanos, MAX_DATE_DAYS, MAX_DECIMAL_SCALE, MIN_DATE_DAYS, +}; use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; @@ -192,14 +193,17 @@ pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { Some(bytes) } -/// A decimal's mantissa and scale, as `rust_decimal`'s orderable bytes, -/// which normalize the scale and a signed zero. `None` if the mantissa does -/// not fit 96 bits or the scale is above 28. +/// A decimal's mantissa and scale, as the 14-byte orderable encoding of +/// its value, ported from the frozen `orderable-bytes` release and checked +/// against it, which normalizes the scale and a signed zero. `None` +/// if the mantissa does not fit 96 bits or the scale is above 28, the +/// range `rust_decimal` represents. pub fn decimal(scale: u8, mantissa: Int) -> Option>> { - let value = - rust_decimal::Decimal::try_from_i128_with_scale(mantissa.to_i128()?, u32::from(scale)) - .ok()?; - let bytes = Protected::new(value.to_orderable_bytes()); + let mantissa = mantissa.to_i128()?; + if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= 1 << 96 { + return None; + } + let bytes = Protected::new(crate::decimal::orderable(mantissa, u32::from(scale))); Some(Protected::new(bytes.risky_ref().to_vec())) } diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index 6bc89e369..7a1b46ba7 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -1,4 +1,5 @@ use super::*; +use orderable_bytes::OrderableBytes; use quickcheck_macros::quickcheck; use vitaminc_aead::UnknownLogical; From 0cc707759360da2623f965f592afb921d1fe5aef Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 18:06:42 +1100 Subject: [PATCH 15/68] fix(normalize): let the decimal encoder refuse a mantissa or scale out of range itself The encoder used to take a rust_decimal, which could not hold an out-of-range value. Since it takes a plain i128 and the range check lived only in its caller, a later caller that forgot the check would get bytes with the top bits dropped: the stored term of another value. orderable now checks the range, returns None outside it and takes the scale as the u8 the leaf carries. Tests pin the 96-bit boundary at both levels, sweep every digit count, scale and sign against orderable-bytes 0.2.0 (random mantissas almost all have 28 or 29 digits), and check strip_trailing_zeros from short significands so every case reaches the comparison. --- packages/vitaminc-normalize/src/decimal.rs | 144 +++++++++++------- .../vitaminc-normalize/src/scalar_tests.rs | 30 ++++ 2 files changed, 119 insertions(+), 55 deletions(-) diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs index 37e86a2f3..cef5b0c9f 100644 --- a/packages/vitaminc-normalize/src/decimal.rs +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -10,45 +10,21 @@ //! The input is the mantissa and scale a [`Logical::Decimal`](vitaminc_aead::Logical::Decimal) //! leaf carries: `value = mantissa × 10^(-scale)`, with the mantissa in //! `(-2^96, 2^96)` and the scale at most 28, which is `rust_decimal`'s -//! range. The caller checks that; the encoder assumes it. +//! range. The encoder refuses anything outside it: a larger mantissa would +//! lose its top bits and take the bytes of another value. //! -//! ## Encoding (scientific form, base 10) -//! -//! Each non-zero value is re-expressed in signed scientific form: -//! -//! ```text -//! value = ±significand × 10^(leading_exp − digits(significand) + 1) -//! ``` -//! -//! where `significand` is the mantissa with trailing zeros stripped and -//! `leading_exp` is the decimal exponent of the leading significant digit, -//! in `[-28, 28]`. The 14 bytes are: -//! -//! ```text -//! byte 0 : [sign:1][biased_exp:7] -//! bytes 1..=13 : padded_significand (104 bits, big-endian) -//! ``` -//! -//! - The sign bit is `1` for positive and zero, `0` for negative, so every -//! negative sorts below zero and zero below every positive. -//! - The biased exponent is `leading_exp + 64`, in `[36, 92]` for a -//! non-zero value. Zero uses `0`, which no non-zero value reaches. -//! - The padded significand is the significand left-justified to 29 -//! digits by appending zeros, so values at one exponent compare -//! byte-wise however many digits they have. A 96-bit mantissa has at -//! most 29 digits, so the padded value fits 104 bits. -//! -//! For a negative, the exponent bits and the significand are inverted, so -//! a larger magnitude sorts lower. `1`, `1.0` and `1.00` reduce to the -//! same significand and exponent, and `+0` and `-0` to the same zero, so -//! equal values are equal bytes, as `rust_decimal` compares them. +//! The layout is documented on [`decimal`](crate::decimal), the public +//! function that wraps this encoder, so it is in the published docs. //! //! ## Constant time //! -//! [`orderable`] is straight-line code with fixed-iteration loops and -//! branchless mask arithmetic: no branch on the sign, the zero-ness, the -//! digit count, the trailing-zero count or the scale, and no hardware -//! division, whose latency is data-dependent on some targets. +//! Past the range check, [`orderable`] is straight-line code with +//! fixed-iteration loops and branchless mask arithmetic: no branch on the +//! sign, the zero-ness, the digit count, the trailing-zero count or the +//! scale, and no hardware division, whose latency is data-dependent on +//! some targets. + +use vitaminc_aead::plaintext::kinds::MAX_DECIMAL_SCALE; /// Width of the padded-significand field in bytes (104 bits). const MANTISSA_BYTES: usize = 13; @@ -66,6 +42,9 @@ const SIGN_BIT: u8 = 0x80; /// The 7-bit exponent field of byte 0. const EXP_MASK: u8 = 0x7F; +/// One past the largest mantissa magnitude: a mantissa fits 96 bits. +const MANTISSA_LIMIT: u128 = 1 << 96; + /// The length of the encoding. pub(crate) const ENCODED_LEN: usize = 14; @@ -79,8 +58,13 @@ const INV5: u128 = 0xCCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCD; const MAX_DIV_5: u128 = u128::MAX / 5; /// The encoding of `mantissa × 10^(-scale)`. Two equal values give the -/// same bytes, and the bytes sort as the values do. -pub(crate) fn orderable(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { +/// same bytes, and the bytes sort as the values do. `None` if the mantissa +/// does not fit 96 bits or the scale is above 28. +pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option<[u8; ENCODED_LEN]> { + if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= MANTISSA_LIMIT { + return None; + } + let scale = u32::from(scale); let mut out = [0u8; ENCODED_LEN]; // The pipeline runs unconditionally: zero goes through the same steps @@ -141,7 +125,7 @@ pub(crate) fn orderable(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { let mant_nonzero_bit = ((abs_mantissa | abs_mantissa.wrapping_neg()) >> 127) as u8; let zero_mask = 0u8.wrapping_sub(mant_nonzero_bit ^ 1); out[0] = (out[0] & !zero_mask) | (SIGN_BIT & zero_mask); - out + Some(out) } /// Divide by ten while the trailing digit is zero: the stripped value and @@ -192,6 +176,12 @@ mod tests { const U96_MAX: u128 = (1u128 << 96) - 1; + /// The encoding of an in-range value. + fn encode(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + let scale = u8::try_from(scale).expect("scale fits u8"); + orderable(mantissa, scale).expect("in range") + } + /// The frozen encoding this one was ported from. fn oracle(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { Decimal::try_from_i128_with_scale(mantissa, scale) @@ -204,20 +194,20 @@ mod tests { let mut expected = [0u8; ENCODED_LEN]; expected[0] = SIGN_BIT; for scale in [0, 1, 3, 28] { - assert_eq!(orderable(0, scale), expected, "scale {scale}"); + assert_eq!(encode(0, scale), expected, "scale {scale}"); } - assert_eq!(orderable(-0, 0), expected); + assert_eq!(encode(-0, 0), expected); } #[test] fn equivalent_forms_encode_identically() { - let one = orderable(1, 0); - assert_eq!(orderable(10, 1), one); - assert_eq!(orderable(100, 2), one); - assert_eq!(orderable(1_000, 3), one); + let one = encode(1, 0); + assert_eq!(encode(10, 1), one); + assert_eq!(encode(100, 2), one); + assert_eq!(encode(1_000, 3), one); // 100 strips to significand 1 at exponent 2: the same significand // bytes as 1, and an exponent two higher. - let hundred = orderable(100, 0); + let hundred = encode(100, 0); assert_eq!(&one[1..], &hundred[1..]); assert_eq!(one[0], SIGN_BIT | EXP_BIAS as u8); assert_eq!(hundred[0], SIGN_BIT | (2 + EXP_BIAS) as u8); @@ -225,9 +215,9 @@ mod tests { #[test] fn worked_examples() { - assert_eq!(orderable(5, 1)[0], SIGN_BIT | (-1 + EXP_BIAS) as u8); - assert_eq!(orderable(10, 0)[0], SIGN_BIT | (1 + EXP_BIAS) as u8); - let (neg_one, pos_one) = (orderable(-1, 0), orderable(1, 0)); + assert_eq!(encode(5, 1)[0], SIGN_BIT | (-1 + EXP_BIAS) as u8); + assert_eq!(encode(10, 0)[0], SIGN_BIT | (1 + EXP_BIAS) as u8); + let (neg_one, pos_one) = (encode(-1, 0), encode(1, 0)); assert_eq!(neg_one[0] & SIGN_BIT, 0); assert_eq!(neg_one[0] & EXP_MASK, !(EXP_BIAS as u8) & EXP_MASK); for i in 1..ENCODED_LEN { @@ -254,10 +244,7 @@ mod tests { ]; for pair in values.windows(2) { let (a, b) = (pair[0], pair[1]); - assert!( - orderable(a.0, a.1) < orderable(b.0, b.1), - "{a:?} < {b:?} failed" - ); + assert!(encode(a.0, a.1) < encode(b.0, b.1), "{a:?} < {b:?} failed"); } } @@ -319,7 +306,7 @@ mod tests { let magnitude = u96(m) as i128; let mantissa = if negative { -magnitude } else { magnitude }; let scale = u32::from(scale) % 29; - orderable(mantissa, scale) == oracle(mantissa, scale) + encode(mantissa, scale) == oracle(mantissa, scale) } #[test] @@ -333,7 +320,7 @@ mod tests { (-1, 28), (0, 28), ] { - assert_eq!(orderable(mantissa, scale), oracle(mantissa, scale)); + assert_eq!(encode(mantissa, scale), oracle(mantissa, scale)); } } @@ -348,6 +335,53 @@ mod tests { Decimal::try_from_i128_with_scale(a, sa).expect("in range"), Decimal::try_from_i128_with_scale(b, sb).expect("in range"), ); - orderable(a, sa).cmp(&orderable(b, sb)) == x.cmp(&y) + encode(a, sa).cmp(&encode(b, sb)) == x.cmp(&y) + } + + /// The encoder checks its own range, so no caller can hand it a + /// mantissa whose top bits it would drop. + #[test] + fn a_mantissa_or_scale_out_of_range_is_refused() { + let limit = 1i128 << 96; + assert!(orderable(limit - 1, 0).is_some(), "the largest mantissa"); + assert!(orderable(1 - limit, 0).is_some(), "the smallest mantissa"); + assert!(orderable(limit, 0).is_none(), "one past the largest"); + assert!(orderable(-limit, 0).is_none(), "one past the smallest"); + assert!(orderable(1, 28).is_some(), "the largest scale"); + assert!(orderable(1, 29).is_none(), "one past the largest scale"); + } + + /// Every digit count, with and without trailing zeros, at every scale + /// and both signs. Random 96-bit mantissas almost all have 28 or 29 + /// digits, so the quickcheck oracle above rarely reaches short ones. + #[test] + fn every_digit_count_scale_and_sign_matches_orderable_bytes() { + for k in 0..=28u32 { + let p = 10i128.pow(k); + for magnitude in [p, p - 1, 7 * p, 123_456_789 * p] { + if magnitude as u128 > U96_MAX { + continue; + } + for scale in 0..=28u32 { + for mantissa in [magnitude, -magnitude] { + assert_eq!( + encode(mantissa, scale), + oracle(mantissa, scale), + "{mantissa} at scale {scale}" + ); + } + } + } + } + } + + /// Built from a short significand, so `s * 10^k` stays in range and + /// every case reaches the comparison. + #[quickcheck] + fn strip_distributes_over_powers_of_ten_for_short_significands(base: u32, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u128::from(base)); + // `s` has at most 10 digits, so `s * 10^k` stays below 10^28. + let k = u32::from(k) % (29 - digit_count(s)); + s == 0 || strip_trailing_zeros(s * 10u128.pow(k)) == (s, k as i32) } } diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index 7a1b46ba7..f537792d3 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -515,3 +515,33 @@ fn a_logical_term_is_the_same_at_every_integer_width(n: i16) -> bool { widths.iter().all(|&w| int(Some(ty), w) == first) }) } + +/// The 96-bit check is the only one between a direct caller and the +/// encoder, which would otherwise drop a mantissa's top bits and give it +/// the term of another value. +#[test] +fn decimal_refuses_a_mantissa_outside_96_bits_by_itself() { + let limit = 1i128 << 96; + assert!( + decimal(0, Int::I128(limit - 1)).is_some(), + "the largest mantissa" + ); + assert!( + decimal(0, Int::I128(1 - limit)).is_some(), + "the smallest mantissa" + ); + assert!( + decimal(0, Int::I128(limit)).is_none(), + "one past the largest" + ); + assert!( + decimal(0, Int::I128(-limit)).is_none(), + "one past the smallest" + ); + assert!( + decimal(5, Int::I128((1i128 << 104) + 10i128.pow(28))).is_none(), + "above 104 bits this would take the term of 10^23" + ); + assert!(decimal(0, Int::I128(i128::MAX)).is_none()); + assert!(decimal(0, Int::I128(i128::MIN)).is_none()); +} From b60a15e0b434bed7b266ed3cf1fdeaa1259853b5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 18:06:42 +1100 Subject: [PATCH 16/68] docs(normalize): publish the frozen decimal layout on the public decimal function The README pointed at the private decimal module, which docs.rs does not show, so an auditor or a port to another language could not find the 14-byte layout of stored terms. --- packages/vitaminc-normalize/README.md | 2 +- packages/vitaminc-normalize/src/scalar.rs | 41 ++++++++++++++++++----- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 6cbaa1ded..ebc257af4 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -120,7 +120,7 @@ new label. | float, either width | `vitaminc/prf/value/float-orderable/v1` | the `f64` value's orderable bytes; `f32` widened exactly, zero signs and NaN payloads folded | | date | `vitaminc/prf/value/date-orderable/v1` | orderable days from 0001-01-01 | | timestamp, any unit | `vitaminc/prf/value/timestamp-micros-orderable/v1` | orderable seconds, then nanoseconds truncated to microseconds | -| decimal | `vitaminc/prf/value/decimal-orderable/v1` | the 14-byte orderable encoding of the value (see the `decimal` module), scale and signed zero normalized | +| decimal | `vitaminc/prf/value/decimal-orderable/v1` | the 14-byte orderable encoding of the value (see [`decimal`]), scale and signed zero normalized | | text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | | bytes | `vitaminc/prf/value/bytes/v1` | as they are | | uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index cbeabf344..3c184c408 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -21,9 +21,7 @@ use unicode_general_category::{get_general_category, GeneralCategory}; use unicode_normalization::UnicodeNormalization; -use vitaminc_aead::plaintext::kinds::{ - timestamp_nanos, MAX_DATE_DAYS, MAX_DECIMAL_SCALE, MIN_DATE_DAYS, -}; +use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; @@ -198,12 +196,39 @@ pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { /// against it, which normalizes the scale and a signed zero. `None` /// if the mantissa does not fit 96 bits or the scale is above 28, the /// range `rust_decimal` represents. +/// +/// # Encoding (scientific form, base 10) +/// +/// Each non-zero value is re-expressed in signed scientific form: +/// +/// ```text +/// value = ±significand × 10^(leading_exp − digits(significand) + 1) +/// ``` +/// +/// where `significand` is the mantissa with trailing zeros stripped and +/// `leading_exp` is the decimal exponent of the leading significant digit, +/// in `[-28, 28]`. The 14 bytes are: +/// +/// ```text +/// byte 0 : [sign:1][biased_exp:7] +/// bytes 1..=13 : padded_significand (104 bits, big-endian) +/// ``` +/// +/// - The sign bit is `1` for positive and zero, `0` for negative, so every +/// negative sorts below zero and zero below every positive. +/// - The biased exponent is `leading_exp + 64`, in `[36, 92]` for a +/// non-zero value. Zero uses `0`, which no non-zero value reaches. +/// - The padded significand is the significand left-justified to 29 +/// digits by appending zeros, so values at one exponent compare +/// byte-wise however many digits they have. A 96-bit mantissa has at +/// most 29 digits, so the padded value fits 104 bits. +/// +/// For a negative, the exponent bits and the significand are inverted, so +/// a larger magnitude sorts lower. `1`, `1.0` and `1.00` reduce to the +/// same significand and exponent, and `+0` and `-0` to the same zero, so +/// equal values are equal bytes, as `rust_decimal` compares them. pub fn decimal(scale: u8, mantissa: Int) -> Option>> { - let mantissa = mantissa.to_i128()?; - if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= 1 << 96 { - return None; - } - let bytes = Protected::new(crate::decimal::orderable(mantissa, u32::from(scale))); + let bytes = Protected::new(crate::decimal::orderable(mantissa.to_i128()?, scale)?); Some(Protected::new(bytes.risky_ref().to_vec())) } From 13309d945b1ca6ec19cfa8641c67b0dbd224aa91 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 13:12:01 +1100 Subject: [PATCH 17/68] feat(normalize): let Terms collect terms under a normalizer of the caller's own Terms did the walking and the equality encoding in one place, so an index of another kind had to copy the path and shape-rule bookkeeping to collect its terms. The sink is now generic over a Normalize, which names its own term type, with Equality and Normalized as the defaults, so Terms::new and terms are unchanged and Terms::by and terms_by run the same walk under another encoder. An order index seals its term, so only a scheme can read it; that is why the term type is the normalizer's to choose. The order index in vitaminc-ore is the first such encoder. --- packages/vitaminc-normalize/src/lib.rs | 4 +- packages/vitaminc-normalize/src/terms.rs | 154 ++++++++++++++---- .../vitaminc-normalize/tests/normalizer.rs | 90 ++++++++++ 3 files changed, 213 insertions(+), 35 deletions(-) create mode 100644 packages/vitaminc-normalize/tests/normalizer.rs diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index b0a0005f7..221e660f1 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -10,7 +10,7 @@ pub use scalar::{ NormalizeError, Normalized, }; pub use terms::{ - encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, terms, Term, TermError, Terms, - TermsError, TermsMap, TermsSeq, WithTerms, + encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, terms, terms_by, Equality, + Normalize, Term, TermError, Terms, TermsError, TermsMap, TermsSeq, WithTerms, }; pub use vitaminc_aead::plaintext::{Path, Step}; diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 52e0d28b4..dbbf5db54 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -6,6 +6,12 @@ //! Terms)`, so a caller holds every term before any cipher is called and, //! with an async cipher, before the first await. [`terms`] runs it alone, //! and then it refuses what encryption would refuse. +//! +//! The sink does the walking and the [`Normalize`] it is given does the +//! encoding, so an index of another kind (an order index, whose bytes +//! differ from an equality term's) collects its terms through the same +//! sink with a normalizer of its own, through [`Terms::by`] and +//! [`terms_by`]. use core::future::Future; use core::marker::PhantomData; @@ -22,18 +28,58 @@ use vitaminc_protected::OpaqueDebug; use crate::scalar::{normalize, NormalizeError, Normalized}; -/// One equality term: where the scalar sits in the value, and its -/// normalized bytes with their domain. +/// How [`Terms`] turns one scalar into a term. +/// +/// [`Equality`] is the normalizer this crate is about. An index of another +/// kind supplies its own, with a term type of its own (an order index +/// seals its term so only a scheme can read it) and the same outcome +/// contract: a scalar whose kind has no term under this index (a null, a +/// boolean) returns [`NormalizeError::NoDomain`], and [`Terms`] skips it +/// when it has no logical type; a scalar whose logical type has no term +/// returns the same error and stops the walk; any other error stops the +/// walk too. +pub trait Normalize { + /// What one scalar becomes. + type Term; + + /// The term for one scalar, or why it has none. + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result; +} + +/// The equality normalizer: [`normalize`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Equality; + +impl Normalize for Equality { + type Term = Normalized; + + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result { + normalize(ty, value) + } +} + +/// One term: where the scalar sits in the value, and what the normalizer +/// made of it. An equality term, a [`Normalized`], unless [`Terms::by`] +/// was given another normalizer. /// /// `Debug` shows the path's shape, with its map keys masked as [`Step`] /// masks them, and masks the term. #[derive(OpaqueDebug)] -pub struct Term { +pub struct Term { /// The path from the root, empty for a scalar at the root. #[non_sensitive] pub path: Path, - /// The term itself: the frozen domain label and the normalized bytes. - pub normalized: Normalized, + /// The term itself: for equality, the frozen domain label and the + /// normalized bytes. + pub normalized: T, } /// A scalar [`Terms`] refused: why, and where in the value. @@ -113,7 +159,9 @@ impl Error for TermsError { /// /// Generic over its error type so it adopts its [`Tee`] partner's. To /// collect terms without encrypting, call [`terms`], whose error type is -/// [`TermsError`]. +/// [`TermsError`]. Generic too over the [`Normalize`] that encodes each +/// scalar, [`Equality`] unless [`by`](Terms::by) is given another, so an +/// index of another kind collects its terms through this same walk. /// /// A scalar whose *kind* has no domain (a null, a boolean, an `undefined`) /// produces no term and does not stop the walk: an absent or unindexable @@ -180,12 +228,13 @@ impl Error for TermsError { /// exactly takes, and a passthrough is framed. Beside `EncryptSink`, /// through [`plan_with_terms`], none of that is paid twice. A caller that /// tees `Terms::new` beside `EncryptSink` itself has both keep the rules. -pub struct Terms<'t, E> { - out: &'t mut Vec, +pub struct Terms<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, keys: Keys<'t>, at: Place<'t>, /// `None` beside an [`EncryptSink`] that keeps the rules itself. rules: Option>, + by: N, _error: PhantomData, } @@ -300,8 +349,29 @@ fn refused(refusal: Refusal) -> E { } impl<'t, E> Terms<'t, E> { - /// A sink that appends to `out` and keeps the shape rules itself. + /// A sink that appends equality terms to `out` and keeps the shape + /// rules itself. pub fn new(out: &'t mut Vec) -> Self { + Self::by(Equality, out) + } + + /// A sink that appends to `out` and leaves the shape rules to the + /// [`EncryptSink`] it is teed beside, which refuses first. + fn beside_encryption(out: &'t mut Vec) -> Self { + Self { + rules: None, + ..Self::new(out) + } + } +} + +impl<'t, E, N: Normalize> Terms<'t, E, N> { + /// A sink that appends the terms `by` makes to `out` and keeps the + /// shape rules itself. + /// + /// The normalizer is copied into every child sink, so it is `Copy`: a + /// normalizer carries no state. + pub fn by(by: N, out: &'t mut Vec>) -> Self { Self { out, keys: Keys::Own(String::new()), @@ -310,19 +380,11 @@ impl<'t, E> Terms<'t, E> { depth: 0, settle: None, }), + by, _error: PhantomData, } } - /// A sink that appends to `out` and leaves the shape rules to the - /// [`EncryptSink`] it is teed beside, which refuses first. - fn beside_encryption(out: &'t mut Vec) -> Self { - Self { - rules: None, - ..Self::new(out) - } - } - fn at(&self) -> At<'_> { At { place: &self.at, @@ -331,17 +393,17 @@ impl<'t, E> Terms<'t, E> { } } -impl<'t, E: Error> Sink for Terms<'t, E> { +impl<'t, E: Error, N: Normalize + Copy> Sink for Terms<'t, E, N> { type Ok = (); type Error = E; - type Seq = TermsSeq<'t, E>; - type Map = TermsMap<'t, E>; + type Seq = TermsSeq<'t, E, N>; + type Map = TermsMap<'t, E, N>; fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { if let Some(rules) = &self.rules { shape::scalar(rules.depth, ty, &value, &self.at()).map_err(refused)?; } - match normalize(ty, value) { + match self.by.normalize(ty, value) { Ok(normalized) => { let path = self.at.path(self.keys.as_str()); self.out.push(Term { path, normalized }); @@ -387,6 +449,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { at: self.at, next: 0, rules, + by: self.by, _error: PhantomData, }) } @@ -415,6 +478,7 @@ impl<'t, E: Error> Sink for Terms<'t, E> { keys: self.keys, at: self.at, rules, + by: self.by, _error: PhantomData, }) } @@ -438,8 +502,8 @@ impl<'t, E: Error> Sink for Terms<'t, E> { /// The sequence side of [`Terms`]: each element's path is the sequence's /// plus its index. -pub struct TermsSeq<'t, E> { - out: &'t mut Vec, +pub struct TermsSeq<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, keys: Keys<'t>, /// Where this sequence's own keys would begin: the length of `keys` /// at its start. @@ -447,18 +511,19 @@ pub struct TermsSeq<'t, E> { at: Place<'t>, next: usize, rules: Option>, + by: N, _error: PhantomData, } -impl SeqSink for TermsSeq<'_, E> { +impl SeqSink for TermsSeq<'_, E, N> { type Ok = (); type Error = E; type Element<'s> - = Terms<'s, E> + = Terms<'s, E, N> where Self: 's; - fn element(&mut self) -> Result, E> { + fn element(&mut self) -> Result, E> { let TermsSeq { out, keys, @@ -466,6 +531,7 @@ impl SeqSink for TermsSeq<'_, E> { at, next, rules, + by, .. } = self; let keys = keys.get(); @@ -488,6 +554,7 @@ impl SeqSink for TermsSeq<'_, E> { keys: Keys::Lent(keys), at: Place::Element { parent: at, index }, rules, + by: *by, _error: PhantomData, }) } @@ -507,32 +574,34 @@ impl SeqSink for TermsSeq<'_, E> { /// The map side of [`Terms`]: each entry's path is the map's plus its /// key. -pub struct TermsMap<'t, E> { - out: &'t mut Vec, +pub struct TermsMap<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, keys: Keys<'t>, /// Where this map's keys begin in `keys`: its length at the map's /// start. Each entry's key replaces the last one there. mark: usize, at: Place<'t>, rules: Option>, + by: N, _error: PhantomData, } -impl MapSink for TermsMap<'_, E> { +impl MapSink for TermsMap<'_, E, N> { type Ok = (); type Error = E; type Entry<'s> - = Terms<'s, E> + = Terms<'s, E, N> where Self: 's; - fn entry(&mut self, key: &str) -> Result, E> { + fn entry(&mut self, key: &str) -> Result, E> { let TermsMap { out, keys, mark, at, rules, + by, .. } = self; let keys = keys.get(); @@ -555,6 +624,7 @@ impl MapSink for TermsMap<'_, E> { keys: Keys::Lent(keys), at: Place::Entry { parent: at, key }, rules, + by: *by, _error: PhantomData, }) } @@ -617,8 +687,26 @@ impl MapSink for TermsMap<'_, E> { /// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse /// included, or the source's own failure. pub fn terms(value: P) -> Result, TermsError> { + terms_by(Equality, value) +} + +/// Every term of `value` under the normalizer `by`, in walk order, without +/// encrypting it: [`terms`] for an index of another kind. +/// +/// It refuses what [`terms`] refuses for the value's shape, and what `by` +/// refuses for a scalar, the way [`Terms`] describes. +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. +pub fn terms_by(by: N, value: P) -> Result>, TermsError> +where + N: Normalize + Copy, + P: Encrypt, +{ let mut out = Vec::new(); - value.visit(Terms::new(&mut out))?; + value.visit(Terms::by(by, &mut out))?; Ok(out) } diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs new file mode 100644 index 000000000..7cfdc98d0 --- /dev/null +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -0,0 +1,90 @@ +//! `Terms` under a normalizer of the caller's own: the walk is the same, +//! the terms are the normalizer's, and the skip-or-stop rule for a scalar +//! with no term is applied to what the normalizer returns. + +use std::collections::BTreeMap; + +use vitaminc_aead::plaintext::render; +use vitaminc_aead::{Encrypt, Int, Logical, Physical, Raw, Tee}; +use vitaminc_normalize::{ + terms, terms_by, Equality, Normalize, NormalizeError, Normalized, Terms, TermsError, +}; +use vitaminc_protected::{Controlled, Protected}; + +/// Every int is one byte under a domain of its own; nothing else has a +/// term. +#[derive(Clone, Copy)] +struct LowByte; + +impl Normalize for LowByte { + type Term = Normalized; + + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result { + match (ty, value) { + (None, Physical::Int(i)) => Ok(Normalized { + domain: "test/low-byte/v1", + bytes: Protected::new(vec![i.to_i128().unwrap_or(0) as u8]), + }), + _ => Err(NormalizeError::NoDomain), + } + } +} + +fn doc() -> BTreeMap<&'static str, Raw<'static>> { + let mut doc = BTreeMap::new(); + doc.insert("a", Raw(None, Physical::Int(Int::I32(0x1_02)))); + doc.insert("b", Raw(None, Physical::Text("text"))); + doc.insert("c", Raw(None, Physical::Null)); + doc +} + +#[test] +fn the_terms_are_the_normalizers_and_the_walk_is_the_same() { + let found = terms_by(LowByte, doc()).expect("terms"); + assert_eq!(found.len(), 1, "text and null have no term under LowByte"); + assert_eq!(render(&found[0].path), ".a"); + assert_eq!(found[0].normalized.domain, "test/low-byte/v1"); + assert_eq!(found[0].normalized.bytes.risky_ref(), &[0x02]); + // `terms` is `terms_by(Equality, ..)`. + let equality = terms(doc()).expect("terms"); + let by_name = terms_by(Equality, doc()).expect("terms"); + assert_eq!(equality.len(), 2); + assert_eq!(equality.len(), by_name.len()); + assert_eq!( + equality[1].normalized.bytes.risky_ref(), + by_name[1].normalized.bytes.risky_ref() + ); +} + +#[test] +fn a_logical_type_the_normalizer_refuses_stops_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("d", Raw(Some(Logical::Date), Physical::Int(Int::I32(1)))); + let err = terms_by(LowByte, doc).expect_err("refused"); + let term = err.term().expect("refused by the normalizer"); + assert_eq!(term.error(), NormalizeError::NoDomain); + assert_eq!(render(term.path()), ".d"); +} + +#[test] +fn two_normalizers_share_one_walk() { + let (mut equality, mut low) = (Vec::new(), Vec::new()); + doc() + .visit(Tee( + Terms::::new(&mut equality), + Terms::by(LowByte, &mut low), + )) + .expect("walk"); + assert_eq!( + equality.iter().map(|t| render(&t.path)).collect::>(), + [".a", ".b"] + ); + assert_eq!( + low.iter().map(|t| render(&t.path)).collect::>(), + [".a"] + ); +} From 5b17c7320c5e84597b0b67a78231a9c6eedda48e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 15:04:03 +1100 Subject: [PATCH 18/68] fix(normalize): name the index a refused term was for, not always equality With Terms generic over its normalizer, a scalar the order normalizer refused was still reported as having no equality term. Normalize now declares the index it serves (INDEX), TermError carries and displays it, and NoDomain's own message no longer names equality, since both normalizers report it. The equality messages are unchanged. --- packages/vitaminc-normalize/src/scalar.rs | 8 +++++--- packages/vitaminc-normalize/src/terms.rs | 18 +++++++++++++++++- .../vitaminc-normalize/tests/normalizer.rs | 8 ++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 3c184c408..b01ffe404 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -70,9 +70,11 @@ pub struct Normalized { #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum NormalizeError { - /// The scalar has no equality domain: a null, an `undefined`, a - /// boolean, or a logical type outside the opt-in table. - #[error("no equality domain for this kind of value")] + /// The scalar has no domain under the normalizer: a null, an + /// `undefined`, a boolean, or a logical type outside its opt-in table. + /// The message does not name an index, because the equality and order + /// normalizers both report it; whatever wraps it says which. + #[error("no domain for this kind of value")] NoDomain, /// The value is not valid for its logical type. #[error("the value is not valid for its logical type")] diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index dbbf5db54..285dbd48f 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -42,6 +42,11 @@ pub trait Normalize { /// What one scalar becomes. type Term; + /// The kind of index the terms are for, as a refusal names it: + /// `"equality"` for [`Equality`], so a scalar it cannot normalize is + /// reported as having no equality term. + const INDEX: &'static str; + /// The term for one scalar, or why it has none. fn normalize( &self, @@ -57,6 +62,8 @@ pub struct Equality; impl Normalize for Equality { type Term = Normalized; + const INDEX: &'static str = "equality"; + fn normalize( &self, ty: Option, @@ -93,8 +100,10 @@ pub struct Term { /// shape, with every key masked. Read the path with /// [`path`](TermError::path). #[derive(Clone, OpaqueDebug, thiserror::Error)] -#[error("no equality term: {error}")] +#[error("no {index} term: {error}")] pub struct TermError { + #[non_sensitive] + index: &'static str, #[non_sensitive] path: Path, #[non_sensitive] @@ -103,6 +112,12 @@ pub struct TermError { } impl TermError { + /// The kind of index the scalar has no term for: the normalizer's + /// [`Normalize::INDEX`]. + pub fn index(&self) -> &'static str { + self.index + } + /// Where the refused scalar sits, from the root. pub fn path(&self) -> &Path { &self.path @@ -413,6 +428,7 @@ impl<'t, E: Error, N: Normalize + Copy> Sink for Terms<'t, E, N> { Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => {} Err(error) => { return Err(E::source(SourceError::new(TermError { + index: N::INDEX, path: self.at.path(self.keys.as_str()), error, }))) diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs index 7cfdc98d0..6abdae340 100644 --- a/packages/vitaminc-normalize/tests/normalizer.rs +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -19,6 +19,8 @@ struct LowByte; impl Normalize for LowByte { type Term = Normalized; + const INDEX: &'static str = "low byte"; + fn normalize( &self, ty: Option, @@ -68,6 +70,12 @@ fn a_logical_type_the_normalizer_refuses_stops_the_walk() { let term = err.term().expect("refused by the normalizer"); assert_eq!(term.error(), NormalizeError::NoDomain); assert_eq!(render(term.path()), ".d"); + // The refusal names the normalizer's index, not equality. + assert_eq!(term.index(), "low byte"); + assert_eq!( + err.to_string(), + "no low byte term: no domain for this kind of value" + ); } #[test] From 00e07a5d77759d0816809aa3c55f844b4c98de22 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 16 Oct 2026 18:22:03 +1100 Subject: [PATCH 19/68] feat(normalize)!: require Copy of every normalizer, and name a value that does not fit an index's type Terms copies its normalizer into every child sink, but only the Sink impls asked for Copy, so a normalizer with state built a Terms and failed later at visit with a missing Sink impl. Copy is now a supertrait, checked where a normalizer is defined. NormalizeError gains Mismatch and OutOfRange for a normalizer that declares a type, as the order index's target does. The equality normalizer declares none and never reports them. --- packages/vitaminc-normalize/src/scalar.rs | 10 ++++++++++ packages/vitaminc-normalize/src/terms.rs | 18 +++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index b01ffe404..b170c225e 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -82,6 +82,16 @@ pub enum NormalizeError { /// Text contains a code point unassigned in Unicode 16. #[error("text contains a code point unassigned in Unicode 16")] UnassignedCodePoint, + /// The value is of another kind than the type the index declares: text + /// for an integer column, say. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value is not of the kind the index declares")] + Mismatch, + /// The value is of the kind the index declares but does not fit it: an + /// integer outside the declared width. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value does not fit the type the index declares")] + OutOfRange, } /// The opt-in table: the domain for a scalar, or `None` for one that has diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index 285dbd48f..a2dd6ae3d 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -38,7 +38,11 @@ use crate::scalar::{normalize, NormalizeError, Normalized}; /// when it has no logical type; a scalar whose logical type has no term /// returns the same error and stops the walk; any other error stops the /// walk too. -pub trait Normalize { +/// +/// A normalizer is copied into every child sink of a walk, so it is +/// `Copy`: it carries settings, such as the type an index declares, but +/// no state that a walk changes. +pub trait Normalize: Copy { /// What one scalar becomes. type Term; @@ -384,8 +388,8 @@ impl<'t, E, N: Normalize> Terms<'t, E, N> { /// A sink that appends the terms `by` makes to `out` and keeps the /// shape rules itself. /// - /// The normalizer is copied into every child sink, so it is `Copy`: a - /// normalizer carries no state. + /// The normalizer is copied into every child sink, which is why + /// [`Normalize`] requires `Copy`. pub fn by(by: N, out: &'t mut Vec>) -> Self { Self { out, @@ -408,7 +412,7 @@ impl<'t, E, N: Normalize> Terms<'t, E, N> { } } -impl<'t, E: Error, N: Normalize + Copy> Sink for Terms<'t, E, N> { +impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { type Ok = (); type Error = E; type Seq = TermsSeq<'t, E, N>; @@ -531,7 +535,7 @@ pub struct TermsSeq<'t, E, N: Normalize = Equality> { _error: PhantomData, } -impl SeqSink for TermsSeq<'_, E, N> { +impl SeqSink for TermsSeq<'_, E, N> { type Ok = (); type Error = E; type Element<'s> @@ -602,7 +606,7 @@ pub struct TermsMap<'t, E, N: Normalize = Equality> { _error: PhantomData, } -impl MapSink for TermsMap<'_, E, N> { +impl MapSink for TermsMap<'_, E, N> { type Ok = (); type Error = E; type Entry<'s> @@ -718,7 +722,7 @@ pub fn terms(value: P) -> Result, TermsError> { /// included, or the source's own failure. pub fn terms_by(by: N, value: P) -> Result>, TermsError> where - N: Normalize + Copy, + N: Normalize, P: Encrypt, { let mut out = Vec::new(); From 33e0d9d107c3a2cec5aa88a5fa84e1f06fa657fc Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:58:44 +0000 Subject: [PATCH 20/68] chore: release v0.6.0 --- packages/vitaminc-normalize/CHANGELOG.md | 32 ++++++++++++++++++++++++ packages/vitaminc-normalize/Cargo.toml | 4 +-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 packages/vitaminc-normalize/CHANGELOG.md diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md new file mode 100644 index 000000000..80956d1fa --- /dev/null +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -0,0 +1,32 @@ + +## [0.6.0] - 2026-10-17 + +### Breaking + +- **Breaking:** rename aead-value to aead-frame and reduce it to the transport +- **Breaking:** name the source trait Encrypt so it pairs with Decrypt +- **Breaking:** require Copy of every normalizer, and name a value that does not fit an index's type + +### Documentation + +- publish the frozen decimal layout on the public decimal function + +### Features + +- add vitaminc-normalize with the Terms sink +- say which field Terms refused +- collect equality terms without encrypting +- compare paths and steps by value +- let Terms collect terms under a normalizer of the caller's own + +### Fixes + +- redact Normalized and Term through OpaqueDebug +- put the NormalizeError on TermError's source chain +- refuse in terms what encryption refuses +- let the decimal encoder refuse a mantissa or scale out of range itself +- name the index a refused term was for, not always equality + +### Performance + +- build a term's path only when it is pushed diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 9517658f9..8120a5754 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.5.1", path = "../aead" } -vitaminc-protected = { version = "0.5.1", path = "../protected" } +vitaminc-aead = { version = "0.6.0", path = "../aead" } +vitaminc-protected = { version = "0.6.0", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From e44e65b153f00ea04aba2e619c24646f0300bb62 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 17 Oct 2026 13:22:13 +1100 Subject: [PATCH 21/68] docs(changelog): rewrite the 0.6.0 entries for someone upgrading from 0.5.1 The generated sections were the commit subjects. Each breaking entry now says what breaks and what to change, and the wire-format entries say plainly what still opens: 0.6.0 ciphertext does not open under 0.5.x, leaves from 0.5's Encrypt path do not open under 0.6.0, and leaves from the tagged 0.5 Value path (aead-value, aead-napi, Go) open through Aes256Cipher::opening_version_1. Equality terms stored with 0.5.1 still match. The cross-width integer and float change applies only to the new normalize terms, which did not exist in 0.5.1: the 0.5.1 prf encodings and domains are unchanged (encoding.rs, impls.rs and traits.rs do not differ from the tag), so nothing needs regenerating. prf says so in a compatibility note rather than a Breaking entry. Security fixes to code that shipped in 0.5.1 get their own section, most of them in aead-napi. Fixes to code new in this release, CI, lint, lockfile and review churn, and entries that surfaced only because a shared commit touched a crate are gone. normalize and ore are first releases and describe what they provide. The MSRV entry says which crates declared one before. --- packages/vitaminc-normalize/CHANGELOG.md | 34 +++++------------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 80956d1fa..0c36c404a 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,32 +1,12 @@ ## [0.6.0] - 2026-10-17 -### Breaking - -- **Breaking:** rename aead-value to aead-frame and reduce it to the transport -- **Breaking:** name the source trait Encrypt so it pairs with Decrypt -- **Breaking:** require Copy of every normalizer, and name a value that does not fit an index's type - -### Documentation - -- publish the frozen decimal layout on the public decimal function - ### Features -- add vitaminc-normalize with the Terms sink -- say which field Terms refused -- collect equality terms without encrypting -- compare paths and steps by value -- let Terms collect terms under a normalizer of the caller's own - -### Fixes - -- redact Normalized and Term through OpaqueDebug -- put the NormalizeError on TermError's source chain -- refuse in terms what encryption refuses -- let the decimal encoder refuse a mantissa or scale out of range itself -- name the index a refused term was for, not always equality - -### Performance - -- build a term's path only when it is pushed +- First release. `vitaminc-normalize` decides the equality terms for `vitaminc-aead`'s plaintext data model: for each scalar kind that can be indexed, a frozen domain label (the `domain` module) and an encoding to bytes. `normalize(logical, physical)` returns a `Normalized` (domain and protected bytes) that a PRF such as `vitaminc-prf` derives a term from. It has no cryptography. +- Equal values give equal terms whatever width or scale wrote them: every integer width shares one domain, `f32` widens exactly to `f64`, decimals normalize scale and signed zero, and timestamps in any unit truncate to microseconds. Values that only look alike do not match: a date, timestamp, decimal and uuid each have their own domain, separate from the physical value they are stored as. Text is Unicode 16 NFC with no case or accent folding. A code point unassigned in Unicode 16 is refused. A null, boolean or `undefined`, and any logical type the crate does not know, has no term (`NormalizeError::NoDomain`). The encodings are documented in the README and on `decimal`; changing one means a new domain label. +- `Terms` is a sink that collects one `Term` (path and normalized value) per indexable scalar. Run it beside encryption with `encrypt_with_terms` or `encrypt_with_terms_async`, which have every term before the first cipher call (and before the first await), with `plan_with_terms`, or alone with `terms`. `terms` refuses exactly what encryption refuses, at the same path: read a shape refusal with `TermsError::refusal`. +- A refused scalar is reported as a `TermError` holding the `NormalizeError`, the `Path` to the field and the index it was for. The error message names neither the field nor the value, because map keys can be user data; read the path with `TermError::path`. `Debug` masks the value of a `Normalized` or `Term`, and the map keys in a path. +- In a walk, a null, boolean or `undefined` produces no term and does not stop the walk. A logical type with no domain does stop it, so an index is never left silently incomplete. +- `Terms::by` and `terms_by` run the same walk under a normalizer of your own (the `Normalize` trait, which must be `Copy`). `vitaminc-ore`'s order index is the first. +- Text normalization is variable-time. The integer and float paths use no floating-point arithmetic. From 7aeefc48d610105b7ad198335800beb869c87010 Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:49:26 +0000 Subject: [PATCH 22/68] chore: release v0.6.1 --- packages/vitaminc-normalize/CHANGELOG.md | 2 ++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 0c36c404a..1e0e8c831 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,6 @@ +## [0.6.1] - 2026-10-18 + ## [0.6.0] - 2026-10-17 ### Features diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 8120a5754..bb18e913b 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.6.0", path = "../aead" } -vitaminc-protected = { version = "0.6.0", path = "../protected" } +vitaminc-aead = { version = "0.6.1", path = "../aead" } +vitaminc-protected = { version = "0.6.1", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 1c18d7a93b4fd88e9d42bd21c4e65220a037392f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 20 Oct 2026 16:53:25 +1100 Subject: [PATCH 23/68] fix(normalize): have each encoder own the wiped buffer it writes, so no caller can pass one that is not decimal::orderable used to write into an array its caller supplied, which put the duty to wipe it on the caller. It now makes and returns its own protected vector, as orderable_f64 does. fixed() writes straight into the returned vector instead of copying from a protected stack array. No encoded byte changes. The capacity test now covers every fixed-width encoder, and the touched tests compare protected bytes with zip_ref instead of risky_ref. --- packages/vitaminc-normalize/src/decimal.rs | 85 ++++++++++++++----- packages/vitaminc-normalize/src/scalar.rs | 61 ++++++++----- .../vitaminc-normalize/src/scalar_tests.rs | 75 ++++++++++++---- 3 files changed, 161 insertions(+), 60 deletions(-) diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs index cef5b0c9f..9a8316ca8 100644 --- a/packages/vitaminc-normalize/src/decimal.rs +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -25,6 +25,9 @@ //! some targets. use vitaminc_aead::plaintext::kinds::MAX_DECIMAL_SCALE; +use vitaminc_protected::Protected; + +use crate::scalar::fixed; /// Width of the padded-significand field in bytes (104 bits). const MANTISSA_BYTES: usize = 13; @@ -60,12 +63,17 @@ const MAX_DIV_5: u128 = u128::MAX / 5; /// The encoding of `mantissa × 10^(-scale)`. Two equal values give the /// same bytes, and the bytes sort as the values do. `None` if the mantissa /// does not fit 96 bits or the scale is above 28. -pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option<[u8; ENCODED_LEN]> { +/// +/// The encoder makes the protected vector it returns and writes every +/// byte of the encoding straight into it, so no caller has to supply a +/// buffer and remember to wipe it. The working values below are plain +/// integers, which the compiler keeps in registers or short-lived stack +/// slots that Rust cannot promise to wipe. +pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option>> { if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= MANTISSA_LIMIT { return None; } let scale = u32::from(scale); - let mut out = [0u8; ENCODED_LEN]; // The pipeline runs unconditionally: zero goes through the same steps // as every other value (the helpers give it significand 0, digits 0, @@ -103,29 +111,33 @@ pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option<[u8; ENCODED_LEN]> let stepped = padded_mantissa.wrapping_mul(10); padded_mantissa = (padded_mantissa & !mask) | (stepped & mask); } - let mant_be = padded_mantissa.to_be_bytes(); debug_assert!( - mant_be[..16 - MANTISSA_BYTES].iter().all(|&b| b == 0), + padded_mantissa >> (8 * MANTISSA_BYTES) == 0, "padded mantissa overflowed 104 bits" ); - let mant_field = &mant_be[16 - MANTISSA_BYTES..]; // One mask handles the sign: 0xFF for a negative, 0x00 otherwise. Byte // 0 keeps the sign bit only when positive and XORs the exponent bits // with the mask; each significand byte is XORed with it too. let neg_mask = (mantissa >> 127) as u8; - out[0] = (SIGN_BIT & !neg_mask) | (biased_exp ^ (neg_mask & EXP_MASK)); - for (i, &b) in mant_field.iter().enumerate() { - out[1 + i] = b ^ neg_mask; - } // The zero plaintext, applied branchlessly: the tail is already all // zero, so only byte 0 is replaced, by the bare sign bit, when the // mantissa is zero. let mant_nonzero_bit = ((abs_mantissa | abs_mantissa.wrapping_neg()) >> 127) as u8; let zero_mask = 0u8.wrapping_sub(mant_nonzero_bit ^ 1); - out[0] = (out[0] & !zero_mask) | (SIGN_BIT & zero_mask); - Some(out) + + // Every byte is written. The significand bytes are taken from the + // integer by shifting, most significant first, rather than through a + // plain array of its bytes. + Some(fixed::(|out| { + let head = (SIGN_BIT & !neg_mask) | (biased_exp ^ (neg_mask & EXP_MASK)); + out[0] = (head & !zero_mask) | (SIGN_BIT & zero_mask); + for i in 0..MANTISSA_BYTES { + let shift = 8 * (MANTISSA_BYTES - 1 - i); + out[1 + i] = (padded_mantissa >> shift) as u8 ^ neg_mask; + } + })) } /// Divide by ten while the trailing digit is zero: the stripped value and @@ -173,13 +185,23 @@ mod tests { use orderable_bytes::OrderableBytes; use quickcheck_macros::quickcheck; use rust_decimal::Decimal; + use vitaminc_protected::Controlled; const U96_MAX: u128 = (1u128 << 96) - 1; - /// The encoding of an in-range value. + /// The encoding of an in-range value, taken out of its protected + /// vector. The tests below index, sort and compare the bytes against + /// another crate's plain arrays, so this is the one place they leave + /// the wrapper. fn encode(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { let scale = u8::try_from(scale).expect("scale fits u8"); - orderable(mantissa, scale).expect("in range") + let bytes = orderable(mantissa, scale).expect("in range").risky_unwrap(); + <[u8; ENCODED_LEN]>::try_from(bytes).expect("the encoding is ENCODED_LEN bytes") + } + + /// Whether the encoder accepts `mantissa` and `scale`. + fn accepts(mantissa: i128, scale: u8) -> bool { + orderable(mantissa, scale).is_some() } /// The frozen encoding this one was ported from. @@ -340,15 +362,34 @@ mod tests { /// The encoder checks its own range, so no caller can hand it a /// mantissa whose top bits it would drop. - #[test] - fn a_mantissa_or_scale_out_of_range_is_refused() { - let limit = 1i128 << 96; - assert!(orderable(limit - 1, 0).is_some(), "the largest mantissa"); - assert!(orderable(1 - limit, 0).is_some(), "the smallest mantissa"); - assert!(orderable(limit, 0).is_none(), "one past the largest"); - assert!(orderable(-limit, 0).is_none(), "one past the smallest"); - assert!(orderable(1, 28).is_some(), "the largest scale"); - assert!(orderable(1, 29).is_none(), "one past the largest scale"); + mod given_a_mantissa_or_scale_at_the_edge_of_the_range { + use super::*; + + #[test] + fn returns_an_encoding() { + let limit = 1i128 << 96; + assert!(accepts(limit - 1, 0), "the largest mantissa is accepted"); + assert!(accepts(1 - limit, 0), "the smallest mantissa is accepted"); + assert!(accepts(1, 28), "the largest scale is accepted"); + } + } + + mod given_a_mantissa_or_scale_one_past_the_range { + use super::*; + + #[test] + fn returns_none() { + let limit = 1i128 << 96; + assert!( + !accepts(limit, 0), + "one past the largest mantissa is refused" + ); + assert!( + !accepts(-limit, 0), + "one past the smallest mantissa is refused" + ); + assert!(!accepts(1, 29), "one past the largest scale is refused"); + } } /// Every digit count, with and without trailing zeros, at every scale diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index b170c225e..ab021f1e7 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -154,11 +154,10 @@ pub fn normalize(ty: Option, v: Physical<'_>) -> Result Protected> { let (negative, word) = value.sign_and_word(); - let word = Protected::new(word.to_be_bytes()); - let mut bytes = Protected::new(Vec::with_capacity(17)); - bytes.risky_inner_mut().push(u8::from(!negative)); - bytes.risky_inner_mut().extend_from_slice(word.risky_ref()); - bytes + fixed::<17>(|b| { + b[0] = u8::from(!negative); + b[1..].copy_from_slice(&word.to_be_bytes()); + }) } /// A float of either width, as the orderable bytes of its `f64` value with @@ -168,7 +167,7 @@ pub fn float(value: Float) -> Protected> { Float::F32(f) => widen_f32(f), Float::F64(f) => f, }; - Protected::new(orderable_f64(canonical_f64(value)).to_vec()) + orderable_f64(canonical_f64(value)) } /// A date's day count since 1970-01-01, as the orderable bytes of its @@ -180,9 +179,9 @@ pub fn date(days: Int) -> Option>> { return None; } let from_ce = days.checked_add(EPOCH_DAYS_FROM_CE)?; - Some(Protected::new( - ((from_ce as u32) ^ (1u32 << 31)).to_be_bytes().to_vec(), - )) + Some(fixed(|b| { + *b = ((from_ce as u32) ^ (1u32 << 31)).to_be_bytes() + })) } /// A count of `unit`s since the Unix epoch, as orderable seconds then @@ -193,14 +192,10 @@ pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { let nanos = timestamp_nanos(unit, count)?; let seconds = i64::try_from(nanos.div_euclid(NANOS_PER_SECOND)).ok()?; let sub = (nanos.rem_euclid(NANOS_PER_SECOND) as u32) / 1_000 * 1_000; - let mut bytes = Protected::new(Vec::with_capacity(12)); - bytes - .risky_inner_mut() - .extend_from_slice(&((seconds as u64) ^ (1u64 << 63)).to_be_bytes()); - bytes - .risky_inner_mut() - .extend_from_slice(&sub.to_be_bytes()); - Some(bytes) + Some(fixed::<12>(|b| { + b[..8].copy_from_slice(&((seconds as u64) ^ (1u64 << 63)).to_be_bytes()); + b[8..].copy_from_slice(&sub.to_be_bytes()); + })) } /// A decimal's mantissa and scale, as the 14-byte orderable encoding of @@ -240,8 +235,7 @@ pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { /// same significand and exponent, and `+0` and `-0` to the same zero, so /// equal values are equal bytes, as `rust_decimal` compares them. pub fn decimal(scale: u8, mantissa: Int) -> Option>> { - let bytes = Protected::new(crate::decimal::orderable(mantissa.to_i128()?, scale)?); - Some(Protected::new(bytes.risky_ref().to_vec())) + crate::decimal::orderable(mantissa.to_i128()?, scale) } /// NFC in the pinned Unicode version, without case or accent folding. @@ -281,6 +275,28 @@ pub fn uuid(value: &[u8]) -> Option>> { (value.len() == 16).then(|| Protected::new(value.to_vec())) } +/// A fixed-width encoding, written by `write` straight into the protected +/// vector that is returned. +/// +/// The vector is allocated once at its final size, so it never +/// reallocates, and `write` fills it in place. No separate array of the +/// encoding is made and copied, so there is no extra copy to wipe. The +/// compiler can still make short-lived temporaries while `write` runs, for +/// example the array that `to_be_bytes` returns, and Rust cannot promise +/// to wipe those. +/// +/// `vitaminc-ore` has its own private copy of this function rather than +/// sharing this one, so it stays out of this crate's public API. +pub(crate) fn fixed(mut write: impl FnMut(&mut [u8; N])) -> Protected> { + let mut bytes = Protected::new(vec![0u8; N]); + bytes.update(|bytes| { + let array = <&mut [u8; N]>::try_from(bytes.as_mut_slice()) + .expect("the vector was made with exactly N bytes"); + write(array); + }); + bytes +} + /// Days from 0001-01-01 (day 1, chrono's "days from CE") to 1970-01-01. const EPOCH_DAYS_FROM_CE: i32 = 719_163; const NANOS_PER_SECOND: i128 = 1_000_000_000; @@ -288,10 +304,13 @@ const NANOS_PER_SECOND: i128 = 1_000_000_000; /// The orderable bytes of an `f64`: negatives flip every bit, positives /// the sign bit, so the bytes sort as the numbers do. Expects a value /// [`canonical_f64`] has already folded. -fn orderable_f64(value: f64) -> [u8; 8] { +/// +/// The bytes are written straight into the protected vector that is +/// returned (see [`fixed`]). +fn orderable_f64(value: f64) -> Protected> { let bits = value.to_bits(); let sign_extension = ((bits as i64) >> 63) as u64; - (bits ^ (sign_extension | (1u64 << 63))).to_be_bytes() + fixed(|b| *b = (bits ^ (sign_extension | (1u64 << 63))).to_be_bytes()) } /// `f64::from(f32)` in integer operations only. A hardware conversion can diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index f537792d3..c33b42759 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -427,10 +427,23 @@ fn f64_canonicalisation_is_idempotent(bits: u64) -> bool { canonical_f64(value).to_bits() == value.to_bits() } -#[quickcheck] -fn orderable_f64_agrees_with_orderable_bytes(bits: u64) -> bool { - let value = canonical_f64(f64::from_bits(bits)); - orderable_f64(value) == value.to_orderable_bytes() +/// Whether `bytes` holds exactly `expected`, compared inside the +/// protected value with `zip_ref` so the encoding never leaves its +/// wrapper. Only the answer, which is not secret, is taken out. +fn holds(bytes: &Protected>, expected: &[u8]) -> bool { + Protected::new(expected.to_vec()) + .zip_ref(bytes, |expected, bytes: &Vec| *bytes == expected) + .risky_unwrap() +} + +mod given_any_canonical_f64 { + use super::*; + + #[quickcheck] + fn returns_the_bytes_orderable_bytes_gives(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + holds(&orderable_f64(value), &value.to_orderable_bytes()) + } } #[test] @@ -448,19 +461,47 @@ fn timestamps_one_past_chronos_range_are_invalid() { } } -/// A `Vec` that grows frees its old buffer without wiping it, so the -/// encoders that append in steps must start at their final size. -#[test] -fn incremental_encoders_never_outgrow_their_buffer() { - for value in [Int::I8(-1), Int::U128(u128::MAX), Int::I128(i128::MIN)] { - let bytes = integer(value); - assert_eq!(bytes.risky_ref().len(), 17); - assert_eq!(bytes.risky_ref().capacity(), 17); - } - for count in [Int::I64(-1), Int::I64(1_700_000_000_123)] { - let bytes = timestamp(TimeUnit::Millis, count).expect("in range"); - assert_eq!(bytes.risky_ref().len(), 12); - assert_eq!(bytes.risky_ref().capacity(), 12); +/// Whether `bytes` holds exactly `len` bytes in a buffer with room for +/// exactly `len`, checked inside the protected value with `zip_ref` so +/// the encoding never leaves its wrapper. Only the answer, which is not +/// secret, is taken out. +fn fills_exactly(bytes: &Protected>, len: usize) -> bool { + Protected::new(len) + .zip_ref(bytes, |len, bytes: &Vec| { + bytes.len() == len && bytes.capacity() == len + }) + .risky_unwrap() +} + +/// A `Vec` that grows frees its old buffer without wiping it, and spare +/// capacity is a sign the buffer was not made at its final size. So every +/// fixed-width encoder must return a buffer whose length is its capacity. +mod given_a_fixed_width_encoder { + use super::*; + + #[test] + fn returns_a_buffer_with_no_spare_capacity() { + for value in [Int::I8(-1), Int::U128(u128::MAX), Int::I128(i128::MIN)] { + assert!(fills_exactly(&integer(value), 17), "integer {value:?}"); + } + for value in [Float::F32(-1.5), Float::F64(f64::MAX), Float::F64(f64::NAN)] { + assert!(fills_exactly(&float(value), 8), "float {value:?}"); + } + for days in [Int::I32(-1), Int::I32(0), Int::I32(20_000)] { + let bytes = date(days).expect("in range"); + assert!(fills_exactly(&bytes, 4), "date {days:?}"); + } + for count in [Int::I64(-1), Int::I64(1_700_000_000_123)] { + let bytes = timestamp(TimeUnit::Millis, count).expect("in range"); + assert!(fills_exactly(&bytes, 12), "timestamp {count:?}"); + } + for (scale, mantissa) in [(0, Int::I64(0)), (2, Int::I64(-12_345)), (28, Int::I128(1))] { + let bytes = decimal(scale, mantissa).expect("in range"); + assert!( + fills_exactly(&bytes, 14), + "decimal {mantissa:?} at scale {scale}" + ); + } } } From f3aa77ee05278c6d4ab8578d7ff8dd2ef400376a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 20 Oct 2026 16:53:58 +1100 Subject: [PATCH 24/68] docs(ore): say exactly when the normalization buffers move to the heap and what they leave behind Decomposition keeps a character's trailing marks in the same four-slot buffer as the next character, so four marks followed by any character already spill it, and a spilled buffer stays on the heap for the rest of the string. Documents ZA-0006 (tracked in cipherstash/vitaminc#488) in fold.rs and on vitaminc_normalize::text. --- packages/vitaminc-normalize/src/scalar.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index ab021f1e7..52ad59cca 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -241,10 +241,19 @@ pub fn decimal(scale: u8, mantissa: Int) -> Option>> { /// NFC in the pinned Unicode version, without case or accent folding. /// /// The result is written into one protected buffer sized exactly up front, -/// so it never reallocates and frees an unwiped partial copy. The -/// `unicode-normalization` iterator keeps its own small buffers of pending -/// code points (inline for four, spilling to the heap for longer combining -/// sequences); those are not wiped and are out of this crate's control. +/// so it never reallocates and frees an unwiped partial copy. +/// +/// The `unicode-normalization` iterators keep pending code points in small +/// buffers of their own, with room for four code points inside the +/// iterator. Decomposition holds the combining marks that follow a +/// character in the same buffer as the decomposed form of the next +/// character, so the buffer moves to the heap as soon as those together +/// pass four code points: four marks followed by any character is enough. +/// Composition moves its buffer to the heap when five marks after one +/// character do not combine with it. Once a buffer is on the heap it stays +/// there for the rest of the string, so every later character passes +/// through it, and it is freed without being wiped. That is out of this +/// crate's control (see #488). pub fn text(text: &str) -> Result>, NormalizeError> { if text .chars() From d64d9fa926fbfa701aa96a68c923b1fd3fc5594d Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:50:11 +0000 Subject: [PATCH 25/68] chore: release v0.7.0 --- packages/vitaminc-normalize/CHANGELOG.md | 10 ++++++++++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 1e0e8c831..479320ee6 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,14 @@ +## [0.7.0] - 2026-10-20 + +### Documentation + +- say exactly when the normalization buffers move to the heap and what they leave behind + +### Fixes + +- have each encoder own the wiped buffer it writes, so no caller can pass one that is not + ## [0.6.1] - 2026-10-18 ## [0.6.0] - 2026-10-17 diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index bb18e913b..8ef8cf72a 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.6.1", path = "../aead" } -vitaminc-protected = { version = "0.6.1", path = "../protected" } +vitaminc-aead = { version = "0.7.0", path = "../aead" } +vitaminc-protected = { version = "0.7.0", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 03bf2bb2a8277dec47a214c43fff23d5aa47ed0d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 20 Oct 2026 20:57:57 +1100 Subject: [PATCH 26/68] docs: rewrite the 0.7.0 changelogs for ore and normalize from the caller's side State that 0.6 order terms stay valid, what a scheme crate must change, and what a query and the text normalization buffers do not guarantee. --- packages/vitaminc-normalize/CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 479320ee6..35c601cdf 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,13 +1,13 @@ ## [0.7.0] - 2026-10-20 -### Documentation +### Fixes -- say exactly when the normalization buffers move to the heap and what they leave behind +- Each fixed-width and decimal encoder writes straight into the wiped buffer it returns, so no unwiped intermediate copy of an encoded value is made. The encoded bytes, and so stored terms, do not change. -### Fixes +### Not guaranteed -- have each encoder own the wiped buffer it writes, so no caller can pass one that is not +- `vitaminc_normalize::text` runs text through the `unicode-normalization` iterators, whose small internal buffers move to the heap as soon as a character's combining marks pass four code points (four marks followed by any character is enough), and are then freed without being wiped. This is outside this crate's control (#488). ## [0.6.1] - 2026-10-18 From c759234623a504d9ab4404fc10e698f1220494f5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 20 Oct 2026 22:15:19 +1100 Subject: [PATCH 27/68] feat(aead)!: seal a fixed-width None as a typed null as long as a Some, so ciphertext length no longer shows which values are absent AES-GCM keeps the plaintext's length, and a sealed null was one byte where the value it stood in for was up to 17. Anyone who could read the ciphertexts could list the absent rows of a column without a key. A `None` of an int, a float, a date, a timestamp or a decimal now seals as a typed null: the new `TYPED_NULL` tag (0x15), the header a value of the type starts with, then zero padding to the value's leaf length. It opens only as `None` of an `Option` of the same type, with its header and padding checked strictly so every absence has one encoding; any other target refuses it as the wrong kind. The one-byte null leaf still opens as before, and bool, text and bytes still seal it. Breaking: `Sink` has a new required method, `typed_null`, which every sink must handle (a forwarding sink must forward it, or the padding is lost). `Encrypt` and `Decrypt` gain a `FIXED` constant, derived for fieldless enums and newtypes. A reader built before this release refuses a typed null. Refs cipherstash/vitaminc#493 --- packages/vitaminc-normalize/src/terms.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index a2dd6ae3d..eb45fa063 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -20,8 +20,8 @@ use vitaminc_aead::plaintext::{Error, Path, Step}; use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; use vitaminc_aead::{ - Encrypt, EncryptError, EncryptSink, IntoAad, Logical, MapSink, Node, Pending, Physical, - Refusal, SeqSink, Sink, SourceError, Tee, + Encrypt, EncryptError, EncryptSink, FixedType, IntoAad, Logical, MapSink, Node, Pending, + Physical, Refusal, SeqSink, Sink, SourceError, Tee, }; use vitaminc_protected::OpaqueDebug; @@ -444,6 +444,13 @@ impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { Ok(()) } + /// Indexed as a plain null, which has no term: whether, and how, an + /// absent value gets one is still to be decided + /// (cipherstash/vitaminc#493). + fn typed_null(self, _: FixedType) -> Result<(), E> { + self.scalar(None, Physical::Null) + } + fn seq(self, _: Option) -> Result { let rules = match self.rules { Some(node) => { From cdadc8795542fbb4015010f94e77b60d96bc8491 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 21 Oct 2026 11:30:01 +1100 Subject: [PATCH 28/68] test(ore,normalize): pin that a fixed-width None gets no index term The ore scalar sink and the normalize Terms sink both forward a typed null to the plain-null path, which has no term. Nothing visited that forward: the existing tests only sent a plain null, so a change to the forward could give an absent field an order or equality term unnoticed. A test on each sink now walks a None of a fixed-width type and checks that only the present field has a term. --- .../vitaminc-normalize/tests/normalizer.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs index 6abdae340..774e83796 100644 --- a/packages/vitaminc-normalize/tests/normalizer.rs +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -96,3 +96,22 @@ fn two_normalizers_share_one_walk() { [".a"] ); } + +/// A fixed-width `None` reaches the sink as a typed null. It is indexed +/// as a plain null, which has no term, so an absent field gains no term +/// and does not stop the walk (cipherstash/vitaminc#493). +#[test] +fn a_fixed_width_none_has_no_term_and_does_not_stop_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("gone", None::); + doc.insert("here", Some(5i32)); + let found = terms(doc).expect("a typed null does not stop the walk"); + assert_eq!( + found.iter().map(|t| render(&t.path)).collect::>(), + [".here"], + "only the present field has a term" + ); + let by_name = terms_by(LowByte, BTreeMap::from([("gone", None::)])) + .expect("a typed null does not stop a normalizer of the caller's own"); + assert!(by_name.is_empty(), "a typed null has no term under LowByte"); +} From b83b2d2527727b7c6d3da9492ee65689379c4c0b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 21 Oct 2026 12:41:14 +1100 Subject: [PATCH 29/68] feat(normalize)!: give every null an equality term so the index no longer shows which values were absent A sealed None is now as long as a sealed Some, but the equality index still gave a null no term, so the term column held a SQL NULL exactly where the value was absent. Every null, typed or plain, now has a term under the new frozen domain vitaminc/prf/value/null/v1, whose bytes are the one byte 0x00. domain_of and normalize return it, the Terms sink pushes it at the null's path, and a typed null is the same term as a plain one. A boolean and an undefined still have no term. Also adds NormalizeError::Reserved, which the order index reports for the value it keeps for nulls. NormalizeError is #[non_exhaustive], so the new variant is not a breaking change. BREAKING CHANGE: a walk over a value with a null now returns one more equality term, and normalize(None, Physical::Null) now succeeds instead of returning NoDomain. A layer that must keep a SQL NULL for a column drops the term whose domain is domain::NULL. domain::ALL has nine labels. --- packages/vitaminc-normalize/README.md | 34 +++++++++-- packages/vitaminc-normalize/src/lib.rs | 4 +- packages/vitaminc-normalize/src/scalar.rs | 58 ++++++++++++++++--- .../vitaminc-normalize/src/scalar_tests.rs | 26 ++++++++- packages/vitaminc-normalize/src/terms.rs | 25 +++++--- .../vitaminc-normalize/tests/agreement.rs | 3 +- .../vitaminc-normalize/tests/allocations.rs | 3 +- .../vitaminc-normalize/tests/known_answers.rs | 44 +++++++++++--- .../vitaminc-normalize/tests/normalizer.rs | 35 ++++++++--- 9 files changed, 187 insertions(+), 45 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index ebc257af4..72293065d 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -43,10 +43,33 @@ assert_ne!(day.bytes.risky_ref(), a.bytes.risky_ref()); ``` Logical types opt in: a date, a timestamp, a decimal and a uuid have -domains of their own. A null, a boolean, an `undefined` and a logical type -this crate does not know have no term, and `normalize` refuses them with +domains of their own. A boolean, an `undefined` and a logical type this +crate does not know have no term, and `normalize` refuses them with [`NormalizeError::NoDomain`]. +Every null has a term, typed or plain, under a domain of its own. It is +the same term in every column, as SQL says `NULL IS NULL` whatever the +column; spaces that must not tie already differ in context. So the term +column of an index holds a term where the value was absent, as it does +where the value was there, and the nulls show only as one more group of +equal terms, which is what any repeated value shows. + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::Physical; +use vitaminc_protected::Controlled; + +let null = normalize(None, Physical::Null)?; +assert_eq!(null.domain, domain::NULL); +assert_eq!(null.bytes.risky_ref(), &[0x00]); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +A layer that must keep a SQL `NULL` in the term column for some column +drops the term it was handed. It knows the term is a null's because its +domain is [`domain::NULL`]. Producing the term is the default, because the +secure path should be the easy one, and dropping it is an explicit act. + ## A whole value, beside encryption [`Terms`] is a sink that collects one [`Term`] per indexable scalar, with @@ -97,9 +120,9 @@ container with children, even though it seals nothing itself. Read such a refusal with `TermsError::refusal`; encryption reports the same one as `EncryptError::Shape`. -A scalar whose kind has no domain (a null, a boolean, an `undefined`) -produces no term and does not stop the walk; passthrough subtrees get none -either. A scalar whose *logical type* has no domain, one from a newer +A null, typed or plain, has its term at its own path. A scalar whose kind +has no domain (a boolean, an `undefined`) produces no term and does not +stop the walk; passthrough subtrees get none either. A scalar whose *logical type* has no domain, one from a newer client, stops the walk: encrypting it with no term and no error would leave an index silently incomplete. That refusal and an unassigned code point arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as @@ -124,6 +147,7 @@ new label. | text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | | bytes | `vitaminc/prf/value/bytes/v1` | as they are | | uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | +| null, typed or plain | `vitaminc/prf/value/null/v1` | one byte, `0x00` | Text normalization is variable-time. The integer and float paths use no floating-point arithmetic. diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index 221e660f1..b6b1211ed 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -6,8 +6,8 @@ mod scalar; mod terms; pub use scalar::{ - bytes, date, decimal, domain, domain_of, float, integer, normalize, text, timestamp, uuid, - NormalizeError, Normalized, + bytes, date, decimal, domain, domain_of, float, integer, normalize, null, text, timestamp, + uuid, NormalizeError, Normalized, }; pub use terms::{ encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, terms, terms_by, Equality, diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 52ad59cca..327c7de25 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -18,6 +18,11 @@ //! a uuid never matches the same sixteen bytes written as bytes. Every other //! logical type, [`Logical::Unknown`] included, has no term and is refused //! with [`NormalizeError::NoDomain`]. +//! +//! A null has a term too, under [`domain::NULL`]: one byte, the same in +//! every column, so an absent value is indexed like any other value and +//! the nulls show only as one more tied group. A boolean and an +//! `undefined` have none. use unicode_general_category::{get_general_category, GeneralCategory}; use unicode_normalization::UnicodeNormalization; @@ -43,9 +48,14 @@ pub mod domain { pub const BYTES: &str = "vitaminc/prf/value/bytes/v1"; /// A uuid, over its sixteen raw bytes. pub const UUID: &str = "vitaminc/prf/value/uuid/v1"; + /// A null, typed or plain, whatever column it sits in: the one byte + /// `0x00`. + pub const NULL: &str = "vitaminc/prf/value/null/v1"; /// Every domain, for a test or an index layer that enumerates them. A /// slice, so a domain added later does not change its type. - pub const ALL: &[&str] = &[INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID]; + pub const ALL: &[&str] = &[ + INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID, NULL, + ]; } /// The normalized bytes for one equality term and the domain they belong @@ -70,10 +80,12 @@ pub struct Normalized { #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum NormalizeError { - /// The scalar has no domain under the normalizer: a null, an - /// `undefined`, a boolean, or a logical type outside its opt-in table. - /// The message does not name an index, because the equality and order - /// normalizers both report it; whatever wraps it says which. + /// The scalar has no domain under the normalizer: an `undefined`, a + /// boolean, a logical type outside its opt-in table, or a null under + /// an index that gives nulls no term (an order index whose space does + /// not place them). The message does not name an index, because the + /// equality and order normalizers both report it; whatever wraps it + /// says which. #[error("no domain for this kind of value")] NoDomain, /// The value is not valid for its logical type. @@ -92,6 +104,13 @@ pub enum NormalizeError { /// normalizer, which declares no type. #[error("the value does not fit the type the index declares")] OutOfRange, + /// The value is of the kind the index declares, and fits it, but its + /// code is the one the index keeps for nulls: the maximum of an + /// integer or uuid target in an order space that places nulls first + /// or last. Not reported by the equality normalizer, which gives a + /// null a domain of its own. + #[error("the value is reserved for nulls in the index it was given to")] + Reserved, } /// The opt-in table: the domain for a scalar, or `None` for one that has @@ -103,7 +122,8 @@ pub fn domain_of(ty: Option, v: &Physical<'_>) -> Option<&'static str> (None, Physical::Float(_)) => Some(domain::FLOAT), (None, Physical::Text(_)) => Some(domain::TEXT), (None, Physical::Bytes(_)) => Some(domain::BYTES), - (None, Physical::Null | Physical::Bool(_)) => None, + (None, Physical::Null) => Some(domain::NULL), + (None, Physical::Bool(_)) => None, (Some(Logical::Date), _) => Some(domain::DATE), (Some(Logical::Timestamp(_)), _) => Some(domain::TIMESTAMP), (Some(Logical::Decimal { .. }), _) => Some(domain::DECIMAL), @@ -124,7 +144,22 @@ pub fn domain_of(ty: Option, v: &Physical<'_>) -> Option<&'static str> /// (`f32` 1.5 matches, `f32` 0.1 does not match `f64` 0.1). Float zero /// signs and NaN payloads are folded. A timestamp in any unit is truncated /// to microseconds. A decimal's scale is normalized, so `1.50` and `1.5` -/// are one term, as are `-0.00` and `0`. +/// are one term, as are `-0.00` and `0`. A null is [`domain::NULL`] and +/// the one byte `0x00`; a typed null is walked as a plain one, so it is +/// the same term. +/// +/// # Examples +/// +/// ``` +/// use vitaminc_aead::Physical; +/// use vitaminc_normalize::{domain, normalize}; +/// use vitaminc_protected::Controlled; +/// +/// let null = normalize(None, Physical::Null)?; +/// assert_eq!(null.domain, domain::NULL); +/// assert_eq!(null.bytes.risky_ref(), &[0x00]); +/// # Ok::<(), vitaminc_normalize::NormalizeError>(()) +/// ``` pub fn normalize(ty: Option, v: Physical<'_>) -> Result { // A value that does not fit its logical type is refused as invalid // before the type is looked up, so `undefined` over an int is `Invalid` @@ -138,6 +173,7 @@ pub fn normalize(ty: Option, v: Physical<'_>) -> Result Some(float(f)), (None, Physical::Text(s)) => Some(text(s)?), (None, Physical::Bytes(b)) => Some(bytes(b)), + (None, Physical::Null) => Some(null()), (Some(Logical::Date), Physical::Int(days)) => date(days), (Some(Logical::Timestamp(unit)), Physical::Int(count)) => timestamp(unit, count), (Some(Logical::Decimal { scale }), Physical::Int(mantissa)) => decimal(scale, mantissa), @@ -279,6 +315,14 @@ pub fn bytes(value: &[u8]) -> Protected> { Protected::new(value.to_vec()) } +/// A null, typed or plain: the one byte `0x00`, under [`domain::NULL`]. +/// Every null is this one term, whatever column it sits in, as SQL says +/// `NULL IS NULL` whatever the column. Spaces that must not tie already +/// differ in context. +pub fn null() -> Protected> { + fixed::<1>(|b| *b = [0x00]) +} + /// A uuid's sixteen raw bytes. `None` for any other length. pub fn uuid(value: &[u8]) -> Option>> { (value.len() == 16).then(|| Protected::new(value.to_vec())) diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index c33b42759..c391639ad 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -105,13 +105,13 @@ fn the_opt_in_table_names_every_domain_and_nothing_else() { domain_of(Some(Logical::Uuid), &Physical::Bytes(&[0; 16])), Some(domain::UUID) ); - assert_eq!(domain_of(None, &Physical::Null), None); + assert_eq!(domain_of(None, &Physical::Null), Some(domain::NULL)); assert_eq!(domain_of(None, &Physical::Bool(true)), None); assert_eq!(domain_of(Some(Logical::Undefined), &Physical::Null), None); let unknown = Logical::from_wire(200, 1).expect("unknown"); assert!(matches!(unknown, Logical::Unknown(UnknownLogical { .. }))); assert_eq!(domain_of(Some(unknown), &one), None); - assert_eq!(domain::ALL.len(), 8); + assert_eq!(domain::ALL.len(), 9); for label in domain::ALL { assert!(label.starts_with("vitaminc/prf/value/"), "{label}"); } @@ -121,7 +121,6 @@ fn the_opt_in_table_names_every_domain_and_nothing_else() { fn a_scalar_with_no_domain_is_refused_with_no_domain() { let unknown = Logical::from_wire(200, 1).expect("unknown"); for (ty, v) in [ - (None, Physical::Null), (None, Physical::Bool(false)), (Some(Logical::Undefined), Physical::Null), (Some(unknown), Physical::Int(Int::I32(1))), @@ -136,6 +135,7 @@ fn a_scalar_with_no_domain_is_refused_with_no_domain() { NormalizeError::NoDomain, NormalizeError::Invalid, NormalizeError::UnassignedCodePoint, + NormalizeError::Reserved, ] { assert!(!error.to_string().is_empty()); } @@ -586,3 +586,23 @@ fn decimal_refuses_a_mantissa_outside_96_bits_by_itself() { assert!(decimal(0, Int::I128(i128::MAX)).is_none()); assert!(decimal(0, Int::I128(i128::MIN)).is_none()); } + +/// A null is one byte under a domain of its own, so every null in a space +/// ties with every other and with nothing else. +#[test] +fn a_null_is_one_zero_byte_under_the_null_domain() { + let null = normalize(None, Physical::Null).expect("a null has a term"); + assert_eq!(null.domain, domain::NULL, "a null has its own domain"); + assert_eq!( + null.domain, "vitaminc/prf/value/null/v1", + "the null label is frozen" + ); + assert_eq!(null.bytes.risky_ref(), &[0x00], "a null is the byte 0x00"); + assert_eq!(super::null().risky_ref(), &[0x00], "the encoder agrees"); + // No other domain's encoding is one zero byte under the null label. + let zero = normalize(None, Physical::Bytes(&[0x00])).expect("bytes"); + assert_ne!( + zero.domain, null.domain, + "the byte 0x00 as bytes is not a null" + ); +} diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index eb45fa063..aa528ec28 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -33,8 +33,9 @@ use crate::scalar::{normalize, NormalizeError, Normalized}; /// [`Equality`] is the normalizer this crate is about. An index of another /// kind supplies its own, with a term type of its own (an order index /// seals its term so only a scheme can read it) and the same outcome -/// contract: a scalar whose kind has no term under this index (a null, a -/// boolean) returns [`NormalizeError::NoDomain`], and [`Terms`] skips it +/// contract: a scalar whose kind has no term under this index (a boolean, +/// or a null where the index gives nulls none) returns +/// [`NormalizeError::NoDomain`], and [`Terms`] skips it /// when it has no logical type; a scalar whose logical type has no term /// returns the same error and stops the walk; any other error stops the /// walk too. @@ -182,10 +183,16 @@ impl Error for TermsError { /// scalar, [`Equality`] unless [`by`](Terms::by) is given another, so an /// index of another kind collects its terms through this same walk. /// -/// A scalar whose *kind* has no domain (a null, a boolean, an `undefined`) -/// produces no term and does not stop the walk: an absent or unindexable -/// value is an ordinary thing to find in a document, and the caller has -/// the paths to see which fields were indexed. A scalar whose *logical +/// Under [`Equality`] every null has a term, typed or plain, at the +/// null's path and under [`domain::NULL`](crate::domain::NULL), so an +/// absent value is indexed like any other. A layer that must keep a SQL +/// `NULL` for some column drops that term; its domain says it is a null. +/// +/// A scalar whose *kind* has no domain (a boolean, an `undefined`, or a +/// null under a normalizer that gives nulls none) produces no term and +/// does not stop the walk: an unindexable value is an ordinary thing to +/// find in a document, and the caller has the paths to see which fields +/// were indexed. A scalar whose *logical /// type* has no domain ([`Logical::Unknown`], or a type this crate does /// not know) stops the walk instead: it came from a newer client and /// means something, and encrypting it with no term and no error would @@ -444,9 +451,9 @@ impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { Ok(()) } - /// Indexed as a plain null, which has no term: whether, and how, an - /// absent value gets one is still to be decided - /// (cipherstash/vitaminc#493). + /// Indexed as a plain null. Equality has no width, so the type adds + /// nothing: under [`Equality`] a typed null is the same term as a + /// plain one. fn typed_null(self, _: FixedType) -> Result<(), E> { self.scalar(None, Physical::Null) } diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs index 3327b8dc6..5bd3c8ffe 100644 --- a/packages/vitaminc-normalize/tests/agreement.rs +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -246,7 +246,8 @@ fn both_accept_a_well_formed_value_with_the_same_terms() { doc.insert("empty", vec![]); doc }; - agree(doc, Terms(vec![".ages[0]".into()])); + // The absent age has a term as the present one does. + agree(doc, Terms(vec![".ages[0]".into(), ".ages[1]".into()])); // A passthrough beside a sealed sibling, and nesting right up to the // limit, are fine. agree(|| Passes("public"), Terms(vec!["[0]".into()])); diff --git a/packages/vitaminc-normalize/tests/allocations.rs b/packages/vitaminc-normalize/tests/allocations.rs index 7092d442d..3f90434cc 100644 --- a/packages/vitaminc-normalize/tests/allocations.rs +++ b/packages/vitaminc-normalize/tests/allocations.rs @@ -50,7 +50,8 @@ fn allocations(f: impl FnOnce()) -> usize { fn a_walk_with_no_terms_allocates_only_the_key_buffer() { let mut inner = BTreeMap::new(); for key in ["a", "b", "c", "d"] { - inner.insert(key, vec![None::, None]); + // Booleans, because they have no equality term. A null has one. + inner.insert(key, vec![true, false]); } let mut doc = BTreeMap::new(); for key in ["p", "q", "r"] { diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index e05a4fa9e..184898543 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -1002,6 +1002,23 @@ fn decimals_normalize_to_their_pinned_terms() { ); } +/// Every null is one term, typed or plain, under a domain of its own: +/// the walk sends a typed null as a plain one, so a `None` of any fixed +/// width is the same pinned byte. +#[test] +fn a_null_is_one_pinned_byte_under_the_null_domain_whatever_its_type() { + pin(None, Physical::Null, "vitaminc/prf/value/null/v1", "00"); + let typed = |found: Vec| { + assert_eq!(found.len(), 1, "a typed null has one term"); + assert_eq!(found[0].normalized.domain, domain::NULL); + hex(found[0].normalized.bytes.risky_ref()) + }; + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); +} + #[test] fn a_uuid_has_a_domain_of_its_own() { let id = uuid::Uuid::from_bytes([ @@ -1106,10 +1123,15 @@ fn refused(error: NormalizeError, at: &str) -> Option<(NormalizeError, String)> #[test] fn plan_with_terms_has_every_term_without_a_cipher() { let (planned, terms) = plan_with_terms::<_, Refused, _>(user(), "ctx").expect("plans"); - assert_eq!(paths(&terms), [".ages[0]", ".ages[2]"]); + assert_eq!(paths(&terms), [".ages[0]", ".ages[1]", ".ages[2]"]); assert_eq!(terms[0].normalized.domain, domain::INTEGER); assert_eq!( - terms[1].normalized.bytes.risky_ref(), + terms[1].normalized.domain, + domain::NULL, + "the absent age has the null term" + ); + assert_eq!( + terms[2].normalized.bytes.risky_ref(), normalize(None, Physical::Int(Int::U32(41))) .expect("int") .bytes @@ -1124,7 +1146,7 @@ fn plan_with_terms_has_every_term_without_a_cipher() { fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { let cipher = Counting::default(); let (sealed, terms) = encrypt_with_terms(user(), &cipher, "ctx").expect("encrypts"); - assert_eq!(terms.len(), 2); + assert_eq!(terms.len(), 3, "the absent age has a term too"); // Three elements, one empty marker. assert_eq!(cipher.calls.load(Ordering::SeqCst), 4); let back: BTreeMap>> = @@ -1133,7 +1155,7 @@ fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { } #[test] -fn scalars_without_a_domain_and_passthroughs_get_no_term() { +fn scalars_without_a_domain_and_passthroughs_get_no_term_and_a_null_gets_one() { struct Doc; impl Encrypt for Doc { fn visit(self, sink: S) -> Result { @@ -1149,8 +1171,13 @@ fn scalars_without_a_domain_and_passthroughs_get_no_term() { } } let (_, terms) = plan_with_terms::<_, Refused, _>(Doc, "ctx").expect("plans"); - assert_eq!(paths(&terms), [".name"]); - assert_eq!(terms[0].normalized.domain, domain::TEXT); + assert_eq!( + paths(&terms), + [".missing", ".name"], + "a boolean, a passthrough and an undefined get no term; a null does" + ); + assert_eq!(terms[0].normalized.domain, domain::NULL); + assert_eq!(terms[1].normalized.domain, domain::TEXT); } /// A logical type this build does not know means something to the client @@ -1305,8 +1332,9 @@ fn the_normalize_error_is_on_the_source_chain() { #[test] fn terms_collects_every_term_without_encrypting() { let found = terms(user()).expect("walks"); - assert_eq!(paths(&found), [".ages[0]", ".ages[2]"]); - assert_eq!(found[1].normalized.domain, domain::INTEGER); + assert_eq!(paths(&found), [".ages[0]", ".ages[1]", ".ages[2]"]); + assert_eq!(found[1].normalized.domain, domain::NULL); + assert_eq!(found[2].normalized.domain, domain::INTEGER); // A borrowed value walks too, and a scalar at the root has no steps. let name = String::from("Ada"); let found = terms(&name).expect("walks"); diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs index 774e83796..f76583f29 100644 --- a/packages/vitaminc-normalize/tests/normalizer.rs +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use vitaminc_aead::plaintext::render; use vitaminc_aead::{Encrypt, Int, Logical, Physical, Raw, Tee}; use vitaminc_normalize::{ - terms, terms_by, Equality, Normalize, NormalizeError, Normalized, Terms, TermsError, + domain, terms, terms_by, Equality, Normalize, NormalizeError, Normalized, Terms, TermsError, }; use vitaminc_protected::{Controlled, Protected}; @@ -54,7 +54,7 @@ fn the_terms_are_the_normalizers_and_the_walk_is_the_same() { // `terms` is `terms_by(Equality, ..)`. let equality = terms(doc()).expect("terms"); let by_name = terms_by(Equality, doc()).expect("terms"); - assert_eq!(equality.len(), 2); + assert_eq!(equality.len(), 3, "under equality the null has a term too"); assert_eq!(equality.len(), by_name.len()); assert_eq!( equality[1].normalized.bytes.risky_ref(), @@ -89,7 +89,7 @@ fn two_normalizers_share_one_walk() { .expect("walk"); assert_eq!( equality.iter().map(|t| render(&t.path)).collect::>(), - [".a", ".b"] + [".a", ".b", ".c"] ); assert_eq!( low.iter().map(|t| render(&t.path)).collect::>(), @@ -97,19 +97,36 @@ fn two_normalizers_share_one_walk() { ); } -/// A fixed-width `None` reaches the sink as a typed null. It is indexed -/// as a plain null, which has no term, so an absent field gains no term -/// and does not stop the walk (cipherstash/vitaminc#493). +/// A fixed-width `None` reaches the sink as a typed null. Under equality +/// it is indexed as a plain null, so the absent field has a term at its +/// own path under the null domain, and the walk carries on. A normalizer +/// that gives nulls no term still skips it. #[test] -fn a_fixed_width_none_has_no_term_and_does_not_stop_the_walk() { +fn a_fixed_width_none_has_the_null_term_at_its_path_and_does_not_stop_the_walk() { let mut doc = BTreeMap::new(); doc.insert("gone", None::); doc.insert("here", Some(5i32)); let found = terms(doc).expect("a typed null does not stop the walk"); assert_eq!( found.iter().map(|t| render(&t.path)).collect::>(), - [".here"], - "only the present field has a term" + [".gone", ".here"], + "the absent field has a term as the present one does" + ); + assert_eq!( + found[0].normalized.domain, + domain::NULL, + "the absent field's term is under the null domain" + ); + assert_eq!( + found[0].normalized.bytes.risky_ref(), + &[0x00], + "the absent field's term is the null's one byte" + ); + let plain = terms(BTreeMap::from([("gone", Raw(None, Physical::Null))])).expect("terms"); + assert_eq!( + plain[0].normalized.bytes.risky_ref(), + found[0].normalized.bytes.risky_ref(), + "a typed null and a plain null are one term" ); let by_name = terms_by(LowByte, BTreeMap::from([("gone", None::)])) .expect("a typed null does not stop a normalizer of the caller's own"); From 4f1ada898ebd11f4ee57a19af11751991352fb91 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 21 Oct 2026 12:59:07 +1100 Subject: [PATCH 30/68] docs(adr,normalize): match the ADR to the shipped API and say what Reserved means in plain words The ADR's walk example now shows that nulls on a runtime target returns a Result, and records that the policy is part of the space's type. The Reserved error says that the value's code is the space's null sentinel, rather than naming the index in a roundabout way. --- packages/vitaminc-normalize/src/scalar.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 327c7de25..cb5795fc3 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -109,7 +109,7 @@ pub enum NormalizeError { /// integer or uuid target in an order space that places nulls first /// or last. Not reported by the equality normalizer, which gives a /// null a domain of its own. - #[error("the value is reserved for nulls in the index it was given to")] + #[error("the value's code is the one this space keeps for the null")] Reserved, } From 5e3a9872f1c1c259d7fe37e817a4de14505cd1c8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 21 Oct 2026 13:21:58 +1100 Subject: [PATCH 31/68] docs(ore,adr): say how terms of the two policies meet, and why a scheme cannot answer for every target Both policies of a marker target are one Rust type, so a nulls-first and a nulls-last term can reach one comparison. `OrderTerm` and `OrderSpace::compare` said a marker term could not meet another target's, which is true, but not that the policy is stored and two policies compare as `None`. They say so now. `Supports` now says the crate answers for a target in a space that places nulls, and that this is why a scheme cannot implement `Supports` for every `T: Target` at once: such an impl conflicts with the crate's. The ADR still described `order` taking a policy, `OrderTarget::domain` gaining one, and `encrypt_query` accepting a null. It now names `order_with_nulls`, `domain_with_nulls`, `encrypt_query_checked` and `null_query`, which are what shipped. A few rustdoc and README lines that ran past the wrap width are rewrapped. --- packages/vitaminc-normalize/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 72293065d..53e124700 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -122,9 +122,10 @@ refusal with `TermsError::refusal`; encryption reports the same one as A null, typed or plain, has its term at its own path. A scalar whose kind has no domain (a boolean, an `undefined`) produces no term and does not -stop the walk; passthrough subtrees get none either. A scalar whose *logical type* has no domain, one from a newer -client, stops the walk: encrypting it with no term and no error would leave -an index silently incomplete. That refusal and an unassigned code point +stop the walk; passthrough subtrees get none either. A scalar whose +*logical type* has no domain, one from a newer client, stops the walk: +encrypting it with no term and no error would leave an index silently +incomplete. That refusal and an unassigned code point arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as `TermsError::term`), which holds the `NormalizeError` and the path to the refused field. Downcast to `TermError`; the `NormalizeError` is also its From 0f39eef00714c5623834bee9de22c966d9500ed0 Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 05:52:04 +0000 Subject: [PATCH 32/68] chore: release v0.8.0 --- packages/vitaminc-normalize/CHANGELOG.md | 12 ++++++++++++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 35c601cdf..e9cff989f 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,16 @@ +## [0.8.0] - 2026-10-21 + +### Breaking + +- **Breaking:** seal a fixed-width None as a typed null as long as a Some, so ciphertext length no longer shows which values are absent +- **Breaking:** give every null an equality term so the index no longer shows which values were absent + +### Documentation + +- match the ADR to the shipped API and say what Reserved means in plain words +- say how terms of the two policies meet, and why a scheme cannot answer for every target + ## [0.7.0] - 2026-10-20 ### Fixes diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 8ef8cf72a..db1ab708b 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.7.0", path = "../aead" } -vitaminc-protected = { version = "0.7.0", path = "../protected" } +vitaminc-aead = { version = "0.8.0", path = "../aead" } +vitaminc-protected = { version = "0.8.0", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 123399ccf99cac1d383e9cd3ee52bea1a120430f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 21 Oct 2026 16:59:18 +1100 Subject: [PATCH 33/68] docs: rewrite the 0.8.0 changelog entries from the caller's side The generated entries were the commit subjects. Each crate's section now says what changed for its callers, what still decrypts or compares across the upgrade, and what a null now reveals; entries about other crates are dropped, and hmac, whose only change was a test, has an empty section. --- packages/vitaminc-normalize/CHANGELOG.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index e9cff989f..c9eb17739 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,15 +1,19 @@ ## [0.8.0] - 2026-10-21 +Existing equality terms do not change: every domain label and encoding of 0.7 stays as it is, and the null term is a new label beside them. An index built by 0.7 holds a SQL `NULL` where a value was absent; 0.8 writes a term there instead. Both read correctly, but the rows 0.7 wrote still show their absences until they are re-indexed. + ### Breaking -- **Breaking:** seal a fixed-width None as a typed null as long as a Some, so ciphertext length no longer shows which values are absent -- **Breaking:** give every null an equality term so the index no longer shows which values were absent +- **Breaking:** Every null, typed or plain, now has an equality term, under the new frozen domain `vitaminc/prf/value/null/v1` with the one byte `0x00`. A sealed `None` is now as long as a `Some` (`vitaminc-aead` 0.8.0), but the term column still held a SQL `NULL` exactly where a value was absent. So `normalize(None, Physical::Null)` succeeds where it returned `NoDomain`, and a walk over a value with a null returns one more term, at the null's path. A layer that must keep a SQL `NULL` for some column drops the term whose domain is `domain::NULL`; producing it is the default because dropping a term should be an explicit act. A boolean and an `undefined` still have no term. `domain::ALL` now lists nine labels. + +### Features -### Documentation +- `NormalizeError::Reserved`, which an order space that places nulls returns for the one value it keeps for them (`vitaminc-ore` 0.8.0). `NormalizeError` is `#[non_exhaustive]`, so a match on it still compiles. + +### Not guaranteed -- match the ADR to the shipped API and say what Reserved means in plain words -- say how terms of the two policies meet, and why a scheme cannot answer for every target +- In an equality index the nulls are one more group of equal terms, as any repeated value is. That is never more than the SQL `NULL` it replaces, which needed no inference to read. ## [0.7.0] - 2026-10-20 From e7bfa5fb13ccc447eb0e92631218a549da8844cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:03:30 +0000 Subject: [PATCH 34/68] chore(deps): bump orderable-bytes from 0.2.0 to 0.2.1 Bumps [orderable-bytes](https://github.com/cipherstash/ore.rs) from 0.2.0 to 0.2.1. - [Release notes](https://github.com/cipherstash/ore.rs/releases) - [Changelog](https://github.com/cipherstash/ore.rs/blob/main/release-plz.toml) - [Commits](https://github.com/cipherstash/ore.rs/compare/orderable-bytes-v0.2.0...orderable-bytes-v0.2.1) --- updated-dependencies: - dependency-name: orderable-bytes dependency-version: 0.2.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- packages/vitaminc-normalize/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index db1ab708b..7b5ee5052 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -42,5 +42,5 @@ futures-executor = "0.3.31" # the tests can check them byte for byte. It is not a dependency of the # crate: ADR 0002 keeps `orderable-bytes` for cipherstash-client's stored # terms and has vitaminc own its encodings. -orderable-bytes = { version = "=0.2.0", features = ["decimal"] } +orderable-bytes = { version = "=0.2.1", features = ["decimal"] } rust_decimal = { version = "1.41", default-features = false, features = ["std"] } From 575e28934d16b96a0e6ed7328c80eb791f5e81aa Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:09:31 +0000 Subject: [PATCH 35/68] chore: release v0.8.1 --- packages/vitaminc-normalize/CHANGELOG.md | 6 ++++++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index c9eb17739..b73d36545 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,10 @@ +## [0.8.1] - 2026-10-26 + +### Dependencies + +- bump orderable-bytes from 0.2.0 to 0.2.1 + ## [0.8.0] - 2026-10-21 Existing equality terms do not change: every domain label and encoding of 0.7 stays as it is, and the null term is a new label beside them. An index built by 0.7 holds a SQL `NULL` where a value was absent; 0.8 writes a term there instead. Both read correctly, but the rows 0.7 wrote still show their absences until they are re-indexed. diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 7b5ee5052..b4cb15a83 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.8.0", path = "../aead" } -vitaminc-protected = { version = "0.8.0", path = "../protected" } +vitaminc-aead = { version = "0.8.1", path = "../aead" } +vitaminc-protected = { version = "0.8.1", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 712fcc6effa15750c9e7210c10d4a38c65af7041 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 26 Oct 2026 14:33:31 +1100 Subject: [PATCH 36/68] docs: rewrite the 0.8.1 changelog entries from the caller's side --- packages/vitaminc-normalize/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index b73d36545..e87b23a30 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -3,7 +3,7 @@ ### Dependencies -- bump orderable-bytes from 0.2.0 to 0.2.1 +- `orderable-bytes` 0.2.1. It changes no encoding, so every term is the same as 0.8.0's, and terms you stored still compare. ## [0.8.0] - 2026-10-21 From 199a928fc0cc218efdd7cbc34af5937cbb43bd69 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 26 Oct 2026 21:31:11 +1100 Subject: [PATCH 37/68] docs: clarify features and Rust requirements --- packages/vitaminc-normalize/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 53e124700..50efb98df 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -22,6 +22,12 @@ own, including the decimal one, which is ported from the frozen [`vitaminc-prf`](https://docs.rs/vitaminc-prf) takes a [`Normalized`] and derives under its domain. +## Installation + +```sh +cargo add vitaminc-normalize +``` + ## One scalar ```rust @@ -152,3 +158,15 @@ new label. Text normalization is variable-time. The integer and float paths use no floating-point arithmetic. + +## Cargo features + +This crate defines no Cargo feature flags. + +## Compatibility + +Requires Rust **1.88.0** and the Rust standard library (`std`). +MSRV increases require a minor release; patch releases retain the existing +floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). + +License: MIT. From bd11cd07fbe187537fb2aeeae9cf79508de02d85 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 26 Oct 2026 22:02:42 +1100 Subject: [PATCH 38/68] ci: keep MSRV docs and checks in sync --- packages/vitaminc-normalize/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 50efb98df..dbfbc74b9 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -165,7 +165,7 @@ This crate defines no Cargo feature flags. ## Compatibility -Requires Rust **1.88.0** and the Rust standard library (`std`). +Requires Rust **1.88.0** and the Rust standard library (`std`). MSRV increases require a minor release; patch releases retain the existing floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). From 286753e050e5026068a98dfc05c1d1272f95344b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 26 Oct 2026 23:29:00 +1100 Subject: [PATCH 39/68] docs: clarify crate guides and navigation --- packages/vitaminc-normalize/README.md | 8 ++++++++ packages/vitaminc-normalize/src/lib.rs | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index dbfbc74b9..69d132a41 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -170,3 +170,11 @@ MSRV increases require a minor release; patch releases retain the existing floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). License: MIT. + + +[`NormalizeError::NoDomain`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/enum.NormalizeError.html#variant.NoDomain +[`Normalized`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Normalized.html +[`Term`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Term.html +[`Terms`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Terms.html +[`decimal`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/fn.decimal.html +[`domain::NULL`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/domain/constant.NULL.html diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index b6b1211ed..4a726a5fb 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -1,3 +1,12 @@ +// These definitions precede the README so rustdoc links to the version being built. +// The README supplies published-API URLs for GitHub. See docs/documentation.md. +//! [`NormalizeError::NoDomain`]: crate::NormalizeError::NoDomain +//! [`Normalized`]: crate::Normalized +//! [`Term`]: crate::Term +//! [`Terms`]: crate::Terms +//! [`decimal`]: crate::decimal +//! [`domain::NULL`]: crate::domain::NULL +//! #![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] #![doc = include_str!("../README.md")] From 6e47551a92b2ab4588057c3690c83b276f5d8b15 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 26 Oct 2026 23:51:34 +1100 Subject: [PATCH 40/68] ci: guard documentation against regressions --- packages/vitaminc-normalize/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index 4a726a5fb..d3391252f 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -7,6 +7,7 @@ //! [`decimal`]: crate::decimal //! [`domain::NULL`]: crate::domain::NULL //! +#![deny(missing_docs)] #![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] #![doc = include_str!("../README.md")] From 7f728a6b90cb07080af69edc63d33299c0f03958 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 2 Nov 2026 17:37:42 +1100 Subject: [PATCH 41/68] test(normalize): compare two test helpers' encodings through a borrow, so no plain copy of one is made holds copied the expected bytes into a Protected only for zip_ref to hand them back as a plain Vec, freed unwiped; decimal::tests::encode took the encoding's Vec out of its Protected with risky_unwrap. Both now read through risky_ref, so the encoding never leaves its wrapper and no copy is left unwiped. The array encode returns is the one plain copy, and is deliberate: the inputs are test values. ZA-0102 and ZA-0103 in the zeroize re-audit of cipherstash/vitaminc#489. Claude-Session: https://claude.ai/code/session_01EnoQSYdggmUYkqNyahDchE --- packages/vitaminc-normalize/src/decimal.rs | 19 +++++++++++++------ .../vitaminc-normalize/src/scalar_tests.rs | 11 +++++------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs index 9a8316ca8..dc23c8c49 100644 --- a/packages/vitaminc-normalize/src/decimal.rs +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -189,14 +189,21 @@ mod tests { const U96_MAX: u128 = (1u128 << 96) - 1; - /// The encoding of an in-range value, taken out of its protected - /// vector. The tests below index, sort and compare the bytes against - /// another crate's plain arrays, so this is the one place they leave - /// the wrapper. + /// The encoding of an in-range value, copied out of its protected + /// vector into a plain array. The tests below index, sort and compare + /// the bytes against another crate's plain arrays, so this is the one + /// place they leave the wrapper. The inputs are test values, not real + /// plaintext, so a plain array of them is fine here. + /// + /// The bytes are copied through a read-only borrow, so the vector + /// itself is never taken out of its `Protected`, and it is wiped when it + /// drops at the end of this function. The returned array is the one + /// plain copy, and it is deliberate. fn encode(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { let scale = u8::try_from(scale).expect("scale fits u8"); - let bytes = orderable(mantissa, scale).expect("in range").risky_unwrap(); - <[u8; ENCODED_LEN]>::try_from(bytes).expect("the encoding is ENCODED_LEN bytes") + let encoded = orderable(mantissa, scale).expect("in range"); + <[u8; ENCODED_LEN]>::try_from(encoded.risky_ref().as_slice()) + .expect("the encoding is ENCODED_LEN bytes") } /// Whether the encoder accepts `mantissa` and `scale`. diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index c391639ad..a93967f05 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -427,13 +427,12 @@ fn f64_canonicalisation_is_idempotent(bits: u64) -> bool { canonical_f64(value).to_bits() == value.to_bits() } -/// Whether `bytes` holds exactly `expected`, compared inside the -/// protected value with `zip_ref` so the encoding never leaves its -/// wrapper. Only the answer, which is not secret, is taken out. +/// Whether `bytes` holds exactly `expected`. The encoding is compared +/// through a borrow, so no copy of it is made outside its `Protected`, and +/// there is nothing left unwiped. Only the answer, which is not secret, +/// is taken out. fn holds(bytes: &Protected>, expected: &[u8]) -> bool { - Protected::new(expected.to_vec()) - .zip_ref(bytes, |expected, bytes: &Vec| *bytes == expected) - .risky_unwrap() + bytes.risky_ref().as_slice() == expected } mod given_any_canonical_f64 { From 6595b6a255043686ebdfd021424f9aa9a34f5d93 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 2 Nov 2026 17:37:42 +1100 Subject: [PATCH 42/68] fix(aead): inline the Int and TimeUnit helpers, so a caller in another crate is not handed plaintext through an unwiped return slot Int::to_i128, sign_and_word, TimeUnit::nanos and timestamp_nanos were not inlinable across crates, so normalize's integer and timestamp got the sign and word, or the nanosecond count, back through a 32-byte slot on their own stack that nothing wipes. Marked #[inline], they compile into the caller, and in both the release build and the audit's mixed build those slots are gone (checked in the IR and assembly for AArch64). Every other caller in the workspace gets the same, without copying the helpers' bodies. ZA-0104 and ZA-0105 in the zeroize re-audit of cipherstash/vitaminc#489. Claude-Session: https://claude.ai/code/session_01EnoQSYdggmUYkqNyahDchE --- packages/vitaminc-normalize/src/scalar.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index cb5795fc3..7017d908e 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -189,6 +189,10 @@ pub fn normalize(ty: Option, v: Physical<'_>) -> Result Protected> { + // `sign_and_word` is `#[inline]`, so it is compiled into this function + // and the sign and word stay in registers until they are written to the + // buffer, rather than coming back through an unwiped stack slot + // (checked in the compiled code for AArch64; Rust does not promise it). let (negative, word) = value.sign_and_word(); fixed::<17>(|b| { b[0] = u8::from(!negative); @@ -225,6 +229,9 @@ pub fn date(days: Int) -> Option>> { /// chrono's `DateTime` orders by, truncated). `None` outside the /// timestamp range. pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { + // `timestamp_nanos` is `#[inline]` for the same reason as + // `sign_and_word` in `integer`: so the count is not returned through + // an unwiped stack slot. let nanos = timestamp_nanos(unit, count)?; let seconds = i64::try_from(nanos.div_euclid(NANOS_PER_SECOND)).ok()?; let sub = (nanos.rem_euclid(NANOS_PER_SECOND) as u32) / 1_000 * 1_000; From 4670e57bb8173510fae06c9a644133e87db66ffc Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Mon, 2 Nov 2026 22:12:55 +1100 Subject: [PATCH 43/68] chore: raise the workspace MSRV to Rust 1.89 uuid 1.27 and later declare rust-version 1.89, so Dependabot's bump to 1.29.0 (cipherstash/vitaminc#554) fails the MSRV job against the 1.88 we declare. Rust 1.89 shipped in August 2025 and CI already tests on 1.96; holding a dependency back for a fifteen-month-old compiler is friction that will recur with other crates. Only the root rust-version changes by hand; the README and doc-comment markers are rewritten by sync_msrv.py and the MSRV matrix reads the manifests. vitaminc-kms keeps its own 1.94.1. --- packages/vitaminc-normalize/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md index 69d132a41..f32fa7074 100644 --- a/packages/vitaminc-normalize/README.md +++ b/packages/vitaminc-normalize/README.md @@ -165,7 +165,7 @@ This crate defines no Cargo feature flags. ## Compatibility -Requires Rust **1.88.0** and the Rust standard library (`std`). +Requires Rust **1.89.0** and the Rust standard library (`std`). MSRV increases require a minor release; patch releases retain the existing floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). From c97749d94cf7a38f2eba503f03870f56d2d2a1ac Mon Sep 17 00:00:00 2001 From: Toby Hede Date: Tue, 3 Nov 2026 15:48:44 +1100 Subject: [PATCH 44/68] docs: fix the remaining doc links a private-items build refuses, so internal docs build with warnings denied A public docs build skips private items, so CI never saw these; building with --document-private-items failed in aead, context, normalize, ore and random too. Links to a name that is both a function and a module now say the function (decimal(), order(), walk()); links to an item not in scope give its path; and links whose explicit target only repeated what the name already resolves to drop it. --- packages/vitaminc-normalize/src/decimal.rs | 2 +- packages/vitaminc-normalize/src/lib.rs | 2 +- packages/vitaminc-normalize/src/terms.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs index dc23c8c49..9b94bd4b7 100644 --- a/packages/vitaminc-normalize/src/decimal.rs +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -13,7 +13,7 @@ //! range. The encoder refuses anything outside it: a larger mantissa would //! lose its top bits and take the bytes of another value. //! -//! The layout is documented on [`decimal`](crate::decimal), the public +//! The layout is documented on [`decimal`](crate::decimal()), the public //! function that wraps this encoder, so it is in the published docs. //! //! ## Constant time diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs index d3391252f..a935af9ec 100644 --- a/packages/vitaminc-normalize/src/lib.rs +++ b/packages/vitaminc-normalize/src/lib.rs @@ -4,7 +4,7 @@ //! [`Normalized`]: crate::Normalized //! [`Term`]: crate::Term //! [`Terms`]: crate::Terms -//! [`decimal`]: crate::decimal +//! [`decimal`]: crate::decimal() //! [`domain::NULL`]: crate::domain::NULL //! #![deny(missing_docs)] diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index aa528ec28..f00a76b29 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -205,7 +205,7 @@ impl Error for TermsError { /// A `Terms` refuses every value [`EncryptSink`] refuses, for the same /// [`Unencryptable`](vitaminc_aead::Unencryptable) reason and at the same path, so an index never holds /// terms for a value that cannot be stored. It keeps the -/// [`shape`](vitaminc_aead::shape) rules through the code `EncryptSink` +/// [`shape`] rules through the code `EncryptSink` /// keeps them with: nothing deeper than the transport's depth limit, every /// scalar valid for its logical type, every passthrough subtree framable, /// no map key given twice, no child sink dropped without a value, and From 05bd5fc09b00ce57208b2f328590d8c43052fb4f Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:18:31 +0000 Subject: [PATCH 45/68] chore: release v0.9.0 --- packages/vitaminc-normalize/CHANGELOG.md | 12 ++++++++++++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index e87b23a30..86bfa060b 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,16 @@ +## [0.9.0] - 2026-11-04 + +### Documentation + +- clarify features and Rust requirements +- clarify crate guides and navigation +- fix the remaining doc links a private-items build refuses, so internal docs build with warnings denied + +### Fixes + +- inline the Int and TimeUnit helpers, so a caller in another crate is not handed plaintext through an unwiped return slot + ## [0.8.1] - 2026-10-26 ### Dependencies diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index b4cb15a83..181cabbdc 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.8.1", path = "../aead" } -vitaminc-protected = { version = "0.8.1", path = "../protected" } +vitaminc-aead = { version = "0.9.0", path = "../aead" } +vitaminc-protected = { version = "0.9.0", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 784374040578ea8100a695e31c0245426d1bdc29 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 4 Nov 2026 20:23:06 +1100 Subject: [PATCH 46/68] docs: rewrite the 0.9.0 changelogs from the caller's side Breaking changes lead, with what to do about each. The MSRV raise to 1.89 is added by hand, since cliff.toml skips its chore commit. The aead and aead-frame entries state that the wire format is unchanged, and the aead, context and protected entries say what is deliberately not guaranteed. Internal docs churn, test-only dependency bumps and lockfile-only advisory fixes are dropped. Co-Authored-By: Claude Opus 5.5 --- packages/vitaminc-normalize/CHANGELOG.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 86bfa060b..c337dd85b 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,15 +1,13 @@ ## [0.9.0] - 2026-11-04 -### Documentation +### Breaking -- clarify features and Rust requirements -- clarify crate guides and navigation -- fix the remaining doc links a private-items build refuses, so internal docs build with warnings denied +- **Breaking:** the minimum supported Rust version is now 1.89. 0.8.1 declared 1.88. ### Fixes -- inline the Int and TimeUnit helpers, so a caller in another crate is not handed plaintext through an unwiped return slot +- Normalizing an integer or a timestamp no longer passes the value through an unwiped stack slot. The `vitaminc-aead` helpers it calls are now inlined. ## [0.8.1] - 2026-10-26 From 4ed51eb199b25a09163574909435ea4d515a097b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 4 Nov 2026 20:32:10 +1100 Subject: [PATCH 47/68] docs: rewrite the 0.9.0 changelogs in plain language Each entry now follows the plain-language skill (github.com/auxesis/plain-language-skill): one idea per sentence, one sentence per line, the change before the reason, and what the caller has to do stated as an instruction. The facts are the same as in the previous rewrite. The skill's checker reports no must-fix findings on the 0.9.0 sections. The spelling stays American, to match the repository. Co-Authored-By: Claude Opus 5.5 --- packages/vitaminc-normalize/CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index c337dd85b..6aa643bcf 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -3,11 +3,13 @@ ### Breaking -- **Breaking:** the minimum supported Rust version is now 1.89. 0.8.1 declared 1.88. +- **Breaking:** the crate now needs Rust 1.89 or later. + Version 0.8.1 needed Rust 1.88. ### Fixes -- Normalizing an integer or a timestamp no longer passes the value through an unwiped stack slot. The `vitaminc-aead` helpers it calls are now inlined. +- Normalizing an integer or a timestamp no longer passes the value through a stack slot that is not wiped. + The `vitaminc-aead` helpers that this crate calls are now inlined into this crate's code. ## [0.8.1] - 2026-10-26 From fb8648c9cb29cd6d3d4747cad5fdf155417befc2 Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:48:37 +0000 Subject: [PATCH 48/68] chore: release v0.9.1 --- packages/vitaminc-normalize/CHANGELOG.md | 2 ++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index 6aa643bcf..bc7842ebc 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,6 @@ +## [0.9.1] - 2026-11-06 + ## [0.9.0] - 2026-11-04 ### Breaking diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 181cabbdc..c01ce2af4 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.9.0", path = "../aead" } -vitaminc-protected = { version = "0.9.0", path = "../protected" } +vitaminc-aead = { version = "0.9.1", path = "../aead" } +vitaminc-protected = { version = "0.9.1", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 59ca508be8f142e29b9f475d15b7ba577e13f5d5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 17 Nov 2026 22:53:04 +1100 Subject: [PATCH 49/68] feat(aead, ore)!: take dates and timestamps from jiff, because chrono is unmaintained MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RUSTSEC-2026-0543 marks chrono unmaintained, and its maintainer points to jiff. The `chrono` feature of vitaminc-aead and vitaminc-ore becomes `jiff`: `jiff::civil::Date` and `jiff::Timestamp` are the Encrypt sources and decrypt targets for the Date and Timestamp logical types. The wire does not change. A date is still days since 1970-01-01 and a timestamp nanoseconds since the epoch, the range constants keep chrono's ±262,143 years so every sealed value still opens, and a test pins the DATE and TIMESTAMP payload bytes chrono wrote. jiff covers ±9999 years: a value past that opens, but a jiff target refuses it as the wrong shape. jiff has no leap seconds, so `vitaminc_aead::Timestamp::new` takes a `jiff::Timestamp` and cannot fail, `LeapSecond` goes away, and `jiff::Timestamp` now fits ore's `Timestamp` target without a check. The Node binding reads and writes dates and timestamps across the whole wire range, past jiff's, so it gets a dependency-free proleptic Gregorian calendar of its own, checked day for day against jiff over jiff's range. The aead-frame conformance test builds its expected dates the same way. portable-atomic and portable-atomic-util, which jiff takes on targets without pointer-width atomics, join deny.toml's build-script allow list after review. Refs cipherstash/vitaminc#626 BREAKING CHANGE: the `chrono` feature is now `jiff`; the chrono types are no longer sources or targets; `Timestamp::new` takes a `jiff::Timestamp` and returns `Timestamp`; `Timestamp::to_datetime` is `to_jiff`; `LeapSecond` is removed; `plaintext::kinds::chrono` is `kinds::jiff`. --- packages/vitaminc-normalize/Cargo.toml | 4 ++-- packages/vitaminc-normalize/src/scalar.rs | 13 +++++++------ packages/vitaminc-normalize/src/scalar_tests.rs | 4 ++-- packages/vitaminc-normalize/tests/known_answers.rs | 11 ++++++----- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index c01ce2af4..2cb4c3cc1 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -31,8 +31,8 @@ version = "=1.1.0" # Path-only, so publish order does not matter. `test-support` for # `plaintext::render`, the path notation the tests assert against, so there # is one copy of it. -vitaminc-aead = { path = "../aead", features = ["chrono", "rust_decimal", "uuid", "test-support"] } -chrono = { version = "0.4.44", default-features = false, features = ["std"] } +vitaminc-aead = { path = "../aead", features = ["jiff", "rust_decimal", "uuid", "test-support"] } +jiff = { version = "1.0.0", default-features = false } uuid = { version = "1", default-features = false } quickcheck = "1.1.0" quickcheck_macros = "1.2.0" diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs index 7017d908e..84330dde3 100644 --- a/packages/vitaminc-normalize/src/scalar.rs +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -211,8 +211,8 @@ pub fn float(value: Float) -> Protected> { } /// A date's day count since 1970-01-01, as the orderable bytes of its -/// count of days from 0001-01-01 (the same bytes chrono's `NaiveDate` -/// orders by). `None` outside the date range. +/// count of days from 0001-01-01, so the bytes order as the dates do. +/// `None` outside the date range. pub fn date(days: Int) -> Option>> { let days = i32::try_from(days.to_i128()?).ok()?; if !(MIN_DATE_DAYS..=MAX_DATE_DAYS).contains(&days) { @@ -225,9 +225,9 @@ pub fn date(days: Int) -> Option>> { } /// A count of `unit`s since the Unix epoch, as orderable seconds then -/// big-endian nanoseconds truncated to microseconds (the same bytes -/// chrono's `DateTime` orders by, truncated). `None` outside the -/// timestamp range. +/// big-endian nanoseconds truncated to microseconds, so the bytes order as +/// the instants do, to the microsecond. `None` outside the timestamp +/// range. pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { // `timestamp_nanos` is `#[inline]` for the same reason as // `sign_and_word` in `integer`: so the count is not returned through @@ -357,7 +357,8 @@ pub(crate) fn fixed(mut write: impl FnMut(&mut [u8; N])) -> Prot bytes } -/// Days from 0001-01-01 (day 1, chrono's "days from CE") to 1970-01-01. +/// Days from 0001-01-01 (counted as day 1, the "days from CE" of the +/// proleptic Gregorian calendar) to 1970-01-01. const EPOCH_DAYS_FROM_CE: i32 = 719_163; const NANOS_PER_SECOND: i128 = 1_000_000_000; diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs index a93967f05..07b156c6f 100644 --- a/packages/vitaminc-normalize/src/scalar_tests.rs +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -170,7 +170,7 @@ fn a_value_that_does_not_fit_its_logical_type_is_invalid() { NormalizeError::Invalid ); // The encoders say the same without going through `admits`, one day - // past chrono's range on either side included. + // past the wire's range on either side included. assert!(date(Int::I64(i64::MAX)).is_none()); assert!(date(Int::I32(MAX_DATE_DAYS + 1)).is_none()); assert!(date(Int::I32(MIN_DATE_DAYS - 1)).is_none()); @@ -446,7 +446,7 @@ mod given_any_canonical_f64 { } #[test] -fn timestamps_one_past_chronos_range_are_invalid() { +fn timestamps_one_past_the_wire_range_are_invalid() { use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; let ns = Logical::Timestamp(TimeUnit::Nanos); assert!(timestamp(TimeUnit::Nanos, Int::I128(MAX_TIMESTAMP_NANOS)).is_some()); diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 184898543..0eb3fa966 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -9,9 +9,8 @@ use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::collections::BTreeMap; -use chrono::NaiveDate; use futures_executor::block_on; -use vitaminc_aead::plaintext::kinds::chrono as conv; +use vitaminc_aead::plaintext::kinds::jiff as conv; use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::{AsyncCipher, Cipher}; use vitaminc_aead::{ @@ -729,7 +728,8 @@ fn text_and_bytes_normalize_to_their_pinned_terms() { #[test] fn dates_normalize_to_their_pinned_terms() { - // NaiveDate::MIN, 0001-01-01, 1969-12-31, 1970-01-01, 2024-02-29, NaiveDate::MAX. + // The wire's minimum (chrono's NaiveDate::MIN), 0001-01-01, 1969-12-31, + // 1970-01-01, 2024-02-29, the wire's maximum (chrono's NaiveDate::MAX). pin( Some(Logical::Date), Physical::Int(Int::I32(-96465292)), @@ -772,7 +772,8 @@ fn dates_normalize_to_their_pinned_terms() { fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { // Five instants as nanoseconds, each then truncated to micros, millis // and seconds (a coarser unit matches the term of the instant at that - // precision), then chrono's MIN_UTC and MAX_UTC. + // precision), then the wire's minimum and maximum (chrono's MIN_UTC and + // MAX_UTC). pin( Some(Logical::Timestamp(TimeUnit::Nanos)), Physical::Int(Int::I128(0)), @@ -1044,7 +1045,7 @@ fn a_uuid_has_a_domain_of_its_own() { #[test] fn a_date_never_matches_its_day_count_and_widths_agree() { - let date = NaiveDate::from_ymd_opt(2024, 2, 29).expect("date"); + let date = jiff::civil::Date::constant(2024, 2, 29); let days = conv::date_days(date); let as_date = normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect("date"); let as_int = normalize(None, Physical::Int(Int::I32(days))).expect("int"); From 128e8976de13b6d30bba3181987c1033c5882a2c Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 18 Nov 2026 09:24:08 +1100 Subject: [PATCH 50/68] feat!: narrow dates and timestamps to jiff's range in every binding, so a value one binding seals every binding opens The wire kept chrono's range (years -262143 to 262142) while Rust moved to jiff, which stops at -9999 to 9999. Go and Node could then seal a value, such as the corpus's timestamp in year 12000, that a Rust jiff target could not open, and the Rust conformance test only passed because it had been given a calendar parser of its own. The range is now jiff's, exactly, everywhere: dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z. A count outside it is refused when it is sealed and when it is opened, so every value opens into jiff's types. - aead: MIN/MAX_DATE_DAYS and MIN/MAX_TIMESTAMP_NANOS are jiff's limits; kinds::jiff::timestamp_nanos is the wire range check, which also refuses the instant jiff 1.0.0 can make before its own minimum (cipherstash/vitaminc#714 upstream). - aead-napi: its own calendar (civil.rs) is gone; dates and timestamps go through jiff. A negative year is a sign and six digits, as jiff and JavaScript write it. Timestamp text is checked for RFC 3339's shape first, since jiff's parser reads more (and reads a leap second as the second before), and the instant is counted without jiff's Offset::to_timestamp. - Go: vcvalue's Date and Timestamp ranges match, and the embedded wasm guest is rebuilt with the new range. - Corpus: the year 12000 vector moves to the refused list, with vectors at and just past each end; aead-frame's conformance test builds dates and timestamps with jiff again, and the pre-ADR 0001 fixture's year 12000 vector is expected to be refused. BREAKING CHANGE: a date or timestamp past years -9999 to 9999 is refused. A leaf sealed past them under the old range authenticates and is then refused as malformed. Node writes a negative year as -000005, not -0005. Refs cipherstash/vitaminc#626 --- .../vitaminc-normalize/tests/known_answers.rs | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 0eb3fa966..9602283a2 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -728,13 +728,14 @@ fn text_and_bytes_normalize_to_their_pinned_terms() { #[test] fn dates_normalize_to_their_pinned_terms() { - // The wire's minimum (chrono's NaiveDate::MIN), 0001-01-01, 1969-12-31, - // 1970-01-01, 2024-02-29, the wire's maximum (chrono's NaiveDate::MAX). + // The wire's minimum (jiff's Date::MIN, -9999-01-01), 0001-01-01, + // 1969-12-31, 1970-01-01, 2024-02-29, the wire's maximum (jiff's + // Date::MAX, 9999-12-31). pin( Some(Logical::Date), - Physical::Int(Int::I32(-96465292)), + Physical::Int(Int::I32(-4371587)), "vitaminc/prf/value/date-orderable/v1", - "7a4b07af", + "7fc844b8", ); pin( Some(Logical::Date), @@ -762,9 +763,9 @@ fn dates_normalize_to_their_pinned_terms() { ); pin( Some(Logical::Date), - Physical::Int(Int::I32(95026236)), + Physical::Int(Int::I32(2932896)), "vitaminc/prf/value/date-orderable/v1", - "85b4f577", + "8037b9db", ); } @@ -772,8 +773,8 @@ fn dates_normalize_to_their_pinned_terms() { fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { // Five instants as nanoseconds, each then truncated to micros, millis // and seconds (a coarser unit matches the term of the instant at that - // precision), then the wire's minimum and maximum (chrono's MIN_UTC and - // MAX_UTC). + // precision), then the wire's minimum and maximum (jiff's + // Timestamp::MIN and Timestamp::MAX). pin( Some(Logical::Timestamp(TimeUnit::Nanos)), Physical::Int(Int::I128(0)), @@ -896,15 +897,15 @@ fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { ); pin( Some(Logical::Timestamp(TimeUnit::Nanos)), - Physical::Int(Int::I128(-8334601228800000000000)), + Physical::Int(Int::I128(-377705023201000000000)), "vitaminc/prf/value/timestamp-micros-orderable/v1", - "7ffff86b730dee0000000000", + "7fffffa80f06b91f00000000", ); pin( Some(Logical::Timestamp(TimeUnit::Nanos)), - Physical::Int(Int::I128(8210266876799999999999)), + Physical::Int(Int::I128(253402207200999999999)), "vitaminc/prf/value/timestamp-micros-orderable/v1", - "800007779a0a6b7f3b9ac618", + "8000003afff2d3e03b9ac618", ); } From 760bc3588e9aeb4c5376339ca58bc686f3be930d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 14 Nov 2026 00:16:25 +1100 Subject: [PATCH 51/68] feat(aead)!: let generic code bound on a borrowed plaintext without copying it Generic code that holds `&T` had no bound it could use. `for<'a> &'a T: Encrypt` overflowed the trait solver (E0275) wherever `T` was still being inferred: the container impls bounded their element on `&'a T: Encrypt`, so with `T` unknown the solver tried `&Option`, `&Option>`, and so on without end. The only bound left was `T: Encrypt`, by value, so a consumer holding a borrow had to clone it, and every plaintext had to be `Clone`. - Add `EncryptRef`, implemented for every `T` whose borrow is a source, with `visit_ref`, `lend` and the borrow's `REF_DEPTH` and `REF_FIXED`, and `Lent`, the borrowed plaintext as an `Encrypt` source. - Bound the container impls (`&Option`, `&Vec`, `&[T]`, the maps, `Protected`, `ProtectedRef`, `&&T`) on `T: EncryptRef`. The solver now stops at a bare type variable and waits, so the higher-ranked bound holds under inference too. - `Sink::passthrough` lends its subtree (`&P` with `P: ?Sized + EncryptRef`) instead of taking it by value with `Clone`. A `Tee` lends the same subtree to each side, so a passthrough is never copied. BREAKING CHANGE: `Sink::passthrough` takes `&P` where `P: ?Sized + EncryptRef`; a sink walks it with `visit_ref` and a caller passes a reference. A passthrough type implements `Encrypt` for `&T` and need not be `Clone`. Refs cipherstash/vitaminc#614 --- packages/vitaminc-normalize/src/terms.rs | 8 ++--- .../vitaminc-normalize/tests/agreement.rs | 34 ++++++++++++++----- .../vitaminc-normalize/tests/known_answers.rs | 2 +- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs index f00a76b29..42bed495e 100644 --- a/packages/vitaminc-normalize/src/terms.rs +++ b/packages/vitaminc-normalize/src/terms.rs @@ -20,8 +20,8 @@ use vitaminc_aead::plaintext::{Error, Path, Step}; use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; use vitaminc_aead::{ - Encrypt, EncryptError, EncryptSink, FixedType, IntoAad, Logical, MapSink, Node, Pending, - Physical, Refusal, SeqSink, Sink, SourceError, Tee, + Encrypt, EncryptError, EncryptRef, EncryptSink, FixedType, IntoAad, Logical, MapSink, Node, + Pending, Physical, Refusal, SeqSink, Sink, SourceError, Tee, }; use vitaminc_protected::OpaqueDebug; @@ -519,13 +519,13 @@ impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { /// No terms. Keeping the shape rules, the subtree is framed, as /// encryption frames it, and the frame dropped. - fn passthrough(self, value: P) -> Result<(), E> { + fn passthrough(self, value: &P) -> Result<(), E> { if let Some(rules) = self.rules { let at = At { place: &self.at, keys: self.keys.as_str(), }; - shape::frame_passthrough(value, rules.depth, &at, refused)?; + shape::frame_passthrough(value.lend(), rules.depth, &at, refused)?; if let Some(settle) = rules.settle { settle.passthrough(); } diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs index 5bd3c8ffe..d3ac4ea28 100644 --- a/packages/vitaminc-normalize/tests/agreement.rs +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -9,8 +9,8 @@ use vitaminc_aead::frame::MAX_DEPTH; use vitaminc_aead::plaintext::render; use vitaminc_aead::seal::Cipher; use vitaminc_aead::{ - Context, Encrypt, EncryptError, Logical, MapSink, Physical, Raw, SeqSink, Sink, SourceError, - Unencryptable, + Context, Encrypt, EncryptError, EncryptRef, Logical, MapSink, Physical, Raw, SeqSink, Sink, + SourceError, Unencryptable, }; use vitaminc_normalize::{encrypt_with_terms, terms, NormalizeError, Term, TermError}; use vitaminc_protected::{Controlled, Protected}; @@ -128,11 +128,11 @@ impl Encrypt for OnlyPass { fn visit(self, sink: S) -> Result { if self.map { let mut map = sink.map(Some(1))?; - map.entry("note")?.passthrough("public")?; + map.entry("note")?.passthrough(&"public")?; map.end() } else { let mut seq = sink.seq(Some(1))?; - seq.element()?.passthrough("public")?; + seq.element()?.passthrough(&"public")?; seq.end() } } @@ -175,14 +175,13 @@ impl Encrypt for Unclosed { } /// `inner` as a passthrough, beside a sealed sibling. -#[derive(Clone)] struct Passes

(P); -impl Encrypt for Passes

{ +impl Encrypt for Passes

{ fn visit(self, sink: S) -> Result { let mut seq = sink.seq(Some(2))?; "sealed".visit(seq.element()?)?; - seq.element()?.passthrough(self.0)?; + seq.element()?.passthrough(&self.0)?; seq.end() } } @@ -233,11 +232,30 @@ impl Encrypt for Nest { inner.visit(map.entry("k")?)?; map.end() } - Kind::Pass => sink.passthrough(inner), + Kind::Pass => sink.passthrough(&inner), } } } +/// A passthrough is lent, so a source a test passes through walks by +/// reference too, as the value it is. +macro_rules! lent_as_owned { + ($($ty:ident => $value:expr),+ $(,)?) => {$( + impl Encrypt for &$ty { + fn visit(self, sink: S) -> Result { + let owned: $ty = $value(self); + owned.visit(sink) + } + } + )+}; +} +lent_as_owned!( + Dup => |_| Dup, + Unclosed => |_| Unclosed, + Throws => |_| Throws, + Nest => |nest: &Nest| *nest, +); + #[test] fn both_accept_a_well_formed_value_with_the_same_terms() { let doc = || { diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index 9602283a2..a386a8be8 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -1165,7 +1165,7 @@ fn scalars_without_a_domain_and_passthroughs_get_no_term_and_a_null_gets_one() { let mut map = sink.map(Some(5))?; true.visit(map.entry("active")?)?; None::.visit(map.entry("missing")?)?; - map.entry("tenant")?.passthrough("acme")?; + map.entry("tenant")?.passthrough(&"acme")?; vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Null) .visit(map.entry("undefined")?)?; "Ada".visit(map.entry("name")?)?; From 683f8a15093f7550f0d3539e96c91364fd335083 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 14 Nov 2026 01:29:05 +1100 Subject: [PATCH 52/68] refactor(aead, normalize): share one constant-time trailing-zero strip for decimals The mutants gate found the wipeable `Decimal`'s hand-written normalization under-tested, and it duplicated `strip_trailing_zeros`, which vitaminc-normalize's decimal encoder already has: division-free (a shift and a multiply by the inverse of five), constant time, tested and gated. `strip_trailing_zeros` moves to `vitaminc_aead::plaintext::kinds`, below both crates, with its test; the encoder imports it. `Decimal`'s equality is built on it: two decimals are equal when both are zero, or when their signs, stripped significands and powers of ten all are. The hand-written division and selects are gone. The pairwise test now includes values that differ only above the low 32 or 64 bits, and `From` both ways is checked. Refs cipherstash/vitaminc#461 --- packages/vitaminc-normalize/src/decimal.rs | 52 +--------------------- 1 file changed, 1 insertion(+), 51 deletions(-) diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs index 9b94bd4b7..ec9654c26 100644 --- a/packages/vitaminc-normalize/src/decimal.rs +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -24,7 +24,7 @@ //! scale, and no hardware division, whose latency is data-dependent on //! some targets. -use vitaminc_aead::plaintext::kinds::MAX_DECIMAL_SCALE; +use vitaminc_aead::plaintext::kinds::{strip_trailing_zeros, MAX_DECIMAL_SCALE}; use vitaminc_protected::Protected; use crate::scalar::fixed; @@ -51,15 +51,6 @@ const MANTISSA_LIMIT: u128 = 1 << 96; /// The length of the encoding. pub(crate) const ENCODED_LEN: usize = 14; -/// `5⁻¹ mod 2¹²⁸`, so that dividing by ten (when exact) is a shift and a -/// multiply rather than a hardware division. -const INV5: u128 = 0xCCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCC_CCCD; - -/// The largest `u128` divisible by 5. Multiplication by [`INV5`] is a -/// bijection that maps the multiples of 5 onto `[0, MAX_DIV_5]`, so -/// `x.wrapping_mul(INV5) <= MAX_DIV_5` exactly when `5 | x`. -const MAX_DIV_5: u128 = u128::MAX / 5; - /// The encoding of `mantissa × 10^(-scale)`. Two equal values give the /// same bytes, and the bytes sort as the values do. `None` if the mantissa /// does not fit 96 bits or the scale is above 28. @@ -140,32 +131,6 @@ pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option>> })) } -/// Divide by ten while the trailing digit is zero: the stripped value and -/// how many zeros were removed. Zero strips to `(0, 0)`. -/// -/// A fixed `PADDED_DIGITS` iterations, each selecting by mask. Division by -/// ten, valid only when exact, is a halving and a multiply by [`INV5`]; -/// divisibility by ten is divisibility by two (the low bit) and by five -/// (the [`MAX_DIV_5`] test), with the comparison done by `overflowing_sub` -/// so it lowers to a borrow rather than a branch. -fn strip_trailing_zeros(mut mantissa: u128) -> (u128, i32) { - let mut exponent: i32 = 0; - for _ in 0..PADDED_DIGITS { - let div = (mantissa >> 1).wrapping_mul(INV5); - let q5 = mantissa.wrapping_mul(INV5); - let (_, borrow) = MAX_DIV_5.overflowing_sub(q5); - let div_by_5 = (borrow as u128) ^ 1; - let div_by_2 = (mantissa & 1) ^ 1; - let div_by_10 = div_by_5 & div_by_2; - let mantissa_nz = (mantissa | mantissa.wrapping_neg()) >> 127; - let do_strip = mantissa_nz & div_by_10; - let mask = 0u128.wrapping_sub(do_strip); - mantissa = (div & mask) | (mantissa & !mask); - exponent = exponent.wrapping_add(do_strip as i32); - } - (mantissa, exponent) -} - /// The number of decimal digits in `m`, `0` for zero: how many powers of /// ten below `10^PADDED_DIGITS` it is at least, each test a borrow. fn digit_count(m: u128) -> u32 { @@ -277,21 +242,6 @@ mod tests { } } - #[test] - fn strip_trailing_zeros_edge_cases() { - assert_eq!(strip_trailing_zeros(0), (0, 0)); - for d in 1u128..=9 { - assert_eq!(strip_trailing_zeros(d), (d, 0), "input {d}"); - } - for k in 0..=28u32 { - assert_eq!(strip_trailing_zeros(10u128.pow(k)), (1, k as i32), "10^{k}"); - } - assert_eq!(strip_trailing_zeros(U96_MAX), (U96_MAX, 0)); - assert_eq!(strip_trailing_zeros(12_340_000), (1234, 4)); - assert_eq!(strip_trailing_zeros(50), (5, 1)); - assert_eq!(strip_trailing_zeros(100_500), (1005, 2)); - } - #[test] fn digit_count_counts_digits() { assert_eq!(digit_count(0), 0); From cf61cef5fca2a68e9c1d55f0b54219c8a6f1859f Mon Sep 17 00:00:00 2001 From: "cipherstash-release-plz[bot]" <262324448+cipherstash-release-plz[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:39:12 +0000 Subject: [PATCH 53/68] chore: release v0.10.0 --- packages/vitaminc-normalize/CHANGELOG.md | 8 ++++++++ packages/vitaminc-normalize/Cargo.toml | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index bc7842ebc..baba643e7 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,4 +1,12 @@ +## [0.10.0] - 2026-11-19 + +### Breaking + +- **Breaking:** take dates and timestamps from jiff, because chrono is unmaintained +- **Breaking:** narrow dates and timestamps to jiff's range in every binding, so a value one binding seals every binding opens +- **Breaking:** let generic code bound on a borrowed plaintext without copying it + ## [0.9.1] - 2026-11-06 ## [0.9.0] - 2026-11-04 diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index 2cb4c3cc1..d8c6a5449 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -13,8 +13,8 @@ categories.workspace = true rust-version.workspace = true [dependencies] -vitaminc-aead = { version = "0.9.1", path = "../aead" } -vitaminc-protected = { version = "0.9.1", path = "../protected" } +vitaminc-aead = { version = "0.10.0", path = "../aead" } +vitaminc-protected = { version = "0.10.0", path = "../protected" } thiserror = { workspace = true } # NFC is stable for assigned code points, and the Unicode 16 assignment check From 1270f27f7a02bc5b8e3eeccd501b84edd98df7a2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 19 Nov 2026 20:58:43 +1100 Subject: [PATCH 54/68] docs: rewrite the 0.10.0 changelogs for callers, and state what the narrower date range means for stored data The generated entries were commit subjects. They also listed walk_legacy_range, which was added and removed again in this release, and the addon's dependency bumps, which do not ship. Each crate's section now says what changed for a caller of that crate, and what to do to upgrade. hmac and kms have no user-visible change, so their sections are empty. --- packages/vitaminc-normalize/CHANGELOG.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md index baba643e7..65c6bf184 100644 --- a/packages/vitaminc-normalize/CHANGELOG.md +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -1,11 +1,15 @@ ## [0.10.0] - 2026-11-19 +### Index terms + +- Index terms for every value in the supported range are the same as in 0.9.1. + ### Breaking -- **Breaking:** take dates and timestamps from jiff, because chrono is unmaintained -- **Breaking:** narrow dates and timestamps to jiff's range in every binding, so a value one binding seals every binding opens -- **Breaking:** let generic code bound on a borrowed plaintext without copying it +- **Breaking:** a date or timestamp outside years -9999 to 9999 no longer has an index term. + In 0.9.1, the range was years -262143 to 262142. + The 0.10.0 changelog for `vitaminc-aead` gives the exact limits. ## [0.9.1] - 2026-11-06 From b4291c4b7b28ef74c01e5b63af7fdbcf96da56d0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:22:57 +1100 Subject: [PATCH 55/68] build(vitaminc-normalize): give the imported manifest its own fields The manifest took its version, licence, edition and thiserror from vitaminc's workspace. That workspace is not here. The manifest now states each field: version 0.10.0, the MIT licence, edition 2021 and rust-version 1.89.0. Only repository changes, to name this repository. thiserror keeps vitaminc's requirement, written out: thiserror 2, not this workspace's thiserror 1. vitaminc-aead stays a path dependency under its directory name here. vitaminc-protected did not move. It comes from crates.io at 0.10.0. The crate is publish = false for now, and release-plz.toml lists it with release = false, so release-plz neither bumps nor publishes it. This is how the AEAD crates were set up when they moved. --- packages/vitaminc-normalize/Cargo.toml | 31 +++++++++++++++----------- release-plz.toml | 9 ++++++++ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml index d8c6a5449..bf2c8c21e 100644 --- a/packages/vitaminc-normalize/Cargo.toml +++ b/packages/vitaminc-normalize/Cargo.toml @@ -2,20 +2,25 @@ name = "vitaminc-normalize" description = "Normalized equality terms for the plaintext data model. Part of the Vitamin-C cryptographic suite." documentation = "https://docs.rs/vitaminc-normalize" -version.workspace = true -repository.workspace = true -authors.workspace = true -edition.workspace = true -homepage.workspace = true -license.workspace = true -keywords.workspace = true -categories.workspace = true -rust-version.workspace = true +version = "0.10.0" +repository = "https://github.com/cipherstash/stack" +authors = ["Dan Draper "] +edition = "2021" +homepage = "https://cipherstash.com" +license = "MIT" +keywords = ["cryptography", "security"] +categories = ["cryptography"] +rust-version = "1.89.0" +# Not published from this repository yet: crates.io serves 0.10.0, which was +# published from cipherstash/vitaminc. release-plz.toml lists it with +# `release = false`. Every workspace that resolves it patches crates.io's +# copy to this one. +publish = false [dependencies] -vitaminc-aead = { version = "0.10.0", path = "../aead" } -vitaminc-protected = { version = "0.10.0", path = "../protected" } -thiserror = { workspace = true } +vitaminc-aead = { version = "0.10.0", path = "../vitaminc-aead" } +vitaminc-protected = "0.10.0" +thiserror = "2.0.18" # NFC is stable for assigned code points, and the Unicode 16 assignment check # refuses everything else, so newer normalization releases are safe. @@ -31,7 +36,7 @@ version = "=1.1.0" # Path-only, so publish order does not matter. `test-support` for # `plaintext::render`, the path notation the tests assert against, so there # is one copy of it. -vitaminc-aead = { path = "../aead", features = ["jiff", "rust_decimal", "uuid", "test-support"] } +vitaminc-aead = { path = "../vitaminc-aead", features = ["jiff", "rust_decimal", "uuid", "test-support"] } jiff = { version = "1.0.0", default-features = false } uuid = { version = "1", default-features = false } quickcheck = "1.1.0" diff --git a/release-plz.toml b/release-plz.toml index 7f28ee209..e230abb8a 100644 --- a/release-plz.toml +++ b/release-plz.toml @@ -103,3 +103,12 @@ publish = false name = "vitaminc-aead-derive" release = false publish = false + +# vitaminc-normalize moved here from cipherstash/vitaminc after the AEAD +# crates. crates.io's 0.10.0 was published from vitaminc. It is listed here +# so that release-plz neither bumps nor publishes it. It stays listed until +# it is published from here under the same name. +[[package]] +name = "vitaminc-normalize" +release = false +publish = false From 6b53e254f576a776e1ea49054d5e34749bd2122c Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:22:58 +1100 Subject: [PATCH 56/68] chore(vitaminc-normalize): add vitaminc's MIT licence to the imported crate In vitaminc the licence file is at the repository root. The import did not bring it. The crate now has a copy of it. The AEAD crates and the stack-* crates each have one too. --- packages/vitaminc-normalize/LICENSE | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 packages/vitaminc-normalize/LICENSE diff --git a/packages/vitaminc-normalize/LICENSE b/packages/vitaminc-normalize/LICENSE new file mode 100644 index 000000000..2212a9966 --- /dev/null +++ b/packages/vitaminc-normalize/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2024-2026 CipherStash Inc + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. From 93bb14086d36110570ef9c98a6e318ff76840b3a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:25:06 +1100 Subject: [PATCH 57/68] build: build the root workspace against the imported vitaminc-normalize vitaminc-normalize joins the root workspace's members. The workspace dependency on it names it by path. The [patch.crates-io] table now lists it too. vitaminc-prf (with its normalize feature) and vitaminc-ore come from crates.io and depend on vitaminc-normalize 0.10. With the patch they build against the copy here. So the build has one vitaminc-normalize 0.10: the path crate. The comment on the patch table now lists, for each patched crate, the crates from crates.io that depend on it. It no longer names vitaminc-encrypt: this workspace resolves no vitaminc-encrypt 0.10. Cargo.lock: vitaminc-normalize changes from a registry entry to a path entry. Its entry now lists the crate's dev-dependencies. The one package it adds is orderable-bytes 0.2.1, a dev-dependency that the tests compare the decimal and float encodings with. No package changes version. --- Cargo.lock | 18 ++++++++++++++++-- Cargo.toml | 36 +++++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5f040e8f9..1a21d5112 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2482,6 +2482,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "orderable-bytes" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7d30b72ffca73d9936fe5fc80a9c9520c73f5b4f64839a810211903d5ace3c" +dependencies = [ + "rust_decimal", +] + [[package]] name = "ore-rs" version = "0.12.0" @@ -4643,12 +4652,17 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ + "futures-executor", + "jiff", + "orderable-bytes", + "quickcheck", + "quickcheck_macros", + "rust_decimal", "thiserror 2.0.18", "unicode-general-category", "unicode-normalization", + "uuid", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", ] diff --git a/Cargo.toml b/Cargo.toml index 98419fe3a..88a49bed2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,8 @@ resolver = "2" # The stack-* crates imported from cipherstash-suite, the three node bindings -# that wrap them, and the three AEAD crates moved from cipherstash/vitaminc. +# that wrap them, and the crates moved from cipherstash/vitaminc: the three +# AEAD crates and vitaminc-normalize. # The root is one of three Cargo workspaces in this repository: EQL and # protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead to the # copies here, as this workspace does; protect-ffi resolves no vitaminc-aead @@ -23,6 +24,10 @@ members = [ "packages/vitaminc-aead", "packages/recipher-frame", "packages/vitaminc-aead-derive", + # Moved from cipherstash/vitaminc after the AEAD crates. It keeps its + # crates.io name, and is not published from here yet; see the patch table + # at the end. + "packages/vitaminc-normalize", "languages/typescript/packages/auth", "languages/typescript/packages/profile", "languages/typescript/packages/stack-auth-wasm", @@ -164,24 +169,29 @@ vitaminc-aead = { path = "./packages/vitaminc-aead", version = "0.10.0" } recipher-frame = { path = "./packages/recipher-frame", version = "0.10.0" } vitaminc-hmac = "0.10.0" # Normalized equality terms (Unicode 16 NFC text, one integer encoding for -# every width), which `vitaminc-prf`'s `normalize` feature derives over. -vitaminc-normalize = "0.10.0" +# every width). `vitaminc-prf`'s `normalize` feature derives over them. The +# crate is in this repository (packages/vitaminc-normalize). +vitaminc-normalize = { path = "./packages/vitaminc-normalize", version = "0.10.0" } # The text order key: the system ADR-0002's fold, pinned to Unicode 16, # which text ORE and OPE terms are derived over (ADR-0009). vitaminc-ore = { version = "0.10.0", features = ["prf"] } vitaminc-prf = { version = "0.10.0", features = ["normalize"] } vitaminc-protected = "0.10.0" -# vitaminc-aead and vitaminc-aead-derive moved here from cipherstash/vitaminc -# and are not published from here yet. The vitaminc crates that stay on -# crates.io (the `vitaminc` umbrella, vitaminc-normalize, -prf, -ore and -# -encrypt) and the order schemes clww-ore and ore-rs depend on vitaminc-aead -# 0.10. This table makes -# them build against the copy here, so the build has one vitaminc-aead 0.10, -# and its types are the ones stack-encrypt passes into them. It applies only -# to the 0.10 line: the vitaminc-aead 0.5.1 that cts-common reaches through -# vitaminc 0.5.1 still comes from crates.io. Every other workspace that -# resolves these crates carries the same table. +# vitaminc-aead, vitaminc-aead-derive and vitaminc-normalize moved here from +# cipherstash/vitaminc. They are not published from here yet. Crates from +# crates.io depend on them at 0.10: +# - vitaminc-aead: the `vitaminc` umbrella, vitaminc-prf and vitaminc-ore; +# - vitaminc-normalize: vitaminc-prf (its `normalize` feature) and +# vitaminc-ore. +# The order schemes clww-ore and ore-rs depend on vitaminc-prf and +# vitaminc-ore. This table makes all of them build against the copies here. +# So the build has one vitaminc-aead 0.10 and one vitaminc-normalize 0.10. +# Their types are the ones stack-encrypt passes into those crates. The table +# applies only to the 0.10 line. The vitaminc-aead 0.5.1 that cts-common +# reaches through vitaminc 0.5.1 still comes from crates.io. Every other +# workspace that resolves these crates has the same table. [patch.crates-io] vitaminc-aead = { path = "./packages/vitaminc-aead" } vitaminc-aead-derive = { path = "./packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "./packages/vitaminc-normalize" } From d536369d0589fee94478cbb8c7c426ddb2dcb8d3 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:25:46 +1100 Subject: [PATCH 58/68] test(vitaminc-normalize): read a refusal's reason from the term error a_refusal_names_the_field_only_on_request failed once the crate built against the vitaminc-aead in this repository. The test expected the Debug of EncryptError::Source to show the term error inside it. Since 8f823d967, SourceError's Debug in vitaminc-aead shows SourceError(..) in place of the inner error. The published 0.10.0 test was written against crates.io's vitaminc-aead 0.10.0. That version showed the text. The test still checks that neither Debug shows a key. It now reads the reason (UnassignedCodePoint) and the position (Index(1)) from the term error's Debug only. The crate's code does not change. --- packages/vitaminc-normalize/tests/known_answers.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs index a386a8be8..75495cfb9 100644 --- a/packages/vitaminc-normalize/tests/known_answers.rs +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -1285,9 +1285,12 @@ fn a_refusal_names_the_field_only_on_request() { for shown in [format!("{term:?}"), format!("{err:?}")] { assert!(!shown.contains("ada"), "{shown}"); assert!(!shown.contains("emails"), "{shown}"); - assert!(shown.contains("UnassignedCodePoint"), "{shown}"); - assert!(shown.contains("Index(1)"), "{shown}"); } + // The walk's error shows `SourceError(..)` in place of the inner + // error, so the reason and the position are read from the term error. + let shown = format!("{term:?}"); + assert!(shown.contains("UnassignedCodePoint"), "{shown}"); + assert!(shown.contains("Index(1)"), "{shown}"); } /// Every error in a chain, from `err` down through each `source()`. From 3f21dced52a1fa8dcc0bd2f7de5fc206e6c71b7d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:27:43 +1100 Subject: [PATCH 59/68] build: build every other Cargo workspace against the imported vitaminc-normalize Five other workspaces resolve vitaminc-normalize 0.10 on their own: - the TypeScript SDK (recipher-js); - the Go encrypt guest; - EQL's workspace; - EQL's block ORE timing generator; - the stack-encrypt fuzz crate. Each already had a [patch.crates-io] table for the AEAD crates. Each table now points vitaminc-normalize at the copy here too, by relative path, as the root workspace does. In each, cargo metadata --locked passes and cargo tree finds one vitaminc-normalize 0.10: the path crate. Each Cargo.lock changes only from a registry entry to a path entry for vitaminc-normalize (2 lines removed). Four workspaces with a patch table for the AEAD crates do not resolve vitaminc-normalize. They are not changed: - the Go auth guest; - the value bridge's test workspace (value-napi/tests/addon); - the stack-auth and stack-kms fuzz crates. The root manifest's header now says that EQL patches vitaminc-normalize too. --- Cargo.toml | 6 +++--- languages/golang/encrypt/guest/Cargo.lock | 2 -- languages/golang/encrypt/guest/Cargo.toml | 7 ++++--- languages/typescript/packages/recipher-js/Cargo.lock | 2 -- languages/typescript/packages/recipher-js/Cargo.toml | 7 ++++--- packages/eql/Cargo.lock | 2 -- packages/eql/Cargo.toml | 7 ++++--- packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock | 2 -- packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml | 7 ++++--- packages/stack-encrypt/fuzz/Cargo.lock | 2 -- packages/stack-encrypt/fuzz/Cargo.toml | 7 ++++--- 11 files changed, 23 insertions(+), 28 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 88a49bed2..9c54adb14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,9 +5,9 @@ resolver = "2" # that wrap them, and the crates moved from cipherstash/vitaminc: the three # AEAD crates and vitaminc-normalize. # The root is one of three Cargo workspaces in this repository: EQL and -# protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead to the -# copies here, as this workspace does; protect-ffi resolves no vitaminc-aead -# 0.10. +# protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead and +# vitaminc-normalize to the copies here, as this workspace does. protect-ffi +# resolves no vitaminc-aead 0.10. members = [ "packages/stack-auth", "packages/stack-profile", diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index c6e996906..b705417d3 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2945,8 +2945,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", diff --git a/languages/golang/encrypt/guest/Cargo.toml b/languages/golang/encrypt/guest/Cargo.toml index c501fb6c6..4a0af714c 100644 --- a/languages/golang/encrypt/guest/Cargo.toml +++ b/languages/golang/encrypt/guest/Cargo.toml @@ -98,9 +98,10 @@ opt-level = 3 lto = true strip = true -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index e538eb4b4..a6965d0f5 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3866,8 +3866,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", diff --git a/languages/typescript/packages/recipher-js/Cargo.toml b/languages/typescript/packages/recipher-js/Cargo.toml index 85f4883f8..53ce0f90a 100644 --- a/languages/typescript/packages/recipher-js/Cargo.toml +++ b/languages/typescript/packages/recipher-js/Cargo.toml @@ -21,9 +21,10 @@ members = ["crate", "value-napi"] edition = "2021" repository = "https://github.com/cipherstash/stack" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 3aa6c47bf..6f5090a8b 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -5181,8 +5181,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", diff --git a/packages/eql/Cargo.toml b/packages/eql/Cargo.toml index 72314769c..c697cf246 100644 --- a/packages/eql/Cargo.toml +++ b/packages/eql/Cargo.toml @@ -36,9 +36,10 @@ default-members = ["tests/sqlx"] dead_code = "deny" unused_imports = "deny" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../vitaminc-aead" } vitaminc-aead-derive = { path = "../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../vitaminc-normalize" } diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock index 02b9d1d35..532286039 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock @@ -791,8 +791,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml index c6d868b09..4b3335898 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml @@ -24,9 +24,10 @@ hex = "0.4" [workspace] -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../../vitaminc-normalize" } diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 3641d40fa..09b5c689e 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2833,8 +2833,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.18", "unicode-general-category", diff --git a/packages/stack-encrypt/fuzz/Cargo.toml b/packages/stack-encrypt/fuzz/Cargo.toml index e91082049..c2fc6a885 100644 --- a/packages/stack-encrypt/fuzz/Cargo.toml +++ b/packages/stack-encrypt/fuzz/Cargo.toml @@ -83,9 +83,10 @@ bench = false [workspace] resolver = "2" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../vitaminc-normalize" } From 71cbf879422965a3630d6bb68b57e27f48e3a35b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:32:16 +1100 Subject: [PATCH 60/68] ci: build, test and document vitaminc-normalize in CI As a root workspace member, the crate is already in tests-crates.yml's fmt, clippy, nextest and doctest runs, with every feature on. Its own tasks.toml gives it a doc:vitaminc-normalize task. So the root doc task builds its rustdoc with warnings as errors, public items and then private items. The crate has no optional features, so it needs no feature task. The workflows that compile the crate now start when it changes. Each one already starts on a change to the AEAD crates: - tests-crates, tests-golang, tests-recipher-js and udeps; - fuzz: the stack-encrypt fuzz crate links it; - test-eql and bench-eql: EQL's encryption tests link it. tests.yml's live jobs skip a change to it, as they skip stack-encrypt. Nothing they build links it. crates-ci.test.mjs lists the new task file and task. The mise.toml header and a test-eql.yml comment name the crate too. --- .github/workflows/bench-eql.yml | 1 + .github/workflows/fuzz.yml | 1 + .github/workflows/test-eql.yml | 6 ++++-- .github/workflows/tests-crates.yml | 2 ++ .github/workflows/tests-golang.yml | 2 ++ .github/workflows/tests-recipher-js.yml | 2 ++ .github/workflows/tests.yml | 5 ++++- .github/workflows/udeps.yml | 2 ++ mise.toml | 6 ++++-- packages/vitaminc-normalize/tasks.toml | 14 ++++++++++++++ scripts/__tests__/crates-ci.test.mjs | 4 +++- 11 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 packages/vitaminc-normalize/tasks.toml diff --git a/.github/workflows/bench-eql.yml b/.github/workflows/bench-eql.yml index 6422ddb9a..8b6acdccc 100644 --- a/.github/workflows/bench-eql.yml +++ b/.github/workflows/bench-eql.yml @@ -71,6 +71,7 @@ on: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 2b02d041e..178932e6c 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -32,6 +32,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - Cargo.lock - mise.toml diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index c6ea81eec..a45da10ce 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -105,8 +105,8 @@ on: # (`eql-bindings`' `stack-encrypt` feature): stack-encrypt, its derive # and stack-kms through `path =`, and stack-auth and stack-profile # through `workspace = true` entries the root `Cargo.toml` resolves to - # paths, and the vitaminc-aead crates through the patch table in - # packages/eql/Cargo.toml. The mise-task derivation in eql-workflow-filters.test.mjs + # paths, and the vitaminc-aead crates and vitaminc-normalize through the + # patch table in packages/eql/Cargo.toml. The mise-task derivation in eql-workflow-filters.test.mjs # cannot see them (a task body names a cargo package, not a path); the # manifest walk in eql-suite-ci.test.mjs does, and fails when one of them # is missing from this list. @@ -117,6 +117,7 @@ on: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -222,6 +223,7 @@ jobs: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index 86f2ad9c3..c46231271 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -29,6 +29,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -59,6 +60,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 5d797f220..3913dd79b 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -46,6 +46,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** @@ -94,6 +95,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** diff --git a/.github/workflows/tests-recipher-js.yml b/.github/workflows/tests-recipher-js.yml index ef5f62a4f..ce7499ccc 100644 --- a/.github/workflows/tests-recipher-js.yml +++ b/.github/workflows/tests-recipher-js.yml @@ -29,6 +29,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - mise.toml - pnpm-lock.yaml @@ -48,6 +49,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - mise.toml - pnpm-lock.yaml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 126b1dc00..904ad33e4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -104,7 +104,9 @@ jobs: # stay in. The auth binding also compiles the vitaminc-aead # crates, through crates.io's `vitaminc` 0.10, but nothing these # jobs run reaches them: tests-crates.yml builds and tests the - # bindings and those crates when either changes. + # bindings and those crates when either changes. These jobs + # build nothing that uses vitaminc-normalize: only stack-encrypt + # reaches it. - '!languages/golang/**' - '!packages/stack-encrypt/**' - '!packages/stack-encrypt-derive/**' @@ -114,6 +116,7 @@ jobs: - '!packages/vitaminc-aead/**' - '!packages/recipher-frame/**' - '!packages/vitaminc-aead-derive/**' + - '!packages/vitaminc-normalize/**' - '!packages/stack-auth/fuzz/**' # The TypeScript SDK on Stack Encrypt. Nothing these jobs build # depends on it, and tests-recipher-js.yml runs its tests. diff --git a/.github/workflows/udeps.yml b/.github/workflows/udeps.yml index 3123e765a..e2121c7ac 100644 --- a/.github/workflows/udeps.yml +++ b/.github/workflows/udeps.yml @@ -21,6 +21,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -44,6 +45,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/mise.toml b/mise.toml index 8a592e922..f78fc6824 100644 --- a/mise.toml +++ b/mise.toml @@ -1,6 +1,7 @@ # The repository root is the root of the Rust and Go toolchains: the Cargo -# workspace in Cargo.toml (the stack-* crates, the three AEAD crates moved from -# vitaminc, and the three node bindings) and the Go module in languages/golang. +# workspace in Cargo.toml (the stack-* crates, the three AEAD crates and +# vitaminc-normalize moved from vitaminc, and the three node bindings) and the +# Go module in languages/golang. # # EQL (packages/eql) and protect-ffi (languages/typescript/packages/protect-ffi) # keep their own mise.toml. A tool they pin there overrides the pin here, in @@ -17,6 +18,7 @@ includes = [ "packages/vitaminc-aead/tasks.toml", "packages/recipher-frame/tasks.toml", "packages/vitaminc-aead-derive/tasks.toml", + "packages/vitaminc-normalize/tasks.toml", ] [tools] diff --git a/packages/vitaminc-normalize/tasks.toml b/packages/vitaminc-normalize/tasks.toml new file mode 100644 index 000000000..c150c12b0 --- /dev/null +++ b/packages/vitaminc-normalize/tasks.toml @@ -0,0 +1,14 @@ +# Tasks for vitaminc-normalize, imported from cipherstash/vitaminc. Included +# from the root mise.toml. + +# Rustdoc with warnings as errors. The root `doc` task runs this task. +# It builds the public docs, then the docs of private items too. Only the +# public build warns when a public doc links to a private item. Only the +# private build checks the links in private docs. +["doc:vitaminc-normalize"] +description = "Build docs for vitaminc-normalize with all features, public then private items (warnings are errors)" +env = { RUSTDOCFLAGS = "-D warnings" } +run = [ + "cargo doc -p vitaminc-normalize --no-deps --all-features", + "cargo doc -p vitaminc-normalize --no-deps --all-features --document-private-items", +] diff --git a/scripts/__tests__/crates-ci.test.mjs b/scripts/__tests__/crates-ci.test.mjs index 52d243f1c..d6743660b 100644 --- a/scripts/__tests__/crates-ci.test.mjs +++ b/scripts/__tests__/crates-ci.test.mjs @@ -238,7 +238,7 @@ const CI_EXEMPT_TASKS = new Map([ ]) describe('the scan sees every task mise sees', () => { - it('reads the nine crate task files from the root mise.toml', () => { + it('reads the ten crate task files from the root mise.toml', () => { expect(INCLUDES.sort()).toEqual( [ 'packages/stack-auth/tasks.toml', @@ -250,6 +250,7 @@ describe('the scan sees every task mise sees', () => { 'packages/vitaminc-aead/tasks.toml', 'packages/recipher-frame/tasks.toml', 'packages/vitaminc-aead-derive/tasks.toml', + 'packages/vitaminc-normalize/tasks.toml', ].sort(), ) }) @@ -303,6 +304,7 @@ describe('the scan sees every task mise sees', () => { 'doc:vitaminc-aead', 'doc:vitaminc-aead-derive', 'doc:recipher-frame', + 'doc:vitaminc-normalize', ].sort(), ) }) From 1f8b2409367c6efc9c25e42301cab8ebc4cb95af Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:33:54 +1100 Subject: [PATCH 61/68] ci: opt vitaminc-normalize into the mutants gate vitaminc gated the crate with cargo-mutants --in-diff. mutants.yml now starts when the crate changes. The pull request run passes -p vitaminc-normalize. A manual dispatch sweeps the crate in its own job. The excludes are the three that vitaminc carried for this crate. Each is an equivalent mutant: - the swap of | for ^ in widen_f32; - the same swap in the decimal encoder's orderable; - null's body replaced with Protected::new(vec![0]) or Protected::from(vec![0]). A cargo-mutants 27.1.0 run over those functions found exactly these 11 mutants missed. It caught the other 6 and found 4 unviable. With the excludes, cargo mutants --list no longer lists the 11. --- .cargo/mutants.toml | 16 ++++++++++++++++ .github/workflows/mutants.yml | 13 +++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 107f70367..1aefaca9f 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -186,6 +186,22 @@ exclude_re = [ # when they are equal `a > b` and `a >= b` return the same number. Its # other mutants stay gated. 'vitaminc-aead/src/plaintext/depth\.rs:\d+:\d+: replace > with >= in max$', + # vitaminc-normalize — equivalent. `widen_f32` builds an f64 by OR-ing bit + # fields that cannot share a set bit: complementary masks, or fields + # shifted into separate bit ranges. For two values with no common set bit, + # `a | b` equals `a ^ b`. Its other mutants stay gated. So does the `| 1` + # in `highest_set_bit`, where the two values can share a set bit. + 'vitaminc-normalize/src/scalar\.rs:\d+:\d+: replace \| with \^ in widen_f32$', + # vitaminc-normalize — equivalent. In the decimal encoder's `orderable`, + # three `|` join two values that cannot share a set bit, as in a select + # `(a & !mask) | (b & mask)`. The fourth, `x | x.wrapping_neg()`, differs + # from `^` only when `x = 2^127`, and no mantissa reaches 2^96. Its other + # mutants stay gated. + 'vitaminc-normalize/src/decimal\.rs:\d+:\d+: replace \| with \^ in orderable$', + # vitaminc-normalize — equivalent. `null` returns the one byte `0x00` in a + # protected vector. `Protected::new(vec![0])` and `Protected::from(vec![0])` + # return the same. Its other replacements stay gated. + 'vitaminc-normalize/src/scalar\.rs:\d+:\d+: replace null -> Protected> with Protected::(new|from)\(vec!\[0\]\)$', ] # Headroom over the measured baseline before a slow-but-correct mutant is diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 5c161ebd6..685231bf8 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -5,9 +5,9 @@ name: Mutants # # Gates pull requests on mutation testing of the lines they change in # stack-auth, stack-encrypt, stack-encrypt-jsonpath (the path grammar, moved -# out of stack-encrypt), and vitaminc-aead, recipher-frame and -# vitaminc-aead-derive (imported from cipherstash/vitaminc, which gated them -# the same way). Ported from cipherstash-suite's `mutants.yml`. +# out of stack-encrypt), and vitaminc-aead, recipher-frame, +# vitaminc-aead-derive and vitaminc-normalize (imported from +# cipherstash/vitaminc, which gated them the same way). Ported from cipherstash-suite's `mutants.yml`. # # cargo-mutants rewrites small pieces of logic (flip `<` to `<=`, replace a # body with `Default::default()`) and reruns the tests; a mutant that survives @@ -40,6 +40,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - Cargo.lock - mise.toml @@ -107,7 +108,7 @@ jobs: strategy: fail-fast: false matrix: - crate: ${{ fromJSON(github.event_name == 'pull_request' && '["all"]' || '["stack-auth","stack-encrypt","stack-encrypt-jsonpath","vitaminc-aead","recipher-frame","vitaminc-aead-derive"]') }} + crate: ${{ fromJSON(github.event_name == 'pull_request' && '["all"]' || '["stack-auth","stack-encrypt","stack-encrypt-jsonpath","vitaminc-aead","recipher-frame","vitaminc-aead-derive","vitaminc-normalize"]') }} permissions: contents: read # Posts and updates the report comment on the PR. @@ -177,7 +178,7 @@ jobs: CRATE: ${{ matrix.crate }} run: | set +e - crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath -p vitaminc-aead -p recipher-frame -p vitaminc-aead-derive) + crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath -p vitaminc-aead -p recipher-frame -p vitaminc-aead-derive -p vitaminc-normalize) if [ "$CRATE" = "all" ]; then cargo mutants --no-shuffle -vV "${crates[@]}" --in-diff pr.diff else @@ -198,7 +199,7 @@ jobs: timeout=$(count timeout.txt) { echo '' - echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive)" + echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive, vitaminc-normalize)" echo if [ ! -d "$out" ]; then # No output dir: either nothing to mutate (exit 0) or the run From 927e9ab7507a080816d26dd35197b03c703628d9 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 19:38:45 +1100 Subject: [PATCH 62/68] docs: describe the imported vitaminc-normalize in AGENTS.md, SECURITY.md and CODEOWNERS AGENTS.md: the repository layout lists the crate. The entry says: - what the crate does; - that it keeps its crates.io name and is not published from here yet; - that every workspace that resolves it patches it to the copy here; - that supply-chain-vitaminc-aead.yml does not check it as a crate of its own yet. Working on the Rust crates now names it with the AEAD crates. It says how to check that a workspace has one vitaminc-normalize 0.10. The Fuzzing, Miri and Mutation testing sections name it too. SECURITY.md lists it as in scope, under MIT. CODEOWNERS names its directory. --- .github/CODEOWNERS | 6 +++-- AGENTS.md | 58 +++++++++++++++++++++++++--------------------- SECURITY.md | 9 +++++++ 3 files changed, 45 insertions(+), 28 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 621d001a2..d3c64e18a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -23,9 +23,11 @@ /languages/typescript/packages/profile/ @cipherstash/developers /languages/typescript/packages/stack-auth-wasm/ @cipherstash/developers -# vitaminc's AEAD crates, moved from cipherstash/vitaminc, and the value -# conformance corpus their tests read. Not published from here yet. +# vitaminc's AEAD crates and vitaminc-normalize, moved from +# cipherstash/vitaminc, and the value conformance corpus the AEAD crates' +# tests read. Not published from here yet. /packages/vitaminc-aead/ @cipherstash/developers /packages/recipher-frame/ @cipherstash/developers /packages/vitaminc-aead-derive/ @cipherstash/developers +/packages/vitaminc-normalize/ @cipherstash/developers /conformance/vitaminc-aead/ @cipherstash/developers diff --git a/AGENTS.md b/AGENTS.md index 7830652cc..adb8f8fd0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,6 +92,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l links are provenance only. - `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates and the three node binding crates below. See "Working on the Rust crates". - `packages/vitaminc-aead`, `packages/recipher-frame`, `packages/vitaminc-aead-derive`: vitaminc's AEAD crates, imported from `cipherstash/vitaminc` with their history at the code of their crates.io 0.10.0 release (`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). They define the value types Stack Encrypt seals, the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`), and the derive macros. `vitaminc-aead` and `vitaminc-aead-derive` keep their crates.io names, because vitaminc crates that stay on crates.io depend on `vitaminc-aead`; the frame crate was `vitaminc-aead-frame` and is now `recipher-frame`, since only crates here depend on it. All three keep the MIT licence, are members of the root workspace, and are `publish = false` with `release = false` in `release-plz.toml`: crates.io's 0.10.0 was published from vitaminc, and they publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` carries a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). The cross-language value conformance corpus their tests read is `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here: the storage corpus append-only check (`storage-corpus.yml`), the Kani proofs of the storage reader (`kani.yml`), `cargo deny` and `cargo vet` over their dependency graph only (`supply-chain-vitaminc-aead.yml`, config in `supply-chain/vitaminc-aead/`; the rest of the workspace is #1842), and mutation testing (`mutants.yml`). See "Working on the Rust crates". +- `packages/vitaminc-normalize`: vitaminc's equality normalization crate, imported from `cipherstash/vitaminc` with its history at the code of its crates.io 0.10.0 release, the way the AEAD crates were. It gives each scalar kind that can be indexed for equality a domain label and the bytes an equality term is derived from. `stack-encrypt`'s equality index uses it, and so do `vitaminc-prf` (its `normalize` feature) and `vitaminc-ore`. It keeps its crates.io name, because `vitaminc-prf` and `vitaminc-ore` stay on crates.io and depend on it. It keeps the MIT licence. It is a member of the root workspace. It is `publish = false`, with `release = false` in `release-plz.toml`. Every Cargo workspace that resolves `vitaminc-normalize` lists it in its `[patch.crates-io]` table. Its tests, rustdoc and the mutants gate run here as for the AEAD crates. `supply-chain-vitaminc-aead.yml` does not check it as a crate of its own yet. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). - `languages/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset`, `Ciphertext`, and `Json` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). The bridge converts JSON documents too. `JsRef::to_json` writes a JavaScript value as a document's JSON text, with the JavaScript number rules. `JsBuilder::build_json` builds a decrypted document. The addon's `json.rs` contains only the `Json` class, and passes the text to the engine's `JsonPlaintext`. A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) contains only `Result`, `RecipherError`, the loader, stand-ins for a build that did not load, and the types that the generated signatures name. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The types are in `src/kinds.ts` and `src/value-types.ts`. `native.d.ts` imports those types, so a module that `native.d.ts` imports from must never load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. Two kinds of call throw: a method called without its object (#1801), and `new` on a class whose type has no constructor (`Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, which an application makes with `RcDate.from(text)` and the like, each returning a `Result`). Every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. - `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing, the `record` wire model, and `wasmtestrun`, the wazero runner that `wasm:auth-guest:test` runs the auth guest's wasm32 tests under). A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), a final version dispatched from anywhere but `main`, and a final version while `languages/golang/go.mod` pins a `github.com/cipherstash/vitaminc/…` module at a pseudo-version (vitaminc's Go bindings have no tags, and a TEMPORARY pin on an unreleased commit must be gone before the module is tagged); a pre-release may come from a branch and may carry such a pin. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `examples/s3` is a fourth, also never tagged: it encrypts S3 object bodies with a plain `encrypt` field through the AWS SDK for Go v2, and `mise run go:example:s3` runs its tests end to end against S3Mock in Docker (they skip in CI, which has no bucket). `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. @@ -748,32 +749,35 @@ requirements, because the published `stack-auth` inherits them, and an exact pin would stop the suite sharing one `cts-common` with it. vitaminc's AEAD crates (`vitaminc-aead`, `recipher-frame`, -`vitaminc-aead-derive`) live here, in `packages/`, and are not published from -here yet. The AES-256-GCM cipher is in `vitaminc-aead`, behind its `aes` -feature, so nothing here uses `vitaminc-encrypt` 0.10. The other vitaminc -crates come from crates.io at 0.10, and three of them depend on -`vitaminc-aead`: `vitaminc-normalize`, `vitaminc-prf` and `vitaminc-ore`, -with the `vitaminc` umbrella crate, `clww-ore` and `ore-rs` above them. So every Cargo workspace that resolves -`vitaminc-aead` 0.10 carries a `[patch.crates-io]` table, with relative paths, -that makes those crates build against the copies here. A workspace must have -exactly one `vitaminc-aead` 0.10, and it must be the path crate: check with -`cargo tree -i vitaminc-aead@0.10.0`. A new workspace that resolves it needs the -same table. The patch covers the 0.10 line only, so the `vitaminc-aead` 0.5.1 -that `cts-common` reaches through `vitaminc` 0.5.1 still comes from crates.io, -and a change to these crates must keep their version on 0.10 until they are -published from here. +`vitaminc-aead-derive`) and `vitaminc-normalize` live here, in `packages/`, +and are not published from here yet. The AES-256-GCM cipher is in +`vitaminc-aead`, behind its `aes` feature, so nothing here uses +`vitaminc-encrypt` 0.10. The other vitaminc crates come from crates.io at +0.10. Two of them depend on both `vitaminc-aead` and `vitaminc-normalize`: +`vitaminc-prf` and `vitaminc-ore`. The `vitaminc` umbrella crate, `clww-ore` +and `ore-rs` build on those two. So every Cargo workspace that resolves +`vitaminc-aead` 0.10 or `vitaminc-normalize` 0.10 has a `[patch.crates-io]` +table. Its relative paths make those crates build against the copies here. A +workspace must have exactly one of each at 0.10: the path crate. Check with +`cargo tree -i vitaminc-aead@0.10.0` and +`cargo tree -i vitaminc-normalize@0.10.0`. A new workspace that resolves +either needs the same table. The patch covers the 0.10 line only, so the +`vitaminc-aead` 0.5.1 that `cts-common` reaches through `vitaminc` 0.5.1 still +comes from crates.io. A change to these crates must keep their version on +0.10 until they are published from here. `cargo publish` drops `[patch]` tables, so a crate published from here (`stack-encrypt`, `stack-kms`, `stack-auth`) depends on crates.io's -`vitaminc-aead` 0.10.x, not on the copies. A change made in the copies +`vitaminc-aead` 0.10.x and `vitaminc-normalize` 0.10.x, not on the copies. A change made in the copies reaches a published crate only once the copies are published from here, which the plan schedules before the next `stack-encrypt` release. - **Three Cargo workspaces, not one.** The root workspace (the seven stack-* - crates, the three AEAD crates and the three node binding crates), - protect-ffi's and EQL's. The root `Cargo.toml` excludes the other two. EQL's - patches `vitaminc-aead` to the copies here, as the root does; protect-ffi's - resolves no `vitaminc-aead` 0.10. The + crates, the three AEAD crates, `vitaminc-normalize` and the three node + binding crates), protect-ffi's and EQL's. The root `Cargo.toml` excludes the + other two. EQL's patches `vitaminc-aead` and `vitaminc-normalize` to the + copies here, as the root does; protect-ffi's resolves no `vitaminc-aead` + 0.10. The TypeScript SDK's crates (`languages/typescript/packages/recipher-js`, napi-rs 3: the addon `crate` and the value bridge `value-napi`) are a detached workspace too, with its own `Cargo.lock`, depending on stack-encrypt by path. The value @@ -851,7 +855,9 @@ replays their seeds, and `mise run go:fuzz` fuzzes them (nightly in The AEAD crates have no fuzz targets of their own. stack-encrypt's targets (`check_record`, `term_decode`) reach parts of them, and `fuzz.yml` replays those when the AEAD crates change. vitaminc fuzzed the frame codec from Go (`vcffi`), and -those targets move with that package. +those targets move with that package. `vitaminc-normalize` has no fuzz +targets either, and `fuzz.yml` replays stack-encrypt's targets when it +changes too. Full walkthrough — layout, adding a target, the CI split — in [`docs/fuzzing.md`](docs/fuzzing.md). For cargo-fuzz mechanics (sanitizers, corpus, crash triage) use the Trail of Bits `cargo-fuzz` skill rather than a @@ -879,10 +885,10 @@ transport's response reclaim). Its hostile-input behaviour is pinned from the Go side (`mise run go:test`). Keep new pointer handling in `stack-guest-abi`, where Miri reaches it, not in a guest. -Miri and the sanitizers do not run on the AEAD crates. All three -`#![deny(unsafe_code)]`, and vitaminc ran neither on them: it ran both on -`vitaminc-protected`, which has the `unsafe` and stays in vitaminc. A crate -that adds `unsafe` needs both. +Miri and the sanitizers do not run on the AEAD crates or on +`vitaminc-normalize`. All four `#![deny(unsafe_code)]`. vitaminc ran neither +on them. It ran both on `vitaminc-protected`, the crate with the `unsafe` +code. That crate stays in vitaminc. A crate that adds `unsafe` needs both. ### Kani @@ -904,8 +910,8 @@ not `mise.test.toml`, so no other job installs it. ### Mutation testing The crates that opt in (stack-auth, stack-encrypt, stack-encrypt-jsonpath, -vitaminc-aead, recipher-frame, vitaminc-aead-derive) are mutation-tested -with cargo-mutants; config in `.cargo/mutants.toml`. CI (`mutants.yml`) +vitaminc-aead, recipher-frame, vitaminc-aead-derive, vitaminc-normalize) are +mutation-tested with cargo-mutants; config in `.cargo/mutants.toml`. CI (`mutants.yml`) gates every PR touching them with `--in-diff`: only the lines the PR changes are mutated, and a surviving mutant fails the job. For now the gate runs only on a pull request into main, and not on the release pull request. #2017 turns it diff --git a/SECURITY.md b/SECURITY.md index b037162ea..370e52178 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,6 +54,15 @@ and 0.2.0-pre that some builds still reach come from crates.io. The three crates are licensed under MIT, and are in scope for security reports on the same terms as the npm packages above. +The source of a fourth crate, **`vitaminc-normalize`** +(`packages/vitaminc-normalize`), moved from `cipherstash/vitaminc` in the +same way. It derives the bytes an equality term is computed from. Its +crates.io releases up to 0.10.0 were published from `cipherstash/vitaminc`. +Every build that uses `vitaminc-normalize` 0.10 uses the copy here. + +`vitaminc-normalize` is licensed under MIT. It is in scope for security +reports on the same terms as the npm packages above. + The `encrypttest` module ships test builds of the engine whose keys derive from a published seed. Those keys are not secret by design: the package is for tests only. A way for a production client to load From cc56f63d7e3e46b82936e89c080aa700efb7fb62 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 20:11:33 +1100 Subject: [PATCH 63/68] chore(supply-chain): say that vitaminc-normalize here is not the crates.io crate vitaminc-normalize is now a member of the root workspace at 0.10.0, and crates.io has a 0.10.0 too. Without --locked, cargo vet stops on that before it checks anything, and asks for an audit-as-crates-io policy. The locked run in CI does not make this check, so CI did not show it. The step that names the kind of a cargo vet failure runs without --locked, as does the README's repair command, and both would have failed. The store now has the policy entry, as it has for vitaminc-aead. The entry names no criteria: whether the store checks this crate's own dependency graph is a separate decision. The safe-to-run exemption for vitaminc-normalize 0.10.0 is removed. It covered the crates.io copy, which is no longer in the graph. --- supply-chain/vitaminc-aead/config.toml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/supply-chain/vitaminc-aead/config.toml b/supply-chain/vitaminc-aead/config.toml index 21ce0c894..38ea26e77 100644 --- a/supply-chain/vitaminc-aead/config.toml +++ b/supply-chain/vitaminc-aead/config.toml @@ -56,6 +56,9 @@ dependency-criteria = { zeroize = ["safe-to-deploy", "crypto-reviewed"] } [policy."vitaminc-aead:0.5.1"] criteria = "safe-to-deploy" +[policy."vitaminc-normalize:0.10.0"] +audit-as-crates-io = false + [[exemptions.aead]] version = "0.5.2" criteria = ["safe-to-deploy", "crypto-reviewed"] @@ -488,10 +491,6 @@ criteria = "safe-to-run" version = "0.10.0" criteria = "safe-to-deploy" -[[exemptions.vitaminc-normalize]] -version = "0.10.0" -criteria = "safe-to-run" - [[exemptions.vitaminc-prf]] version = "0.10.0" criteria = "safe-to-run" From 40f9510363c46abf7d8af0ec65f4bb69a493da9f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Fri, 4 Dec 2026 20:11:33 +1100 Subject: [PATCH 64/68] docs: where vitaminc-normalize builds from, and that it is a workspace member SECURITY.md said every build that uses vitaminc-normalize 0.10 uses the copy here. That holds for builds made from this repository. cargo publish drops patch tables, so a stack-encrypt from crates.io uses the crates.io release. The Repository Layout in AGENTS.md listed the members of the root Cargo workspace without the crate. The plan for the vitaminc-aead move listed it among the crates that stay in cipherstash/vitaminc. --- AGENTS.md | 2 +- SECURITY.md | 4 +++- docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md | 6 ++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index adb8f8fd0..f3892cf4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l EQL issues in this repository, never in the historical `cipherstash/encrypt-query-language` repository. Old upstream issue and PR links are provenance only. -- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates and the three node binding crates below. See "Working on the Rust crates". +- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates, `vitaminc-normalize` and the three node binding crates below. See "Working on the Rust crates". - `packages/vitaminc-aead`, `packages/recipher-frame`, `packages/vitaminc-aead-derive`: vitaminc's AEAD crates, imported from `cipherstash/vitaminc` with their history at the code of their crates.io 0.10.0 release (`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). They define the value types Stack Encrypt seals, the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`), and the derive macros. `vitaminc-aead` and `vitaminc-aead-derive` keep their crates.io names, because vitaminc crates that stay on crates.io depend on `vitaminc-aead`; the frame crate was `vitaminc-aead-frame` and is now `recipher-frame`, since only crates here depend on it. All three keep the MIT licence, are members of the root workspace, and are `publish = false` with `release = false` in `release-plz.toml`: crates.io's 0.10.0 was published from vitaminc, and they publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` carries a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). The cross-language value conformance corpus their tests read is `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here: the storage corpus append-only check (`storage-corpus.yml`), the Kani proofs of the storage reader (`kani.yml`), `cargo deny` and `cargo vet` over their dependency graph only (`supply-chain-vitaminc-aead.yml`, config in `supply-chain/vitaminc-aead/`; the rest of the workspace is #1842), and mutation testing (`mutants.yml`). See "Working on the Rust crates". - `packages/vitaminc-normalize`: vitaminc's equality normalization crate, imported from `cipherstash/vitaminc` with its history at the code of its crates.io 0.10.0 release, the way the AEAD crates were. It gives each scalar kind that can be indexed for equality a domain label and the bytes an equality term is derived from. `stack-encrypt`'s equality index uses it, and so do `vitaminc-prf` (its `normalize` feature) and `vitaminc-ore`. It keeps its crates.io name, because `vitaminc-prf` and `vitaminc-ore` stay on crates.io and depend on it. It keeps the MIT licence. It is a member of the root workspace. It is `publish = false`, with `release = false` in `release-plz.toml`. Every Cargo workspace that resolves `vitaminc-normalize` lists it in its `[patch.crates-io]` table. Its tests, rustdoc and the mutants gate run here as for the AEAD crates. `supply-chain-vitaminc-aead.yml` does not check it as a crate of its own yet. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). diff --git a/SECURITY.md b/SECURITY.md index 370e52178..5b0fb7540 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -58,7 +58,9 @@ The source of a fourth crate, **`vitaminc-normalize`** (`packages/vitaminc-normalize`), moved from `cipherstash/vitaminc` in the same way. It derives the bytes an equality term is computed from. Its crates.io releases up to 0.10.0 were published from `cipherstash/vitaminc`. -Every build that uses `vitaminc-normalize` 0.10 uses the copy here. +Every build made from this repository that uses `vitaminc-normalize` 0.10 +uses the copy here. A `stack-encrypt` from crates.io uses the crates.io +release, because `cargo publish` drops the patch that selects the copy. `vitaminc-normalize` is licensed under MIT. It is in scope for security reports on the same terms as the npm packages above. diff --git a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md index 5ab0eebda..eae0f5f14 100644 --- a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md +++ b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md @@ -138,8 +138,10 @@ copy of `vitaminc-aead-napi` 0.10.0, and depends only on `vitaminc-aead` and - **Stays, and does not depend on the AEAD crates:** `vitaminc-context` (`vitaminc-aead` depends on it), `vitaminc-hmac` (it depends on `vitaminc-prf`), `vitaminc-traits`, and the rest. -- **Stays for now, and depends on `vitaminc-aead`:** `vitaminc-normalize`, - `vitaminc-prf`, `vitaminc-ore`, `vitaminc-encrypt`. See the next section. +- **Stays for now, and depends on `vitaminc-aead`:** `vitaminc-prf`, + `vitaminc-ore`, `vitaminc-encrypt`. See the next section. +- **Moved after this plan was written:** `vitaminc-normalize`, in #2052, + in the same way as the AEAD crates. It depends on `vitaminc-aead` too. `clww-ore` and `ore-rs` stay in `cipherstash/ore.rs`. From 99816db897e945334002bebe11a75713e51d5ddc Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 15:30:14 +1100 Subject: [PATCH 65/68] build(deps): move tinyvec to 1.13.3 The root lock had tinyvec 1.10.0, which the vitaminc-aead store exempts only at safe-to-run. vitaminc-normalize reaches it at runtime, through unicode-normalization, so the store needs safe-to-deploy once it checks vitaminc-normalize. Imported audits already cover 1.13.3. The move also drops tinyvec_macros, which 1.13 no longer uses. --- Cargo.lock | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 515289763..32e72147a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4022,18 +4022,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" From 56cfd5d62494d24c30225a241a250da3bd696837 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 15:30:15 +1100 Subject: [PATCH 66/68] chore(supply-chain): allow unicode-general-category's build script vitaminc-normalize depends on unicode-general-category 1.1.0. Its build script reads the Unicode table compiled into the crate and writes a lookup table to OUT_DIR. It reads only the OUT_DIR variable and starts no process. cipherstash/vitaminc's deny.toml allowed it. --- supply-chain/vitaminc-aead/deny.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/supply-chain/vitaminc-aead/deny.toml b/supply-chain/vitaminc-aead/deny.toml index b9619acde..947ae93aa 100644 --- a/supply-chain/vitaminc-aead/deny.toml +++ b/supply-chain/vitaminc-aead/deny.toml @@ -116,6 +116,10 @@ allow-build-scripts = [ "target-tuple", "thiserror", "typenum", + # unicode-general-category: a dependency of vitaminc-normalize. The build + # script reads the Unicode table compiled into the crate and writes a + # lookup table to OUT_DIR. It reads only OUT_DIR, and starts no process. + "unicode-general-category", "vitaminc-protected", "wasm-bindgen", "wasm-bindgen-shared", From d4404d0330e1329748998bff3d8fe5f227f904c3 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 15:30:15 +1100 Subject: [PATCH 67/68] chore(supply-chain): trust the cipherstash/ore.rs publisher for orderable-bytes orderable-bytes is a CipherStash crate, published from the cipherstash/ore.rs repository by crates.io trusted publishing. vitaminc-normalize uses it only in tests, to check its decimal encoding against it, so the store needs safe-to-run. cipherstash/vitaminc exempted it. A trust entry covers later versions from the same repository without a new exemption each time. --- supply-chain/vitaminc-aead/audits.toml | 7 +++++++ supply-chain/vitaminc-aead/imports.lock | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/supply-chain/vitaminc-aead/audits.toml b/supply-chain/vitaminc-aead/audits.toml index 95873dfb3..4cbf3956b 100644 --- a/supply-chain/vitaminc-aead/audits.toml +++ b/supply-chain/vitaminc-aead/audits.toml @@ -286,3 +286,10 @@ trusted-publisher = "github:rust-lang/cc-rs" start = "2025-09-01" end = "2027-12-04" notes = "cc runs the C compiler for build scripts. Here aws-lc-sys uses it, directly and through cmake, to compile the AWS-LC C library. Versions up to 1.2.34 were published by the crates.io user rust-lang-owner. Later versions, 1.2.55 among them, are published by the crates.io trusted publisher of the rust-lang/cc-rs repository. 1.2.55 is the version in the graph." + +[[trusted.orderable-bytes]] +criteria = "safe-to-run" +trusted-publisher = "github:cipherstash/ore.rs" +start = "2026-05-05" +end = "2027-12-05" +notes = "orderable-bytes is a CipherStash crate, published from the cipherstash/ore.rs repository by crates.io trusted publishing. vitaminc-normalize uses it only in tests, to check its decimal encoding against it byte for byte." diff --git a/supply-chain/vitaminc-aead/imports.lock b/supply-chain/vitaminc-aead/imports.lock index c38cd07bc..05a6dfa25 100644 --- a/supply-chain/vitaminc-aead/imports.lock +++ b/supply-chain/vitaminc-aead/imports.lock @@ -20,6 +20,11 @@ version = "1.2.55" when = "2026-01-30" trusted-publisher = "github:rust-lang/cc-rs" +[[publisher.orderable-bytes]] +version = "0.2.1" +when = "2026-10-19" +trusted-publisher = "github:cipherstash/ore.rs" + [[publisher.unicode-normalization]] version = "0.1.25" when = "2025-10-30" From f544b1fa1503714136951ac2beb0a851dbb351b7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 5 Dec 2026 15:30:15 +1100 Subject: [PATCH 68/68] ci(supply-chain): check vitaminc-normalize with cargo deny and cargo vet cipherstash/vitaminc ran both tools on vitaminc-normalize. Now that the crate is here, the vitaminc-aead store checks it with the other three: the cargo vet filter keeps it, its policy asks safe-to-deploy of its dependencies, and the workflow runs cargo deny on it and starts when it changes. --- .github/workflows/supply-chain-vitaminc-aead.yml | 13 +++++++------ supply-chain/vitaminc-aead/README.md | 10 +++++----- supply-chain/vitaminc-aead/config.toml | 1 + supply-chain/vitaminc-aead/filter-graph | 2 +- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/.github/workflows/supply-chain-vitaminc-aead.yml b/.github/workflows/supply-chain-vitaminc-aead.yml index cb2fceb8c..08d3c2ee6 100644 --- a/.github/workflows/supply-chain-vitaminc-aead.yml +++ b/.github/workflows/supply-chain-vitaminc-aead.yml @@ -1,14 +1,14 @@ name: Supply chain (vitaminc-aead) -# cargo deny and cargo vet over vitaminc-aead, recipher-frame and -# vitaminc-aead-derive and their dependency graph ONLY. Their config is -# supply-chain/vitaminc-aead/ (see its README.md). The rest of the root +# cargo deny and cargo vet over vitaminc-aead, recipher-frame, +# vitaminc-aead-derive and vitaminc-normalize, and their dependency graph +# ONLY. Their config is supply-chain/vitaminc-aead/ (see its README.md). The rest of the root # workspace is not checked by either tool; that is #1842. # # Neither tool compiles anything: both read `cargo metadata` and Cargo.lock, # so each job takes about a minute, most of it setup. # -# Pull requests that change the three crates, the lockfile or the config +# Pull requests that change the four crates, the lockfile or the config # run both jobs. The nightly schedule runs cargo deny only, on the default # branch: a RustSec advisory published against a version already in # Cargo.lock has no pull request to fail. cargo vet reads only the tree, so @@ -22,6 +22,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - supply-chain/vitaminc-aead/** - Cargo.toml - Cargo.lock @@ -77,7 +78,7 @@ jobs: - name: cargo deny check, one crate at a time run: | status=0 - for crate in vitaminc-aead recipher-frame vitaminc-aead-derive; do + for crate in vitaminc-aead recipher-frame vitaminc-aead-derive vitaminc-normalize; do echo "::group::$crate" cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ --manifest-path "packages/$crate/Cargo.toml" check || status=1 @@ -106,7 +107,7 @@ jobs: cache_key_prefix: mise-v1-ubuntu-2404 # The filter drops every other root workspace member, so the graph - # vetted is the three crates and their dependencies. `--locked` reads + # vetted is the four crates and their dependencies. `--locked` reads # imports.lock as committed rather than fetching the registries. - name: cargo vet id: vet diff --git a/supply-chain/vitaminc-aead/README.md b/supply-chain/vitaminc-aead/README.md index 39f8778e5..c15823469 100644 --- a/supply-chain/vitaminc-aead/README.md +++ b/supply-chain/vitaminc-aead/README.md @@ -1,12 +1,12 @@ # Supply-chain checks for the vitaminc-aead crates This directory holds the `cargo deny` config and the `cargo vet` store for -`vitaminc-aead`, `recipher-frame` and `vitaminc-aead-derive`, and their -dependency graph **only**. Nothing here checks the rest of the root +`vitaminc-aead`, `recipher-frame`, `vitaminc-aead-derive` and +`vitaminc-normalize`, and their dependency graph **only**. Nothing here checks the rest of the root workspace; that is #1842. CI runs both in `.github/workflows/supply-chain-vitaminc-aead.yml`, on pull -requests that change the three crates, `Cargo.lock`, `Cargo.toml` or this +requests that change the four crates, `Cargo.lock`, `Cargo.toml` or this directory. `cargo deny` also runs nightly, for advisories published against versions already in the lockfile. @@ -16,13 +16,13 @@ versions already in the lockfile. started as `cipherstash/vitaminc`'s, with its audits and imported registries. The policies name every root workspace member, because cargo vet checks policies against the whole workspace before it applies the - filter; naming one does not vet it. The three crates' policies set + filter; naming one does not vet it. The four crates' policies set `criteria = "safe-to-deploy"`: they are not roots of the workspace graph (stack-encrypt depends on them), and once the filter drops their dependents nothing else would require more than `safe-to-run` of their runtime dependencies. - `filter-graph`: the `--filter-graph` expression that drops every other - root workspace member, so the graph vetted is the three crates and their + root workspace member, so the graph vetted is the four crates and their dependencies. ## Commands diff --git a/supply-chain/vitaminc-aead/config.toml b/supply-chain/vitaminc-aead/config.toml index 679576b6b..2bb13c58a 100644 --- a/supply-chain/vitaminc-aead/config.toml +++ b/supply-chain/vitaminc-aead/config.toml @@ -58,6 +58,7 @@ criteria = "safe-to-deploy" [policy."vitaminc-normalize:0.10.0"] audit-as-crates-io = false +criteria = "safe-to-deploy" [[exemptions.aead]] version = "0.5.2" diff --git a/supply-chain/vitaminc-aead/filter-graph b/supply-chain/vitaminc-aead/filter-graph index 6b8e9b3ac..620431ba0 100644 --- a/supply-chain/vitaminc-aead/filter-graph +++ b/supply-chain/vitaminc-aead/filter-graph @@ -1 +1 @@ -exclude(all(is_workspace_member(true),not(any(name(vitaminc-aead),name(recipher-frame),name(vitaminc-aead-derive))))) +exclude(all(is_workspace_member(true),not(any(name(vitaminc-aead),name(recipher-frame),name(vitaminc-aead-derive),name(vitaminc-normalize)))))